From 0759574d3438ea9a3958d90b93118429a6c3cf1c Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Wed, 2 Dec 2026 15:06:05 -0800 Subject: [PATCH 01/14] use the latest aind python-template --- .copier-answers.yml | 17 + .flake8 | 11 - .gitattributes | 1 + .github/workflows/lint.yml | 24 - .github/workflows/tag_and_publish.yml | 84 +- .github/workflows/tests_and_format_check.yml | 31 + .gitignore | 13 +- CONTRIBUTING.md | 90 +- LICENSE | 2 +- docs/source/_static/dark-logo.svg | 154 +- docs/source/_static/favicon.ico | Bin 259838 -> 135869 bytes docs/source/_static/light-logo.svg | 153 +- docs/source/conf.py | 51 +- tests/__init__.py | 2 +- uv.lock | 5480 ++++++++++++++++++ 15 files changed, 5644 insertions(+), 469 deletions(-) create mode 100644 .copier-answers.yml delete mode 100644 .flake8 create mode 100644 .gitattributes delete mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/tests_and_format_check.yml create mode 100644 uv.lock 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..f03672c5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +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..4cdf9cb1 --- /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", "3.13", "3.14"] + 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..e9664de5 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 @@ -51,6 +52,7 @@ where scope (optional) describes the packages affected by the code changes and t - **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 4cec150488e1d2c857ce6e4c1f73b0f048a6bc42..bffe942857ce22038917d1833f3792298d08f012 100644 GIT binary patch literal 135869 zcmY&h30zcF7r$z$rGeC!;+{B3sR&{!B7)^gqGUKC`zOn=ZL5CC&0nHK{ zwowFyL3rkZ2!dw7DBGwA$}*tDVxWBIE^oB?{k|{cy?5`qXZfH1IrqNd;5X}5eenK- z_Yp!LSgv0FE&Rt5{ue!RIQ%B;k1PA(Kkxahw%dcyoay*~Ljr!c@I&YmWV!sy4FMK=+GKFiIyn`1rn@Q_=`cbBt`TdwnI*yaBgir5VK77m-o$*WG>3FsN*LS_z zZgBq``+86G`qMwwcx4SviSf&+8VYkD#QTXWXP2}k6}>VlDH->wvdi$_!H{dayF;qB zNEN-Wo2ni>8ufY|xfKP(edsxa{Mg^N@ZsMbdVlO2b=J)?+I((gyP{&u50{_#f3Gwg zO#Egvxk+O2UM~58OIk1X{^{H7fq9pLTC25UCwWW84jfD^m>ghG-6w zu$I3|e)7CNF)lsq^~((1R#C~7rj1w1gIAvqdEVtPu4t^`zA>Rx49{bdQRMc3iwoyC zCT$&=k$l@F#P9C=eplNgD=bF17-oem$*ro-*TQ;*#g6*Hfc&7ev2ZH*chR-uMSX3z zKJGl$pS~s2)!F4=d$WB$cj=JIh3ww=h?Jq}adBDBVacB^dhlpA7w5dv*}v%DTKnLE zm)cZ|ZSP+hO9qbGB)%M#(UjI(>ai(%q?~(}ANoA-T#$v^$O7rs`}PiAd&ZFa_#z#u zO8%I*vQ*WQ@rlP+ow0mMP_)8%xKl-(Vv2)@zxV6U$<3VM3?-R|Gu$BVsw{3E)7os( zdh+UQRHe@T`I2566=K0sro4`C#Mz_cvg-4r=SN0vLN;9?=RER)UTYQDdqmEOq(dfs zLWh)eywbaIJgYwQyCI#kDys93>G)FJ&SJ}-ktJ(Ni>VlQ&hf@ji9_<~OhrMo;#fwG z>qRkL$&HcJ%E~~)AJS7AQfummqJ2-NWo7Mo^~x)w&bO9YG~_U~6?gZetwZF+$uDef ze*EP)GDOsIc1bO35tVF~rZoI88}(go9_3U~(Xiguqy1dXOmd@g3ll2$JKs-Rn?Lh7 z)_AsICWibaKZTx4@%M+qSPrn$2`f{3E9V=|}#_F*9Qki@9 zO;1~6mz};P{i-PS)z~3u;wMd1+uF?CJGI5#A)mKCxjsAYJmMOC%es3NIk{~M-y=fZ zSVq+@PnGRBR=vKetN-jh5t8)QHT#z3cxD)ws)<-!#z)lRR<+jE=hsOm%~;f)_a0I% zwjQsSsSw3jj@@;Xcpi64DOJlQRDn#ZxNQ>tO!I-kU8kAk%FLHCNnSTeQh@jDLW zhsBL6;=8*l)AvVbBedY5d5Lja#H?jEbDmxrL9W-YpfVbL_2+EFxdh!D<71%LNLDHN zk&Q9=J$SaTY}o-1$BK&cIeyjtAChPLSF`nfDxP04#`U(;Y@c~c&Ily2u64h3%{Q)6 zoLTkY{NpL)<{9hg&7Idl8Qs69H<#KKW1V&$s7YT2%k9yi4HK!nGAUmYUaY3A`g8^x2GQf#xM712YHByP!*6rF0P21{~}XCn1P z48= z@GZP83-874sU{wUK~w*6cn6`WGaeC@$0NFO`8-*RQR`=|FAd5;l3U9i$>@t$(zQnY zHM2ZuyjzlJQ49D9TKUyA5=chh(HM~YPqrhu`uk%h;579e3$mtXD$0Y&06h#9mHD!u z!ua_vmtz!KLlL(dgp^r`EnYnJ!30mCyg-EU_XCi~WUe*pKr zoBTpgb<5{q>$z4vGT`Lt6ng60Q(Nu2L?b3Q!>?qPp!Yu)~OgD4~MXN7Do>1CcqzhZp!xlE4YCQfV=<@``z_!WV zwV45L#+zI4n~EhH2I%Q8^GH2xmc%2$oNgl`pqi9hfj z9%tn;o~YUL1a?T{=SB((Am|r78Vbe+b?9 zn#P0oS=rSBtqajX01`;DS3U2V!@`W56%8au^6^v{$?r1f;r7K&cm}zLS9U&MX|HHq zLel?J3L<>HOcpzOSCyUgUZDrv7Jrzn>pZoOB#mmn?U3xaYv`A)vrE1#!g1erq(A*} zMq)WZT7SC2ko?c_E?Ati-W5tx(#o%h36?HQn`PfM`unQw4Ok&Y;|;UC>n>C=LvgS4=)-BU zmf5Xq>{o^2z~G%PRhZW2GZUPl>49KQ>n!_y-Pre0JOX_@*EUisXUIE;qi)1b(3-bC5uvOu&zO{i6aY(+z;(YYQV{ELmOtcJH zkk*AJ%jkaz)~r;Sr?omjQm)?uPaugWm8{@fak!n!-Q)U;o|=w?-|J?FryF|L{WAqz z9HA{V8GQm$ncn#~jf9TGeTl1Y;H+hQw=xg_7NNZq29-9TifMOD0S1Vd8LhyoxJLZ2 z?IRLq{1m$t_RZrnw@>aS=nlRrsviF+!<9yd+>RKXJD4WR2J_iT_m}U%6R5Kb3w*1C z30)7FPe*#^AVvXh^7F&f>hs5X;}A6Zm_Ggq z%1dkl7tr>M`XA1`7F9cJY7o;?2tu7s_KN^%9S`bAL}k z4v-W9f(I#7>rNw&@`{0*|NeU{02`89KZek%s2^A3f2wTgs8K%<^g216KCm)^c*9eg zTIH^KI2O2!56SZ6V!AwoG28LFqJE$QAEFWN89@e?{9Wii@}gIeHoiq-{|?c<3uKq< z=nL!mi6f{cC!a6O{}kvi$Z?O}k@An;U#4qb*fx_$4>>`Hwx&aeaCGPw$&WMAsvbCX zki68UMHMpjtgLx8c5M2rXYsNF0j>50I8KG?VPF(l9x^l&<&}@|Ht1hRq>G|+17OCA zn#b#9oF+JjbpPld{k-ZB6~UdZ`6yr<=zaQMMCgiv)w^S-)d#f^lX78X9NyVsg}plr z^EjC-IzDQuB?Q>Q%i$mil82IkBpn+nHy^;_x)4M`Mo!k_GrgQHR*j{>Bmb1%=e?nF z&uz`ZV3l)S*rQSXmjou;ew3M( znf_&}rZ@fDcck%5j$d6cMgder*~`idS$XVb0%Qt>$a2D4A|EO%>iqojeZFe44SOj`5FRzfl2bHhcp*w`^tthQmq zHRT^;ULqtt)RsDR{GS<#^~>s?~j`v z{6BO)LtCI;S=%T3p1}Tx2I@nlY1r1q6id(0iZ&!cW?C_3ds2@Rz3UWFmV-wm)q)>Y zR^Kl~S&f>A;hUFiy_E0U-hxHoQ)tZXOP6WQd&hp9W%Oc#VrW4#R@ND+EGLS%kOZ16 z%O4*nvbQCMzm27jsXoIzeAl*`U7ark7pLRnO8{sg4Vpw}$9w-)`I8dS=v!bkQpdb} z9J`FZzHXwUcYb*h$4T!LytF&C{P0D=DEo8o(G-#|Ufg983H*3Y>Cl#D&6c0@29mD{VWMx}Y`!sVZ+G zkS=yLpY_15Nb$=hJzrAd>#_4L30{tb+sczNH&}h7Xv7kN7N||$KYHB7%wUoldg91U zrZQRJfp1zJ8a~BKN3r1kGp|-=xHe<6@yWzKOGk)(lOGj4j*;|vH3Kzv$df9u#P+a|pxFh#L+JEK~1%ACd2{d`0a7W3{)O)7=cfNvl z@O%%tG^5F6`F&qed+3#XSwZL`DyRw7V2PxcxEmq-%g%OZP#q!jho6^-rL90g2@FbB z(Yrp9wP5=8fW`oFX$wA(=HO4WhJrfMKFFW3j$23OFe-&4SH0#r*5<31V2@FLKx7I? zl^y>y&uTa13__C-%2i_&1laAxC?zQ%tLrp`dKi$Bc^jt_@b&K4#`DmpA@NOq2&zBXvsF$uWdfCXKAzbB9nss8b%AFT3PR@%v5+F|U-G#oLMG zKqN1nB6S4bIc2do9@dnYS6=;Jf!+g~yd{v*mDl%8fJg1PPe$&L9rxlgGE zC>01k4VbmuzFA(q=%}ZDnY5HZDFI3D1L99cc9=^3 z{clw;K^Qd9h)p-^AqG0DNW3(zUMRaYo@;_SSv|qj@ zbe{=X*y0SZ?Fs$7h;PVL-1bXralUy*7S^|inAY!G@$K_kIa)zp#2VZOfvb1lw^vZ} z2UyT?TtD97G~;EJFG-)svtpUFb+oOZ>eoLJp_9H5ca0vG^CPC7P^qP*ifnc8m^`KI zx;f&rz6p&isFCi`4$Can)o=QQwM_^z&Blt_{Tb30UC$UI=P6bqrcfuOyNz zYN2q3{BG?$5a|#}29Y!npMRPOhH|`@zk0XeJ8kD{U>HgpxlmGFot$`z)Y%c*YD&-)^;FnEt^^#UpewmWmf`6r zP7(<^M?oJEB^)5aDdT0w-7mcf$j;bQ$ZLPH8o|hbSfua-H5aU|R}}XrmZEP0y%Hr{ zIqrikT1e24vrZ$tVm$*oe%u%`r9R2;eMW4lRu5vZs1)1eYlx@=bJ@kVqgY2{sUGGK zKkf7q6yQN*2pDk%>#RsD4!11V`6&yeG-@eDa6vfr;b+mVJ8! z#VCy*Vj+VGw#oIGGcI)}V)l@NMDmFJmcNN3n5}sRnR&+7X9)zLs1sPhoF%DTtu&+0 zCF9T(Yy?m~{uFg1c_LY=6`f!xpl*pPWWhCL#mIc^C5#U12>WRh>|wN-4CW`rekB?4 z9#hW}J*)^xDv`&JMJ`fqv5-1ms5(Xs)Il#oTj$ffpP8;y!QjX=oKyyb&!E)?O=ieQ zVguUU`Q{Y*PNp6quOX_~ODMt9)l8pq9qaMGW>E2z7C(Sbb6U`N zy?Sx+`%JV2&C^O;J=!T_?g=MKiQIUq>Uzr}M!b>4WhBn_N>a-5W0^ytmC$QnA@GBH zB)*k$8IqBVvnT9}@!kc?nP^5q7cI*LB#Mt7{0H|UjOL5yXUPFLAfaB#AhZQoqCy?L29T*BNC;h**T{0Jf`P#C>l{LB z9*LzzEbAfFC^Of-iz!fZZXq>i+Y}ro{D_RNGD=4`T%t(JUjUVF%b?Vh_agW-a7t!s zwfkI<7Ht85`LZGNy^l2$U`WP*sx@-7t$@U+|H*=7mvTrp<8~1rELirR+<{JJ*NB>d z&2>zJL89*M3&O1r-E7%$+e#6!thV#XzPOB>G!o!X z$-ZOfduiTlLbNU=Z<(Vr4$lfS47N%bJ6}p&$B;Ggkuvxq00f0JPeKbMqgV?c1wUIQ zjTDk*F6leoDVeBKZC3JSu_YN9dEV$9{jh2aS+-{~ak=Gq&*a_Amn{Z#p8zRCp#qRP zzK8XDW-U(h&=T&Ra}vM7ao&B9B(3EI(VNjT^G`tHCmtPLnmqbWzZ5bGXx(bAFhJ)0ndyhDRmZZyf^7ObN)%ROMX;T-RDmwV4&rVu$vhrN= z1>QRxcZv4t!Cq{NN4`WRmpha2i;BHBK>Tr{8UcYFZkf&{k2_+wbXubuo z32_H+=fH>G_6mZ+fapGcCQ(`}I9&R$%*UBq$Q|egR=re%FE(VyNAd!1ca=K0v#v7w z#Bz$UV@*Dxgp#jGPHuyaN68qkJZMJ`Obzz;|F}9KV`pE&*U0#=-#hZ@V-^p+r*n4F zl{3?~!6^s5F+ZRDePooL(N=CAH?qlJ{&Z(v&9UzN@#36JkEjX0K`B|!3qAsgxW;AD zwf+t3Fk5dMwjZl!<89gxN8DhSX-S}e!&-9Dm|X0OXeF&K#NVpZU(~8DeFm)*&dHUu zHun80b8fs?>Yy(yV^fT_-2sQ{dlp5AmCnn}BTTfZpLzDjzC2sM5fxg^BX?|u7LjX#?}W!#*^npv>)glhbRrh8qT(35xEs*g_;672 z1js4Piy!?($+&<4ERrnI+6@t z{2iHj7HkZ>Y;QRxOkv<9^~~=NBBMCaQN9lSqTY1P?k`S|?h86B%F2eSI1y{6&z=~3 zsjOwivFBAYZZJPh@1I?rTTcuS@&WN-mA|aT1Vs6wr0YJ}cSMrw=3Bu^#0DYn(VMKr zm6l->y(dTAAZ9`yds7;JRaB&6H#LtV9@uFo+Y#$}sr#xAt&HU63-Pk4PO@}K_ub_; zXoNe~z2(YPO}^4Dbs?2`9+8>1O_PnYEI;p9A7nm(t}Oj}C-1UKJ#fG` zzRbT4PH9Y6cvGRM`OIVx7RC=AhyoYkJwy1k0dxtz+-XRM^0yHio*#X2fn~Dx8FCZq zZ=X?eMv+B^B2L2TuNSA<&GEi`oZ)0om9^!Z{C+QNk4=VDOO}u|z=7A4wt%)@~|0@qD^ z3*~+-zI@Z$_Tn3PALDy2Vr=1GlgL838^uWwZLf@I&lI&4zFBzNLL#uFmG&AT!hhAa zT#&gFCTxf#)|A`ORvtoAO04Tb%_qa9wyE?fea%xpB!W9-Vl8p6HWROHGqc4k1b*TD zkBu~vS=KLw4!UqkrdN{dc<;$p7(?K*xVajSfRT)=qswpm{lCliD{B=s6VY5sNz^Gl z#J(quBs7ol0Qcr?>AE+b!ai0DyD1^Lr27sj%{%r)UM|og=FSpdI6(AP_(}Tf z-1Bm~i7k~MP&4fiGkn|6@J-Tsxx%=1_fEj=J`q(!HzcZ(?b0q$g}Vn?4rkEx01%-w zj`$2R|5mJTm-)s7o`%HE7BoS0j=;hBuxduhm93P$%8xqM04}{gOti)8;|9|`QM086 zh#hX`08Xm>+3+@C;k^9r-HfU#XA(6H785n8M&T8VyXbuA0Fe#V+`td>^r8oL)kw(c zS_jA$AL80oSoHK0bnfYAWowV6IaIi>VGDamuKvQV${_Y&=ylZA=rNX?`Vv8Y zBTD67x+X0ZCEu}EX+qdULPJtP01ug+ zlL2;EgJo%RL-!Gus%2(7^xN+E?5^b|Yya|j{z4`sQ ziiMW1XO+}208l+MvwpEh>|}*mgGvLCus=133C(I@7q#whJa+BUtQ?^Iz#C|d}Fn+kp94g#$4Gt66+RC ze}dW(KV|nWYT}I#L#2ms5XzmXYxcxH#CL#gF1r9#p#gq9`x*INVT!u2O+C&stn3AG zCrH_b6|n=3;&BAO{-j#^co!SI=fPUQHo}|al*XW0{}|Om_e_8`v%(_(i;*zB(KWin z-*I5xzgod`*i#w~DC31?mr(kGHkJ$5szQ(5ts-fC(?`UQkW`mqJU=Bk1zeGE1rN$J z_>Pb-YX2=}p53`E?6&cPe9W-8&|XhdygIJ^uR8y_(B#G1629p}E`VbdG zo$b+5N83s_oOXJSj3Q}07es~4@peBD}7!7_4fN6gufDiOd#njPM7MRSwac_8RX zSPzW-@~2;JyVM=?jCz48?F~OxuAm-n2FK3+qX35j>+{bj!BT!o?+IB5P~WImQmPqe z;JE7r-}#umDIVS5OP1T8rpQwCi%JH!zC20YvF%v1Wmu-Hi|F!Wrpv8BPo6xgy29v5 z=M(d-dAYue@lZ8o#BDfz(l?wEc7UiA$sI7wCTxk%rPwA}F21~acXDIpHcCc2=R0HK zM%+iafC?Q2=Z1io#ASa<#N)^1Yoa^1glW1eLy?saGRIhk2~J|(uwI%bGsPT-+xdtD z7;^ZXZ2vCOT}K_syaDq!HBOh3<1}_0Qt{r1C~$rq0Rk@myueTffnpMz($wY?1 zOhre2aBSl~X^1ZKN%M*>QPBqKlUBQNiwzDs*oqTH&35Mh(4lHNmOB zJ%DG}I<+`MRm4^7P7w@Z{frqTBwAhAs_qgE9&LOjct|yIqh>PJFVu}B`amjS^Ffni zDtvGOLFjjgH?^8PHosq{a1p)yyhJn9_EnadX)Swk1Qb#pgZ%9MQ}h?Dd*NpSNgh6Z z7xs$=(`AHD_a(~|sT1*URqHpvgpsqe_OkW0&M4VV%RPR}9;$-Nck68HLQgbySgKQl z@k7uI_Wh+XpCX^?TpnRLyt7Pp753M{G=^#S^-o#53NUfYToNOaELa>Q_b!%7R3CXs z!7OxfY3}!kJv*29_KN+BR==>3_6s;0Gx^iJOxZo`x_uj&5+*>_DOn+%>b8bTWF1gf z=Y9{4t9Is4vusKVuU=#*HB0fLe)9UxTIoG?AqhysZVF5&+1|fs&F&M8sX{Pm!&G4b zKYjp}=Fb#K(&3mCW>HCE(U2c%ypQ*5p9WW@#x`!LVpt_DpqL=RCBx}f(eCj2lXtYoD z@Btjk7@W)^;Pt(5QEFW%!Q{bm61K?v6cntEGZsx?_k?wrmu{oQn0XIde6F3pi+}Gf zX^P;u4U1MoVot)P5MN9klB?JNb%0|{(4q;{K?W4PmJ8Tq)D*mXi@HW_Zuz2D)XPd} z-aBmdZYOauc5Rv@kjq(xp>&daUSQncOD;()PPLp9J85(( z{wHi&1SUfDLTLUbO0-emN=$|>XiBQi#6-M!j9Gj>BORPmHO@E38@=Cntf*wYv{hz` z%`agIS#<;~ATpE|Ol3+MJHqm{otOk<`YPYvy(ICsfghO~W`~gXOAu-bT@3_-06^P9 znzmGneJ}%tPi}dss9Nl6hJ^{E?1St04REIai;@Outu^b>1tvGf$sS<-BQK)Ps#?59 zGen{+KV5beJA03{AVfOs8qR=?Tp_!|i5JLJxP0bbJ*2p3HVqRm_(;+w;c$s1BZN~# zG&_gk=bmWan%x$4WLapI|KY}FnQ01Eh{Xnf>xKAP9#eb>V&`Z^kS$-BL(xYppmbvP zKB+EjSI3I>krD$QGHQn-3~beE3Y#eR+STHQQVsEx`}Nw**?AcQxulo5vBR%8N12pZ z-=nlvzMH6@5T3RvRJD>(OThQy8ecMYkzT8Db>53?f`HP$@pr*M7sS%|MzyQ7HN3bA zz|D|C6LQFut;5m4poyEWu-;u&7l+-`lfk8O2u5+IW42}lF1ST3%DHx0nV`kL$;x3% z<{9N2oAR`=1u#eC+PBcSTzuv~F~`mCpARvIDJ<9ig2h~)vG&w3YiYq0>T=xt;N(V` zYypvE99uIqTDL=z8No=q+)X12izPT6q7_@P=7j)B8{3v)Xd~LKV%bzxv$xmDKSlI% zyP%dfP>akI_lP9ND748}O)(!@1Vy26OA9tOY3CVTC5#g(r`LrhHJX(4Gl1Om2gxFY zMz}FU2Ezg@=bR7GrKM$Zy(S?Cn9}qwFNX35Z>_Q3&Ze|CL3=NNCFBqbJe3IQ1lj=F zly({ilQ9mad$bbbmf*m?Z24k~COK?6y&v<)`#85ZxCrsmxtvURteROfwYTTtsre95 zv{*ywR^rK+`t8uHd`5{SZDe-#C9fTUV*y#GDLSS&s|V(4@@)ED0wP$4s^_%);=lIo zb(O}>&I+LTXx$nJl!XL$=Or54lI!{Xrr-(fjAo_Z{Za}f&Kxi7@gEHPP%eLURI>M( z#bj#9@AWgFc}ns_;UOBso%`^b6rze$$}=QCy-A-g9gJtlm%v;lyQIBBP<;i=VCs}j z!;oYZ6&MxWqu?myyiKR}W7dP|GnZvkx1^3p;Q0p}341Z8w0JZ5r)v9UwL1G5D7i3- ziDQZDzHP1BSlzkt8SY0B=jjX-R9KUtfIfpLa51Yd)Baf|O$#3Zv8fzF(FCPrfcMl} z`IBk*_kk2YQ@3L5GQUk-P?e1}JXro>Jvms10!&9(h6M&VegIV?ZI7UkBjIt2T|{}~ zg{TU$fx-#Mz`!C(^;MC+5DioH0~gm(GtK&^NbGAT4#$BvklLbtMtoNSp*N!>QHb$V zi6VWP>UeKzO3r(uxES`8gbc+$sKvcmoSx-^AGZ~T$MA;d3mR$VVV1NX&@m?g#~tkl zA+w(`8b20!3zl@%k`@4oz^j&OWT`MKc=XaOpQ81~r#t<<&rC9>YA`d%qmDhXmvCkN zI1BI)pnuhMsg};xv_R%>0W0~PqLv43Bp|bcYV$QO9`B{0lYS==QVUe*n<6#qS%KYG ze9U$U1=!Rs=nG&Q^)t#60Q+-#;NPoQksvpPBuBf65|<^koq(!RsY6)^4z=eOz|Ux0 z#`YYgsK%d_p$)C)C8_xT8RN)`)lF`k{wKno*|0 zFm}ND4SIB)k(FcR_gD%5vsC&UfIVQa20NRWfqLlX1CooeV#RMTFHw^*;LRzvoId5% zRjOE#cQ~bv#6UsBwX+(ju<{&Pi*ZSs;F1ab*d><$bjTwqLxZNKzqfS2q>iW+&DwML z$zN3^0Ehe>TA!g@dw&nYCU2j`OqRfgiqUDCAKQzHcP*!ZVd zuY%(IeVUfIq&s!hmg}UojGXZg22RW7q=HubeqxGW_lNB2?6}-$jVqbs@*RU1x0AL< zklY4RP6_}5>%e++8JAREeY^vr@I7H3u^0%*S_TNWY6U>xb_y!V#&uiAJzB@fjYj~r zn2bZvb2^Q7Nvdxzlm@8`OCh=jz7;1DF<7c@D^M3&y|@U3l{UuY3%q45nAA%W1u6tl z3SH^lN1uqTDFQw#Xjk9f`wr|0G2)?|ND|f@+#&|*WD^X6i+xSNHbxA(BpqfUqYJ-= z-3S__9(!UNfevC{JHuiN=w%GAZ)g7gFfxmE^JgVT*Ek^lI792;XQ%I031!2k#M7dS zlxZ1Vp+sNlfMZkNvYz!FAvU+>U2whdE=rH4KrQdh5B}&h{YX`wKvx{X)J6Ca=E|mTu1cc4G$SQ`fgqZk>D_3l=A2 z7ONI@t4QBct%;myX|1_g=5Qom$e_A%-UFg_Zte)n%&1(5e+E@!1eyNHx?A-Ot6~eK z7brjidc&VB;4;}XL>g|w@7G47^kgK(~&qaRB-8r}G~{Rn;;< zRm!h1!<<=iS3?78)b&;nVIiMW&quF+1k2-(QHxmYwC+Ebe$ZT+QBrbsnFm4+v~`NO zBGq5Cr4(iQ_3rLYegeFoMvD*BH<}4#bPLp|98b-PQc9RoS3K+viR>apzIcJpM>(C*q-MXj2)53=@WO z$3uP0hVtIZ4DcBA_Yz!fsZZLsHSwfkt}HrCLnYN3eB`O-cGQXRP@Jnby5d;(9) zy@osRgYF&m<&Vv>JP(y$e}|hq>SqE0>=xnTU4S9Q)F z9`e8Mf7ZFA`~At06Cxzt@0RXZKjK5tH#sdvE8pqp9<=BpHZs%b0xuv+V`UQ)vG4J% z35_94%IL~|QA5U5*lANvV2k{~E+%)QWwMY=kNkVM@lR}>Gc0YR@ExzZpfVLWoX>CN zv9qgV(uW{Vy8Dgz;l8~yOI8S~{TWAwnAvuso1lc(^Bx4@{pm@CLJsCm%U{1&V71$r z;ZZRV{_Fpqn~%6d4AUfQ99h)t(%-cmgfe168`#I>7ACSdpN{A7WL%m*=G$vr(#kTF z$#>vB{0(O2(NEPHDgWBH(gBxT{ALa3HL-6^;Tx0WsKvfqmV zQ*>=F23qUuloWE4zY#}@vKU=f-OK}l%#PDMgchHK{Ozb2b`Pv0;0qRGeyhcGqL=-Q zr%YND2f*OXk`wQhXZ2z;WC8qv3B}M=9fI2Qg-5NR2)CQDh_ws2E&g>-L+U`O&q7D} zW$WFlnI&D%XgHee#;ULlWc3Z-0UT7?0c`-rqK-hqhy=8h>|@$$JF9m7G%o_Ii9c2t zzosy{CkfA31=^!2kApipjhMX`XDYm<1>OiO9Nh7G>KAj0oPxM&<+NESnZHaO?M_Po_@bLK=C28*7v`j*Se ze*G}`NQ?zXX@p&~<+0Wg)$o2Ng@K;CK^NdSaTtpZBUoY>Jvaa_#e-8%HQYI# zpZp&`I4pX37&h;5X6D+NHBCNgjWdmV*|%Gt3}93N3W;XL5C1*HuvhE}p;0vzgywZL zmcC~{*akgu3#Orvy~$hi!uEcEOnjJjN1RpITFzkvg>wNF@<&(>GWn)1G`6vuS*CLo zXu)Kt@L0NHoMq;J9{XNsp1}(MvKBEkDs{iXo2#zGCHfIYckEY13C z%@01(C=iRjAMuD08vPI7P-zT%7}PkbkETi;>F!J?+l)fdfB*YaxmeoF3Rzwsj4p{0 zh_mFzzxo~i(B7j7le0bnyUJ5thM^w8LOQK#v2-De7`_9mIGGU(lifHl1Z3%(3=2{& ztE{^RU0?XLak6}9W(uPDn~T^P7gZ^9;?>f0muAPN#~w-K0p2UHp$?auyoT3H7N)yA z0iYE;V4%KKW{-2d3#(Xp!~Ec*F)%UyNO}v5L2-4=Z+ZRv{uw0-K>%&+ThVXKJVIQ# zR$3&eeBaZ2g(0wTu7O3pN*mfoQdemgqgARH{JfU1?ZJDss1?xR6NnRM(IbXu(a&AGuY3$nJ?sMa{xq zd^5JoSk|&e5}3|OS{gD?Lg{W>W~``GM)G&KAmJ*9qHCItK;N%}QMq{US@jJA=1vg~ zxNyO5BC&Dy3mZMiWK8Q+MVh92#2EtZpophBEG!|`Zt%`4Aua+AcVRwd%@{7HUs;zX z8f0ZNnsN!Gl&#+0Z zQx_W7xSJ_AKn^Vv>=~g#Ox)NDhS$Wz6w&5gWu72+A+KRblB&@v?0uV<+*jy%Yxiia&ibE4rTlMQWS2nfoco ztlZnX^9>%_F2)Ey@Hx8(+SM!37QoVWvGsYZe5VaUH;~tHC@O@_n61KQVo-Hm=prCT zife3nD~bCGzL!`ali^CS?L%P#-`=&-eXOWQ4UJ;)}AdSM2HqvI_H@qUr7z?dqO z(#Y>C|AtTVG#a=M>EEVh3ZJoVTBJD;#|TE-T-u@$k;@|A3#HCZl=M z(_?V3D@_LA*(-qOXH)b0v5q`TS<4>v&BMs6iN9aENY3DMh43s-dwT`zGZp<9pcb%Z z1M0c*gzo;M&TUz;7Tl}wWIN($aTXAcdO`m&Jq=WQiEq@S{jE4n)GWBb=~t%}xZf!G zNYL*@+?^{DkardApa3g?o=U(Dc0vZJPE}d#Y|zXBO3DjM{{U&RjZ_2&l=Ig@!;D4g z1?`ss+sP@LWX&C?OX+bKq_RBG{P_0_yyqJ*Q!ql3+IhyCreAvK7&0pO|)98X*Yt8(`0%+ z7EZf~E?TY=_PkSjX}ET}v*Jyqf`-T&yjcmGy*M8G<}tkYk^hISHbT1G+lvpzhS3v^ zh}$m~yIY1$C?|-97Cc^N9!-vUsH%k?5Pt?^n!n()D}e)Uti%nS0ihC{bfMe&!CNG9 zrK5i@ZVU{Bvr=)=1$E&X4cSq~+tQkEP%zf2{}^jx7hRt>>+{umuze_OV>2t5=_6uxG zc@|hf_cAXe_hmsb>8QHU@suZZ`{%RA4idZ!}12!FV0cS`eu3sLXyw;35`+p0}Y+rncM6Vhovg`>_~P%DO}g zv0k-ULhL&VV3sG8?YS+kVgtOe(VB(HZT^b_a@Qp0KS1vdz6>9d?v*x2{ywA><1kmXP{?7d9N=fRflr^l}&T zT-`1jJQ54$H^@a^c-~hi?4#^x==2C)*NNcUqZ(5mk}u#vl5&mmy#)14IjQh|e2ex{ zCS_Cgx0y4xr1~B=pLa@QS(PLy_w{#yj;mZDENuj?lWYZSISar5bb}YpH=x2Fm|pn@ z4f(<3(k^mb3U)~U{P$K>4I>(o+O=?^1_llm2KN5uZJnNm@^X_!-*9B9xvp^?4fXESFE_)(U> zTC;g4|0rzT3tAe)cd@<>>ap`Tj4en}Q>gR%lj^gKB~Gq5croKnZBcQAx=Yyh12U5e zLVE)%EQQ!~dy_}%(`1n%3n3XUev(yp84|KY!B_`=rRGhWK;jOYL3CFMplMY`L zB6Qs%%kz-q-g+7r4gG>8Qkjbi4IVDFTS$S*MOm_27VmJ=Sq4PbxIv@ov?O%_U&5AX z60?Ici2o9w`qE&(qS?FzPWD3rmh2G>sh|70q=h+Pr-QzwmkgiK<8BMqT)-ct)Lb?1 zb!8o9TguVQJtf1cY;)^{xLdq^{$#{A3D%tWtr*Uu3QXAVRz+Rt0xX;6`d@XWm(J6T zjF1)#u8B|RW+L)DEZ8DTqsj%vj2tOHv87Eq&Lz*dYN$yFOV#{=JT_YTD~tUG+|_1b zw0Jh!QmMxl1Maa(`2F|n_dfr;{tFIc>mbkMQ51#b?`D!?yog`le`V7sRRH5We2?SW z5!AP)4*(A8X>icz3t7to=&4eik$BYm_hJ;T5z>cewZ`$&9IJ<#7z$L#0+0@?ve-6G0F#xoqjFGm98-xAIau_?36i0Z+2x|Wa3t~_G*1wATI#Z;<+9EB|?x=e7c;TbMUI8nm}J=lB09to;0&;(3u07NbSrYUR^ zB+mJIw>f(%Bs+zibmRhs>AWr-XK+8|3HB?+6~T3M#J-78{!$ZmR)Qf^P_7@l+wmMUf813gliT7=V%|p?Q#+< z#6s|_uuWFf19%;U8qV#HL_Paihp6rQZflhwgle?`yj7u`$~dgtB9p#kfm9~bHrfAVO8$gP_34*P{b}{G5ZFb*cfC`TZ^Tl0fta8#3?Cg-4v@B<7RJD|x-^ZsLdSV20OL3&Hb#k}u zbit!C1QRUT@Sm!YpY|_v))dVh7s4vL1e&jP2RmzwP=vJofnN(~U>M*d!M0ehc@Ved zG>YX47FG>aof8aIw9}q(2R1a*dM z;(d?U_ef(gdln$++~I$m@m~Jk?6j8L#Y4Gg@T#vD#c#h)<{3_Z z6t1Rlrkk)2dZ_X>f>Z5HXRK7RwI1v!_Yf}pxV35L@=3mw5A&^;^Zh3+V)le@Q6TdG78{FOU8kSmxeU@YR8Wq}Mi7?p!`l#h`px&QqB6f#5Um z-71UIdF~-RT;?R6><bq2-g*wmEVIce&t_l?I%%2W}3RwPNBa_q!c>~Cs{7<;>r*W4^ zuYSHed2Z>&!37`2R-QavsGk>PY%r4TZH+wQ{BI$Sj_{(*7V0=?*b8d0i=bt|q}itGHs z(b69U=Hwp7W|I$F1C~EPUv+~+`a%!soFX#96(Tf*ZJ{7HnQYGE*O8vYopjUIROcXF zb}j?OFJwaMX0L#N9EcS}Ok_W7={_S{04wgawiDOU&BCRp%L)!foMt%E_cgSgA%M|q zA?FJe|3=d-u*oUr1wzQ^CgO=gzSh|I&g{2MGUeeJ**XXll?`)7q^BoDbm!_w2*bWf zOu?V%Jpwl)ANq$@~coXVscFa(>tUX>Sc1JAj`E*17Q~-3UW{N>_?^ z$V`Gw9>X@FHCEzIeg2z*`Bg(Do(x{O zefA9F_$sWP!i^eD8yUSFO=S-#e)83mbZcf>{zK66lnvr)O~mo(18(rJl5GZ}lsydn_;iflD*F8hFii^U z(D0|ACySl6@F?@|PAIO49LVjeuK}7NWG{FxGyhOT8k1v2#~Ili1#AtB6SQn-$Fyt| zh@Db-G+m~q?*d48o3f*JjU7Mdy>=RY-5b$mK@j5ettj;;{iR)0Bx z`i3cws;AxTW&ts(szhQ$EN#&^|+NL5+n=@hiDU z*XyE1VvK9|F1&JV7W{5yD@7qm3fNouN6dju`p+M}U-hyl1qjF^)%v}``|?^-PG_za z?|dMGhdKSyvYH5!7Ut`}y!I9wV0Xcf2V59&V^gutuKZUX)$#yYZ(M%8c7B!4E(dY- zp|$WV@4mIkb@{*@3hVsSS^@KUbMWiVxR~K~+OO_SjD6O5C%)8m4m`2#Si(4+=WCb) zp6=?9*#i&a3*q*%)oz7TU6KYK7k?5tH~;7Uxz#g9=fNYYlW%hhBlC(S&F}J)z|vM_ z!%nC7+MX}}SEf2yubr3KFlds3^`VGMNQ?+z(93Uwv-**sOp|w@8FJ)SS=Xhh-z6Pb zKQ^RfZHTT<#?=U1?H1a(W$HZ=3vxZoAB(b~xnv~Kb}Th*czrK1@?p*RT~MC$3vZT1 zM)dto(=fNbFGJ>xJ^B;~G@4&^HNE$7dhb5-9c4c(%0Jj1FiWpW>|2+J{p{+|w?LTN z)mKQ;vCn4^B_oa{G(Y@qY*dMOAoSXk_s7BAo~}(ZLhu(pz?99vGXuegC;c@D*k)DP z^TAd9T^6^3_AP2%VXNJ_)x9PqBI0J*#pk_4s?X@- z4=1EP-~5Yj;j6CoTR!wLS-5M^=Yi>H{KpaE6UquAB3uL)PKOr)fLC$Lpt0Zgbwc2j zsWpd?v)@ol`5NZe0$?5m2z_)#D#R2XF(CYU2JnKhSjat9ZE1$53dzpVQqSOa}mp`Xd z`nI9I%!`bOmF2g?mYWuwGM&A(DKJFWJ!#do^;@*~W$H&^1v%0EL*le&VvYUOUV20z zu|~7utog5ig85+K*zC}yjb`Ri+0Oq|BD4GAkV}O*+r99bDsGjnU2etzSz?qNtbUJM z1j<`k(LGx-ynf}inNb(<&}YjWS6maYdH5B;ZMO=^DBYuFX3_oYs{(7aFO-`GqY1kB z`+ST{5(0H}iuQu};A1qBu@zGYmi@;P^q=>BUlmz6fx9vnf6K3AOm52K%O2(A-jfZm zjRZip6keB;d;_2kB9~8pWaqBUN06cK%$&FIVV4=cnakVbGzvks-_~$o+V62eekshoZ+pqdwo7DTEnY!QP1s41Gq2Qv;TZ*gM!jI zle5j@92_{)fVRC}<2I!@e3X4Nlv3FvxCOR4=VUUmKh7ABk0cZZz<(j|Vit;h??Sd% z28n+8H5c0p&R+YRzi38Avlr@|dq1@l)*SF-S%Fr{Tyk2Z?59?H)Cu%H{*U&LGkV8e za9(+By~h}|<@pSCxI=Z_G#GQVjoX~*k5U-}=uyjL^FYArYzu>vaDWgv`6RGC>! zgkUx$2x0PvtOhiq3tx<;D=#xU6amRPCSn{csk5DY)rgyDUg!`|1cc&}!A#i-EL+l* zv7@cr3ZweJuPTL<<1h>bZ@vVmZ8R()aI*7qg5O5-2Z0}>!Zw8(slt9cnvjNz5En3z z5s=?}=M~o!WsYu5yZmuE9=wNPDZlRW+^V5mF?5J0curlnFYndMQ;S9*Q>d#Tdd$l} zkoaS7W41DZx!znOq9#A!N)Z{isbD(%o&GKAjZ+Owd0-}bm z1rl;zHkQPJ**dr6<<}HVw9k>OE+$1kuY?ti)7?IVSJf`RwnChtzz)%O{_WDR@BwYI z@VcSZlhLxH3F8t1$Ls7{dCd?U4=sB>TQ97lth;AzJ3KkMhP7Uh_4zg}#GNx%{t&aZ zskF>-XG7l((C}5iu{s^bd(K^s0Mz1*ghH)vhd{tjdvuY!v&}090%_Dz28gfmJ>}@z2+XhbzJCblw zXV>41%AIDUNq63UgBb?%Vjf>z-I@-6Gs;AscBv@Ww+@cVAtV2UJgpS`=X2oeOs@|H zH4R6Fw;@*L+6ga>=h;HLYx%&3Q{Xk#MW&Gv7RGz-;)j+BwLrixxck%RH^+1C_=La- zy>ZyP&dwi>bdQ4^53h;xD-{Q9=Q>9bJha`FXJU);2ES&iie<1xzexsmd_3&wjs(y4$* z;qH=e$x?A|ySLd>=5jL&TeY~Buh#pn5-e)-o&3740kn4jQR9CZ+zK%g zL)>zPr?8i_AI@4}O2pItZZcGud{2tIF5L{%`XXszu=LPZZd;|&v$K( zJcr986zlgtog%lUzj8nX?s7m4ZB6kF1sG`R<|)7X0^*gHy>1UvBR07=ZO8t{Uvp&1 zzjGlj7~}Q!8?4+M{P4TG;4EdgA}>wd=|r5)>ZY)3Q8ds547v@z&S1;A2?4KS23!yF?tn7O3owNVn5Z)jcr)>`jpiK$Ms=eYy8N+wbL8Aj zxYN4)S|pZ|kPi-W>sn10RQ1vkDfRao4By$m^dFr1`KtBH2aYF{Ul|7EF{$)A(a~iu z*$$$82*Epnx)YG@uPMfRk`juEE~m3H^Nt5@d)T_+A{{vI+MGx`GWq6xqN=?*7<>W{f~l71jxXd6)kOUsT99*8y|JpRzl@Lv=jq zz?HGfE^8-p$azy3baXAwE)U0h-kmeA0x%TYJNfd@5jl4;t#DZYvf zIcSAjWUTydBwYxL;cZAWps!Dyx8-crsNHB8x7wYU@7 zG!vHb{rFOW{BQFar_;{rLo8O86+FeJF%e!Ft0RrGT2SI(T7hAqfS-NcOvUhJ+gA5?(o%|l z2k#4T+M{!oiZZi<{kVhW((xHt%XYyTqH3L%JNm&4Q*}Lejg0gG3a4@)DzOn>K)YzS z@o0tp5XsW>viym#x3TQ{K3uF>U2|G~Vk1NjCZ)E?XOE)2nbjZk^Q=P-17D3@Jx_a_~;cGgfoxaB) zy!ccM>PFLQTI~}fOm?grg5nc9F3$%Fq?`6O_g?vkrd7@wZ0zK40K8yncxjng`~TVc z60oR_rR`%#Ac+W>8x>HN1QJbLa0HhT5y=%LMqCm_lto4n5CH)dMP(T;QHdaG+#nJm zn&1M15Cvor4uYaG0TN{qMMj8#qB6L!$o5zDS?1vP_w(G`gwxYYb#>KS)z#IpFs_i( z+#Zi2OI87Oe!YdJWK9AH9Pa?L#{3JLh^8!9>Gk#+0VB#X)^XWwt(R5%2g+JnaWyKc z4EO^4UAe3v)E`#S_8$GAzF)?tU<8Wh;?jNM9seY97LYB5TMLctdf=fEf2`^9>^3sD ztg!DW$a5sJ`x8!3Dp_C_8ecTJVUnf$0><2oxTH|rA)Q`Seh#Y*zpg-IdjZH(H&vMl zq-HmqU*gHiGwYw(gObEf=HP;E()a6FZ1IZKIjSUYQ4k#YfXnh*_UJG47meYR*i_TS z`d+7V@oC^FS%p=Z0!3w;ts5OY9mT$ z%473Laz+Lx7i=JjvYoI)jb&|P3TpViyRdY0&1`O*-WznVvRSkCle0Y1Bt>gaMu}SwSX2v+#woGy;8}7k0Y{v5;Wqv3$v8c%9`afM z+0r4pr{inTHK+S0X!rPifPRs={6m4QzX1kJWGX>{Q|o1?v`A7yI^x@1P~@Bnvx z?VQNT13riYX=#Edvvs7$t67q2sn`ws!oaUX4-P4*5SlyR12#L2Tt|n)X3jw9MMb`v z#K=|p8OK?j&zRF$tR)hOKpx@TRp~YHJ08GV0nFx*R>f#+YycX2NW@W*)yIWXh}eUc zpWQwHGZp*eN!GOcYiizJMM4$rTH|;UH@no>;*K6k%R{eVj~Jv79Bg_m6Xb=lH%^Z! z;>|N*FN?!8T`aS&rUm0X>96v^_eENn@q*nCol@Kn&mgNS+6B}CPjc#_xWR&ZI<|g~ z_Y_JxT06^20gOhSQu_7og0*CdyEk+2Mh_VH{dJ#A=6h#?t}d|wW#Z|m)|6uS{RGP? z*GLmLjzL4pPx3uMXM;ZcdFGh2^&2UQ$qPVyZ(xQ=eG8CGR7@Q<%M_^{q1+>VzrQMB zKVCwOw&3|B@I{z`7+lDy{bx6iAqn9a{uKey(*LYs(IGSwLt}fANs;pSAdurSqn&RC z@8xAT&G^TB@tNM}?)HVcH#2Ns+m0FjvGK?{jV!Hu#z~X)D>aU5$+VK-e?NY(%bfmr zl%v(5k^h;k>pOqNU89#dN0UM`Tzs>uP^FNf(RnofrN`J_G3ZJCE z6R6CZhxJ#lSNyKI-Vr$E?$p{}_NBqdWw&}C zIOoY@;mbJhMB+gSIU9@(UM2EQc zm(NH8S*h4}^5>RaRRG+e1l&c^7yoT>DR;M}ul#v2m^L!!!P4ksAXR2vuI`&hyfxyj zrHcGCAkE(5J@TIjo9$k;g6RfYalJ`KGFmTd+zs3invGvuwqHON?(miSn>KDi90v{R z^1L8>6u8#+zYv8+No{R1t2eKdecvPf(`>*U z)K1=TGCmw`sdSr1%6(dqrb?{>^)z26;nMAeU;ayesbs#L>2hVc<-l3RgBA8bPZ)hT zGy0On?2_qcl0N_yX08Ojq0CGD{?V z_m`3K!|1)0iF$rudWNronx#>zkmZWK)2FW?8ztlnJag?I4BJ7xBtGZ-CelVo2D2xm z-P&0T&SiFfX=>vHdyAg^06BpveaXn0VmOp)BK$$m1`C1x=Fxd5z8ChC)DV78R(rwI zMYvF;&;dv`S%D6@v`qGyltW*>K znunJSE+k;T>3&_zc$lAxEs=-Bn>1ZC-fVWm2qoG193oB@_>fV8Qoh0NfgsD;F=@R~ zS1!Z?)h+YVkUk5ZP0)G#xHSqnh#0OW;FyEn+geu}C< z{m&J#S&AYQH&pUeSMTHnuYmGARKcA;r6pu)%De|$`Sj9N>1^#e-zgLanrMWmU` zw3HWU(kxsOsSSKPm$_{$l1=O`X#2P^Z~zDg#lE6yPu!7M#6R>h4M;Cn<0j3At`TpL zMM(N58ChIEGmP1e;_vP=GWpfI^x#=UERsgxA93+S&Oo@O9xy;`RPR$5-B(#^N#gbR zQ2aq8XCL%%!-83hq*_)#<47iw{kT-qZGgG|bjWxRm z2x4qA&Z?)slF%;H!0%1KYUEmtbTxB(HKCla{X9}`oLOC9SJHyR)0e4NPCT}a;cbXj zOmQbu(~nY1Au%E6AKF<|B1{un&T@ z)4t^%-{Xo3i4=#r+r1xAbR{%#kZHn$VJ!G6-qD5=3^4Hf^&8*kR;I^M@`$;-Hn7x* zEc>beB)(d;pu`brt9^552hJ!|R3L_07ihNEpb%4LqFiH&*oWo*zNn(=fDLjusAbqlzfj5vy4OB#H~@%ZDJ(^e z9P<1kgI$>>js)LS1jD%L3Vpw@WjM`&RI*YCMVQjMoJ?V&ri)1nZiD=+zZ8qrY_!@Q z=Kv?bZ?6!9tnHu{qYib59F>!`vuu(wvtpu75+?ry=Ru0h#t0#){zsAWgR4oXLr}n!*K(9OArm9zU3s{-WV<`O*R$V}mg>gmT#RKt zZ->VgA!>*$;b(&fuDCD*2 z<=s=^&!i+p0ETq52XEBTqUwt~J|9I1)Ds~bM@_Omz>d~U0<+vrU4~!?42-AdYb;wOc7_wA5@I(#~=3fD-bW^j;Sd?;f zJFxw3K(Kb9=H;+*Ajw@-zG1;VN=>(k!^5b1m+eV@ANjbIDmCRQd4EH@H=Ab`_N4D;5{El;Qk>L>5JISF1RHTS!^jjXEPYj^Z%l46@d_I^%I`kT5xQSX^6^+nO3 z@b&aE0Y50n9Dll`DglBNK=cr|Xv7g2HR10WrpNbk6Q?O73nBxP zmYVya^N!vM^el9(;#N*G759DX{ZuU%c_!Sxa0UM^)uQ@DlnqK5&zMN*-hF2KSm2$w zH`0ldUJrw?EV%K~fRQg-f|&pfV8f+^3CthC7U3qPkv9KrDl&20fz>)$&c544 z9p`bG9@5J=5v!laIuu-QPttNBV58WZea044A;w?PsftbM@WwX_D*I%=ajYu-60`tr zYuA6CX}ScB@pZ%hpl9lc{`PFn<+rvnhUn`>C!3^gMB5HLx+rnGQ>SL8gnLJ}n*zCh zsgkB-ZqpMbBFvAw3W~I8+TFUEWR@7zYcKSyEL*!WQjSMdGUxkvB(Cl$$y=-aTX23( zKUuUAcjsu7x{C78O^u7Eg9ai6uFrt=;pICcQZ6}=Nnmi?9*=|t&IjXrRv7_xNC{jE zEa(KYSrLDS88x_ZCKl*qo=Wjxt5Ew>^JfEuyf;Y`SOLO*5GBxG82E5Zke_t{SmoTb z=%SUxnB1ZM6xtBk^)*Bzo&=j8y)*PVqbAR!QKGT#6F5feTZYD z&*Gt=mF4#9+;k`pl@oDJP!|@5r;id5fw16_{@LBt4NjLk|Cr8=w&@a%M*n{cb%7JW zJk61Sz3`~+M%lMzqqxRo4SzBkmj1+HCp1QkMD5$l6EvMqO5Fb5X)fpH78i>h^o3T*e!PkNB(L@@SKUJ+W=A-aI)Ff&W`M;yX7GP*I|oSI62L-zSEcafuwL=h_iqAOy8I3m$~ z%uqM}z_4;sfcn>5i&p?lr}}O#4>j_BeoeydSlJOYwxl=5S=Meu+;tX^jqLEw z>E#fV>kliz6pdijCV-a}i@nlEA==JA#&=DbR5=1^Fq{t!ItajGN}%~Zg)6eWcKsK~ z(Vlj$jxgwvmgO8vCM_knbZT6QbRz66_@SN`M6NM~{?f>79f~Kh<{1+|aJ`u|9&FU6 zWH$ayZzR4>54fELGq(V}4-Pu*1#@dZMhNFKmG43tMKF=a)ICMjXlc<}>H&&1Sy-hX z{XH@05GJ|9{Z?^6HFVKw>Lj59_s z@Z+K&M`%`YW9pJKsf&^L6C>FaQUu$-<`Iu&T{PM5$T9uQ_GYtS>@~k@A?Hi)?95JR!1gX4#cM zv@_Sg(r_hXVu)9s8A}Kt-o7uy!1H>UZP|%=T&=*BDQI0x9oxjn9#=J2Qm)mJ+u<^8 zc*QvZ2V52N%Ol%K095UPjfAb}75Y5;&?;-j#F9Q+fUF6i*962bou^&`T0%fvvUD1^ zKMP-v6!i+4&$!26Ug^gWjx0O4bN|H?m$nr^dSRx>zIQ>^b+`@}33!ofspdiI4j2{a zxR;&Rzb>5!f?l@BLOu8$=p&($*Tazpa)858^`21NXN|t)7TrK#f01Y=3|>4;%_DR+ z;mqZh@E!NNNydRYVqdr_z|ocN;x@qaNMqomG&C^6AGZfpH^3yW&*AGyQW5yV2H2=M zr*{9HRq*u5dz5C0dbK6wSZ${mHNQfzaVt--%G%*?DY6(KyECBA%>_Tb@&z*aPK#QU zsDLb!#;XTt`-i;iI7Pk1OIH1}ZulI{+|e`m@B}AkDHg9SpK%jeY=)`LC~r9B4V_(H z=h<99?*5P|C}*FtAm;~S&qzbUW!fjzgcLK}bsnw*$P(3}gGz2>VeR>`4;Uqn1Xlbk z_@yTbDpy*mNpQ#s42oro;?`8tYGnT{klurECU7115C>l5Wu&Mnx@^ZE2#;p77$8WGVoFdWUS{1MhGhot0!w)$c(}= z3TX|tFJQkUC-quUCo)-0{6Kph*=r7eeZFSF>YynR6vL?bQ#j+J>U?os09_d^Wc>A@lv!+)1uczdn-baxN6MO6`0Z4NMo-xbvB zmZ`)WNHwSKOwXJYZbRR-zTOs8Em%6)aB?8loaTpkG&*XjV}(|nY#ywhzgh@VUhRzk ziQ3|{W3BJ%Za-PZtQ%$Gw#S9P9;xDI6zbs!l(T&fG7xI~cK=3O+v;8(bAa^S#G2~+ z8BufPe8>!%ngb&`UMS{t8Kqi7+-Bn)^|Fr7ulV5HwwS2J`7xJF*PV#3IQ9+SSq!+8 zW+MM4tQe6s8Y*77?4NJ!{d|!xUnTA|N`Ki!a~npj|Mf@W@W5e9gT{D2H(hrmKCjW3 zubSM>tSeP;;R;YHWE`Di)YSGkb#X$P_Z&6Op~Q<&T~ljP^!+A(eCi`r-l;~+q>2Id`;r2k|=H~XX9ylhSgCid8$IS!={x;?#C-T2>%VaZLOOes#4xK-3u zHLD5m8Bt!{@NAFtt5c0{-lT?ka;6+$CJ2D6!4>XvZO0xVobFA(p>#!T$L3iRmjD&i zKpf7$2-6g9`)RmK*>GzO{j7QU#v7h*+`{)I-5M+ESOr*$zUa0tJ@X1}DODs7%bKL(k29t^aj^jShZ_OM80gyPe32Q#gV#OUa8;^fXVT*-Kk|(Su0j1zJxp$g z?oZ7%xsvYzyeOos^sRAUoE1ffyq;6*{JO6P5Iqv^j;*iLNuKqoOLtHgtF~Po!CoXX7>2K+|(=|BT25g_g zd0sZ?=uw4-!8V)|X0EE6y55gqF_5ECYG4ug2Y3y*9G~c4F+L!s6D7*a-tb{-a>Z;L#Nk}#= z6=kHw!q5B18NtQL9d@C=ygXSsOHf5=5680}=(1{``DV}LnoMPvpkY}9I#`wTVp!Y7 zeRCvR1$3r;>n~RuUoe9kB5}7gT`*EGG5M{rA>4ga59})1&#m-Py{xoxeWMM3?hP^6 zP+tYAmn&LNADWERr7Gbum5|wjUrIL;7x$gG_36j(Hpi^%+0xww*I(JTRkOs!7UGI# z&OP%XReA6{I$-86EzrIEqOoUxwFhrDQdDIg5j1zE*8VTbKVSRurV(nw$>!8$RnNe! z=+IIeDaZRjh2uBu4%@N6UNZ62lnrwPLX9fL7z$arL(p2^IOSMz_LPjg(^byB&UlxI zEuVDs?W+txn#5I)jFhK*R4{CL-oX>QtK9^AM=zDT_!5Bb0KrvjLZj<#C!Vr*9;o02 zACIPW?KY$7#oHwHGDZjJoqtlIqQ za8b3`@qPQpF8QvNxf3^W&>X_XvdJ0ItDQB{i5N3|=l3sPZyYE3vS@r1GrH zEOd=Z*R)?v51#Jx!PTDsVi2S$;CjK=q0vBWf8odf%t6mwpy5O7 zS_spMx{~nQp5l&?6&mvUA;vyK)^}0^9`DNfLm+ifO=j$!Y~}167+y)}Z%IHLU2QQHoo_-;U`T zkcCmQrdLmqZ|q9$#Y}c66;{|uc2#c|WSl5=6@}I=e`da6&qTHGq!y+7%j?lImmUE} zO7iCYO1FaRn|^<6(yX54Xm8@hxsigqevBy5Yty5Of|9at+kTs&<~*5uExWbuhCJUR zPgy;&`xx1N(cq}yO31H-4T1qFwzyai&U@=NbZM!8S0hE};HIADZ%d!9FbMkh)Vl5S zVQc!#saC67N;S-PuI|TF;DZ4Pta3_}7oZb=BT6kOJ*DDt>y8QvCw7eKsm==l-a?5CflC?3<=I>dI`gd^-zKp29|Xe*OqPk!0k*_roX}xf<^K0Dk`;g5k8$(v3Om!BzTQfnY;zUT! z?{Ag~!){MpyAg|oq>{FKBjGQE!W#A8W%bKi?=)fw(J zbvIsp>w9M?@6o3ItQI-mv>l=t+(pA*PChmGW8`czwalj0ti|P(u6C{6-~FG86PI5& z`wk(JVeHwEfmtg+?w2mr0uB&~#_!s6??n5cG*nLnqbe03V@l_4UBzjjXh30Zde!}4 zIkG_C*9<5j<91j})cMQT*0nI?FXa%b$+u-}m_thBOOoYFRl9(%mMG$V%&6)3MDRWud+El3VKC zmA;f59UpHyWbUW-z=CV_c|qnjbhOc%`*9%q;8yIyo`Yv=M_e{-EdN$5xn&;^zfQW} zU_pAY;}0E;i72kJ1YAgkUw&hm2H@{jp_a?MZz2zKZa$dHJ}Du64+MS^ZC!UK56mN< z`sYs;b29}sf6?F9A7k?9m;E82i+bekW=OU+1>TKk3w?A33Pr=cCR#2|mZ1&8AKmPi||*z!cHX%y28UpQ?l&06T`#Z%7i2Jn2CtCcQER(u0QmotoAR-GFtQK2o4q#N)9d@$Ad>TWXXvotTa!j~s>Et4mqFO4syUdTk1 zhufkgJ04%W`itfIuZOfS4&cs3gpfw7uRf|d<=Nb0ZBT||<_bO40M`fR2#RS}Q^45d zDXT{hA@KDqMz~ZS?l3C!j=QopXh;vEc>-s<*X$RPPiD?CvMe^Hy)Vo=e#cbLoBs@1 zer+NLuGYHM>(=W=`D=cMgzjCEkE zi?_9GB2<>e`{s@2vXC(?_@nJ%WwAtc;D{nWPB}Z8%R+>oZ7Vi``atr`xry-Wm)0%C zb`7h!d|z0F+BpMv`PP4}OqYy%TfL(A;&m>y7k*80>Ozs@@O0<30JkOG^7%tQay`EvcAl(4h7mp5H9n!bnOhOh9Wc*VP$8>g-7YG-= zG8%yjEbE+t>CZak_k^;mGLn_lxUADm)4ICd z%F6oeY7%#4^=Cz!vq*F}zPO+vfqNo^Okf}JH&#aDHQv=lcjgtHyd>mZkXFw`de%LE#V*oZ=y<V)i}To&rf@qMaJ z_nzOZlx9O(7>O1pQrFQg!Et-vwPi*aw8L>8Acz0)H)^vNmHb%;|c4?70a6NSu4J5&QsBw`ox4Pj_a$N?B3_-oVy zSe1*0j;;NTr!uE87c?HSxe!SO*_U~!sHI~7PwWeFn`qkTw|&GjaFVDgoW7or$UZGa z2k_phk zCsilzCba#|N5IaAZ3uZ1qb-vyR%qo95vz-)5}6IRSH!9Y}ApbQ9q5S8g@}Qf7?tTa1C-uEF6A&1p@h;h2vjA@Dig_Q(nXs z!4!sm2geR0pDb2tDgIp^OmnZl66!C5dBYZ;@1^s1ORzkuyJc=eqi}yN^StkTe+2-G zt?Pk6_n>t!`qj(7;vRua>$ZnI{WI6YOAiJw)cCf0&N2ZZTY*05xcRv^ahT56*1scS z!X)?lz1^k>S#$!iRjpw3&;Ew)A%lRr`)Bt7?lbI*fZD0bXczL=J9RJumB5zsv9-v+ zONAU#dzRRzUQK!N)n*vo>>)EK=DGiZRZ=BP@SV?O@X-oG$OoExrgEXzDJT2BA%J-c zgxcLF{kuA8O`_)q(-(!~6KAvV99X#QhX_6INys7)9jd0H!k^jV8CKHI)e*^n^S`Pm zF&YQzgXI<14HgBhe)oqA^T1)2bfLwT!%kU3!p4;iS(}nBu zGEMWnTDop1(Nv-ah#ny@1z^0+5X;7m*!o~Ofgdk5x5*ZS*wB{O+^>dcZ(NR=s$p6R zHi15wuMS3qQ=i@f`EH&vTc?(=xSf!NRW_{Q*$SMNq!E4PPoaRMck%eK)@|=w*Mz?{ zgyKV|8l9O*W*)(|<6(1h35-eC4`1MwDVfjuW}ho*(?{tE^qS;bUTa!yCZrNBWB&CM zjD>HjyR8Op6(&1|dk$gIY(kK&|4uMna>2}sdqM|0rHiicI6PIS6?Xg(L(Z2Vs>1{- z2HSHf|H){TpMj0T;6w zFX%{2J%Zs2aJad_ zX_3$zNP0lHO%K4-i7F%eXZela3+Y$@vYNG`s)pI8tsi27(eK!pK+LO({MxRQLe2}# zMmJ6C%~eJaxF=lvWsO5b1H@ODnl^?u=#CLU!A~B&2XWp<)65!wxB6dHlzwM_l91G_ zd6{b^i*S9``;BnmoCPw$wZ{2pSmFAXNa3hTIjI2}CC&UNK>)pEUFKKnO*S4zNg zXU)qLjqX2|zWbRwWMa(AJV|83O~qBWdqRXRK?#HBgGgA~L?{%+CrJccaz@mJBcFrd={01!Gi%JvjdYsz?$3#{8Vm!pe^e8^ z^LE!i6RMQhQZRthSVd-ZJUYypd*}n_9%xOlBYsPk}$OdglPtq5!*72N&A&Y0o=mJGnDXiO|v_EhKL<1Z{LTEc~(DJg&_ zCV+2~%{E;c!Un?b!)a*>toF|IyzwroMAohG|u)KKtJHPGE6%urv zV|~%SUn}}$0-DvH{|U1WXQ&#Fh0$zn8c4T@kkJ&O1}UD2sdWZsXBH zg&6lBb?~Hc6Tfcy+LWBs8m)HJ5+77pC$`-e(zkzAHb>vFufd>{+O%v5s}<7Mgjl=? zR}~xM+KPog4!gpelWD$hUWBIUjur6CYjPmcdJ~rQ((J^czuea@v?MiM`t$k*pVilY z@6lG3_GqeWo1v%7!qy;3`xk9z@ad;}Yq}VOKK(GpOl+r`Y%jf;^pmn)>xZ!`^CG(A z|EUZOc5}S@w2DscErEMF8w{To2?u$Hm4T3Ba)o_hNc^n1C0m5TJ6SD_ezTIDi8pEd zZOG3t^Bnyx8l)hj4gYHVL{})?3n9EoXC-7M)co8IifPb0~Pc$SevFrTS^L|=ULwstcrB!DRe7H9p(j7(=E2l>a-j( zrIxJB&P-y6_O>~LA$rczq<8m_Spm34E6vf!_IyvR?lb|n#vPx+`F7VgPlA|0qodBT z{kB38?85?aBavQ}=;$v8hJJklkfnb$>%gEMr`-q_>J54;*zAm_9|iQXDVBO3Hf;Jr zLKW#4W8U+AK|^A2X{rhP{5Sb59syG(9s+|j-wwZ7&5&D`7Y5Xl1`l6u)OW5&XU`qihV+=CuBkFKl;UyF!Zg}F+FTDGtzl&C zIij(xOwBKtNmjqgFc!k~z+Yatfdfpx3bgK#Ed6(W>O+1Ch7KfH2=|{+9XW(D6})Ny z0*-IrnW{Bp>Zi!Sr*zh20B2P_L>`odL& zv=>r~W)Ewjlvi%$y}GbX9Bzlk>=UY&gjlfth~rMzVhaSs?6-_NeqCQzXc|jK@UR{> z%fE_u`@e!$%A|%2zsH?wn`%5n^^JiQVVojy$%;PJ(7Ek&=bY`ex|@LE9jY78=nB0q z=d$HwRVLu7#HIGwn+Rd}vNnP7*&X%nS6@~Ifz*{8V zap|DV5cO8Rj8UMjkaH;X!JBt_Zpu(g5Ne1c(lLwOX7ghL4L&j**dl*kFYGq9omUJ_ zT9wD{*%#as$QNZdC>?S<12~9y8k43(9}K-DT=EWLd>Gec>fi4(Yw!~s-2}Sw1ih(P z4L3$+x0e5(Dr6hmL-zmgjlS95Y|`T;lrT*>MDwly-IKeu=Wu`!jZ02(G8Jw%NDe7n z^SgElrC)55JBQXm)NJ+dd>9~d6rbOxa)hGZXsHWpiYPPGqdJ%NzJ3`i9+LP*2nZn!?lxVvCiXu25Qe>taNh&0h> zI>oHT!SCk_kMHPi_3;@_BeZ6vt_Ly1g18`4G$bxH z?LFg!!wLd(pU8i5`30~4s$phKi%=u(xPMTyK`2F})RR_2u>FU%6B*%fJ3KWQ6CSa(Sk9~(mYyBjHj|9+ z$l>_tsF0|rl*W-vEm?aQ2QH<9Hy(lk6*7f%_@7P>d0y0&uOL4mDcy$&yV+Mi%3PNa zd)=jwJgXwv!Cm2`f65c8%Y0RHjX42u<0oUz<3h~NN=iZ+!}h&3F>Wij(~Ej%o{E@` zT`JdmHbZp#S-f_LMX4uLph_*TfSz@v-WQ(DGfW5EgF*9Sp#wNg>P^R6OTCk?**F#ySP`G!`0Nfa7u{WFavS>GCvm zsNg*@odJDeaJ9*U7-uDxTn!$<&Z7VYXv!VfnM%T#bjV zRgsg?Ya;vp$_1A3wm$pXlq7kw0_Tcs`<0!~^>T6ip>Z4$Y+Gh<8;fX*3FWd#l4Cq1 zyWdgn&$sltjng@R7L->z0|EzKNao4*pW|m{do1&AJ$m2)8!CS%wLi z%94f`8LTbaO&iu!X;oa1o6Y*tHwF^o-{nGsAf;-mnu$YMOO7c`^}@v{c&YfzZc@wXMLy>vt!?Qowqf#tlw2|Qj1F$;QYIasgP z7xW`U5GqTa?Q?Du2sFu;JP-r#)dZ3h)cXrdr}&;vM1wQADN_a6{_lWg!)q_MyOT_O z3A+{fKh@{aZY#Mk(F8Gu{oR02A8$y`44#!$UXZ%L+;qU0lao~8OFo`QkuV>Qhc$H8 z59CcDFJN08g%#8{ZOqLAIf6xM!Qwr$#?w~sk&1}tWU=}X_e4s5*;O>0&p112*?x%& z+{$0NruT7z(eX;!{D$ye=fzkdPCSoYdYNvo6X$0EdAOq21^20HTYQc}0hg53D-cRj zu7LTs<5RRA12@1TRJ9;jk^YyzKfd4%kF4Qj#ol7DYW$$&2bhRzSbWa@C`Wi%fEjWO z2?#n2+>n1`geiGQSKdaDGfoAUFzO^e!4u^ z&b7LlX^+~CP&8z0==)bxqd_Q+(Vkc`ygIu&H(B-V( zV7ci$IE5a;j!$CZPGCXlz+bno4jkBWsk>@C&Nb;Tu;v zu&?t5I|l#c7En2<{|t9{(H{){!ScWRoDvbo$;?p3q^|3VelnkZ{1sT5oU?5GcU=Cs z*jKO1Wc)=R{s`Mn!=S7z0CX?SVfe^KpL#Qb1)O46oX$Qv}%l+~4+Z z_zuqxcOH+AuC7a*`!)f=Z_F2#Eg55dY^{P7*TForFC8 zZQJr75DBErok>nVO)XE5+plLy@WaEk5sQ5@2Lu0MZ)zwn&&gEpTIKtb%o<3gWK%A=`KH1KkALaaw-ocAJ$%#zc-+^Q zC6*)!Rw|K5FK}GJC0OXY@~R@CbW>91{-_l8txJlE_2P}*lfM^7+)}KDh|aEv0BG0t z1PnFraP?xl&8!BQlBTzdn##4fr4-9a2e!4W2;8bGQ-y zd*=T7Z_9RgvXd@=2vZh0gT&sCJ452LfJGWqei8WW8Lv+Ktb67Al6d@UCx zOqUXXV6=K)&6}b;bQuIrgYH{)SD)n{uR0XGZMUdVo0)z>-&H@*a3rz+W$ z6#S{k>G~{oj;|Rn#m&WVZh7%d@n9;UY%WZpWs&oV%;{{ktuHv68XP%PGKPT3bjuVw ztaUHjI6~8;1a9M$mSf17Z6QY#3E<3JGk~}5DS#AZ5N3=w&Bw4hj?UTXC->)}=SRQT zmlT&3;+&O^1$n14W1^ySS>QxPMMbencIM_nn3FLMQ?)#81ItK(*G`!>GKd%quefvf zx*`ZKN33r)-PV-q2|RazttxW|A9ew{PQbC>@+de`wI;gz#b00G@|LgiDsSxhU$up) z`NUo9tdz(203aB`PBc*h7j$aKA4eZdxyCJC$VGC{a3iA-4;nObu~ub{!u7_cgy2s# zIhJ|7mWM~>vr%GE`<}j6x3rzg5gmFcmZv- z2HM_SMP?rVg=OJ^O9lORru>&BN4i?Rg6bi`d|&+>f2q6eP3n9A?BiG}(_h26JmY~< zCBF@)=%A-pPxKdOVQ$iccXR<0+j28DeyNdS1E%E6Z;66iIyH zy?|qj*$(M*18{|yw`N+B2O?wxq=Ef7d&s zoP=V|&d_5kh7>ZEJR%1t;8i;1d4tcR`(j@Meok~q0SU*5MT833+9c!S zb2iBP4Nx@n{TES?;_Zxoa#NqNOiSg?VAcc}#(P8Ob6sfG*6!Kp`i{_9Kuf1TzG3^O zXY~wq<}AY?kn+j_tqxBRiD|s>kX;fUchLA`pv*G8@Kk0DNNi6}c(sBQdN?141PVSd z*{fjyJ(|A;&EZbg;`9-bFZek=MRj9fnWspUjqXM9jx;_S#iyM@-~-$uTX@gC;_VED z^WL`ATtAnGczY;lBJdyFXuzA@pL4>twRE}KYfsgJ+gJ7}Q2(MgykK-%%%TiRd5B?{ zT9c2in3v18WOsMM^+yVYL2dtumzxJ4?OV@wt8}#{;wui;>N9q3_J5jenCu?vI*Qxf z)CvfLXZ-m^pq&8;De>lkz)Wz&@!z8md)tHr%Q8f(RFM|D2>sIc(cQ_b{$o>LU1zxxj_h&?mglNYz?aayJDe=K!Ga zcvo2pTSVd#pA&`J`ycKSlx%=?0hmmH{k#N2b-bJMcB4-Em;?V*`7Pd)07|Jlfbcco z3fpXS*w0*>#KI=XrX)OKQSS2+frVdrxZl>dr?EI5&222QonS;VM_)KQ^ka>iXzATy zU7q`qnyAY!a|bR(19TBC&`g*?+|mAzYCPc{q0=Ay3gzG65szvYkSgIaAdgq0Sb$UCW=m?$Pb~=r_U?tN9FCsbsbS}#GEYFULa)ANf_H15k zeeiPHcOJ|f;I=bkLpFiS%NY_eUxdgV8q#u^!Zou*buGzJf+WmlLh3IEbh2t?yT6{| z(G>~LR;sl=CAlKBO_XnNt)luz$xrr|ItIb%15-*fdDlIuyb~LU8Ycg zo_`RAbr?1;==%|w=HEqfvNAv8EA4jRM1j3D*MOnCu`-C+-m9`Y#1H!j?cVCW)qS-COhFJbZwA$%F9U z-#l+R&6#45HGKz%aZxlhfmoJ&!y5)*4v>8U=h0D7;004QS!{t#9QYpW2)Ntp$-5e; zz&aj;!uh?}7?!}a;lO2^Q7s&`Xcq`D8|t2o0i~pjQeRSQC0e=(fFK671->7j^RXE( zy56dIe@_255S*wbHiu3$ZYcszT;62bD45a>BIE$Ltnt;Z2j!rDn76K|U-S5bB55dW zd=oIgYWtJ$Axfs$wi70Slk^Gs1Nyme{-M(8JzPCuo0+_y+-msb$str!0!@cq}mz#^*QU^=xNt`_Xj75oBVESgR!kVFf;8^2Yb!=62lP_4ec>0I#loWVj-XCZup@x6kNaVuCs5??UB>UFKb3|%d# z=0mQmq9doj?ZjNzfm$%QgkKd2*TG(ng<}iOZlEN={7DnOa5l`_j2P)}UF$ieL4Df6 zoH;$yT^cgkGGSQcjcK4-d$dJu)FS(y;D0!jvi=eZ(3lVIx zgPrLS2jKKD0emA#V=)@SQSvG07@<6BQ67Q!29H-|XI8=a$C2aluR;ovg9Vf9SBFA^ zI*tXx#{G^vWV(Fmbq?TDm1Z1l2~2pe973PP2ED${DgFCQR&k806!TjR+!|CVgoh^N z_n!_O1>5*bu2SG=j%_S39mV#$wefp)g~-ht=4l=pwq9nj0m4&O86^B#^u6Y2k#?-q z?)^wJiK#}Ea<<;h=P$Mm?)ECKd)xVHMb5`RCO_St{ru~z&Um4L?gbC^I3Mu&j9NNR zeulT8skpHIt{*{fC>}XQtqCe-kDxMQNjMGBkE149KVT+{J?y{5GgDB8-i`^ zv_(M%qaSho1%Ab^jNw&TP9CrxIQ*wHJ^7_t*qbQ;T;9@4f}4%1MKHfp<~}3V4&$}y zzKsOf&G$0D=AE(|Tlxw@@75VC)ys^X0M;l|WKKB&Y{(%>qB}r#>qTCtO7DEzc7byj z0T{T>1arb!s~#-$G@$(4%Y%CRKJP2zG$r-=->FVFUlQ6fz~=YoH5;kRG@ zZivAbTvNDiK>rAhCBk#mcBzd%_5R#B07doJk&Uw+W|0h+=(&a90NSu^Y}^BxYs5}mKyk2bvhZGQkPu=MPOczq1a9xi_s-NEA2}V~iw;+&UDF9e0I3Lma%u=u8 za!J8C&i@TByDG?t4?`N}Kz(g^99uA6rz@M}&o4kvI}gQ|!V}*wD4ocn(GHaZE8v*d zrusNHYf8(HK<&exc7~98V&5Ya91!6LNzLr~3f0+)sqlKZlg6D0$h^0#9X?JPVGK9W z8lsnTjmd1dGY?OQE!|G-gUos#Ki>zEb8fi@&zc@r7;OtZ1+LQ0O1c^Dc~wWf)>2na ztBGK*PXS%q?l(w3{Bhq5t{ZUyfLvb81%}vwhZ<RB_-~phe+Y`9`G#CUP29C2=hBx!~-A}4pxM^Lud zF5#|vg)R9bgGX^%s_#tT)U*;LqSr&al8E9}yl6f5#z|m5O8^I{-ox7}Zg!z+6-f$>HdFuj5|(j8ogdK6A*T` zCh%zXYz&cv^v4-$k*J(_5b}p&G#;o{+24JzILqO|Sy9GMQJ2(MNY=g@+_o&kpM6xR zB{tQ|l1{NaXbEqD4-WU>MTxYo8Y2vh5Fi)8z5<`viH_G1(u5VVe=GR%Vlveti;u zAP)S2uMf)bOb_mU%*N02yVRMmDXTyT2sqDq0a{NCciCFz$PaKyom( zP_vzDjEOc$v}xtlUGQS-8ZTpS4A%HmWY2r{A@-(@M|*{7!Hx;TUI%o!1P{w!fLDTn zvjyvvKa3psV#4I+qCJy!R^oxQP-wl~TJL-xGwOiT{Gi!7u$&Z;@C0i@zrk%V@Q&`~ z*B~FV4uMp@1d8wJhf-tL+D3S=5l&h5Wbm@PGW$N~200EoC=?!G{RF^(a^j8`H(Il3bp$i@yoyemwDnwU^Eg;!-?Ye(D7d89y2k#X1ifn$k;-m*g zzp5N+{EX2RLC9AyD+@%>@vbfh+zQ(>Dx zS*UP%`RF9@^0wm{Ye!-F3Vvz3A25bnZ-qP&v>Uv3*o;rHN8qb2Y;jP8G5KLCQ7hZp zmB8x1o(NCXKe_L2Gx{u7jdFl{rHm1dVRKrx;9Lp#0xxWgGcDh^h_5#8$<$Le9&qj^ z0Yb>&y5ZDZe5Kak&Ty2VttuXT^cSIwJYO4j&OB*Kd=4L01r83A9Whb(j0ZWimQ_3h zZkpDcQH`m8x$^0Dk|jj~;k#*&-oF6er~eAxOE%ujRiG+Zbp#Mfm8lD%>NaY@D)Y{J z7jkq%SY+Ry{l)%cMc!)birTkM2suI_+9~`e^**Dc>p58m>ND<($jNIaVVW|5XrN*gI6y+Q^3H!ooy9)sdONbD|~|{2LHd$T2oU zJ;sBRXI4T_2xgn&&xH+>932zNsqU{MCl}mOD`x3P#^!&9NvW^ zc2~-5D!g$jJmh;(u-#&q)9srROk+Wehc}wT_X^?n=4wpc0rI0-zFzR-)EilltBe(00Lg9+4wm zet=(ls(-B-#~Em*h~20)N*K29al!8&mUuwUcaZH{;T<_;r8Qhl`)i5UseJ<4y5PMO z4if;VkZ34RK&_kMshRQ@JX5#cB{mlxbki3tYJd5u;)b)mfL-V0ZX;3Qh|`>4yAZIhrL?T)7lJ@2ZL__-u_h{+Xe?WZnq#=ippOto&(y! zN6Y{V+#b%ri$4~voQWnfkWe7UEz`-g;9=keCG&$c=?(B=RK@{FKER!y!8>jt+L6G8 zQ}Gx9;whindV&9rJUh$`S~^bcZn)^{2HvR{c*utKY__mY;O0d=BzYN#ry=Iwj&?wl zIuHY9+Ia9OZ>`G=a)yX0c*{utR(-=;}aX&N$I(?!c`a9J*(O0LAk z16t-a4}Ei6#Go`i*cKHOTqEFWQI-&hLr!U?6bDaEnwwV`0sVb~ObKqh6>2~rwgh0o z-}s~g;B~7&zia>F4r-{RYmAElwKB@9?DgrvaBMwFWCGHID_*TrPZb2h%P2vZoctl= zL9 z7Rz8YB&bA4pq!)cw|Irun!U>pa&@RlBikMxDXPBw;73crSb0=N2w2qA0!RLf?Es*{^*qjcqr_WyTNiFY8By)Z z7q8$PeB5WK@CF6ALh*nTcIc)#CrzI|0wPBEvJR43oQs9&@}){+A_^KuL}EZg3x z>H&|@^t~#IA4}Z-_!R)nm$a>44jjuB zh`=GaHWpym0tA#*&#t?;rvjg7VN2A9CSPe%`isGN2QZ*uTjJol^fya@e=&Z7Ephu{ zgYy0c+hf&rFJ3i_$a+}u30mb`Ey~W057aa!tGOH=4Aa3RPvKL_`C7_b?6Y$ixlYCX z2i_&iz~C;nD33rO0ejyj zHdMEQIm1(79gA0HW#^~X?wp4n^CRjFOxZ9VI|xw5WmuPY(Oq1-)2#Oo)iO1Q(&N<* z2JtYa%4`hT;07%Hj#Jc#t-HrX%4en*rg?tNi&3!=oQm)v#8fg!ZU5A3Kk)KM`W-RI z;X*N^u;QYg*G$p(J3wAdW_pp`;(e!$manL}!2Si~-BflE;xC78qvc-d(@&!#4xDG) zIH`dSeRwMZmdglWrE(FO%9t92H*BHxs?`qdgwRRla7YYG-Btrn)xyCEU+oLRV8j|W zgxAM9ByGGF6Hl%oSj`M9qQjrcF3t&Wn;$6`Ju|U}Mc^8s3dqUn))J@@k=I)t4G-0> znqTrgz&NfX_T6LcR%yh)5b~mo*UnmVD-z^CQ=~r=ni;L$Yc`&0c&U=>jmTP40Vs|w zGM^l{O-+K-8gG6?XV-_}IBHzLU(6NN2SZ?j1fG()s4U`lj(8Sm5yq^9U=-DV;VZfA z$^KjgNv$9NfgAyXx|4l$pUl+#a)b(FSJ)ypf=DSw6`}ny4<15mOHfZUPVF=>H3x%3 z=jWp8DYbJ$Y({%?Er2hQJOZSD2Np^kEYEzNy=G?Z+v!MUwm6jWPPzWWM_|Qek#K?c zzpPh{t3?%%oLM1;vxbFy5Gg;AM`REG)rJQJN}$)J`tWvLO_wR&0xq7+fbdbV2~__6 zqUzz8I}4I`@hzxs`E$|SWjI&w^fwkmM#%tabP_EL)}nXUk}fKaf_F9u{1RL{^mw2< zf8>A>gL4`f*DO~k7euwNtPVYlNLZ?1Q z`!ZF+FR?6wyE6_EVxaw6_Y_sXTJ(s->pGk1(%zb&AIeOycuMX%_4!o-o* zWTN_+18)dUMOJ4^GD%@yDbiX3F6~azg&;G8%;yTXanRfK8idtsi#yJ0VP!P~6d$G- zWjx%5>HAFj|AyBAh3aB2uP%@iG`4r)FvAidP=PJxpD54QiWws_cW|))(zdZ^ zGsOzER4F`<8jHCiVC^d*9ZL9abWpP8PWmQw&IbU8GN;~q5oe*x`|5|qDH$AKsO|q* z@YdgV=uiV*2Y&r1;>{wmlhL#ta=Lj2XsBoTPhlDAx`#sOWaoD7q&S zrT*WwpL0&l@Ap5S&-;1bSI@Jbz1Los?^kWrz{mXSZ)=`(? z9f!`0y@cy8c8r5!qBug2m1acLd(Ib{doGcq`etBo1GulOo2_n3J_UhxPNn`gHu_ZH|SUp|#qFU;gK=-w2OY0Q_VW-If|z}wjDN-)sCRi)ouQxlFS(%uw@Vx;Wd+`g zIZ5Lb{d+O<)K=#VU4qaOIA$Hm?saQioc4;^Ub8E>oNMi~FTLaIMESpKG_bM(0%P(1 z`{5i{k;*3s1aom!`$%?p0Bz8DFU_K2K4KV|(gQJPZyxC~aJ4Gl6WQ8JvW980q%!-J z7ZD1GIXiS!(VmzZ5xYRfiMtERFCR-gXtM9~^UvKHXFHCZw&SGvpfP>?%mxjw;++kFXU95w9R8@~1^>Jt+;Ro~+sV#}(Z zk1<|GoC7un9C24SaXO z`v+%Zrb%J9qpGLiP_XJJ_bpvtO?Ap=7_4xwF>J}P))o&vS|Uetcl9Gsa!W}Qo6zx% zL57C0N3u71Y4<31J?~=@-p*Vqyk}O4n7{Z)EJo<1sb)kRW+R}!B_V!?p9VTF+}xXr zl7dtKNWCiAsyf_P6&FcLqfzyG!uEp2bwp+TV<;whs%ins3QEg$-!7s>P(MKr8vLi_mk9g0h9>OQ*H3jt1( zF{Zi&11+}548I%ouNl;x<6C6j-&y!{IUTa+nrCMfWf%9N_QDj1Cz#I6tQ>md|Nc3N zZ?87P5j<;jq0HUI_RRLg-gEqjc{Q(pPf3l8OoLqseca&g;(<(~>L+f>NTWr34=~2% zynHs`bEzAXoq4YWe>NkN5Vs%w&C=^9yT<-i(|3yfD%(6 ziMaPKxAI&aqScGGp?B4^MVVtx9(ei3tffEo633jz(Uz+}ocNsM46!?rL964m_5{zmey`Kh~Nlc|J1O8TbyK4Y3BENkIGSY zH1a(LS-y)~*jC%H!m#%OF7p`aQsH^CN>9L^g#k8sv-Nroel;hkY5Wi1f!OWIK;MH? z2YQrYM(W>Q<|z=R^La`q*Y8fh6{nLLKtitinWyfLT*zc934FfQD}p_t{wvp>8LJ5W zi?rKJ_XbPqn@>PIZU2jyYZS{m@CYkMka=DUA~6{HGoA$me!hZ}n&w zBhq5Op}6y_iZLB4=9_MwFo*V<_vpa!{R4@Ri#OvL339r;A-Mmun&d+aTT-FjhCVR} zo=A*|3y`X`lu==r>o%r3BC)QA{x<(yul`2HE*Wwz3K_2p<;}!)9NLDjnv=I5l9gTT zbt~%bCZbBr=voiuQ@-`NU|abC`eOFe69r#09=mZ%{r8r0o%-5PmAL_lZ)u1hT+8)?FN0A$ zX>9SBOmLnmIxG?q20tzn?D`$Id|ycht&WM7+RIaEzZ6KA(-{_IU+N^+zVP*L-b zJ52@lXGp%~>BCf1vbHNp;keyM@lsoHB9=UL z%q!Rp^3ZPqRN4Ml&BFj2V3W-&!+dqP+^5D>zuV(K`1_Tl{gL?!+dEH1^fa{aCLtk7 zN|AFrOH8VM_bZX5P`h@qWTGks_`RE2YBW}UjY*wfGSN)wq+Y?J6=Zg)djS~_!CwtY z6Kp|{2qH+#&smYyR_fuZlbHZpdlY4!#|HRhty>keRNHyPkba!_P!tUlk=QMi#{zvNRRc+=I*M(1m zfpqRC<0-FPh<@|Rj>vR0srFY*uRFwa=2+buOU++GssgvLfLgcI+$|VT0?_ zmAt(bOgKL2;hI8l6)3%xOqy>)ba2ZR*AA<0`%G|-up9T#)J zQ={6Fd6Nm{2Y*I<>ZwVGj-N^KQy~~d?r_fXp<1N`soF{2H-t33PqS$o$n@6g*14_| zAnxqfPKmwVaQlI0bl6T){AVHv+)fQCvHx05=Z|Bbq zW4$KTs8()tFiW7~alw~x-BIrEQXw*)tH5t#e1EC=q9%Jy{?5O!t1pVyKrmGIRN~j0 zs)FID>x(Os0cX;0$60xhRu)J4t7#c?boiAfFzcz5fDwiS0If}ir$&#p3`|T31ETQK z;>2ck3RFbosnzVkCJ;?)vp#!B&*N@z?$V#egLf1~x@xXFbm^XgKd}JUf+eoyx9bdh-BSzb2a59!35 zP9!nknMsTKV+x)swekr5{xeRTkscMP5zIrWD$M6;2urHC+qlH)=o@+AvrCdNkc~5b zQWI2q4ho5vCFS*hVVp667iTrOO_%x0$W0KNuW+jty4o#?P|@IP1|rC4&dw`=kS_R- zP_vz#i7yZwy9^MK{`4{pzlx6e$?l$Y^cjwfuf9Q*f5@sEdPV1}BsL7y1r?Pta z1U{Ry7MFXpK@w5%RpzYI8$H7)VscgGVt^T&EmSzAK# zVkAf3Q}r&txHBK~#~!{uLHpeO)jjUSjp|>mEKvrNGz516TQ9Et;Muv|Yk%0|bU8XhT=P=jC1;M$d3xboAG_n)#ZfY2% z=v<OY0Py8i5IQHErSS968ZEFAlME|ADopTkBhDyP7qEwI-LN*4Ev|A33gxHrSPI~BO z%89jrX)jxVVamfEyLoCmhaZq&VHXd0OJ-#XuaAjB_ffJn<_t z=qeX~@3qslH*`{SMp}BCSLS4DqwstgY7DqOZTy&xEbuPLZT%mpG78|zH`YtNJVbSM zw$=kUdD6Ka+J0L3Y&L+}GFm?=QWb(;RJ_dY%#%sUwdJP@SKualcOn*e!Up_KXdSf) zeoTC~2sC|hca^IPlO%Yf17I|55z*Q3_-^=LnJvW|s*xbF>%6K1sptqQl|FX};&*e~ z^Aq-*cspFAYsnQ{XVK|b)!}Ee-}Pm*KQW-B2gS&}OVwbT@a^9Jd1)DoMc@5s3IJ}Q zg(O%aFJOxvpo^Qx2nBmC?`Jhgy{M5AM~phKeN`O z>0h@qV+hiO#U;M($es87Fm30GnlFZPTzuUGvk8-07pqOusV#>j`hVgZGsvMTAL_;l zCj42FVy5RYeOCnBlAvf530itwfoa@7`^t1F{#%DK-f;CPTJd0P_o@f-!a(B%7njq? zB*E5>$o2!00cS=*bdC2Fz-Y`cDAe!P=8Wbrn~!{gk%_kRr)%;7Q7SeM-R}&vtCEMk zU>pv`V2sO_)qT#&?M=OWt*xa7eMO8$y1gE|VD0hvAVC=AeqlMm3aL=*{azP#{}@zP&9Mj3IU zZH<+_35C*WP|4zAQczsBT1Fl{w}uR4EB%9YPajv=4ero}?-`|h zh|#aZq&CyPaXPJ2%_i8s25khx-V!|K7Rp9E+_@HBb>Rw|D7xOt&GGz(@%826XZeGj zQ#tOmr>UXoq}E#5Y-m~WCZ4pmS6Mtr&4X+)hqosdWsm{}gy`7{H~y?f=*=m7uX$eD zwodVQV+QTD7ExVJo*br7MCBF&3Ua4av^Du(O6kGy$MU85irU@ZxswBTh0=vVzW_8? z-vxV!p004mVVNt8%~$&#r_LM9cWAfszQ(j!_{wd?Ds&bD9U{rP&a>Z*4Smf@ z3BWE|>3`anDHD~p8u)fyr>&RB-HFjv(h(yW8nI?8Rz2;oWfUg4l$I%8J{!xxt zllc{|$DcnR?uE}pvvb3ok1Bx5hv-C;=Dh3tYkT7M4b`*S`@j+o_IL~miGH=u!7Ith zDJ+sn%731ttCw_mPM*BbaDDZBcok>1OD%$t#`NT;v{QYU34! z?H=v6*ra)~PHOa5mVtENN1GE}vvaM^NCbZ8LgynqMMQFS=Q*(O=>~`F1mJ-m+9EQJ zEt(|rUysvFHxt3>wq>gvIzKeKe2m9)YW&!YY&s%+#OOQWa~`fpOdJ%o_e7ch=k#6i zNAIxHlBu;;f8&L{cNj2_Ire|UgRgO^Fz33w@T2wBqvIMs;+m(I$cO{QM|`EzfzN+r zt7cgW!FRFv!X`2~0|@XI&(4d*)g;EHlPo{bJwbU?N?`zt$APbQ`SWhTR-d37@4Jal zz6&>LZF3)X-hCF5Y&tZ%lnVNLiB(mn4v4v*@GT~Qrp=T}xK@Q3CjaT`ht}J53 zZEtj%vg1!{E*uCy*Kkfn|PeEU6JDdN4a#87+FxS2tsV0S@RZ+Txy=BE* z2=Q%ao9saj+&XrIeFgrPZIK%DsDiJrM*GVEgb&_P#PT>S8O04+ zb3^Fj2#NuOM)p7M2^Xg()9=J6PJV*4;FdK|R>nH1HyWmyHA>Clj69i>S7GVr8}t`^ z81A$e+p&4kJ8@Qt;5G$ljpUE?mraySUK(%d84d^`zFjgW@6DR8jPV86lPn%E;U50?jfPXX@Vs_EvsupRv=vb@B}jjG>S)w# z<;6v?{HIWc@xT56jx}NwB_TGc%{>Y<$zYjLH+E_uTf-6qhSuOJ{wj8 zZ(-~LtrMo)x~``txiXc&6x@%B3@?`>eA&z8glO){#@Jn zYY6V;W*o0=mFc98R@@)LH4iT#ePD6s{S7Mkz2L=Yvo=Cu@~_n41{MKdm650)G#0Ln z+r|N$D_F$NSSMx5^vbM!0g?nUc5^Sb;YRyP%GxYt`&?;i4C*~>Q5>tc@*-W?> zcpaCpqy3i=Ko^_0$4QXuw!mlH=ra?-_C~fURx&OTUtM*xY9^{~$g@kyufpO2Mj$wB zRKA`CKWcvg_rJJ-vgEGpB7byEvm}HJA{Y0_j)Jv%n_vfL9Km*9VB2lJDe>6#D*OAU zxRNfeS?-vpb|3^uy(~0rVb?&EUld9*{$e{0r|$})nlHY0O|9Ksgq5wk^5jy=gauk$ ze09;j6@0wVXLD4L?FI<;iwZ^#b3zfBm#}B!wVjXUDlxuZ5l z!RBzv7lqpnY1~)r;fuckArY^-o400T-4Q&Z3}mm!BN669WpY}W@#BAa5fhN!a!J_W z>aRWK(F)i{x)LB)B$}_?#5%R#sPQqY_k@S*g;#ZumdIDx!hmO4OStHfmd^gU?oVWs zEvW?Xab5@ctv`jW<@T;5)+RlHvNe2=TYv5sFoZsOKue)03B8kvq;u3{G`<0ArAApylq^Hs~!bJf5( zgv8`6fLOcllc0V}hCco0$hWvOgmVqHU7nY3D= z=X_>MPb?&deYYsLPyxtHcYW5OTFAUoyAj>-P%VG6fcw0PXRRNEw%Z!PWT)MkPQu}g z*$99tgBme~wYc;aNk=+6jkj&lf#xT#KbU8__lF1zp}-Zq=VEn6zp~>8E_%~q6Tx6@ z=T1l0ZF?f~Uu-lpa4uY_56Pdp8+6C&FQQo|wCKuxFqNl}qjxRLg{Zi1zS)O`1= zBemQORM$l*bOL*QxY@8Xb8X`@(|9GoG#`DHTc|!pKom=dxXrq_CaP)LygZagFvW;I zU%w?~kl<2C_42t~-(SXoU9L^Bv`8>#S&oqY6+id!S!wTvcy{E;V%haT+ANpZc@aUS z-}K=wKb?cPhHZgjILi{qj~M4zrt4Kmptxd~Rbb~2){N(((RxSl#qiXi!`MDsuafsk z*8OmtR2Dy{Rw89-r?*zfzK%x{3c0T^APO5_W@Ju78GKJRCv&KJ&|1pjGs{DTXNWH z4L9%hDhHfqV(}I3#m@OKLxQj0N`hTf-yF@3NZr4De5-SgNEEdU%4v4qB=jagG3U^N zX=Y0=U&abyTCc)ZaC>j)Mp*TsGfAb-C^+@nf~5Dpp2x)gC8?az*^Z#jj!TH$d17hY zeVbYM+V@_jhBbT?n-17OhtLhaGUTK;_~+g4`T->s^h^E+B5?%vFEXkrkh;dZXV;>S9^}~+rHWkqLF>H4D0>2 z-xzdy>?h%wNeMaI;#1PUaKHVk>DuYr(ydpTysSGRD#FK^8IVk_cvkGrb>RqkeZ(!(z3bwk}ZZ1 zA;dJ&tngXi6~$IHzJbX%mpeGP#_u|gGj%DUQfXBqd<8>~c<-)qII7$JlGb|__p|ay zvJ|4^O&}_%PVFadDV>uCQZ5!=PLQUs%cO!aLjT1=)5^wSIw(C-^PA(_b&31V!WV9P zKtUJL$T4hkt&QSU6N}fLk=Fj$`tADyL*KG8ZFwa^Gv0>2PQsf){|6={*3HvnKkW*y zYvckdQT1hrp?z3Q@bf2DU7vHZu;bENsZAeF)HfDfm&yf=UmPeuk9+1{OKZ_w61wXIO^^N$vkGwH4 z3rwc7+1SuK)0`_FP9v@t`di7|CbbG0&!6lr#zUoH(UHk_b?0L^E-G!RBw$bE>Z6Or zHSY!+)=7`Xzw*AL@DH-k;j*^42p!7+VNTsrBt!<4fQT;XiPD{ok*j=jhg>)>Juj`b zHtVu9yBF)n#T)_W%q=ZD{pKpmU>kiWEL-w8D?MwzvD0q+2^*YjyRFvAy=rRr2u|6u zfF?TUpyVcQ<;&|Nnc4xj2RdIW>8$knY}<)ctugkTcu9Hryhn+W??dsx?XHjMX2D-B3u}n7!H4;!h z3}vI5H-9c#4IjlaZ6owM*YTreB}VKh9HcD&@a%^KY39>v`{J7mIGN>@;EMj7%tR7A z*s%KrT(}FJoBqikp_dx-o5D6S>%rk?L*y|Nsv6Dz@E4YSlSXt@T&tdud?g@IJ_6DA zhv_z=AIB7ox5R1VuBHiHPdM34uY}qYwAq6tQ+MV5$puZ%?at}4&(v0)lxCil3LT8$ zVuZMJ#lO_0cTD|IBi*`8c!s}yz1kx_s(WnX9CLYH`o748zJXh7vZPPnj9UCqzZ)Z8 zP*bw$n$rMr(PV$!`lG{BV^S2hsF>yu>M>ADdDg2cfBuSG7a?gAnWtCDj$;bE%^uxJxh0XAI`(k^?YtxCYOD_Li%HwNzz;$=W#o*UNZ>F^3t#uK84KK z$(F=E^jMhtbE<6oTitobmOd6Pb6|vD)%}hW#9UeS_`5)aWcp93c+r(SRa^X_)vv~~ zqo~=mOsm;Q=r0uBG;Hy62;Gx4)SY{swJ+=Vk?xg3U7^1ROK&$%68bL^IvTbdX|^?X zsq`y7c0c%g;TX%HmbxcnIS-YV(0is8# zrR`mAR|mImatN*W+P*72I;;C`+}(x^-mW8N=hzlXT1-hKm9%@~)I?IMDwh1qfXgWAB)o2dga`{>>jZ3}GfSky6QtPbJfoZk_ zA|e+i$!d;(C7ylBW#i9VjsBPRP<0U-nxr zY|1ouL1C!eJBr-&;a(;Xr+Y)hlC0<~1LH!{SY)8&RU4|mZj9d*qJQt!J@d6D157qe z$I{_262VTkRqvd@iHnr*>5q0^mM&0@n6KCw**+-H;#~Nqds;D3t?ipXZV>t*fW~na zvS9sf#(@P_!$eoVnoyOG5@=Q%ve52k?>H^xRH!h2Hc!yRp))X0mkZhC?NuwZIvg^Dr}=7iQ=L)=M!pWDj~zk zy+(bmZJ}^OV6Hn9wZ(L6&)3$anf>;@*0{&|#Zay*aJef9RZ+^1E$qbsur!hUR&F#B7h>dxH!Xt)peh775iHl<)<;u1 zJNhAzEkDd^#XN=iDSw|REi5yfV5s83~g-wgKxKv#FMEx-^O0n}1;hXa| zl_@Cbb$EJEa9DSrl6?1K?=;`HGjs7SQC{XFc{d@)wmU%l#M-Oss`Y4=`^;XuwOV!f`4i&tVpQ+gC970L-nH2;NTB)-SwJ3KVP-l{>SuJk!;4vw?qcUyt)i^-5dE$RaZgJcx~j)jokQ=Rv3pIll7fXdt%I>2v+2%ypN+a3Z2IVv1G&>Bc_8d>iiJ!j$K> zdA@J;9%?PNJc8Tz?d}kB#a@bNrLOmr|4pj6*d5cG73hHa+%X65TI_8K&mN#X;l&pF zdztqB0kwCDjACDp_y|+4ZKd5Aql)$eYt1hmc+smezjbczxm~Xw4CXpxOQh3YkXY=( z;4#|)05@2X~&PPe-9c0#ou_w?OP`zxlRun#rMg#K@iE>fTz~-8x*JbBW3Fw&mg1*}+~&2A;appZ%klJqoNRvV&Tg1A9q#>y zB|@t*!&O}iaSC^u^vCz_FHBG0SJyRq!mJ6?!lvKJjEs!+{t!5njiO^o1Ty6AZv;s= z!GS}~CSP$M?!65@_ZiAyhIqDqs=V~B<;n=X4E?J719cT8rL|t1&M%S(U#s#=(}39y#-3g6 z6ILc?IlP^94ta>X`y(wZ_FJ@l$owBRP!Pf;ADb@Gl7(w*RJ;Wz_>^hd2X_ZL%a;lt z3qyy!4)y!2LwWdoq(z$F_38^Iw(WjZ=gWeu<$KzT7TYv=-`e~iiq0TBael0sU4SDe z|Bo}pXn+~^6aEV>?x6H_s#qtsBqGV z==>W_)CDDMVOVxQ#`yYHf!YECsM1q&m$qFC-$E`T{ctB}F{q#Y%VN~U5jWgYi|+)Lp7 zIOZ8P%R#a+nwzq%#6WWWL<-N4xAP3RsrvdrX9M!e_+dENL5WLcAHnbW(yc|LU-u}o z_e7=W9I8A{Qc8@kKRPe`Qu4h)AP0^!o#oiMT?`KgL;J3{DDz*T*@-1$ARg zG4-WBC%!PROv_Kx6;xo)K6rbRuxtz28m2Ids`a?`qdQmRu-26{o@iUPQb#oS42Dzj zR+02hYdtRWl1|1i=J;8-*Qv@w%q*B&8X&j_@`pb63zV; z^FXhn_dQMETfZTq4+wp#htiorCqX8xN$~(1LrpmNU+X{Xf8Y*#@S3G6GUy>FzdB=! zQ@$zcsPm7+oS_-Tzs#1NCiJj99TD!SM?p!2hLXFbwWvT1n4=t~cEjMaeEs zu;_;L$30ojb2-sHERK^+_bTcmx(7M!^+*?etUVeS@i8&_4tUd%Re(C}+DGEGY@^k8 z=H;F9!6wZn7=bH}Kg4fNI6%z)9Z$_t27Ue+j(fNR!nTZ^k^nY%tcyk6GZ#4rje{@7@PPV7M+3}m_@7* z?Dtpkr@h3uS(}9;JnnJg5H(cVqlh!B3$D$RZRK@C+lL++pt(+rauHB0VagBNqv%1cr&TFRUQk_eo( zfZMSxFZtyd*6EUV)G3-6`x-zYS3=AtHf^t09zLUCe5c5}b6fHWf<6W4silw2bRF>% zL8>bV%KfZijKdr7w&()WZaSO)2J`Mmd_d;VGoMLdds&)Y7Ol``N}4-}E(kml-_Mph zIk2C6$CBS3&eM9and!6xz~ZOj!fg|knV=Y>T72^T%8~OepL#)hmi)Vs3E-okpD>rR zJ#%rRxip;v$1_dKi{Un9rgTE4`C-;MkG>}grmbwd^Dq6#X1!kXwE>HTiycbADKaZ| zUmfwUQ;|Uxp#FYYqrTH5jRDvIS>lQZq%lU75|`Ot^B1n#;y6yCS>7b#<@#L@@m2An z_0?;Lbv6)p^~j)vrnEb7I8A`x5XWhC`c9d>WFGZA5W1faPRf11M0k_;OH0qcDS)C4 z+RO9Sv>x6%vUq`3@t=(CXGAj{U>jK8M>Fr|G;gEAUYqNX_Z`NzMNO6=z)Jkij3ad< zmoe?3vl(#}@RZWfD*+Yp2587WI zvZUgz`7KYJ+(UZi=F!^c!$rhCMy*`-IJ1Xwb|g275B4mxf|fa`5ZgpwLtr=u6pNRO z+@mxj9WIF4g8GnC%ogxQl~{dYa|Vgo9F6If`3NV&sLO)R*eRg6qA3EmpFD@b`u$3J zm}X)e=p)q(QhRKQ9%;6yH)o~iL2r^_AeWOgBV}n~NeQ+7Vn2b-m=k@PSCS-% zx5wcsA!r}er{Hkl$OLJYY6r#RZz*D%7a4I2{nVk{<`6$_$O|_sZ|~!p%da;Gq{yt< zP+(DCl#7&&J91-17B!*bKSmluJp14B_q%_f{4WiO_(8s6%Ua~&RkW3m!@@0vCIV?M zK2H4tu`S)TTxYSr&;;<6fa@7vwif!Z0M(r58nlx{3UAysX6FYZ7z?m7t{~G!)FY|u zV1jUR52vQP1~l&P#mV2Ke0&!_fR?j5=b!?OwE6}a9Nq5xkl?5-Kzew zgE%=kfLBFKo^$cNEgH>GHMI^(Ce<#3=`)JX*pWf84BDN&uIC{(sYG7-7GQ$PVG{@< zuI)7rd*siBcDIO8cz`nQ0X}7_VN1Q!QY2uBd!H=Fq&U5QV7-8_a{hpJdyN^ z;!dz|K0|1}h?vaX^0KX=sAuy=pZTLt^L@4PQW-%@Xv((POND{Zm+WVAK;qJ0dl1r} z8p(@-drO@644UF)bg{0N8X6fD1%uMbvVRHR>nBciZ#47Y>yAI3C{ycMW>wvw){1+; zan-9nBgFm~hnz1A+o&~n_TcbAaNOMJxfazFfBBNY3mVbU~(|hg&x84Ai*0CmszL^ zNFw$|&`x5PwY}p_&z#QDoH8+|Wi@oNsbT8Rk??7`=6PO4KcdkCPfbA%@!c~2oMH8S z;NaZECNtm#E+W2k=bYep=(sc7Qpg<&EM8Fio-POPG(Q)KA=+L9uRyPSHi4q zJqk+mR2NTQgs`_ZXOqM@lj(!(`v`?-9tdMdVrkfUX#&#+m;}}@dI|NfVcq)JWPB^N z_7YH%Xe7mW!4TQH>KHjCF8WC3~&7fuv#@j$wmd_-Fn=Kt2K=;*;-8rEfz z>xemd_OX^|HldD&&30V?Z6JTeM_)>jz2iSDk3TC#G0etB+!JPIeooTVM|lV%{MoVo z++-AC?i&}E?4t7w*?A>SV*CnVgkxP8CY=D z2x;3xGPTJJ2JoJ#v*_I9S(@*J{3S)Emvr8kcbDG18_tP`-a%r)`X!`dymf=VvO*(; z^%qFK#td0v`JtOH9a1k1=mS^Rg0x1WZp+iYMZlo1;2ND&J?c)pzzdt@T% zZp4q2TT~h_TN0)A;bi^ng^$5+71bIuIDIMO>53GHI6<8p>J@OK8BnKOLs{!4d@&YD z(@PBIkZj8+9+Fd_W->AHbk561o1Oq<9#lI9sn1fSwhxa@Rnvnb9?RLpyTxR|JZ@*& zh;01s9gzA@q20l#9;@SnqdeF{TJ`Og7*OIn9__*C1c2Rx;JI8wn z6bW>)8}2^7r^;XWKj*N38UF$)#TT(b7QHt}Pn`!8eG`7+YtzrLjO`U^eFP_%qE2%mc~ct!v9i% zQ4yyRL>{b+&m0)xHV~OKp8jGA3UNakFREf@r0PZa_ohU+P3*6c>22#_PMp#of{96s zM)&};R<+cN1ieMt$#sN7UK2QUfdBv9qE$;DXEpXu%^#@Q_hqVht^C`mqlU9+3Pn(i z;4X+8G!S1o5$a9cFLNNH$3u!4)yw~XPfRN-{h>dj>KYuOxW|b-JN|icHHJk zta!a+m~zv$R}Vg8kY*YPYE%%u^zkE;t8JPPocQK@1Yl(&7u-XD}V13l&&w^1mL41mfkRX1u$w_r*CIG4(d&hfyw4gN-5bk4VM0 zj^f>g!&B=w_-OdS_B!!{UkyA}IA40}N%(CL)DWd<_#tQy@q@&foQ__yh=_9Vy=m5( zS;eo#v}2Mqit-OArT|23l;4cipZW1G%UK*IG!A@RC1 zJu5b8&z?Fs>T1teOGpOwj;S;Rl5$~Cll9lIdqoF(>A)Ro9Vjq|FghXIGzuyFTMB=i z0l~7yXEE#T5}{FrLBHG``3#UlH0K`m8%SN}mvtB@)qDjIz}6n3kOM55vy@bT_EZ>R zu?f7g|MS4;e|ZlJpkPG0b|KqjDD$n_?I1SLXoj}bK^2iMq%He=FAz86E0tG#{{_yg zXHp#Cpkx^zHA$_{lL>K1Rq9+M((dxe)PBL-R~h=V=CEjnNDKQvW9NLP z*i+NoFJn+~Kig#xx0wdSlwuRADcyd&A)Mg1(QWX#Y@LOnZ;1&xjU-*;@>+MAGjk%7 zQN8GnhVYe>Pt!aU=cOa6T7$HdPKc?WQN;<6wzfi)`xBRI1Irxm(u769V5!s(P0RK{ zYB+9gM)&*GeFS^ioMvDPIoW{_-5g`;sEoPc7){rkZ)ArQp%uT9k1hL^Sje$aTFYXX zebF1ru>82TKw8qsZDo8u?h7;}+~2Ld{1k^qVZi>TZ6!VmVe+Su0D$BHagJmQXeknW?R7cbwFUxhxO@Z$vmaahH6}^3Epj*a`c&7ujiS- zu|%k7W?Gq6y(#0!CfW24?v@Yt+uT+>o@Y-2ctR+gZ`gudZ1bEz;hRS!Dags}i;RU7 zI^DV{-C7?l>Sinudb}gjTGCPzY|WUA40zBfp7EDXZ0hjmipO{rRT?lVhn}LV0a23h zdYoms*J()%z^LrqEW12@5GM|{mJb#$y1eA^X`3A%7~E_gIH?sERI~5ze|z9_JZ?m0 zs##~j4IM7#J39SK2y;l~us*AQ<#oN!pj0c-d_&)h_b&wf9N8*;f9XC>-+|F2VD|j! zj#^H4{Dj8>9hnKkUi?n)zv9{FID=WuACmyaI<=XfLWb#zl7Icr4lrgD3?j2uE)-O* zdjHrd%AR@k&C}A7Vs&rVnRMdsoOl)Ge{&xEOLz4v15;Nprp{pvoG+hR9hf?O1Ks6P z-Y2wQvGF1A!DpjR19?pcYAEwm%$HXVU)wS0U2b%E!;d$w;1UEXYY5*AHY~t%7hZqD z=<$%qJ`QIhkBi1yJZPOiOqXY# z{3(XMg|D-g&F5cPV7HRfr(-i*brr%|bE@wTb@`GH`-qy>qmSgaP4j}zN*~^+plLO` zmJC;P!_{d1EKqe4?P^=W_JxMNf8$=#+;=CX@mNwg+bV)0x|hJs*NA^f|wf^Uzp3a+z&u zz5;jocbm#UX4E;(dy%kXbL>=kQ`qa1fOO}WLO%fo62Z{z$gbeOi~Iv`nx@}Vv_e(j zvsPPQQ0@{E#{7b}peO$4fZ(%IIPm;i)>|d0fNYv+)0IcthKUU)9=Ot4KkGlZSQva^ zp!}Bc`)gKgC!<%m#^2})7hHN8K&Z|bbH%lx(2cmSe~8WmFm5@4aUxjg$T|RD{M)4E zvoT0nKuLnZLWGY88&cBP+2R>}U@E2NL^GLiUwy{FV)Rm61$Y+sibWF;Nj*gxrY==# zM}QF7`vUXIOggA|>7~9>z&68iEM5Ea3%qG%T{49%8Jig1A=-{)y8r$x@>Y#U({3nV zpiPKz^?-L|b7{e(U=4j)R52KhA<2PH^32q>Ua8WSHpyY4P9vN!7+>+yVu2^A3w~G{UBEj}P5p<9v!65j;B8mOybv z+ti3Z%eO!fc1$VLqJEi}+s5_PxI$Ie7<8&mVcQf<6Kr1qVext71r33KfnDhdJ$bsz zHNU>)I3I+2IUlp@R9QBz1Wh!LUm5|I7OxxKA`Tm}Wwr2lrn$9;YDH1h3Kpl_ZYsKR zXVH3;gEmwzc8CKrIo2>M3{s0iM70s5Xzzoo;WVsa0VKgC@bbikUO6~v!M+AdD}N9? z1s5%2etY|v+gpFtDQYUy$){q?D*v!qt7TO(k#wf~BwR1?sbsb8LPZ=P2c{^{FBX(q zv!QzQjj-=SKUpxIc2S>#amK$5g*VPA;IMNr=uA8&veAJoVktD}#Cz#JK2RnMLr356 z#Kw|$joJ#6fslRy*YBm!AZN6I;xOUssnGkfA1^o}06>v70}hKk zD(r{Dg_xA)o@B&a2;JK+^H=|K7;kb)5j6qoOv%zV+D*p7^;gMa5-7mAplJE;{JP>4 zr9UMV9!cLoAj8^7_{NAVm|Orkgr+Rc2?RTf)_WDLUBotZ=51V9N3f$l0|J7d+zN(O zJSzJqgG5*(c0!@w<)3!0=2_84kUAzP>_wwBr`msl`g(|CYBX5xOewebu3z6FEX-*9 z6B>&H-9>AwBsl0#s63-%Y{{~PIZ4|Jr}E{-(O{ba&w8J|7kJnP&^0g#Wf&;NWF<*1*;7BwoCZz7NmD9BCAmSqu@|n zwAoShj2MF~{RSiVyDR{Vb$m>!(MPpyPBi`*ah|5q8uV2Zh8D}^+P;++M-HWphH-BPSBYbn#hL~PCchbWF9?Fz$ugLJ) z;*7gl*J_d$BEmh2@yK0@@hL&!iaXyqlp+a=U+DE&nA;$iYl)#8=l5#DF!90Q=ote@ z%ZpayvI6e=Rm)HhAg>E!EpJfv*c803N8#RA8 zD<|_df%&9hz?%NwFblc@p55M*fS0Zz-!i>hepY(3z0FsEHg^3m$eH~bw-o|y{Lr}MuU_4o`SUL57rT|#IE(juF2Bau4ymd71+k@^@Q~KvNNkF zMRTj|*Yh`#G4~pUD-JX&=-UMQ6tt~xXM$Q~?XnNl5?B`)ZmeN^;g-5Cajfm@vZ2Iw zppOMf=w-hW9?7oU^_Kq#$M|9b>M|jg*!|k8Vyvfe8?fLw>BA*hi2G<-q%+$W+7gD=WKdIxSy8w@0u5ZxG1A76H(Z zXBpBdEEP@)SH2^@?ELi{w#P$$qqFB3Sv&3h4@u6@BPdquSAo3bE)qGiXsE!BugG`6 z95tgS5dLv37H&{x68ad77r+>=^B(lgrI3#bCTMZhTZrTXHqW&RQDJ4H`)%vb<04q| zd|WsrD+6LhMmFqIh9kSZ;zOYD-Croyr9(|h!rkFFehCNYx*f~N39_(}wT;SHfFqh) z*GZKdeBw6-%P9tY%Vlp$F*~9uKbLxDGd!TbKfm@i=!gXIeR}7LFV=G@Lu25)1ukqs zz?kKXd0mskZiSfMSP|i&Viw#H0M2aM4#k|uOL!Yf1mnc62LpD;l&M_CQs@q|n=f!gH@tO*8;mIQxB%!+A&TiY!en^=`Z z2SLJRpQcHI>6ijQ@@43Br_#9&9+|*F{Helz8LOf$Gouvx>AJ*IexEEjMUTEO!`z~> z5~XUOi)-~>#2Z+=(w*1pVr^<&{_dNqL)C)=nh;hL?Bn`RJ0#&|%wQ!$CeX=?er)tMkToAq?pG4Fb z7%u)=M;LeG%}{g!-^DPy#Zx;)*-sG}p#h)pFCJY2>7@XzYaml82i`vWV8>M@oz@-!yvUHg)TtbUdU3Fb~v zN=Wge%IU`KJO;$_PFfhp@fc3D-^jh?f4bB7gYTT&_laHB`w(Efs2b@s@)3}8wcGu+ zliOQ|l(;cZ(koWGBGN<4=DWsIkO3u)|5OR9Xb2-0Wru?b4CLtuKFwsp)HT-9>e;9X z7yLdk96J5Z`9sUi3_c=h$|5i=K1Den?*NtBMGxXY zoG+98>Xzp2`6|l-D9^+xgVvuOTIQ2(ySOhGbMWm4POouH+7`dR z7*cb*m+M^q;)|6wge>aIVNsjQ8uw8QAnEd|{ElthoHrilu8$(`RBY~g?)p3w0i<&i z81}DHOuhn!g)okgAPZg7@K(j*zY!F!b;Ygdm+M#JVbM@htzEdn6`Gu-xmdH%ymGAB zf}@K$(MQN_l$&UIGYn#lZf+1*Mcp_UI=1Sn?}htWm?|{61m*`K`xC`wXt$kNrX_kF z#fWAF>gK*LXwY4ZFLH3f5E@HDE;&VQ(y)uyYj#f75`6>Y*`GoaV)M1!Tbybh<#CW-9c@#H9b-yJ5evmQ1anE^WOEQ%i` z&?AA98)Er4x7}6%apPf;hZ;gA&>pi`KIIV8VP*u73UF9l(vbPgU~}?CWLhu46{Axp zaz3t%5TVf?%KYgmoTBES5nm(N5@$w9mRF~ct7vq+Eg+E(CqdyW#`2LHCvnn{5DG%_ z+QMitbpfk5YALorz!OokN2nZwkYA|-J5oPRi3>hi=As3RHd@2nlN?oZN|)Bsb(27D z^%i&B&=u@&*!~$#jn{uPJBVfL6bkFUZFiXaF}S3u4@2QvV96jh4Kb$SgW4Iq z1{TDv#z>~lP;uiKPh6pRr#-5j66{8aJi zfkTnSJaV3eIDzukWrw^l#$a9)BBH4l_aj!c9wf=oUpM~7tEzyXh;YrWaNmyWn$Or@ zLj1yqi1$a*`5w_n1_=5(k>QYQp}sK-&kRT}%kdzB$B^UiSl=s3M6r?prqA0-14y-L z4Zzts!i3mUqj<|1`)yb-VqJ*xPj8fOe88egvi}fWWH&*VPkJ~X08xIBxy34%p9nKS zmE#YWJ4Knl9(v{l&BOaQ3Br;PHOGI>OP8ubNe?4~5MQbu%*B+<60Y)hluuxar0qb` z5XT>r!%ztoD<1;;Vk}|UaK=&+*cgl=!*y&-#|_h2>-MY)qQ@y4U?#223{*)~9uO(t zX*se4LK|vQxK^(-a`!FWrkH0j3NMJ$(wp?f=9|^<`FhQ)2~bPegBJ(*__ibSLvLS! z#giGhpz)D(MAj^NGxySTqua?-oC?+9?Q5u!YV?RLVumiU{S3=>$iFf9qA$bD8GtuhsdWun1X`>>fn~oGU5I*!~1OG zjxzu7>hX+wYKU+EqZ^f~xY=8m;paY}(|xx1&yC!#CX{(~2h&V~Ql#$(8v;!W{zBgEqjOXp$Dfg>Cocpubwmty7hnxRi_tY{9yk#f?p zkbP@7puRChtAvS}usAq#4IMN%XA~zIhYaE-SwE%_kHH7E`$;#kc}QA`b1h!uTaEs|S9)R*$0w! zwD(TJBebPB(S8QL9^x~@An_Sjhjdyn-PmVuipaP7H;LUK+8LL1XzQwFZTtV&diS^( z^Y?%JPRK55ciCi(Vnx>KKvdF!x225^EF8QcdYJw)bwV6w^|4vfC;dq;n6x)`_)Yu}FY1HblCBNtEzGve7`TpjQ_xrKA=broZx~}VaJ+H&-x<4ZHw$Fid zPN2U=Az(;?<(9jL0gYjwVJkZ3j5GtA`QM<*s zt)}%?5)TxziPmn?d!4&vI>1)hZ)8{HP%Sa2t?jlxk?U&xz zE70LUSs3JE4c!u%Hb|{~8Ud@&XSK%!niAV@V9p()ya74C0~ zuZ|!^8ASn9#%78x#&{%Gqh3dveJ0A$Usz(s(t+;A?i)G%B)vJT_|A%NHXzq1AmA%8 z%CGJvQ*v}Lj^sRJ0!P)LNm>3|cK5L=m|0V9ebntasEKhzi3gJN-whBseZ!6X`2h0R zHdG2WkM#2(IYJp!q+QT2W=?bs93=U->;r{6-Ly*N&Jl*|$=3#mcL-N%V)ZM;850df zkf}=!qEZoMA!p~`Y`w3;PX?_Z$Mb*~r1N5xm(ree=TuHn$@|H2sOhm4-SIFoSXu>JE`+0u^+rs9=6Rn@VE_gPk zUgv!;Ld4GpNQoj@hMpKjKk>T4%)}EZKm&*VBkD8;y<45lp$(a=J~H3@v!MK$g_d(gG9xjm3izV}>%Oytb%$gb<%_ogWpvcGo( z&qefD)d3kqEqqD77hfJJpyn}I0(3p)G6l(j0w{4B30Vy``E0t?dZEr4B4~2B)tZtI zy}`GriUz~R&K{-i&cDf7fQj3mjn_Rgf;R?kL)kwubRof7lyo+bAG4kC=>_6e(I>UF z|Go_6&z))p@QOLe8~1nJy3x-_ZIYJE#e1lX@C>0>jVv|FUkTM3yXjilQsg_m!1idD zbS4~Oj#=?+PJ|Ur-hcwxFwXC7uN33(GX~^j)7aEs#*+FWg2gtZJd-P+Rm;?euJU9A z*^k}?vh#a~yrJZ5ZtY^K|SviaU^8q!|EGEH4Yzmth!7}u>v zs!8^EA4-}2Y`oS9yAnsLEBg03KgIF=&8cAG< zaD6tKZ!4#f=$B;BlVh~zwhIYfhks3~#19VG;6Qz^sO?p04xUYT9T6&B37{p|!xoE^ z%NSbEA46nTzoKFNE+o$I$~GM)wzG*)$I2F&;p$*OS{IB~zsk+%RV=^8tVhJG$1rGE z>`hFp#85pF4a9+TYR;CA84M5K`Kg3C65f9Jz5nSoWLD4bMT(KM)zEAb43k6gs;&m1hx zS=!Knu#TRDo)YK~6qf`cPoyt&g0lTyLYqfBatW!fG*AY-5MPdsG+qTn7v{2Vn>9pF(V5KS^gO4kLGp{6hROq6P~uO#a#qZxDp4E%doWy18Nz8Kb2J z4xS__j9jr^$q5_cc zMQVWGPB<<7Wq!eJ7wo2L{ciRrk^G^p*=7{X6|)H%jGoxeOnUG^@~ye6d<-Hns{b~- zX@tAv26+rMCe$2QM+n6vRM$WpNDmxcIkyV~|4bb8KBIcKGD;_T2X+>ET2241_2^O@ z9EdJUXH%&>ij)L;o~$($1|Xs8K^k2co+KrNzHVEoy{2+EfLHx#3z+n-f;nWR@&RT4 z((wAa(Tep~e2G1DH@wC0M&0ubMHl_|pMQI+V}&`UHXitV|GH0;Ki{tyRr&KG{_w16 z7N75bF>3fS-rQj^pZ;P{HaK>}v2Bi?`qPi-6ejN-6Bn5IMUF}1-l|98K~(Rgiu;iN zv){z}tH9f%%aOKa1?P&Z0p{+g5xzT;;YjH_Ubq0+}Bc!+g%hs-xkz3Znl#S zW=8NE5B@|7fuZIc;pqQ%dEBRd;HRWyVSqrmS{IA4GmWJ z`~~Lt>fpBoHp5eNXXPf^8KsTjElW4<^JLZ=;v~pTd>mh;WwfV3J|PoxZ2>w-{ z4=fzHkp12t;x6OTZL4Qfy#8MRJQS~BL%c3!L|&CZA74}JESiwHm!c;Wz1-dEA&D7} zOL}K>gV%5$IG5nZ6x2*c|CQ?w>r&ByNiAD~pqdjsg2F{6XT?5lv z`kv3GbiQGq?K)XhVwW;%A=wTNmM%()*-Ft#|NbF;fM+%GklWj8!*ayp^cf2ht~(2l zM!i(#-JgnwR2<<`g zjQ9**1_n{dL}*AC=Rp*T(ej|4zUQCN*<3+F6)+$^Im>CIabF03JmsJa7FmuHktco4 zJysFCtpBpq9kPO7coBKSR+d<{3f0|#JgEm3n&Crw7Mw+5Tj#*Z+f9WVyXVTjFIq$- zZ}_10ImNL{M8YD!b>1B>tn0xYFNqNm!?#@1#A4@8Km6QaV;3uiQBX0PogRi;ajc;h z&r9_V6TA*EXdn9{NSO9ot`j#nt)&)1cw8a|w;KC#`wbW# zWjkpyRcORK?cB+Bn@pJ9%x`rTHD%pBh%eFCy$r`d z4>x!Y)ES0W5B1i)wOvp;8FDUCYEL(L==aEW zGNS=LE!YvCS7K={quobu;(__@jteFU-(~~uQKdiU)#}`69A;&!M=fk~7I}-mpJPj6 z>&hG0ARm7sKYD{p&(_A(l*C>6w;u-X7lj9b`IRin7VVDhkDyhRA3C4Loq&FC|Q%{*?Z5ErEy9w*=SJ|%6M zab;p!jHee+4hqW+{%pG`?tko}eq}7#Aj3bz&Eg`r&hLZtG3TSedF^uSIHlsQ&D6G7 zSYWtaV_AjS00H5vRRna#<$tdw*$zqMykvE|esvPLoZZWtmo~QDe9ocxdXB+8kPY3v zh6M~07rhteznvLDUoTt{=(Eofzw_9edxgJay;8&p?rFHc7@p;n*i2N+0p2?#?$t`3 zN`kJC-47fu`f=Pigzhx`{$)_$PX8Dlf;*qi!3>B$&gs7Z%`4%EZHA1|G~F< zOEIKZ7Ld7Dl61bPe;e^ySI&roMLP(3?cmR#bZ9hq2%Xk)O^9%JY%;!*Zg`4pw$XEC zn=wp9l4Q1wIDn+6FsmOW^ow@es;8p=bMrk^f@`b0UHs~SYd;|9(sO~C% zfj3cRi)n|5AF+IUPu_NasxX#VjB1qlrLinn)S=^~CCq(oEUR9v1q7x-1LoUO;XBmk z5-@jD9CkkAiPb^t3H&L{kKVh)ZJV2N&Z~M^tCrBTuSC37119yK0%_~N7C4)+M#^|E zOVgtMS5U_0mC)eODcsx6F66~ze~_eHBq@` znlXn%Al~$(;aTq;d3Ym(?#%=;+18!KqWwgm6U_XH@Z)`@brofED8=5{*<)YPT7M`F z)3nf!1&=N|WL!;l>F93J?4tgC3~q+{)l5lz7gtqQ)qhJHKLKmlF7hBUZ7O`BY{o8^ z?;u{u15GI0;PjRPm?xLRQQG0+Ia)V`#Kak!PyW0w{qFU> zaC7g;)3023okRG=uL|Um^VGi>T-*fi_wdr#dZLA2ao=1bz;p1r1J(OQlSeIv7aV5D zs9rl+XccjUa2g|(`%1Ow^XtL);u!UvApZU+6zOTbF=a8SI&p(X?F+`DRYD@v)w`wr zYKBPQH@Z2N;Th~#O}N1uxH-m-CSh}Jbg9a_iN=T)``B-PLL9ODIj232m<-|D@rlI- z1Qnm;OOrsNq>BkOe8+XqE^jWqsbxgjUFyhrxvyv)wpe(@6QsedaK)CLW67y_P*o~= zE6i20kVsUtruIu2B)T<`q8EpyZ=3&iA(80bi(gC@rt$AH{2athY`eTOkdOIozdT^X zT0fb^mNAz8Z)_3{dr=mTa-H=J=iu=ybZWN#*`!m>D-I|Mw(O~`&uTzl7x>|!C= zUQ5`HLcu)r40CLL*zp!ut|@Cerr_c9N`_PUw9J+zf+Q)-Hw5?GgrzHquhLz{O02b1aL9%Q3I1;=}(=*BsozQmqzq{&F+s~ve>rb*_OYapc^UII}xV( ziupZ0ICk3Im7nRBy9$gzHiEDhL9*>u*dE?m@yj#fwa$$`r3o+d8CFCkf2#LHtDXzj{C&_UUIEMHRkc~M4Lh7S9j+P%?$}_QEswNkem3Gx zP{`Yi`wK$ny;JTczBvDs*zMxPy3v&MnVD=AaXQ26{R#gF&lT%C*AdY!c|BW(vBVrk zv<}<%74EgP)k*ln(L)6dMhbaD!5_en7xt#bz7i(A7DXny_TF)T#J zkmgm~HiMU=>D^aYXYrQcu4J6}r7t(lq|YA6ONTtnhbO1ah@sUD1x*BYTm4`y(ZpJo zxGp`nT?8jyo~1?kumY4Z0_6M-#^r|!jCVZI_-TeWv?aTM%(X-iWN&^tku`0jN!YO# zSv_7IwjUJTm7C^KTXTOi9@l0JH~5#9ZGIo;`>E~idUtvP5k=wQfM~_ntnzYTaIS%d zIqh1)3%e6%yCB4cQ|H!tTIofMF-u91Dy{H>G~NpF_s3cYFIDZ2-nW8^Foik`omO*A zYNj@rLvN{D;m7ahpIgChaK6|!z3N7E+{L=bsR;~ouCelhiwu$F-tnTXh|{nue8GS9 zrEWbXlm{nmdnh;D04P*(vwoezSkko^u-w0ZrieFyrbXX&2Ex>ndzCu*w?MTNWov5h z2T8iaf4PhsbQ{YOxR+1fd4^T<13*q%Z0~sO4S8`NZZO0}FqeeFq8~e=c}# z(fG@pvszSt%TiHO&i4ykzX3NBmd+n*A$93o0b19kI>k~%HUqNXTiPE8gLe>1opvDp z+p_Pk2&=aw5TjI=cjui*zx)NUSD~ECt+1KkI6hYzP69ic;}YOf_gXNIl0Gq$?GfZ+ zHP4#g5s%XDxD>#Xl|DUeHMexeg1r{VIMK1hxi9tm%hs5U1rAuxz=NN*)}r$Xypbf) zii>ee=25&x<;4Z3-jFXTXz(ekn`r^%GoBpX_@QP-VZ^xVuAbe2cN4+Y>)pARlXa`3 z;-GvM(e9#wb=(Iv!%^I)bXOubu))c*?Gv~KLQ%zD-*}D|%K1s#um}rxVz51PC!aKJ zR*a!+{Bjdh)zJnO8d{@@KV&n>am^4lAnz#B?Gp$xfYFtS#Bc5B<7L)W@7Xz$Qq7eW ziK~{82vYHcNnXte8@Ho5c1S%x8So!Vn-zXnH_T8(zH0IiZ$nZQ?7sLgU%kO#XxYwH zqT(;oetg2v{oll1)5GT2>QKggSxh3RYdefkwaN-_mWn_spm9y@QtsrjKxWXmlOs=T zbn-kjHZdO=l5LO9pGFeFtaq{J=+K>Hk1zQ^uV;SgheF%TKZ{~rnkQ9=QpS9dy zF-x@*k1N#PO4j;GlZmH$VgtTq@VnSe{L;4Sc3-%L58!#@3Xn{&nT^e%_gk2br+7Oa z&sfl=WH(0_8#^5#_m-WXbl>C(GMFGmCm+$|w5aFGr@*Mq7eKRo5Q49*Jpsx?Eqv-p zLV7OOB=b6!S@|%?E$V1X4|b*OZRmVzCP zf*d#4n6!QkMWZB3YmRKz{z=Q=g%P_ip=4r~t(I#cYH6?@7N zDwvx`;%A;244!QBWwOnF@aK})tcuo(VsmJ(g?Y7T02KGde^7-KI`*A9^Ja$O51nt6 zBBWf2H`sv~mVXahO~S$JYnl9~>V){^ycBKI3DpQPp3ah8M9z?`AP(8QhkpN=doRxa z-(MLDOjVZsW8L3@94fz%T>|x^DOIn{y?pywXWv6Ga%xPsZOY$uOsFI*&pLBcyXb!) z`9NudmO-l#1TIxXli=0?)$p~o7sYkXQN*`XDHV5{a$auPcLqCe5zY;sXWu(uZy4EW zVRj77vH4qzN>ze|ROY~`vm@F+hCktzyXbiAaMpKDkHhFkx~hMw?26NNNR7h<*{G_h z{<}Ce_RV4cI>wGFkfLa%6jP8_eGPBif#d}pe@5KwXO`wV5$SOUr6|>D4-hi>qot;X z4~Gn*rm3^7ccGzh&LFbZk`;qH5S!Qpaf7`OO_VMLa}@T6i|+o8*`}u16)Umz;7IP- zz5{K3C422UTjp$F?eP$Ek0?kv6R-{N%(*1>~DsGWE4T#N<#N zWbUL4Tc8GAU>t_4xRbYAy52sGw1eI&Gsvr&q2|2?OHD)Q(jww@P+El6iZYzATE*k( z3odLNUB48%LV|yrl+mq82rhBHXm{RMyMYw|x+62czhF6}spOS{iwFG=d?m?&_fu%O z*2L&LZ;Erpg+C+cqu2fH)t=lDF%4wMiJN8|2D(YP4pcv9Q)g?q z6Oe~w91taa;b|3}dmgTLEXgX@7wJ{qjdt&xb;qkc{*WeS%LF_(ub&0|s)B9yE{9{k zyJlsqI}9>Y>Swh(t)UR)%J2H6Rl82KJiRwXwMXC_AEAwfl+XLUtZ9(4%gRwYOq@JS z!6?Us-L{z5+a-^i< z!tiv}L`1r-tJ?aI5~Wnhn@l|SVU`UQQ5h6ca^N@p{^no-$+{A%vyY@!WVntK57rSB zG)h=~8qgBG*{dPy_}%S!*Qdi}KWxMLHzp8i$60@V`M7iXVb@_jKI$^eTx6yf;K(4h zgN>guRzTMV0r7cXeScyU#$rSV9lLw$TrFXlbo0rq)(lt2B~|rKALJAodaY27P_Lm- z57=-!y1>^oE92lPtiad9*{le`IYJV}X4lr%3ghh828nOG-L=0Zmi?%xzYAQE6Nlgz zIaWmpG|y&djn%oOq5vdeaGE73zCGkb`6?kwaf!#RX^H*J?0g5^Q6>8L8L< zmlI+%wtX5NK{wtXZbTA{BvE4O!kH+Ey|r?^<82%^$Lb@$T0#CdjO;mmNzC%Ce6+){ zaAC~m6rhpa&kvlBGdc;u+rcfSbamw!1l<~V9MW@NP3LnARM?N+Kcv+}`M-nmSDqxl zXi>?vx~bl-a@QTtcRWn})p6p95r+3lrTr0V6Ghy}0McU?ki3`Rr#;26+?x6<=xL_h zXZ7PE1Hu#QlMOx7Z%(xB5+t>pkv7Fcj21fF;E7G2Qg-ptK_u-+Wr}| zrv13oxD~q|Zcnz1lL|$-dn#|cXvfwXIukt*B(DKbzw~QQ4>DjjV@g{0dqQ=2xsm*` zh~q7NNVZXQYgk&#<8S66Ll|0qsN(*f6`4lLko`{5?Y!CL+pbi_}f~7uwZ|#6jOr!0lkYU&^Y%?eIo-=lI8?wfAOX z;$v0v458V@E4(NxtFh3&Y4E@^JVSc+@u5`)C3Dd~zNuW5roTkgVUD<3(M^ynyI>~C0l%t_q< z{f8UOQU*VQ1&v=1uU5Z{8=UIuToGm)aYCw$vQ=jUnH(XNe9ovSe1Yw7dI?!}Th@xF zORbXbRNq2mOX=R@T0K3dvH5}1zA1HIru=riE2!7ja32y^&Y+Whk;s`nYh%4n=uQ}* z-;W|ZwIl|c?voeXwlBy4%9{-&Td?{ail@nkP`dpo1a82IyU{po0i0J}P*O`FVu2XS zZXPhBq<)@jtNe6l*HNUTsli+RqAueJhAM2`wV*5@>WP07k9zWc+9c>iz{83BQ=hqn=4j7)S`Mn!^XGFPRR>SnDpfJ!1Yhi7de!%wpj75o#X|m1ZRBr-AS`V z_uqbpu5U>-r}w8U z_d4V^Bg&Q!xrKI^bsSosL@2vt5|SH@Ntebr#$0e|CBxXnUdDZ4h|GOjv!n^|b_PHV z1@)CLzW2C+Xz2tna{^ciezSbj+)9Z8Tm26=(cx>v6?aN9f{#8d`O;2bkx5K5wz@s9 zq1Zg&T=_CoKBl^kdv@#+&pPq}jAse3Zn1{0oD(owg*M}m9qDAxuC|j zxx~UnATT!H+yRI5e&Rm;9FeSHJd+Rp4mEW`&UsdYwQ}N@ z+CRfW_xq8tSBh!76F1DbLZX(<2v%$7je0dt_GMN5lTU`yYCO=G^*+9RybgOzc?AJSFF3bO_1Aen60U`nyG`gq$v>LJmWbwR6ORr)O)7Sp?!G z$hXf5n0_Vbg%-v6`9<<8{2tDecNwP~YM#Id$6~9; z!|{b?2t%RJbR9AnjTw2-3+IlOSeB?;44%=bC+0tAm4!YJ5bRwZU1Z~M@I^WnVOPRv z^T-`qRAGUy!J{uz_I4AMkv_|pCNT65xtE)td{31$=E@_1th5=nyD%HB-ckS3Sslb! zyrjp|J)cJIZ+le_fBx=4P~D(1_3gZ$e$|S;OL}Kb{}8i0gx7)ML7?78Dqq+|baTuP zb95)Qi?f>XhIHh1zqxh+)qC)djZn4y^rl^k}b+DD!1L z&^4h`P-4&1bG7v|5ziSM80mMEQ56ytY(ia_-lV1--9KK_=kv1;rkgm&XPyFrQAYpH zPZ{_Y3K6man(xvN41(5~QL1s@S&5XtbBvA!27w zHa?9E+cn?nV@hHgJ!@y$jg|9wanb))!J8s4zoN4lj<@|>iqe6Af)Tbne0$N%LCL8% zTegvoJVojFLJW5OYNyu1=d5dFvUKH?A5~JhQPfP*-@_yc(Ic`5Qwz2!c*0+Z(=GvRR8kLqw6OcJxqspkxDc9;N?=5of?duXim@5B03k08m_vtr|9+5=jakF>*#1&0Gc6DZYF<=kTh z7a!7>zc@LP3Za7rqeOQf_B*GRYIk)mVLIRtWBC@Aqn1xelKe_X)&rVAR7N)k!{ua> z1#|@_Ivy{qTT+9!Ira0x>!j~4+mBAp0nd=X4MD_1!tq1K=1#!34z&XA1+>~7K-Wtr zs=>GguWnHC&p&|FJ=2l)jQ4NJ0AV`a)vls(0)MIj8iUH0 z*Nm|FFg`@{D|cV~iobEkYK7O~!`jq453c>){w;M<(eYQF^wj=aBR4XxzstA@`FwiQ zm5Qvh!N`r#sQ^r{leKe3AUH)LZAORno{dt!VTudfTIaz+`xOgDE3Urh>snLWP*ic! z;*}0ak$8xuk|+IWs#v@LAqt@RFYaLB!4(Hb3(xhgUeIPE>-u#+6_WA40G~VXNS+OV zuRMB9U!};Zcwvow#b@Afj^D`Y;;;9d`zcF{m+h)u(db`k>lQfv>1;GLy{8_Hw|M@P zLz6#rm}FOJ4s<`^+CM~;Ja>6ZU!-S^BEJi z=sQOl5|!GM1ji2UTnGFeQI(Y@AS7_wbj(4L(|x-*D4f-rhRfZ1Z4b z=uB&Qq@9|;+WvHiQuV2U{27unps89>|Z^nO&;xN zWbl!&2!66l7sE{VoosO=R^Fw&_|-0wE8*|Nik^sH&Xu7dhinb! zjAKCSza8$sj_&>C#pe3h>1Xu{w%boi8Y7(CeYh00c|^s>NnKY9$;k6e1=!{rtcPE7 zdTG)->e=tY=DltF zJWteev)N>rf*M%;#0bQ02*rJ&!UH|;tSQ5vujxxHImp|>Nk7`?FmuoL)i1wm|G~8X z)PXmfwc6xAokg6icVGnN@j>UvyNs*S1p)n)f7%VCmiU+l58pDf?wctt!*Bk)XytHM zCksCQXC-g=bf=YTMs6GKy3}IJ@E!U;SS-XVy~@BOGJ3Ie6iO;uH$a#t&ZK`I_9syY+g-Mx*#5QBUcPf76am z(D_vyRT^?^U{BDSCmD$?H@Ajp(b{-t&W;-N?XOtHwSFz1g$++qHo7=b=qTr)xviq# zyw2`~Dcmx}D{G8UwL0ou9UOS@LfPiD^Y3p5Ui{7N%+2vI>Tk<_J$)AC){vuYbaTSl z`!c2Avvii+DN*stRB5H~55`U4@@$FSsU_HyQ@3G4-XU8>}is_mk#7&KHGehUCsw;tM>FbR~7ZkL1&p8 z=YWb0JRk=pkcbcM`Y}2xDIwvyL+iic|1rG%a?-oEtznK?|Bm-KODQbg{wYs+0UA8L z-hO$PWV8V4abmq0Un z%tts*bR&C%Pe~(JpcYB6Ddljzx{16nE!njJlVH-6798U`>U$`Y4Js1((kZ>e-IQT}D}O zxp`44Jn6b4hm75`rs2{F(imKL=B4t*NMY{9aMNeDGWY9Wu@6d@t3^V8x2ATZXa}a0 zaDG7?zQuN!uzK(2(KcU5^Uk#uJ2sPn!1!>|?;?;O7u#Zp!NC1<7xd{pd|YQs!uSq$ zrVlPK!kc9B$i|-LBPrl`#XT^8p%8U;a!Xq|`nq!8U+RZ_p^pCs-&;3Kk+2r`Ex!&w zw3AyKESjLXOxT7@LVt^N6*VBMmPam_tVKT{H}h!?i*Ed!eYoVOE4D&L7p3R7BmdoT z9_K*gF+-kzDP+e+56zAEe=8IHh_&c%v&YLo$`Fsv!OaRR>xadA37U+<=F8PWG-(g) zssECq9M8a)6mzPeE{{z-`%g?#*g$`sa-{{%=QW$I_{KjQtI*$ON$$C>Lw6Fz|1a$L zbm8s(yj=G2=;kXgl~P9Am|856VqojLtv7ABmazZ(3?fABH8^p1v zG`PnH|8KNfZZF5H;YjmI0y)(}J~mqDfSNxUhh~OL+q?vG>WA3`2PE1xO`c0B4qTCp zn7v%!ZPFK}Q9L)=#}-DsxN7U!5qxlpRLt9(9W#18{Ux{7N>-t{>$;f_kl^e-BUXy+ zaJrWF7i-ZHBQrm(6~RYaLTm~A;-mllLKNjBYb0?rbY4ze&oX^O6v;t3ScBwK3z zfdU@zV-*k)6;_d;{7o7F>ksAB%4^0_3A=li-whUJ{Ir^VV#U4x$L#II-qMEPrNVK4 zBZ?G-v~H{J8Z4g8Uas;@!qXDB(1w$JsVA*rquJ%K(cejjqvMbfECS0KvU)|!;~Ac> zbjMQs|By}a`X2?a$n6?z*F0on2+?V1Rv1wk8ODcG*>{mWNdr2!n7tQQa!5wY zS!t7NER<$3*FUj16|QO3hF7{DQT%Io)cS{!^_Na6*`*7$CG$x+IzeoEh^V$2F6?4V zg?d3i=^-cWSDjaZsJiPHU38JyB)>^L@?eNK97 zSdBb~LEJN9V*l%ka+Jg{`0KEw-v272l6qQicf@KG;DQEq>wvoJig2i$a=3-fGCzZc z>gWv3>UBaIl{d465^vA!yegOjnQm5ZA#_4#QgY3!$ zeJTSwMSFU_l--2c<&mO1WfVvhaFF}PR_0Aq<`WN`5~Ng~0GWsw zdF-0juy>gA$b4p(oyOzQQEO^Fp)N~f(Mm}X9otxFk``b-Q-uD1Bd*J zBM;63@8*~QG27vYX2}UaOd$g?oOALV8|>>BYC<6lc(Y!R!N6RZGW;6>sy5k_#JjZJ zuvbSIKz3KJKCNKm)3;ZUQzRdo8H~k_4m5;WoxU;`o;4iXD$(J-vFkAR?>mjWGWnD% zTm`wn3F3d%ARn+h@ob1*zcy_R|H{)V>Yu@&4|93MbjBh4E@rew)DLN>Vu;CPl0LJh zA>mH^0Ox1O-0}DJn;l!vr2v=XQy{nSzvM|DV3#GM>3|nTys}3a#vKX!R%nIJ*I|BF zs2vQ}r`E&siNzq3JoBhV`^S2eV4bn28dGevUui0SK)v>#d8dK zaG6jG#NLF=R$w%{N=W*qb2Q-nZ6IR>jARESz_x@GO7#iO8)KY6K;i~6bB28QeE*-l1;s(;FpTW|)-l@4LHo!u{*N-3A z2!>z;R05iiTHl^F-9dT_@Cn^HBwIX>&G$IDBh~5EQYzhC&cY}5nqjBj;6Jl5wVc-&CTajm zG9Ue?7vTn2Fix8uwjdQW5V=(H)oe@;;?*l-E_M}1KP9JM@af*nken%GRV5Euf^V~N zJ~urbr?twm2yjz~igP~r{eH#YQhV6% zCu8@wzJ^1jVu{nhiAVRu$2ZKQ*+umh7sw;6CWDOPo~%&4gKFi3=k{6xF?H7oN>>D? zw?r{R8xgU@wZQGABTtyib)`_5@O{PDodO%YFx2`CpQVRC%0t`E8@O?qvHWR zN(Z7+jA~!DJ{L;PuIbw(`CE-$&6aupWJ&cF_ZzoH>5o(#A-6rKY@9JfhJ`VK87+at z3KtU-h^UJc5g#3kl0QzNbB-!YT!t{4E(?9N6y4r$>o-2wNA#ujoU|XL97i1S5VwPR zY-Ir&E#&-{36)qKJnJEU3u~oHeu7x{c$r)Qon$_|zdj@cfpg?qvMJy{qyk(n$H=rnjZ zBU;O5IT7pyWr?hR#rmG>>PXP;{D+ZU>~kwwAM7AP5AxFI^{mJo!XeenA7a+py+e<|z@I5V79Y$F?!kd2(Xjkm#qA{vePgt~Pn-8+Q zh9YA-Bn&*ZShmLhG%f3LC_ zYc~=Sb6ZJ{&bz5SqRR6_moa1FE-gM8cIftC7Bj*CI~DuVK}LXtO`6zjCf+^u3pmSh zwek)P1oO|B2{Ky2`C`N`S^Iax*m1J?NavFf&H_h*KcoV}=)V7@cP7sZlnxp3l<*_i zATxRbzs=FlO~6qIoH}&vd%#q9QNHpXtw#gEc^J+V2gVolv04jtyZhRviLfq6lNTWVKBeWUM&??~Y7*4h9pR6Cy9A}kj0m@q{SL2@w-u^cl4=2) zQnm=T}L_NykoFyI_z0U~B*hT&V>f!9Ql%V6kLg5ooeLPdzi5w2mwtS)OHe#y^SIxi|syxnS=(Jkx?S} znBXm^84Ukjs&>2l--#GLg?mP^O`%Z|kw3hhCPUl1iLBr@P}$(ZB>$@#auzz}!#o^) z6cMLT3y>Cv^haDi^K-)OMgMHKVPfb!<7i~bY?k$a=?On2m(6{|1};RYNnV})fg~v6 zF;zelpGYiM|#_#me&=2j> zBb?QJMFLTrQ&-eB#5t&;Y_lK}Zw%m}bbo=P=8Q;E@3{6eg7Jo$Ou9}Lxg`02FUe11 zx%WPjDljJk(MCFwzHgzHi0-{eQN??Y%g0aghm*b5m=(SMVF+RtQbhqK8=J>kQo1L| zW|Beh@m0Go1uvAd3ik<>R={Ytrp%%H3%Siia+~i2 zrH9liV6ltAwkZ>sn29rGt0`sk9|kg2@{ruGG1tdeZB;g=?`86ayfY-4K)TZ%Y<2w5 zRv*!9BB^LZcju9xG>4t68?M;E4*vraXYLN;*7!; ztTVti>9bR~5T#Q|(&{Mys>K+v(_)UoRxAzK>z`pX*U$wN24hCD)wEX8`!*ZHvq&C{ z$^HvB<7Xu+!6qd;HDD1Qh@uK6bxL(Y4__9p-huxh??$Hoo~TBXaLIeZ!+f95%4B9p zuH}a^F+&}LgckH??IopXJ&^G~rpFT*YT@_zb2U3vQo|zRS+L7gGxG1Bl79~z`u8$6 z#ZJv$%9T$Kv%)BIvO>255J)OVBf0>^dy+%@5>OgP?9rs+G)vSKqlbc-HMOo0?%Fo? zM8AI^cD7ApXAwj8`Z-4G{zK$-Fc4^)*!m~yMpd8o$lnGbuo$Xq2%SLrC=>8($}L@^ z9Znk<_p_9nhA`L0l)U7K_65vSA(};npnUPlFjAXR=%@=ZLZ?oaZPBx#le}{EbMtnP zIp~l^o7XKb`VRmNB?7?FMjBV7XC=aIyzKfLwlF2b&~!~ zf2s$D7)Ote&%p=aZyczP2Uim@tk}cmt#Jqk6BO-` zS&<^UHk`821!|}!tL=_A=fm2eWJizlT2eq7MsX6}p@b{kiX?||DHtsCacub@y>zp= zfWAoN&_w1~M=cTrh>A77v!sE^t1#(@aH2O6WK4bUV)@m>YRKbcei%-+L=~*GEz?&ofKCMNQnxH4Vt&^KALPKMjvZxL*q_CNobNi1l z9f^}>bMF_jW#leAb$N%Cj6k|Xk8H0tsSz~vZf6=MD9&%z@~bCFsEY`1MJL{7pwM~z z?Cth*0(fP5E`W{FJ0#WgSezMAo|*e2_xELpPESg!{h>KSmsH!u8vhPuxfh#gaoc;aA(Bc!ww!4uU03SoYz8uP#uRHL8 z%cD0FW7qwOTqXQabNM%z95|{CY${8S_m zNsc)pcIqZ zH|1hWG>XYN`Q9Y=Va&dQkGZ@lgrVg=A$xT~{#6H8l=I{lymMQgcKL*l@1&9mk0CZir-EP{oSK=V%g=K z2}*Pp<3pccV1#0p#pm41aRAVTZe$seL@@0a#6`0bAE(>;1FlrW#Q|!WLAbXP+37rgw(i|XqGQc zP_o;(IGyzBgI25|jVwKx3z1b`KDR^JPdcm}n|A{8Rc%%#rS48FJkwK{NdZ~EiJw7? zw+OIwr$dx3HyjV=uZ>~rq>B0HM33Xh;~v2`6II+GpbA2}}#f6_CVvX~C9WU)&AHu=qIQ}q*My^J7P ziT{$RJGy_Oh0w_fM|;T230&%*)t(3w<*L`jYuIg_kc9TBLskzi1N$F@;I(>`3z?qk zvO$2hCOg@i=Pa+O|BX3OI_{!Npq=e7o0%BTG9TckIE}$-yD_!jnY(d%-#m2&G3x$< zyIZ&8H&NN15w;L7SRIvPjH)IY_9&Hzcy{fJ3#LZdYA!!YI(pXQzynsFyY<*M5(RNc z5?4X_JLC^KXs)}4<6Mjg;9lH2cL(WMgz4cpVx%Kcg!v3Ooss5>B5wa%`vtRY^(G%m zc2nb$x+GGs6UH#QFA<-djyVN(>JXu%Tr6$U+db}|wx~bE)}G#v_F1cMK3F+Rb};%McodAwWQ@SV zGYO>;!W742r9wY+79$Hibons=DIMZ>eit$T=1>13_YH!m7m42N%#luTKJTPPb!+A* zb@C@mK2}UWd(m(gX257s2ComCOQ#V@Z^j-#T0N`uQl{cj-joRpuC*V9m@3)ptJs_Yzj=ntx)=Z-l2n(vluGY5(^GGtT$t zqP$5DK3BFHSBRIZ0YB7p0tN+8YKVxsONIgjki#bJF`3Ne4^!tkPG)0UdfPeC1_s!U zJbg~ytthG_-k$VzQL5Ee*>~OZ2B+X=_%sCFmse*ZUzLTKMxux>QnlK1V~z8aB}Sxg z!JXY{%tP>T##AyrH}=VG@kUCG6pQdGCe>cUizR2DE*=XKh^`q*wZba5wK8vT5&IjZ zFHuA%&8{z9MK_=8^30*8mH3N-)U>G5N@k8QjuqH4s6BOub3EW8ymbW&8|`_RM~V?% z|HaH-k$WavR;yo8Ab&Lso23u^w8u#G-Z^SK;588u`qe%QPOG>N+rX#&v>G{(RZ+cN z>+C=v&My`YojycH#Wkr>SYllg(i5SE?X98$!1h(uFWc_Rd&oJptZPJwOZ_%A^c{KA z#y*BBV*{B2ll=4DX*p1$p3raS60%Tl21r)i4C>h^f~l&QhoCdU9@z~a35z1*WW%3W z$%>^JPLQ7qc^QK0H>=!^%8OBlb(o7wo@#W{PS$^aGF>HADls*mqASoGMs0fh?0S`5 zn@1RPts-N{Enw6sUA6EPhIYUXzJi;lHo+4JdcGV2(U3boPJoV}A=>TlB7IdWHY22m zoHrEyk)t#Otwb6h6Eq{$9`gD*Q7VxUIhDzPYrS)haTlu`{84~WYLoogvGfGb=ur%X zQSjx=-j+WrI*z?I)$?>bPLforyb_Du$cgKdmL#Gaa1c(=pJurxC6n!S(qFzYrtl^t()!{)FUUG z!er(pmR7m{Y5+-bGmT6_BKD2@t_xp27d1r6pc=ZtYh6=2TZVHyWo#AGuSw%9NXU3N z_H4OVHBlrqlTh`G<&hb{qF6R;$$BsETV9LMHcmLAP)>Y=1QiNbQHpVg8bKulgUAU; z`OT)kp4^L6Vkj=aXy9uC;c2zw#`Q6A@9k`H5UM6Uoe!?W|i}j3R(C&qdqnZkDD4cpe4`?xG3?-aQ$VmIKyKRf| z&U%k#uH-px5cD)N3VcS4fn+d3j~;jtBESAJL?HDGL$as62K`W{vwNAirzGp7kX z@|FialDCq5?v27Mx=9ojg~?;n`~1}^9sP2bpqkJTm!({LG-2r8oCQnlAeN}w%B&L2 zfyRBwZ**ocs|=|o*zbXpdLma;Z#`sm>@_) zdmm%xs=egyGd6dfyk{qSpw^Lr3BB8gWLSeB$EeP@)LhYWv z{{db8!=x4|z@-{s+Y4hp*I%nygFIMD{2`QsS(k z9g2Hr$zjVbqVQjx5vQOVrbs*VQ$5dw%L7pu1N;f|6~qU|d1oE5YJ61t%m(rhP~)II zWX}_W3O?%@N74Tfut=1p5X5=+kgLZfJZt-H_I3LRG|);Lf+v!kqJA@Mlin`;GxJeZ zLjy=Un>Hfr8Te5dh&g_2mIk7ybXER_adzk4i0p)CHbLxwOzk6b-LcgiKfD zbbS&jK>?Nf`c$52qDzWNfLEF;3oEo7g77JNR3g+ec2^Ntl>}XcRpJmlzVG+UXBVD+ zpFb>iXJ_Vpz23*nXGYk<43-X7Nu#FL)6|`lgyXpJd4>>JgMzPHExykJX|5iN2ZkZ? zjad+dJr?jB1`5)6K!VncNmOeg zz?SnYl!H#nl>KbMV-UgVDT^?R4i{Vkw9#HTgV_ScKzuTkMM%#=iOVuL=^nfeB^dsx zd+ee=uSTnZ?cKj4MkE!*EqoxVs_dU|a(!?NCeftF7n$pS9pQPI5uTwFE<1nelk@bP z5~9St81V9LX}Z{};00%*C>f%P_O=X4bp>Ny+DZVPnc{~1o2fZMM>;3ic@a&Gn4E?k zC4?J$y}nz#L0mqdjW>7;3?oP#R+|hTUg#?+Z5EgB>+fZ4jx4c-9kcG~O&u`@WtoMt za|4yryxs%!*By_qk{-o5L++I+DiJ@~95!6w4*%1IHX4SI(~mIQ<&SI2etmzSM(A{4 zCRkQ7yp6ax?ijqHl?57%2s$!+;wYHHrzrB-r%J6$6Ar_P>84?_*4RAN z)`uWcy^Fe~6=zuNKI5D6kkP?t8-Fo46u}E{$Wi) z*H_B^d;cJCLpuU_Leq)OvNFqhBRR_8BJtr|I4w;Xz8~u@hK?C|i)-><%rokf^PAu( zFp}iwVyGvb^p7Euf5IU~;SkGk2-r{b4+H6$ZychX4xyZrq4|D;ZwhZ@n0Bmjh&PZ5 z=M}hERV2hmKxN9Ee^>pdV+ruZ^9z*8b_qm#%OOjE;n?#+2hKzS4Nl)johMEq9ld`7 zOnzreZcH~^l?93D_1{9*ot+)AZEf3 zZRJa+U+b;>m(T}a7-;t``jv=J(YT@F@MVje-r|&ziaI5RSa1N0l_gkNo&wHVh5ybz z21noK4s;w{8V}j`s5cX)gMY#s+`Z5n&ons&t%p#5Ad6uaJ~)OVI4h!7+}6R94CLg?gEalwvTyIKNkW8e)~2?AOa>Ov8rDLf=0PLYZn zbd<8&<|fW1*EF;6fxm_UyL2jg11L|}`F`DIA2Kthvy4zBFWj8-&+vmOlB3j+2Vxn1Qzit-IKdS7Wwiz*)C6o6{XYwBVhYKJ>%9 z=anf{pD}CKbz*eRd*Sha10AU}JE;b2@gDN!gH>pY$}yNCi)D4DC{CGYRNhMnd|c*A zc!B!ry;~qs`Xr|A%E{YE9RWdW)dFk{tX+ZS+;GI#&}g6{rOucnE{k!G?zXQ=H=(@p z%Pe&Kn068^g#~2?dV(pr!h$-K{ooC%w*jL0&1@nX2rur79fzJVGIq&15x6=8X;O+y zqoix8q^6*}urt~e7L>{J#AbkhQVYtopaks7&{y^rL->+y`$kd#tzbOd_^^_xR8eVAmYChZwA!H!{snw(c`d}BirG4jxAOi z_+R>H!}|^K*#y)`Td0W0KqKAXH~NF*tLbfXtaUm9ia(Y|gJ! zG?3Qe>XCg_rBJE{n6Pk6`wfv^>WWf1a;h!4war)NWO5d|cPPW*1tE%}Veo1w!OW>y z{Nky@^7Cm-g1ILgIft4Up$xziz46iQsJET==U_-dakl~) zT5aM((3Qr#jSfhr&VT|Xk(&fh#VH~orXc3uq5X_B5!4fmPM(NSYFtXc7Q0_TY}HxQ z&)p+Ty|g#UVMIeX{k%eF()yI2Y5R=-?{mW&J}?`u0-Ya8v@;EC-ViL?>VaeAVep5q zLv)Bk@M;J1`L{Jk6eAs`>ybD*YcQbyQlsGGOn_+Y7w;%`uY-Js&wlnJyfPm z@qQt75xO&U2q!qw9Z}ihbpcJK{sRp0C2eyU-u04om=sr;2X$0=6fPzZ?OKdulnYG; z*s5^Cv#UTT+7$fCFc{OyN&VluQqmQ!=t{}TKkI$O;BQSnLFY|Pi>5}(##l+ruWnNN zsIsu2LT*s6U3Q|aeA)D6PlAof6MsAwv!1c&*!fVbhmqGH1y*YcjpaTt8F{s+c_(cE zTkhaWNR0U6OvN>z@NvJ$Dq%w;4MDu}0dJCpJ+x3m@B0I4L6bovDlw&mXk7l5uSJnb zwR@(m#bdB(G^A5nVl9`v@P-$!XNkAW5f(z=c*1^AQjVZ1XDOj^$VE$|+g28AE-06G zet?qGwX-&`feiC6Go#1Vx_D!?6{9maf0gpr>IX>t_nK;Z;A*13Z4&CjBoSWv2N*nv z(3RDndGetNOY&RUQX)yg4IHG)Qv&bu9crpDfpOVRiF&Nc5!VOcwF!hT?MjKuwfN$G zFy{A`EZ+j98q7mTxrVx2T{G6K0jEreT=?kUa5*cje2_kPy#@rsVN|*V)+}ITe0Zk| zo^aGQ^@b!F-YJ0yc?m?ev%LF5AKl_PA_xH}qq((_)WEb^ZRJb0$eQ9!YSHay^Yk{Y zeL{_fGI5U_@~?BEaG{n2SbVk);fyj`>d)FhX{v3mxIdHQt=(+kn(7gVX3~wc&5(~I zcD`%t;!W@_ecsX}L`WnS_tnD|06dIiQh(~h|Mc|e`UfX~9Oo#Co16xAw1P+-g;FeF z;U|ZhK4BR?=K)*g;gi!)((1E^L^b&*)Fyaz-v`*vy6NT!xlF`JwxB|WNNT57E$r83 zep@06gDy0XAl#8aB6OJWiq%edt~WlzzrjR?-I{0t)y78#IaFfKQ^-aK)m!I3oHRz>yLEK-qV|c<xCM?;1c znfE#}d*-~OzP%$?%e(PM$!(P3B!e`7`-&3zy82YHZ8xCJ3 zLEfkbo{Jz8`_67wTPb)hd|q4$mc4fzy5);0FRRYVZw%z6!9VxC?S3;E`O%bo8M5eR z?@hhiP}WCzvt!j~p_^_dAYa=T({XOO-iBp2m2tvr60St72>qS4pfhRR4t~W~G^-7L zC_Hc_=7BqvuQ~aJc3->-ow{z_mmeE;EOW@iT@IHS2omTKSe|a=Q)$Fr! zFC?l(Ad1@q=%My2eJ}^Q=B`ad8;M>md1N=s-#sC-nGQ#s9R?UcPXMK?Sy8FjD_WZn z&O|2t+iH5ipMHPiQ1h&@1*ei94IWlh{-{CoG%ivlDn50wWGQ>~^~YbNxaKL@&ipuEzR2BDldQNTC6^AB-wbK79n7amgLAKBo5u{)xQ;mDNGb|3+t#G`O1wL-O! zVn~=fx^UhaW0Q_y!i-M0PORMZH1J1tTS6*KTRH)SLBfGBP>x8Wp_LW9-1`yeI_FO5 ziXEzt&`+vb*UT0~Nm)&>tV4Z^sr)4|>V*L=T6n+mzltx*m(iKPrNDa8nGbPZ4G)=3 zoIa&0{1k1%uF9i%7HjqF7PZu^lH*;l2=ZbxOYs6e?K-q^4A%h-$a)y}~1l{_tm}VA936ZDzfR`tEG|1hD^{l)N6!Y?MF8rtfj@vHjA+dD;W2Eb z!`o8Kab9N}ei@a*5qsLd`ADHB{}17=7s5AD!A9>EC}>$gKfO8HL^OhAb7*(Ev6K(bW(f0awWl3Dv&DImJX_X3ml>JabV3zf zOYwFe^~s#O@yn_UR{@I|TJQTBeHAy;f0w@<9LX@@??9#=WuK#6lLi_*@TGG34M9rM zFg80cI*-I*!aVl<4C@T)Tg%%g!mpg)q*I^!r|WIFr0RAItLhtm3EsKaj|C;tjqK-N zfsZUMwh?BX%)0)GeK$quI`P6T*hb}O^b7o-RDLZd3-M8rMQWF*Mn0?S-yMJU+7_p`S z1n-4Wk=^**&6a}J@(Tj(W`!#p5-`prb5p5mXZlFaV4H5{viSu88;q`&WYdmFD5T0G zHzx^P=0<@JIEd!cm|zC|T&MkzAoPy~W{=fD*BHo!T`V=z7^hS>AI+S&eJ-p5OvoTBmz}*r_zMUQ`;fJK*%$h)BKBVWYo> zGua`?W=wLRP{YA!1!iN5u9|R#-&ImG@-r3|l1mhmNjTi0z$}}h6+gSgGyhW~k1kQ* zB<-i<_s2VKPI};mL=a8`B?pYxYGW`6cHY1y6(Vt|9tpN{Q(wZGt-XMi3OO(;4o%5< z5N+4Wv+K)q|*McS8i7ZeQo6=fw2TR3lk zdmykMIF%l4)1TF~N+781K%17{r5b*HJ~h{V{BrhfoE~sPu*X(&s+!wSHKFdmjYX2q zuUd%T8vmg}(umOt??@q?Kg?9~{VJoBCvVG`_y-FC;o3>sQP^?0Yt6`TV@Rre%WNrf%C9PXf8?mNS$$Y?7)q)6;23s4EM8|ew8a)Cn5 zz-b#+r;FcGsDdeClN1`U;5zDJK-IKjmK*Q89Jn*oZ-nMY;1GA7Mm+p0lGEjunKDpQK=Jfy|Ym z&64N?=P2^>c9F~RZ|y8ffp%RkLj&tyT=2Kj5b6pzk??W&{iAPr51*Pq$f!KLBLJGr zqx!**5L)Cl9YwX_$I$+Cy8`N|Q6%%UKhBy40i>eoA+~}=NY>hklEwMNZHdy0s)96_ zvetL zhK$}2VVswSG#k+Wb-0 z1bpm(vHp%uZ<^w9D(VKsZSs;@2U&Dd-c?X?Axg{oNzAPl`6yI^!u8CelsPZO{XU1A zL{;;dbPdzMut9&VT1JKOdR~5<@Z@vI#DVq(ch!)>^CwUjP&^UqE^Y zm7w&@s#>><*w8%2(CGidEgohE)pE*pGWQ7MmoM_G!6=&>TY+Cy;OGQ~WixNkS|-1B z4ZP3$Rgo;b*{Ai`xkL{*U&|PqMD2lO0angORTcjP^A`P3g_1-{oKrvG;8<#BM^B#iDFC8GHN9TFZE-%g~y4NqYUw>2i5&V z-xEd&0k2h4>+qQ3L)U1$3WXTjs0@hp5*m~#qpW21lkl1nqWhB3ICoDh0@SgLT|hjf z>prx0L7X?SNtrXctiAA37bu;vPp`61+ZVA#dIjXh0S_VuH5RL zB5gP7Hurc8rPX;Oo5t`_l#i36GN8mIhb(h8bMuJ7S}4feFp9Br_GyUS0RR_Kt|sQ}GW%RTeG-*e^meMK z(p`#sinyJeei>CRe*Nv>F`ouTQ3jE0hJEv7r{rBwW$ftGGb;HbG)4rBq)`$%HkFzg zX_QF3??J^O6sdK9rTl|;WNLXkMNF*~rJ5w4mG7Uv9daP^+1F6=y|Gs!7U~g98e?ef zCCrX>mIphH!W_es9#E6*iHPxC><4JVMwGt62z+)PEC{$H&eud?xzAv=xuE2P5tmrb zMYtHa#aZn2-hu#uTX~NiJWi>?6be@=0d58JDTawqZoKmlgqfa2L*$f_W%<9s>;&6B z@&=n(_6fM9dU!F5;JHjn=U3|GEaGtXWpvIBgqsV8K~6Ct8h7)M8=VK5rerMh>rSF& zF@7`ifY&7m&vDe-p#nK?F1q=OUv)WsGfg^^x?Q53qSyP|=`VMpv8J3uc%>%xv&|t6zDMhs&%vvMj1r9fU$7jA8C3J?K%3T z=bot)SDZg)RM;Me>$`>*@9)b6S#drIS9-r#9e~%=5F^u^XTjV$!UpGlnFZkh>1Je1 z^#iUYX=o-nkAVT{*#jAXtgF^-fV$i&$VYxwTwctB5j(%G89!Jt^>Zo%gCApMtQ|O^4o-ipjuwgUO}p+_ zs6NcnHS&qjjm0D#Fjwn`O5nphA{jH8#wncllSw*M^zhfgEqgt+yZ-A)@Y1Y|;K|%H zafNFj+$wk*>?PKEFtzk!%n6dPJ!1!HR>+u~7A-hN(I)J5rXgWx&L=SA(bvRpE35MzpAB?Lw_ujZaC{u!86+UlzRU~1*7ioS9ha*{%puaek9 zsE)d$m)~^6<@L*Y-_*#%dSBEJQo+(yQugiC08otKx$I5aGFCnTzZVp6Cq6N12Qaws z@+S4V)v|Xq1@xBc$n!g@ zU(OSm_Dk~@0R3Ud^&pQ!9{{z00`bD6yy8Yj&Pg&a-4A_!W%ZrW>QnEO-*Qn{n4x1WH~bXf;|PRErAwzt{do;&TUL*Uii$Mp zYyIO%8n@g?IMRF1IVRpR!M6CJaa+FDPium%Zf}M6HTIWQr~PYc)vvYoI3Q`r5ayN! z6{KrUkr3Rss)iEj7gp0>@lEwX-K);}k~Y;^GKO&uD* z4oJ8-V-P8e$bchqrvvF56%Mn3xA1T=40MPV4iX&~Uh~AQ#kCc#XF760pYvr-PTmHU zi9=i}i~b3m3h>RuhNG7yjzkyrBFbTE6{uEuqX_#WEiB?Cyf-XBXY39wOy1w;FqpU& zSKnW%c8^>Qfqghz-!=Mwl5$EOv?w6e=fW=m#M!HHZ+@G9=uFF*bbiM8ip0iv|0lP7 zVPHZ%T-a80^OrSy{za9GG_c$Tu9NhUbad9m%~+vHmQ{MC!TV@d`6UOU((e36J*5i6 zu0po{7`>axh*QwOW6Q-vb63y7+@_9L8~wE3{A|Ur?j}spz~Vx}|FEj|o=a}~#kQ#L zUL);)1s~|V778>sJ5!o<8bNhEe@#0U+Ld{Eha)Ncsk1k#B>BztjEwDqCTjmJ>3lN9 zNA{a0FL&D@!|E9EYVWKR$MwMG3ks^VWG*cYLdRGi+qpO3gd@p{-*?_>a!ym#A$!ev zIwZG%;UGzA8oEMr@2}kFqFr;M2N^EsYVu}|{~{;lL=LRZ-ms;OrQ3!189tY9EKi>8 z?_PD^Ph(&8Q%Kt&?fle<>W$Au8RyoVQ{S3G+mm*IZsHFoatAfXmuX$9ZJ)R<&F_9t zNeXXl+BsrPm2G)%^Q6_X4E3$&)z)n0J!VX$Ayl^WDb2bR=;Yy)Udo*>Nq&-ClAQGR zx{{p~E6Bbtm*Ww6LY~VsU8K-O%%66SMSV z*E(gFrHo%UT)4lXK?onnHXn)8kUY`16+Q8Xn}7FFyBBm%JSm;+c5!p(r%&(dYkQwA z4t?|&!yZ`0FizzZMCLn3to5#W(ypEQH0F)2CBrU-COPFSEg!Q|;ZV^LGE<>ye?F5< zYTPJ>nS`IZs`i;(%AD%%O68g4t`2WlLVZ@#ULU2Yc$#!B(LF2vp>3l@o~)@{72T2X z(uurC>5Kko2r(NnZJ&Gf^pg47kdM!(7mXZD)oRVJf)+Sm54P`HZgaLxSci|jL+&q# VK6p&7e1;PcFZ5cF`=RuU{{!(%QYQca literal 259838 zcmeI52b^6+`TlPpbVEY#B+^Mj3F#0?C>9_T6|jL6D13GVxKd+g&ZTpOYJrVu~1_A?tfxtjuATSUZ2n+-U z0t118z(8OiFc26B3k;6(5qZ~)i`>;N_e z>vc9yTLZUGdb&8*zFhT@Fe&n_yf2eoDV(*4hFk{jnMx!adYa04)@#37Tmx< zU?7))u0_)_-3w;s=uKyf(WCXzC+YejK=1GCzzXmLcm)hqw}(<66uRf%q~mX(8{7cC z2Hp+EgAKdY9&mMl+6NuTs^8%V3^XzW(gFW&^!kBI+j{CQ;ApT2=v^yae+?AUzgj%6 zcE{7;E^rw*0qlwXzeRNbeuq#OG_npfn(TU~ceG^t@lF@iXP*tu0>1%I0kykpQLl%Z zCbd(Z0k?q#;83u2=c4KA&&2A3&@N~+ok+X99nI4+_g%1SRK~lojZx+|18URD4yShW z%V4OwRgd?n&u}03CO8&s*U@5Z8-}M2XZuKd*$DEbmjS)oyKEoc>;5RpxoqhRf$VhB zfqK;4Qm0vMod>{G;BcTZ2G1Gpv`kO)r1Tb)AX#b{=xUxEE4S!>>lBTX?Fvo@OF^T( z=Zmc?R3~Or{P z+6#UNckcxo1H*4eD=zJ-a0CXb%|NHh;-$7+y7DPo-Uq?2L3r1frry)o$8vBQ*sjaj z2D<1M2;m3}RGI}ZA#Gl^lJ$fIn!_^k}DcIBPtzz=N0gHVQ83rf^2Cl!aJ*+f$FJ4}PKb?F$L_U8A zj09#aLD$0RK_?o70j-EIt_Kc$8PI;|TF0gFA5&IRstOG!md{W2k*hN~ zU~#Yu)>|FWwK!)VKCRWg0%-gI}P=w1C5&A&erVr zX2?I)?Rzpp*5U$}b0v?`gi*K>1uuxY~#6C%ypm z&8tVjy+CV(mIIZUrQi=hdj#A8RsikyEjx2B_&azB{09{C>~L-6`RXK(CIRLQhy4a? zS^L|XbN1-jo;N&`0Nw?rf!%=S3~vFn@5CrDy!Oz6)_b0QLb}fpvRYa_kB5XC?eOa|;t;QM;ti`EKnaY{#B7 zA8mJ_I!5ynzX|RFYHOtJn_$J{PqnXAy*wF2c~^T{(6}jz<;&Lie+dRtUY_N;rQkfE zckwu|4v6wN=`RPveD^BfcR+0#7MXfS?FZEfM}q}m8BiPHe_$|jhHFa0QxAOa1;{Vz z`CtzyhdLA;r}D!=@6I2B{>r;_Ui|`nk7p9t0Qmcj+r~b!`o=^xkJU|?OnXaCeyb}JB{meY>V0Z<8ckq-?5N)3h3|9e3Xtv8u-588pyH@I10#y zpt>OR6Y`gXd}U)O=VaR*3rxGMzdQ?JT&r()=)U;TMgRKuOFnAjis=&fs7}#)btX6t zoCCfCRQKNlo&*{n_!m&y`wft+f4siwyxz&W?iHZ>{sR64t_O$EpB$+^q2gD$Bj#0w$1O;me;xuy_1gs=YpHSgWyF_YCD_if==*7FcGZt$h_?{9Rqy3hU?5; z6~=XXuJz3ELwyMCTOPj#zuFle1hRW*Z``2wrQtwzeiP+zOkY=YfR^J;OF2mpm%h+^h5QO>Xl=`Ccw*K zzA2_Qef+TDx%E`XMN{=10@*q?iwTr(1ZUtKRS?==s z63_S{Q2$>#XwvD%{3C|$W>4C7V~fm|rOxKb((z4!`XQ%+Z-N!zZlLz(`@r_tC}o>4 z@p>Dfk68PgCHe&yYNji`N7Zu!$5|6k$oK)~Md(=y9jXL{;`TVe*pG1v%v8OY|Q ze!AVm4c8y~4kWg5qYozBzHi@)zmj&bS9#vgz&n9Wr_!oWvp^g6OdWSF*pIk#IMH(s20sBxYrgoyxxw+$ z1AjXK!?__m{3|&Fj$g{STc7Fp_HAeXjR$j`)^6Hyn$vOHK{?y@aXnGLa2a?vSPz&o zA=mFaZ*;U}Ms%KZs}H#|_!#&xcoHa{c)SDoC7myZ}iW&c22L_if4c}@ERzW{%G#gZQvt7?Ix3sHu@m)>qzz&I6oe!-yz#p zxzd%^c>e)shk?wh0p@d+RWTYMa&a8PDEudbm7vmPOFDcQ{dl$E>Dyb|gV8OuMVxJz z_2YUk>;)ErM?fXhslG%f_#}wx0ev4=^PRG3jW|``;b@?KZ6(v0hG&Vhw}PmSZ2)zw zn27QB6?0~!Q~QIPK&9un=$$WJ-Wo)8k6}zrk;O=;EECcha|x872RL;C4{yav;6A9;p8wrAgTn z|BYYoR@nh%53F<=i+SG5r0-i`FK@TNPanqab!FRH(VQvS1vEAh#s~(Nr>ZY^5uZXh zhQ@&QU24nj>!tNFUj)^7=RePLzXUb_nOi<{n90{}_8W9#4vgiS{>VXu-wM>{E=Cut zdF|t*_5T4oZlSgS(4qEBThtaX<6B?jx))oI@~$MgFs zP>p=Qf#+_g^knDGPGg?8we53$6wrKwXF)a6SFUGj9@0%)`vHfBCzq0Z3J5~=E8=&fk zYV=1cr4x@J-|_SVMoM-g|NO~Wdxt$ITc^f0D?R>NDGo~U9F6-<7JsTw!;zl>!;dXf zvazWztvT(b;J=tS^h}M}tq)9@kAF+djqe>mSQjWJ-g>=OWB&_*sSA79J3)ID#K&X^ zTNj)SUIq0kXSvh;ZMZSEz_!It?X`UAt+jLF(jGM-wfB}gdM4Y_N>J%CptgqE z9FeV01)1L-qw!x2s?jE?G#AA_Pj*4g#VpWfGV2{bO}OU36dQM%uh%%qaUj#>_OCFN zXM_F|4`3_sXHe;U{~piO_?6N3gzl@Kb|nb9UpQaXo^4`IfU}qOnJ1+7fov+F-;~SY zGB`2iu48dyj|akobZ;DZ0#s7}m-4*rKtA1HkMm1FX!8%8CwiZq%U%L`$4powsq>2h zmpNry_2IFg;pYPw4(#_W|AxO(`hP#q+RHsVqx}QDA6Ii-nt<#Al}b;&KSy=I*Fk?a zly3z-bIQ}r@S%AwnMR%yDEWbO@i|ZlJ&^6{2*4P&*0%D!Pn(9!3cJqjQ-p0|8lJH8^L-kNbi%p~I&C}YOXUP5^mFw6Vf{C2J7Ze+BTCcy3ITWV8Y;gVGk20b9 zu-y6leV$?3T)2kvSlQg0a}QP^4ds@x+VQI%|B!84X}yH@LsT0p`mTxQz&#syHf3FX zUegcNw`UviKz_X^-UiA&PV^_9v8#KY)qVGl;@lP>v`tG_|7w2p+r@Pk-#PI8EB$U? zV)Fa*_+>Mwc3o8q&!4AnS+*~-`>-}z9iTD+W`lC}xiwaOjQaX3=kH;^f#LTQYBA&2 zvh~+OSx8eF)Xv`nWcvZm&pC~+TnEx5?@(n~2@jitO#C~wjZzOtZg2qjHyA311KoEy zahrK6?8BWg>-oI?+qoF!ZhH)rzO;s`O|>P+R|kyad^bp|?1Pm{V}b8A9JxK$8b$Xd zr;*$4;ax5r{3FkJt9y>2*86eCg9pH1^D10dJXcq+my^~9M`PU`%zHDx?RvO>1pcR9 zFFT-LPt}0>UoQKf>edrf*18w%k;yxlw+;PkBQgX`zdoeI$YV~yy^vwSvPvwtAzZ2 zh3EYNdEIA@@MfG}*5LV|Ip&`<{J3)J^&>5=#@H^$X-*2c$*ibL5a*V11zVv{9HlzZV$9&DcI zI`#3)+-uDVO5}^yV)cMx;!E4LrVr50oQX6YR{xF7=j-IJ8SC)!@mqSS@lVaqDOG-6 z(A{F+_j-=z`06>l`(=l|p@h#VReBpKo=*7RM)@J=xb5N@zHZjK_(rzL{E+sM8K*YH zq~xE=Yqk6D1Rv9Hf4HzwxOah4=z-q-ySsSJW4s@CF3?<{p*% zY6BW)d=#i{QO>yxLrHtB-Ls&xWwPm;X>Op#z2HpP0Q?lxT6!y$9+e+6R_*np-rcq( z=KDCx+sWXc;7kzhe`fr4ZqCo~mxAY(yopm74 zd;z_?HU^`Z+pahT)oq&swPE)JZwH?MnpgNcpz)p8K`G=*LmXOTH5-_`Q9gOUJKw0b zK+TCZ?c=n}1?XmvGncog;HvCOC)oQaI}YU9=U2M$;goOL{8i6Hb4`rjmNUKk2byD~ za(6TMG}s%cUEe6*^ ze*_A}-Ah<2m;u%US-p0)gDAp5dW>z`tuyxV-Lqtt;@t`y4ZaUlUlmGI+Rv*FJPBl0 zcW-Q1mES>i?_WULImjp9UC6zm|NinIi(AcJ=JIn3+1*{kGKS zKGMaNEKgcrsJ=&%Z_P_t0Cr#T?Sp;U%dBXbl<6t)dMw#M6YT}nQ&YfV@DxaQKDiVu8Zo1!TYCVZoTg9nV$KR zVlh#^-8=*zPsakYU;ZBaz63l6;^}Mz|Celg*Y*cvw!n#S@k9gip?9FhK{Q^KQ+Dd@ zhrSahIl!sFm*p4m7n%bg`=`IISa%-xn&*ipap!*Th#QahF@ArH_EkOemuW}71-AlUYJGR&PdO+oAd+TJqf3Jz}TQsS90s_dMZF0)GSb zDARD#EIn8s`c0P@H4Q03%cV9G?j{!{wFA>cI-m+t|7n|HC7jo-RVf6pDB8Ok4`kjFZT}X#7o_>k zIl|NqR+}Ns??JVlJ|UTV7$eaU8w)sr^NnN^Re8V6z60u1|Cx8YqSd^IuRxZ3`uj!Y z^&MB+wN9O8KR(m$T~Ofqd~xWU`t@rlE`P`mq%-QLoA-zh^KKq}Uzc-l1#bgKgA>6? z;21C)>E`;GXYtJKfb4&T(wsd1GS{k)qWespFIR{CZTdE{qn-l% zIBGJEH2hwMe6klA+11~YAE;e$FGz!ogO%Yo$g6jl;iBIDDcvspzs1cb^Dj6b*#Khg z-FI>R)dKhAi$^v%o|Ua9?QipZ(^rpkcld-2d4KcHw|YDhcQ5cI@N3WuUIwp&)edjq zz5<>AzXNB3sbFp3<1vruV9roXj*UsjHAToF*;au4qjm8v?>Q$fW!F$W_c`!ykdKRc zKc_y9^55_%Qe_9^`=XM6QA%YllxM2%a@w`=a$M_vn}?=vTd3ZCf@?HZ9-FUY@_BR4 ztpbI3iJw<_F@66oY<~S6N9;Z(($ym;tUm(Xoer)6PXn*(gLR+dp6`MEsY}+t&CCTy zPTbJ$Eo{oKkwtxv?+sEGFV|CCe_ZE6yFL!T5lgOv`U&R)wU_-pX>zgmPobW3`?Y1| z-XD3>-2X}D;WNmqd13t(>zWNyy1{rL`+HJ0{Z{$?Ffe^y31a=`zQNY@k8#g9-Phl7 z1bX@Qu^V~)-voVa0z=XJWc~0w@ic?20PPC32dr(t$YMEA+jSYp$3dZUD(7m~j0A?4 zh#&iV6z9JS3f*7N=X;UMycg8|kI5~WZ%e7n`SMF`ytjk?igwM0DcwNt=Kk99dN-Of z9?NIlH`uyf<-yqY3lX9B^5GMscKUeq^k$IM9x>n<9vGOgQE@U@|bADY%^Yjt^-Xu@5(;q!{W3Q9a&u%bWT`zS1 z{lq<6`ahTF9zJ0s%C9fCrXJAyyjUBy>VQwNZ|Vqfq&BhER9HKM;rE@Ke;&j+NrV3; zWQuHGvH2m>IRB3n%3CPU&PLW~Eqk(j*Xr-i?3({G29Z~%O2(d6+kcPQd{y@iq%ZSy z@5%ywf9axw-uva$eP1X1ndith$a6O|*`xG1jKTdKD3sTQ&a1p1ZR40?#>TZ?-u$-p z!g)i8v(U3@<-GcgnhQeN&v`F2S|8wYz1uV&w4RRk?3(`OL6lADL^O9dD%*Ci=#>N9 z{}GiDzuqs-k@U~${-(I)X!CoWPr7&TylvdGO_F58Ryx5^puhf5A^m%V`=+=!Oq|}2 zyCrA`h3>7_^J*_;x|i7XldJFouGrXXq$#&qIX&JU$t>F;^f4%7IsnZKdDjg6}w#Ci3Ls-3<{Jbx*2YW`!g zc-QoAr5CIPehCJ{)Bm|SZbq)yysz!J|DFPIXdcYIpbr-@d!NSmN@3?Ow!V0Q=N>Hm z7j(qR?@6S2pngpu&dzC{KV^jG2WY%AHpfzBhDbk(YvjyIhsrJ8P4akAwJ9bJ#^R5T|<$Hf&Kcy`}-8v=HvzYyju$wAg zupapNFyig+nbiur!hb8+@W;AMC+jIGld}-ND&sp!=6X6@9%=64eV~wR$@72XTH6M2 z^167G=kEo{K3^~Aw%0ZB07)pavC_d<%~ER+ug+qj018vUpI0_wXz zT4Www%|2KoHJ9J)%jfpq<((-z(6m{JAfxaF)~Zu1A!^e64v{1#{>0;e0&e%@6$JO`acf$F;K1dzJKoDNy9{? z$seRyGK~Yhz{^sstG3XgfHsBOH#0kC(lm^Ci%mzluh(3_6OEk6s>Au!hq@7z`}x(5 zU+;+hBy&9-N-vP@_OGB=4u8cxqX2RA*%MZ_^VeLQkKw9~kwcAi4XEF(b$nhAtL6TO zG#mz^G%CG7bAh@*vE0P3mko@zQdTeI2Qz`{(fGCX?7vv^sIzlmej*u#vr;5uq5RR9 z?i|TmPlwVA^uB%?6q2pb`PaFJ`QMr|%Y0Yn(Z|LE)epGJ#i_Q1+88<1NY}u7L3|Bw zwe(-l{fN@!52Y7qZtL$sAr1y}Uh=Ds&2(K7-#ctbd#DWNdDXfGo~ErYId!aD64?OW z&AI=AYNe|Z&y}s`ATPTwL$&TIyZTtz4>6mZl$ZGDSTXVEvm~s1O)PgG;(pbsq z5Bb5KK=!d(NMpIuptkNifET?kT%{LG1Vhz-@u@Mg^+2``$lA}I1laGQ?M!-i_)5zYRqBEI*J9@E%Yu-K&Lo>skMY+Wz;vYaHto zVDw*eXw5n>jS1L#;5~$CU2Rk@|D|aEi>HTx+Cvcs@&ok? z{sKIg_3TDAz|O@v`y#G`d^e{=#zOg{_W!{k%HMkMD7`>sa47b_I2Y>U%AS>6AFTM- z04f7HlsNt0ANQ3S(0|$g4p*A|q4a`M*#E?n>_a)_!^J-uw++O(tY`mulB@fo{S1w! z{pKgtc<2S zd@)5b=Hv4f0=6+fRK>K~E{avj#z)L)P4v6$$b69}d=HDqHFCD}sdqTvA{NQNt zIw%$Y)r?1WB-xXaGNyeDP&VA1;&Mj>)UZeC1!}LW?_SDsqx$gZ?0g_Q?wzE<=-h_??~PBr6s5jk?k zdigCG$AVr^&9s&C*_z|NE$~@e7p~F^)FvJ79G86DK1IBTX>OpNlbsiurN-&M+5nmd ztiAdxT?c6H@u48L_SdGDG@k&}pUEfNP|iJ0Tw_5*fc!vvqiF1WC~?->JsJx>1SDnL zjB{z81F#DDHi^p}5m3V(y`Q^Vri~!o-v;F0>9+!;g^$PZ*UlKrTZ&#G2jvhm5*my}WKM3$#S z#(dnW{j4$*$z2bg*nZ8eWy~AZ0f%M#0=XQSegF0ToiKV!@CQ(-Hb4i@8VAhxK$Ks0 zErZd?!%6eMO3aD+#=C&1XvhzyfHbWGGIPPakXFWN>*C%D^65?*&ixeG){?CCbj0+( z+~c!)_Z{82AhN6H(4=qiNDsjza4#r#9q=g6Fnj(S$#;TvDDNCL#JvTSx?HM1lw%`u z&zpvumiNCnJ415$!^tS!_&F#wr?nE_RsI_?UhaBvUH%-8tNEMdw^1lf;8ai!dwehP%BJYW_VvwvoO=b7llw}> zJufLEZ9k0%e?LVsCi!fV%!R&h6J>Y}dX#P;8+0YcXI0L>2G$3r{A>R}9p+m++3$bt zgMKaprEUkP%|9#K=jik8kIAH~7bNqy6u<8y-h5-@@8G=FkCfsWwGhVwWQj_;zNv8g zV$<%sHbpWfdH!fz=1BND@F?9tYXF}CNx91LTkqCy0L?oxb%0zQ+7tAMiKBcwK;Pr{6e8+Vkkb>vZA0hRsxK_z+r9nYHta_WG&d+2*WwlBbYdQJ58 z0B|E1NuG}uZ}w}-OtPYsWLyel6k6UT_PD* ze0`>o^T~6zGwou|U6wLAJ+JE5?j@P)@ld+KdO-T5YK!+bK=!M)VGK--EN;e z^wqZmR3EIv@0s9Sa0mDscnu``2U^Fcz5G^ygc@9lQ&i2u^c28TU}2eLP3U<`+lz zD^jgZGqBH6zFh~(t@|n~#x9=tPG&jhUik7^Y4=L)Z`8KX?g3ypw_K}VQ0cT(;(2;+ z>iucTY`y){yga2HsC-s}uR_oG1J9q;wa|_cDqV4VDmtC7E{Js7hG*-ExyF`g?R(0T z*jT4&XYi~k;P(}h`9C~Ia|)v3AwPHvDD~XyLi|?h{N>XB+s}KOk+pk%G^a}af=Z>K zlFzxagFSDQpY?hu?Lg&I<+PIAC7<;-p8sXADKMP&#MjIYf#6R16P?!nWa1-U?YVIp z(7dGN^UL*HbANUNkp%LCaiABJ>$%m4_hQL*$N962toNQDt)*7Kpc?5Z_cK2$dG*bh zdOehWFdjS&%FWk6@vAL<2Y5e_t}1N?J?Qd^))@oR+}(=JIlG3}->-M=kw7;7*TF#P zC}p_h83jz*yO%`o#7d33mQt31;%f17O4v@?0_yW{u3G)efzmsi@P8xMJLB>WSU79& z0;L~}0UcmCe3bHDjjP-SWFObOc{9Hf*Xwh_jruY1^CP+bt>7czx8PM!$}|o(E~68& zZ|dlvZ%jIb&sQlugH88PuDd|8`9uA#_7?Mv`ER9A)+do^r?|Xc?s{^SM;$F@y?ZU@ zk=g@~gC7Cui{6>457bA{nu~QE(Y(c#?+Uo<+7!;=^g$T@JDb5PiY6@&5yp- zGMl`6C52_On&sqb#xh2DosjD=7gv3pYNo9m&pui5`NPSo@v&tolU41~lO&(kw$}S0 zIlxw+((?ezQ3h)zPT7YJbKIIDqP0dHEoP6QG|q>SUG+VZ*B?&yjc~g_t>jB7((xSf z>?8ToaHtLgY3-AiBEN?c$8ySt%DyQgv3-TN0Ti28)w9wbE6t=l%nk za^8vjmb^QHr$D)$Ta9=x?O9~Und@2aecJzsEH1C6xLyX^! zW2SX2ylk)1bziJ}nVQ16G?gj!bKWO86vG0ykB!+bvSP2 zN*A6D*{G~ZwwGBTm z9@`gZbzi^1?%;8dR{5`Id}9sCs-v?tDo z{R-YT1ZK^l(F6S5T6f$$b$-e@Jx_A?EZNJbL`TbX_H!_Hr7Kb-xB6~-OV0Qj=d{!T zlFMN%?wz1gdXt9dJPlv79Dk-rct7qWkTx55GS5CDdA0sZhm&3HWbJ*FytZC{{~B3x z`Zz||l>A%TG{@(gT$R~-Q1?L2iMTjuDdVH|4q9{_&WBuHCw*y&Ou(Sp(z!AX^rP6a5P$FL(t*< zxJLl(bCg!uCD&iUt{^J;^1E{iOM~o^V}j(8j->gBtqD>dz6)r~BMo_24jD9;Z#R%n z_chmVc>{3QiHsUMj?_Yaa4=BYpd7qcI!@LwPNOZC-gkeLd3e~D)44T(*}@kz2xs4?zq6+LJUYz2OIH6snG*RmuJb`a9yf;mD<3r< z!0r)f_Ha26`R`9jewLyR(44m8%oF$?^)Zw z-FMCKaB)iH{}Xa-Eg3r)*KDN2ejh8^Uq|!TR-`0Phoe*K&wr|O@g%dh*S85(J{&aG zuQD^7XVlBRTFY>xzgvLc6a~2so8bN&B=1Y>Z}owU{ln{o<3Z~m9!UWY&mx1~d*pB9wEcZv zdRJ}R*qD}VJ?8`ILR!mpKDo5+`{VGSzP-_R@#FoRUl;!+Am6=dJ$D!KM*Ew#Utsre z=bY98zmftjZa{{$fmelwb?;mdeYZ+$Th@e=V}aJXrL}Cw<$4S`-`m+bKGJuq`?hby z{OOT|e-)&0ZEu{1r2kT6j_Sg$#Zh1Jbj~NQt+(GAyExp)hkYj;mI0sN&Q;s*J0MMK zyprWq@3@(6eN3GkBtq-x0+4hmjL^+;W$vA(H z3>!+mwk6qb8Z}xy(C)s=6VGSuu^-!KU$!2V1C51OGJnebEUkmO3Ty|A4MhDQU(U@r zTh>2~ztQ?a;{NYo5Aom+`N3vj6)1Q9lrw&f`F$8WwY$Rk%)x&v>bIF#QX>V=ZcYmzBPlk(Az+1$L|E`t~*SC9hepTz< za&_(1K(^C*$m@6-HD-SW*ai6VEHUv%wk@6C0GtQZMu^|vNd618ZoHdstm){m?+J19 z**fRs4buNHz})_vuxcmV5zAAlRd?!ceV+<49?1MAFmEbR+*7ZVt z_n!gH=aVhZe!t4S^CeeIwyg=j7O0%mx?JT-pX$9sff*O_`Oj~0cLONbb1M;V8|hac z#*}GOxEuJNnG0;WkZ!20`v6dXU*la-J>V&dpX+KdV`b_iHUaesYt25ccIr=o?7XVu z`jN-H|EF=yQc#IerP<_mb8+Jftk28!cRAg=q%i*kkOz5Nil1nduT>ajNV zL)M}6$7Iko9|dXN!>1U&zuDP3ZG`%Po-4RfJ|6}C1B!{Omabh&+Q$IX-ZR35e@3sx z378IK_w{)ueK-?r39O#Gxq_ZHo!4HNQ8;Tw@V^zj52%084K$zrP2l4#wX6E-L2x}d z4veKeKLR&Om!I3+zJPixJKs^^>hGw|dJU91UG*5B>TTtn;m+%So6X}TbHj zYTUVgUT@>Bwe`~nZZSI3oXBJ8Z6`PxYz$1fXlE^q#t8lK(8W8&#|+Iit1dEgigeFZ zcmGAWzXg8=nr|naE2du1wbFIfQFntMgR{ZAz_vhjk9oFn-FTkTsBxa0F#8_R*q-W* zdeqZ$rCII!vEs@f@&ommdqBCKTkd#&NZQu}W(}j4Ex48e!;8)5o$yOPllh_d!X4lw zusJaL^hZ!Bf;;$8z3oXqyPRU^B~rM7eire@7T99;`?xK#U-X^BVXn(<=WA?pF8CR!*K%BL-BaIQeSFhLQYjJtu8v>C z`EozMT=6UIra#!obN%vbefDguUo0ERErZDK$GGMSp!fJjppRZ>WAESh$oYF@o;zzV z_LZGZKScX&Ok;d@YUWS8%kN&8eV_Lii^^&{_ebflb=lVZR=eRhAn1MnI;=j`79gTo zexSDhN>DESEN8rbB;DhHDHoAo!IPJP*m&RpaHc-`VDd(K)eh87KM-uj{?Ix0H_m15 zYTh@qYLVSXBJabCJgK>hZOmVew-MYpzUr?zU?KPuDAbl2jBJf`&4niao!unXhtv3} zY&G@9h0?6LKeMuVMv00RFBIhQ_Zvu_1W6H%-H-?zQQp$24ZahwVm6Bk@s(Mui6l@7id1gSAoWsRL*t) zn*im{$ez|2zP$Bu+b-RabJJwom+esZ>fLI0j<*e;E8}{JvEArMCEs;0d61!XJRf@va4zfMy__ zz7WW6Bm2L`18xMr1L}wB-j~7uK&jHz$nnUgdmO<2>*oAqzZ-oD=ijU|p8rdFKiR1{ z3&^9f>2MUsfS=PtyJ-!$lrA>1exzM?jq4k`U*a1-8*u*CI?Q{uHQjvg>>QQiG$33J zhrTVY@qWFh)2;`ND&Lot*X@zrFUt1=Isa0f<@Gp$@2D4)pHd2ShrvYQaoDm-2MZ*UOln=9kPhb5^u| zg)zTyl!pP$$&bwqdN;g34?-PKpB!A&?bgJow2+S;TjH;mb-uDiop$5J2N?TB(Eal0 zeLPmL|89QJXW>8C1M5%!pCI4%0Fm9VBfD%)Hxf_~LD2U>e^ zD&U>zzjxx+d)oDr_trrkt{{zOzLMn7w`#&sJqB!9GHtN!@T*=9bwKTMp!HK5`8-pp z(Yn|UyHCp3>LBm#CXHskLOc67ck*4Da8#E8?X~C26R!3STn0iNPq$Jh(lfs;eE1@pLmTm@P|co83|4WvQ0SdAZVd8F^y% zOYLGmwVs9Udwz?i>0GVv@9}5SI16|?MPn#d9Z9LRBOTgX-_`?Ke--M0+IgR@qS#j!L)9s7Sid{@EGa&0BsYq4+;LdFY7^o{0t~>W6=2E55fO{FAKpP z9v5oUe=6I~pTeHLGu&9evBwZL^}jX5_wA%*I*7_e{*n{UriB6R8?dU`%{^j_Ek!)YF#rR1F4!-s@5y(y z``!aIM=jI=L+9W(@V5ns>3;NH)%m40!msKezRhF5HKz1-yS0b|6q^v7G6t0QG3<(8 z^8{+CeOfQ|k><%w@LZ~xct7r1;380MS+uXfZ@~=B<-?8YsgxD#AWjhsXz!V>#nD^= z*{9S;?FH2?ul4f$zrfYOfOWj=>64w?m+69A&VL;I8&p%C=Xib-*aVpINV(w%42XfQ zt8&&5tISRUKLVjG(7)bl-Oh2E&ui9Sp;PTI-Isx$i=(jt|E}1DGITkp%P*}2HpqUJU(mJ8El@1>jDEw1}IDMvb`a{PX^U&*H&7ulF$1F@{5Oj zy07`wUj>z}BOm0MX8?^eM){?2-f#p4hRZ+??MU~%5nr~pa^>xQ+@yY_`S-QRJI3pn zc=i6}i_LeMW$S+hREmQqc-94AC%10x?rYBhsGK;t{;xTK)D&PdqG(} z&|bEbL)8Okfu$<4(-dwWv_3iIV@9bP3#@44kRz_Ks2Cdap z{kn74qJ0e4U8;LXLpTBh)nF2undO+{WqreZq-$6Nbv|Mp(9PNBi$j&cW=YWSm zInto<)|8C!W`Iadtfd6lfXRC1*B8u(3Mih`6B83 z98mg=JQ7y&`QNy+f$Z+3e75ElXdRaN_HP4G-P5i)h9De)fm&yvZHa8*SzU2^-D^(F zTyPbTy-;Pnl)6)@xYUn7zPrWF>%(v8mTO_`9S7kr)q7v#_K$<_f)9Xg+OyvRH+u(m zvY&G}0t5BP0Oi@(rR6%vZnYhdz5JU%V~Dk4E6_T=gZvsEZ%^l(PrF>%`W^$rsc%&G z$(E=7k>*qEOkZB#0W#0gT)i+~uO3T#NOOM-`0^cdRTs!+coH}$R;4xraT<7_1Y$##QPJbmRgr$W6mG?Z5 zoqaEG61Wny1KAH{10Rac4dx!TJ*1PH1Ln`DeQ)Q_=(oY5DVo=(xjoN=!NjRCLtQJo z{kOrV!E~^3=K^cL$M5Fl^UPq!PfM{5atwh1qYE*6fqt*LXqI$ObM5p_)_eC{@Kc~U z2C5VO0|uju{avHII!^`Bo?RN#zqg5f@15?`2UrjPS>RtFUtIs?ymb9Oa1&Srjt7$g zHjgQ5;70Lz{}5;jw*&?nf`N`iU0`&^jF>cUy z@pK=3a03H@fg%{_XjQvBtEX|@QeDCK&eT311!POu9qbEKKO6`2e*ZE!A1nsyS2Tfb zL8PPc}M_bg|)h+#FigH+*cIfTq6TIRx|#&LKeJk6xWCL_7x(Uq5@}(ZmVh&RK-bj)%wVnb$HS zniQTx!@R5jFJ#u$t+R8oVRkmWH#0}!`)8KPaYrnC*$8uP@5~q0P zM?a$Q9NMGcYzgdJ`prdSef)WoAIpH=Y@BgllmW})XS4n&yeWGw?u#-Yelq6w;RVEt z>ZqZH`wS{{|3KkhLkitLV7SY`g7*&;KHFws!TX0BK6ZfkW8rbdjk3@cfP(3B;TJ?V zBs{V3If)?i(-n}l^M&bLEW9b-H7-1+)45mK@HYv!^;2%Bf5#|1_h@oIZ4ILEK9`s) zvf=#9tz2W_Z*cQSy{}xXS;rPog;N`5GACw3tj~p$_;ppcn>spvO+37B?EW43hJ+uH zFWeUJ*9af8&g!Ok%+7Dhk6ue-Mz79S$++;Q%$RNC6saONM-;yI-u_gMn+=~6KOeCj zJ%4snJUsHd@HvS$Ulcx17bxLhi%!WCm4+z%t2yD(4;MZzb7piZ#}nP32yb#%x$rTW z({pZ%-g43XhFpJF_Sz`C*Pipl%yF0GhWoRbjQ1tOz2JqyU9^#tyx%8$oVy}7+@H;4 zyszl+IX2>g_q*^h_A=X%5qG^hF;4%?Q80X5f8leYD3bTD)2sXD3^{zw#Qj?;Iu6gz zh+gwEliAz4$?%M16!|XP*989lsC*R)_YoEf_YoEfA8FH7@cF)Ajf&06%t_yeX@9cT+D=xgr z-xj&K_ZJLz?UQBEecm(9dR%y~KOMQ_tj~qN5S{lP7e3aM-<$$$ugDFL7m%Fr+4lZC z8E7wa;eB82b8^F*?9c4~Io3PR#=m-5HpKeoSjUC;O`p5o-QG96$zI^YeeK|G^SwM< zd{?h7biWTTB!4#C<+qRD6=PTYXn5J`Yg{7S6+bo1niORI$>WYFyvfvi*=DMf$7TO& znojF*%ijJzTh+umxXUt`H!`D}qHyOK>-Z7>>%>cmt8Jt3-sGM3_iTTE-vVeZm{%y= zRWDKaYx(2%xA(~)M|Z(+8=cRd)vNPoV3a+1TE>bYqJQAc?pWqrxM!dh|!amps}&^apqa`;^BD+hzI8(ATEAB0&>L9LqLxBc?if6KVe!^`e)~)uW#>XUT%0F0ds@< zs6eiGTx>YY{!1jkj{u3}_Yq)r;`vDd<|V^(E8#xLOC+#Q@)8N`le|O%`y?;7nddDp z@kGWekwoU(%bK$6<$1jA2f9n<#Uu9qECYF@*G16-@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + \ 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/tests/__init__.py b/tests/__init__.py index e6af51ce..48622532 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1 @@ -"""GIAnT-Python tests.""" +"""Tests for giant_python.""" diff --git a/uv.lock b/uv.lock new file mode 100644 index 00000000..903cebb2 --- /dev/null +++ b/uv.lock @@ -0,0 +1,5480 @@ +version = 1 +revision = 3 +requires-python = ">=3.10" +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.11'", +] + +[[package]] +name = "accessible-pygments" +version = "0.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c1/bbac6a50d02774f91572938964c582fff4270eee73ab822a4aeea4d8b11b/accessible_pygments-0.0.5.tar.gz", hash = "sha256:40918d3e6a2b619ad424cb91e556bd3bd8865443d9f22f1dcdf79e33c8046872", size = 1377899, upload-time = "2024-05-10T11:23:10.216Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/3f/95338030883d8c8b91223b4e21744b04d11b161a3ef117295d8241f50ab4/accessible_pygments-0.0.5-py3-none-any.whl", hash = "sha256:88ae3211e68a1d0b011504b2ffc1691feafce124b845bd072ab6f9f66f34d4b7", size = 1395903, upload-time = "2024-05-10T11:23:08.421Z" }, +] + +[[package]] +name = "alabaster" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/f8/d9c74d0daf3f742840fd818d69cfae176fa332022fd44e3469487d5a9420/alabaster-1.0.0.tar.gz", hash = "sha256:c00dca57bca26fa62a6d7d0a9fcce65f3e026e9bfe33e9c538fd3fbb2144fd9e", size = 24210, upload-time = "2024-07-26T18:15:03.762Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/b3/6b4067be973ae96ba0d615946e314c5ae35f9f993eca561b356540bb0c2b/alabaster-1.0.0-py3-none-any.whl", hash = "sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b", size = 13929, upload-time = "2024-07-26T18:15:02.05Z" }, +] + +[[package]] +name = "asciitree" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f0/0f/c9686d87934dbbd59d9dee7fbcd98d0e9c8f44e0c5d4965a5bd2f4385865/asciitree-1.0.0.tar.gz", hash = "sha256:0c396808c13cab27b60cbe402b99ef37fa681c6b59d337a008719efa201cdd07", size = 4940, upload-time = "2026-10-25T17:50:11.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/6a/6683d280e053ab42276234ba73e648ce0db8dce40adc5d409e7e27aaa037/asciitree-1.0.0-py3-none-any.whl", hash = "sha256:4ec3e9dbf093e4b52577325071c11c669ad6fb180a78f168962d35b535d3f430", size = 5255, upload-time = "2026-10-25T17:50:10.284Z" }, +] + +[[package]] +name = "asttokens" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "babel" +version = "2.19.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/32/44/744169ce3677a541439bc9506ef08bd85674e9d6e3895ebe5a87ff65fb7a/babel-2.19.0.tar.gz", hash = "sha256:fddd2cbbbac7c299af3c2880be23609c331bd94f0912baca6cb0abfe054dfc27", size = 10695455, upload-time = "2026-11-24T20:14:32.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/3b/ddf4b07be846bfa361683729b5948c9c61a87fbdf09e69540d8e586bb7c5/babel-2.19.0-py3-none-any.whl", hash = "sha256:6d49734aed1d595b2c065d012174df8c83964692f26fc461702281634dd7555b", size = 10983582, upload-time = "2026-11-24T20:14:30.163Z" }, +] + +[[package]] +name = "beautifulsoup4" +version = "4.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "soupsieve", version = "2.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11.5'" }, + { name = "soupsieve", version = "4.1.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11.5'" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" }, +] + +[[package]] +name = "black" +version = "26.10.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "mypy-extensions" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "platformdirs", version = "4.12.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "platformdirs", version = "4.14.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "pytokens" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f8/65/a9611a6ec0a8c88d86e59385da02d68d9533f7e86a05913d20c67be54029/black-26.10.1.tar.gz", hash = "sha256:5f9f83beae62437e060dafd53d7f1fc327e3d3494f74d72ee5c2b73eb90fc4e7", size = 741979, upload-time = "2026-10-10T04:13:40.776Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/35/46e9ee9a1b0b5f06d7702fb484e73a5b944acece76898a7ac4d75123514a/black-26.10.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:51d5e417e700fe6ec0b0ecdc408c6f6cb5def80328f31f724993d82c6486b746", size = 2140312, upload-time = "2026-10-10T04:18:26.873Z" }, + { url = "https://files.pythonhosted.org/packages/64/9d/a8f1fdff294ece6cac5d465b9c2349d6c0ca8173977c8b617ea2e12f673e/black-26.10.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:70ccbd175b7f6be29d2b727ee7ca6b4c54053df59da653a6df80b175d20a94fa", size = 1982094, upload-time = "2026-10-10T04:18:29.124Z" }, + { url = "https://files.pythonhosted.org/packages/8e/57/84c7274ecf3732d85a1533ce93d0eb25b318981a26e5c98a37c8f91274a8/black-26.10.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5bd3518d8e97138fef295230b1e9804076d69fa4e3594071494a8c68abe6266", size = 2038822, upload-time = "2026-10-10T04:18:30.829Z" }, + { url = "https://files.pythonhosted.org/packages/14/40/ca69d7af0b8da635fe16eabca737b1e414d44aad967e18ae59f9cd5d00bf/black-26.10.1-cp310-cp310-win_amd64.whl", hash = "sha256:0ce08b367307b0fd91c9dd1d4084e62b05b3055475f951f0f34a46b6e2393b64", size = 1606468, upload-time = "2026-10-10T04:18:33.142Z" }, + { url = "https://files.pythonhosted.org/packages/d8/21/71a49a1f337a89aae496ca864896e499440f36608cbc64054119d71c7cbe/black-26.10.1-cp310-cp310-win_arm64.whl", hash = "sha256:19fa8f5beb5e77c54c9c7e21d00cc93ed6c8b6228ee385616906d6befe081143", size = 1459642, upload-time = "2026-10-10T04:18:34.898Z" }, + { url = "https://files.pythonhosted.org/packages/6f/1e/c1d4f71299d45f4ff54c9c42ef9214d6b228223f196bc1bb2ee196aeaeee/black-26.10.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9a0219b29cd70e49f920acb7081e6ce5025c719008447c521d0200dcad93206a", size = 2121821, upload-time = "2026-10-10T04:18:36.793Z" }, + { url = "https://files.pythonhosted.org/packages/7f/e2/43944049c0945199bbd5c8b291b85306bfd0eeccbc908bf65538a69ff1b0/black-26.10.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7bdade400bfe24d78a7762896acc2f9a8e1a17fb0fd0536bf6b7c7097cf3eec7", size = 1961908, upload-time = "2026-10-10T04:18:38.942Z" }, + { url = "https://files.pythonhosted.org/packages/d5/e9/9616d58f69f0e4bfa89ebe8686b6ef50f4b4f0f91237ae4c76f34dabf8aa/black-26.10.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ff57f63029aa1353fa8b1b0c8971fd88a6c92dc766608d2eee33ad2deb23270e", size = 2019042, upload-time = "2026-10-10T04:18:40.612Z" }, + { url = "https://files.pythonhosted.org/packages/c5/de/0415cce69e2402a5c186cdb5462a0edd3fa44d69d1a1630e68e58daaa6a4/black-26.10.1-cp311-cp311-win_amd64.whl", hash = "sha256:3414a0c52901964dceabd98c7c56beac0f964115a116ecedcce7247359b14017", size = 1608383, upload-time = "2026-10-10T04:18:42.25Z" }, + { url = "https://files.pythonhosted.org/packages/a9/61/af18e716432e932f166ce9dfa419ce3f05fd5ef8c52c0510d27ae41aaa51/black-26.10.1-cp311-cp311-win_arm64.whl", hash = "sha256:1935b32f5326028019856e18cb42b4da63db23765dc84464cec723e0de478a9b", size = 1466048, upload-time = "2026-10-10T04:18:44.271Z" }, + { url = "https://files.pythonhosted.org/packages/f7/ca/357ccdd12e8f8429539f8f52edc153de58acba84f6670ac36c254a276691/black-26.10.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fe85fc4019bee59bc495c0f2a8ee76c5cd02c7015508d94a967ba2376f39a52c", size = 2167369, upload-time = "2026-10-10T04:18:45.948Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a2/4709110a7ca326ba7b4f81a669fbebc20653c79a972b0f8de4ba5b5c5e68/black-26.10.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:182f6c32be38074b16d378498c498b32cb51928178ee611485344972c35ec9c6", size = 1990732, upload-time = "2026-10-10T04:18:48.252Z" }, + { url = "https://files.pythonhosted.org/packages/1e/96/9f8fa839c169d19c38ce6582d9449f2d7d70dabd313ac28f15a930260c1f/black-26.10.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b5347d760f0c02bb00dd249384cab71c3bf828b4f68d5b401eb116e0390f147d", size = 2065235, upload-time = "2026-10-10T04:18:50.064Z" }, + { url = "https://files.pythonhosted.org/packages/2b/ee/929eaf7de6f05a3141d6df72acf9248118f49a5e48f9375be3180e9babf7/black-26.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:4d9a90516db1d99c25dbb20cc0998e0e01531dd903466c7744e56d66f864220a", size = 1621579, upload-time = "2026-10-10T04:18:51.59Z" }, + { url = "https://files.pythonhosted.org/packages/90/3a/8b6a44abf9648b087311003b91298226c1763172cd8d223ece5b7cf8f795/black-26.10.1-cp312-cp312-win_arm64.whl", hash = "sha256:2ffbc023a12d0c729408823b8f10514490bd0baa301d0d4e21a7240249f9507f", size = 1469662, upload-time = "2026-10-10T04:18:53.245Z" }, + { url = "https://files.pythonhosted.org/packages/99/6b/bc0d39990bd7a71457d669639fa06acf6191bec28bafe8b8103f597cce76/black-26.10.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b6272cfd7e1e8e271f5b0e0207259fe2834687e5cb9b5f620b34a44db9754993", size = 2153812, upload-time = "2026-10-10T04:18:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/85/0e/cc83b88a6b1a51fc051aa4e24663918f0bf4fa9fca98552ee93a125a6780/black-26.10.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:978113a40223a6aaefc17364176a809a320e6b288683841427fff04c6d7b4130", size = 1980352, upload-time = "2026-10-10T04:18:56.849Z" }, + { url = "https://files.pythonhosted.org/packages/7b/0f/4dd24ea0ebadbe05e293c3ea7fbebd4389f50508f714640c9b309a0849d2/black-26.10.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:03c0ddd93bb392e71209903a691767eb366fe1a76deb9509ccbaae9e1f14bb52", size = 2055268, upload-time = "2026-10-10T04:18:58.974Z" }, + { url = "https://files.pythonhosted.org/packages/a2/06/221f8e81891ecf5e4df9c258a11037997f1f218533ffe4fa1dc4db37f19c/black-26.10.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6dba8138cdc99061ef07b958ac082d2aa057b6961d1936f9717c350f02bab5f", size = 1625938, upload-time = "2026-10-10T04:19:00.65Z" }, + { url = "https://files.pythonhosted.org/packages/2b/3b/763d2dd073fc1e2cbf0fe5e584fe96913bf0d14cd725d1116f4b38453adf/black-26.10.1-cp313-cp313-win_arm64.whl", hash = "sha256:d42dd2fac7c342ae67e64ee99c9532e20b2a84e92c79ed3317fa2ef54c801d93", size = 1470752, upload-time = "2026-10-10T04:19:03.009Z" }, + { url = "https://files.pythonhosted.org/packages/76/7b/e8d275b23f3023881c0b0d8ce3bbda0d100c79bdef87fb6518bf9e0c5040/black-26.10.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:8375962579d537364cc0efa19b1474481915d3a793f9fc0774901814c5e5b5f4", size = 2147731, upload-time = "2026-10-10T04:19:04.643Z" }, + { url = "https://files.pythonhosted.org/packages/ee/62/e44f86ee5fc7b893ee0ee935a79c785932da7758d2c339749d90a20ef213/black-26.10.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d8b3a9074a680b3c5749633714e9ae3992a1e5a23343a97ad61cd9b119b444d2", size = 1981714, upload-time = "2026-10-10T04:19:06.287Z" }, + { url = "https://files.pythonhosted.org/packages/89/2f/e12ca76edfcd037fe9e7e7635d9468d1d51255cf25a01b2f8f97a38f147d/black-26.10.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:289282aa2e09d3162312a3be1788ff21b08e9ea9cc4a81e656024728b32428fb", size = 2047807, upload-time = "2026-10-10T04:19:08.193Z" }, + { url = "https://files.pythonhosted.org/packages/c3/af/676d3c5cbb2ab0f17c8459b3ae8ea15ebdcc5a2f1c1c586228ec85b8897f/black-26.10.1-cp314-cp314-win_amd64.whl", hash = "sha256:5cd88fd7b444ca51f3fc883b6f6657ea53a258b0b2eef6d9f2dfcfa17ce0e27b", size = 1652537, upload-time = "2026-10-10T04:19:09.817Z" }, + { url = "https://files.pythonhosted.org/packages/ad/7b/860022d369fdd5fe14280b1e7109f58753c371ff91ce2311d68a056e488a/black-26.10.1-cp314-cp314-win_arm64.whl", hash = "sha256:2520037aa62f8a1454d0811b8f5c88b444445b03a4bfba480d8d220893b64c34", size = 1504226, upload-time = "2026-10-10T04:19:11.367Z" }, + { url = "https://files.pythonhosted.org/packages/b1/28/9dd29175c1db777e6189e2a0bb5f37101adf19c3e509b236c8920f778d0b/black-26.10.1-py3-none-any.whl", hash = "sha256:28842f9a8207cc1df6eb983a35a14c5a0dfcd603d214fe82d84bef552afd2e3a", size = 239267, upload-time = "2026-10-10T04:13:38.808Z" }, +] + +[[package]] +name = "bottleneck" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/14/d8/6d641573e210768816023a64966d66463f2ce9fc9945fa03290c8a18f87c/bottleneck-1.6.0.tar.gz", hash = "sha256:028d46ee4b025ad9ab4d79924113816f825f62b17b87c9e1d0d8ce144a4a0e31", size = 104311, upload-time = "2025-09-08T16:30:38.617Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/38/144fb32c9efb196f651ddb30e7c48f6047a86972e5b350f3f10c9a5f6a16/bottleneck-1.6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:40de6be68218ba32cd15addbf4ad7bbbf0075b5c5c4347c579aeae110a5c9a96", size = 100393, upload-time = "2025-09-08T16:29:35.466Z" }, + { url = "https://files.pythonhosted.org/packages/0d/e3/dbbf4b102f4e6aaf49ad3749a6d778f309473a2950c5ce3bb20b94f2ba84/bottleneck-1.6.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1ad1882ba8c8da1f404de2610b45b05291e39eec56150270b03b5b25cf2bbb7f", size = 371509, upload-time = "2025-09-08T16:29:37.037Z" }, + { url = "https://files.pythonhosted.org/packages/66/ea/60fcbddee5fdf32923ba33ce2337a4cf12834b69de4f8e07219b5ef7c931/bottleneck-1.6.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f29b14b0ba5a816df6ab559add415c88ea8cf2146364e55f5f4c24ff7c85e494", size = 363480, upload-time = "2025-09-08T16:29:38.311Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/a25434dcadf083e05b0c71ece2de71fad5521268f905721e06e0a7efc5db/bottleneck-1.6.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:17c227ed361cf9a2ab3751a727620298faca9a1e33dd76711ae80834cf34b254", size = 357120, upload-time = "2025-09-08T16:29:39.541Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b9/99580349c827695dfc094ac672eedba6e1ca244b6e745ff7447c0239d6d8/bottleneck-1.6.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:d278b5633cea38bdae6eaf7df23d54ecb5e4db52f2ebc13fe40c0e738842f2a1", size = 367579, upload-time = "2025-09-08T16:29:40.695Z" }, + { url = "https://files.pythonhosted.org/packages/95/06/6326994249388ceb2400d07c6a96a50941749d2d9ec80da22a99046e3a38/bottleneck-1.6.0-cp310-cp310-win32.whl", hash = "sha256:26c87c2f6364d82b67eab7218f0346e9c42f336088ca4e19d77dc76eecf272fc", size = 107838, upload-time = "2025-09-08T16:29:41.907Z" }, + { url = "https://files.pythonhosted.org/packages/2f/75/8f0e8e266ea99ffbc69500a927f0c114a07fe465bfbc59871d6fe22d9ee0/bottleneck-1.6.0-cp310-cp310-win_amd64.whl", hash = "sha256:9d33bcd60a13d0603f5db9d953352a3c098242c46f8f919290fd11c54b42b9e5", size = 113364, upload-time = "2025-09-08T16:29:43.437Z" }, + { url = "https://files.pythonhosted.org/packages/83/96/9d51012d729f97de1e75aad986f3ba50956742a40fc99cbab4c2aa896c1c/bottleneck-1.6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:69ef4514782afe39db2497aaea93b1c167ab7ab3bc5e3930500ef9cf11841db7", size = 100400, upload-time = "2025-09-08T16:29:44.464Z" }, + { url = "https://files.pythonhosted.org/packages/16/f4/4fcbebcbc42376a77e395a6838575950587e5eb82edf47d103f8daa7ba22/bottleneck-1.6.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:727363f99edc6dc83d52ed28224d4cb858c07a01c336c7499c0c2e5dd4fd3e4a", size = 375920, upload-time = "2025-09-08T16:29:45.52Z" }, + { url = "https://files.pythonhosted.org/packages/36/13/7fa8cdc41cbf2dfe0540f98e1e0caf9ffbd681b1a0fc679a91c2698adaf9/bottleneck-1.6.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:847671a9e392220d1dfd2ff2524b4d61ec47b2a36ea78e169d2aa357fd9d933a", size = 367922, upload-time = "2025-09-08T16:29:46.743Z" }, + { url = "https://files.pythonhosted.org/packages/13/7d/dccfa4a2792c1bdc0efdde8267e527727e517df1ff0d4976b84e0268c2f9/bottleneck-1.6.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:daef2603ab7b4ec4f032bb54facf5fa92dacd3a264c2fd9677c9fc22bcb5a245", size = 361379, upload-time = "2025-09-08T16:29:48.042Z" }, + { url = "https://files.pythonhosted.org/packages/93/42/21c0fad823b71c3a8904cbb847ad45136d25573a2d001a9cff48d3985fab/bottleneck-1.6.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:fc7f09bda980d967f2e9f1a746eda57479f824f66de0b92b9835c431a8c922d4", size = 371911, upload-time = "2025-09-08T16:29:49.366Z" }, + { url = "https://files.pythonhosted.org/packages/3b/b0/830ff80f8c74577d53034c494639eac7a0ffc70935c01ceadfbe77f590c2/bottleneck-1.6.0-cp311-cp311-win32.whl", hash = "sha256:1f78bad13ad190180f73cceb92d22f4101bde3d768f4647030089f704ae7cac7", size = 107831, upload-time = "2025-09-08T16:29:51.397Z" }, + { url = "https://files.pythonhosted.org/packages/6f/42/01d4920b0aa51fba503f112c90714547609bbe17b6ecfc1c7ae1da3183df/bottleneck-1.6.0-cp311-cp311-win_amd64.whl", hash = "sha256:8f2adef59fdb9edf2983fe3a4c07e5d1b677c43e5669f4711da2c3daad8321ad", size = 113358, upload-time = "2025-09-08T16:29:52.602Z" }, + { url = "https://files.pythonhosted.org/packages/8d/72/7e3593a2a3dd69ec831a9981a7b1443647acb66a5aec34c1620a5f7f8498/bottleneck-1.6.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3bb16a16a86a655fdbb34df672109a8a227bb5f9c9cf5bb8ae400a639bc52fa3", size = 100515, upload-time = "2025-09-08T16:29:55.141Z" }, + { url = "https://files.pythonhosted.org/packages/b5/d4/e7bbea08f4c0f0bab819d38c1a613da5f194fba7b19aae3e2b3a27e78886/bottleneck-1.6.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0fbf5d0787af9aee6cef4db9cdd14975ce24bd02e0cc30155a51411ebe2ff35f", size = 377451, upload-time = "2025-09-08T16:29:56.718Z" }, + { url = "https://files.pythonhosted.org/packages/fe/80/a6da430e3b1a12fd85f9fe90d3ad8fe9a527ecb046644c37b4b3f4baacfc/bottleneck-1.6.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d08966f4a22384862258940346a72087a6f7cebb19038fbf3a3f6690ee7fd39f", size = 368303, upload-time = "2025-09-08T16:29:57.834Z" }, + { url = "https://files.pythonhosted.org/packages/30/11/abd30a49f3251f4538430e5f876df96f2b39dabf49e05c5836820d2c31fe/bottleneck-1.6.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:604f0b898b43b7bc631c564630e936a8759d2d952641c8b02f71e31dbcd9deaa", size = 361232, upload-time = "2025-09-08T16:29:59.104Z" }, + { url = "https://files.pythonhosted.org/packages/1d/ac/1c0e09d8d92b9951f675bd42463ce76c3c3657b31c5bf53ca1f6dd9eccff/bottleneck-1.6.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d33720bad761e642abc18eda5f188ff2841191c9f63f9d0c052245decc0faeb9", size = 373234, upload-time = "2025-09-08T16:30:00.488Z" }, + { url = "https://files.pythonhosted.org/packages/fb/ea/382c572ae3057ba885d484726bb63629d1f63abedf91c6cd23974eb35a9b/bottleneck-1.6.0-cp312-cp312-win32.whl", hash = "sha256:a1e5907ec2714efbe7075d9207b58c22ab6984a59102e4ecd78dced80dab8374", size = 108020, upload-time = "2025-09-08T16:30:01.773Z" }, + { url = "https://files.pythonhosted.org/packages/48/ad/d71da675eef85ac153eef5111ca0caa924548c9591da00939bcabba8de8e/bottleneck-1.6.0-cp312-cp312-win_amd64.whl", hash = "sha256:81e3822499f057a917b7d3972ebc631ac63c6bbcc79ad3542a66c4c40634e3a6", size = 113493, upload-time = "2025-09-08T16:30:02.872Z" }, + { url = "https://files.pythonhosted.org/packages/97/1a/e117cd5ff7056126d3291deb29ac8066476e60b852555b95beb3fc9d62a0/bottleneck-1.6.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d015de414ca016ebe56440bdf5d3d1204085080527a3c51f5b7b7a3e704fe6fd", size = 100521, upload-time = "2025-09-08T16:30:03.89Z" }, + { url = "https://files.pythonhosted.org/packages/bd/22/05555a9752357e24caa1cd92324d1a7fdde6386aab162fcc451f8f8eedc2/bottleneck-1.6.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:456757c9525b0b12356f472e38020ed4b76b18375fd76e055f8d33fb62956f5e", size = 377719, upload-time = "2025-09-08T16:30:05.135Z" }, + { url = "https://files.pythonhosted.org/packages/11/ee/76593af47097d9633109bed04dbcf2170707dd84313ca29f436f9234bc51/bottleneck-1.6.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c65254d51b6063c55f6272f175e867e2078342ae75f74be29d6612e9627b2c0", size = 368577, upload-time = "2025-09-08T16:30:06.387Z" }, + { url = "https://files.pythonhosted.org/packages/f9/f7/4dcacaf637d2b8d89ea746c74159adda43858d47358978880614c3fa4391/bottleneck-1.6.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a172322895fbb79c6127474f1b0db0866895f0b804a18d5c6b841fea093927fe", size = 361441, upload-time = "2025-09-08T16:30:07.613Z" }, + { url = "https://files.pythonhosted.org/packages/05/34/21eb1eb1c42cb7be2872d0647c292fc75768d14e1f0db66bf907b24b2464/bottleneck-1.6.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d5e81b642eb0d5a5bf00312598d7ed142d389728b694322a118c26813f3d1fa9", size = 373416, upload-time = "2025-09-08T16:30:08.899Z" }, + { url = "https://files.pythonhosted.org/packages/48/cb/7957ff40367a151139b5f1854616bf92e578f10804d226fbcdecfd73aead/bottleneck-1.6.0-cp313-cp313-win32.whl", hash = "sha256:543d3a89d22880cd322e44caff859af6c0489657bf9897977d1f5d3d3f77299c", size = 108029, upload-time = "2025-09-08T16:30:09.909Z" }, + { url = "https://files.pythonhosted.org/packages/90/a8/735df4156fa5595501d5d96a6ee102f49c13d2ce9e2a287ad51806bc3ba0/bottleneck-1.6.0-cp313-cp313-win_amd64.whl", hash = "sha256:48a44307d604ceb81e256903e5d57d3adb96a461b1d3c6a69baa2c67e823bd36", size = 113497, upload-time = "2025-09-08T16:30:10.82Z" }, + { url = "https://files.pythonhosted.org/packages/c7/5c/8c1260df8ade7cebc2a8af513a27082b5e36aa4a5fb762d56ea6d969d893/bottleneck-1.6.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:547e6715115867c4657c9ae8cc5ddac1fec8fdad66690be3a322a7488721b06b", size = 101606, upload-time = "2025-09-08T16:30:11.935Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ea/f03e2944e91ee962922c834ed21e5be6d067c8395681f5dc6c67a0a26853/bottleneck-1.6.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5e4a4a6e05b6f014c307969129e10d1a0afd18f3a2c127b085532a4a76677aef", size = 391804, upload-time = "2025-09-08T16:30:13.13Z" }, + { url = "https://files.pythonhosted.org/packages/0b/58/2b356b8a81eb97637dccee6cf58237198dd828890e38be9afb4e5e58e38e/bottleneck-1.6.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2baae0d1589b4a520b2f9cf03528c0c8b20717b3f05675e212ec2200cf628f12", size = 383443, upload-time = "2025-09-08T16:30:14.318Z" }, + { url = "https://files.pythonhosted.org/packages/55/52/cf7d09ed3736ad0d50c624787f9b580ae3206494d95cc0f4814b93eef728/bottleneck-1.6.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2e407139b322f01d8d5b6b2e8091b810f48a25c7fa5c678cfcdc420dfe8aea0a", size = 375458, upload-time = "2025-09-08T16:30:15.379Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e9/7c87a34a24e339860064f20fac49f6738e94f1717bc8726b9c47705601d8/bottleneck-1.6.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:1adefb89b92aba6de9c6ea871d99bcd29d519f4fb012cc5197917813b4fc2c7f", size = 386384, upload-time = "2025-09-08T16:30:17.012Z" }, + { url = "https://files.pythonhosted.org/packages/59/57/db51855e18a47671801180be748939b4c9422a0544849af1919116346b5f/bottleneck-1.6.0-cp313-cp313t-win32.whl", hash = "sha256:64b8690393494074923780f6abdf5f5577d844b9d9689725d1575a936e74e5f0", size = 109448, upload-time = "2025-09-08T16:30:18.076Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1e/683c090b624f13a5bf88a0be2241dc301e98b2fb72a45812a7ae6e456cc4/bottleneck-1.6.0-cp313-cp313t-win_amd64.whl", hash = "sha256:cb67247f65dcdf62af947c76c6c8b77d9f0ead442cac0edbaa17850d6da4e48d", size = 115190, upload-time = "2025-09-08T16:30:19.106Z" }, + { url = "https://files.pythonhosted.org/packages/77/e2/eb7c08964a3f3c4719f98795ccd21807ee9dd3071a0f9ad652a5f19196ff/bottleneck-1.6.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:98f1d789042511a0f042b3bdcd2903e8567e956d3aa3be189cce3746daeb8550", size = 100544, upload-time = "2025-09-08T16:30:20.22Z" }, + { url = "https://files.pythonhosted.org/packages/99/ec/c6f3be848f37689f481797ce7d9807d5f69a199d7fc0e46044f9b708c468/bottleneck-1.6.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1fad24c99e39ad7623fc2a76d37feb26bd32e4dd170885edf4dbf4bfce2199a3", size = 378315, upload-time = "2025-09-08T16:30:21.409Z" }, + { url = "https://files.pythonhosted.org/packages/bf/8f/2d6600836e2ea8f14fcefac592dc83497e5b88d381470c958cb9cdf88706/bottleneck-1.6.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:643e61e50a6f993debc399b495a1609a55b3bd76b057e433e4089505d9f605c7", size = 368978, upload-time = "2025-09-08T16:30:23.458Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/bf72b49f5040212873b985feef5050015645e0a02204b591e1d265fc522a/bottleneck-1.6.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa668efbe4c6b200524ea0ebd537212da9b9801287138016fdf64119d6fcf201", size = 362074, upload-time = "2025-09-08T16:30:24.71Z" }, + { url = "https://files.pythonhosted.org/packages/1d/c8/c4891a0604eb680031390182c6e264247e3a9a8d067d654362245396fadf/bottleneck-1.6.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9f7dd35262e89e28fedd79d45022394b1fa1aceb61d2e747c6d6842e50546daa", size = 374019, upload-time = "2025-09-08T16:30:26.438Z" }, + { url = "https://files.pythonhosted.org/packages/e6/2d/ed096f8d1b9147e84914045dd89bc64e3c32eee49b862d1e20d573a9ab0d/bottleneck-1.6.0-cp314-cp314-win32.whl", hash = "sha256:bd90bec3c470b7fdfafc2fbdcd7a1c55a4e57b5cdad88d40eea5bc9bab759bf1", size = 110173, upload-time = "2025-09-08T16:30:27.521Z" }, + { url = "https://files.pythonhosted.org/packages/33/70/1414acb6ae378a15063cfb19a0a39d69d1b6baae1120a64d2b069902549b/bottleneck-1.6.0-cp314-cp314-win_amd64.whl", hash = "sha256:b43b6d36a62ffdedc6368cf9a708e4d0a30d98656c2b5f33d88894e1bcfd6857", size = 115899, upload-time = "2025-09-08T16:30:28.524Z" }, + { url = "https://files.pythonhosted.org/packages/4e/ed/4570b5d8c1c85ce3c54963ebc37472231ed54f0b0d8dbb5dde14303f775f/bottleneck-1.6.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:53296707a8e195b5dcaa804b714bd222b5e446bd93cd496008122277eb43fa87", size = 101615, upload-time = "2025-09-08T16:30:29.556Z" }, + { url = "https://files.pythonhosted.org/packages/2d/93/c148faa07ae91f266be1f3fad1fde95aa2449e12937f3f3df2dd720b86e0/bottleneck-1.6.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d6df19cc48a83efd70f6d6874332aa31c3f5ca06a98b782449064abbd564cf0e", size = 392411, upload-time = "2025-09-08T16:30:31.186Z" }, + { url = "https://files.pythonhosted.org/packages/6e/1c/e6ad221d345a059e7efb2ad1d46a22d9fdae0486faef70555766e1123966/bottleneck-1.6.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96bb3a52cb3c0aadfedce3106f93ab940a49c9d35cd4ed612e031f6deb27e80f", size = 384022, upload-time = "2025-09-08T16:30:32.364Z" }, + { url = "https://files.pythonhosted.org/packages/4f/40/5b15c01eb8c59d59bc84c94d01d3d30797c961f10ec190f53c27e05d62ab/bottleneck-1.6.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d1db9e831b69d5595b12e79aeb04cb02873db35576467c8dd26cdc1ee6b74581", size = 376004, upload-time = "2025-09-08T16:30:33.731Z" }, + { url = "https://files.pythonhosted.org/packages/74/f6/cb228f5949553a5c01d1d5a3c933f0216d78540d9e0bf8dd4343bb449681/bottleneck-1.6.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4dd7ac619570865fcb7a0e8925df418005f076286ad2c702dd0f447231d7a055", size = 386909, upload-time = "2025-09-08T16:30:34.973Z" }, + { url = "https://files.pythonhosted.org/packages/09/9a/425065c37a67a9120bf53290371579b83d05bf46f3212cce65d8c01d470a/bottleneck-1.6.0-cp314-cp314t-win32.whl", hash = "sha256:7fb694165df95d428fe00b98b9ea7d126ef786c4a4b7d43ae2530248396cadcb", size = 111636, upload-time = "2025-09-08T16:30:36.044Z" }, + { url = "https://files.pythonhosted.org/packages/ad/23/c41006e42909ec5114a8961818412310aa54646d1eae0495dbff3598a095/bottleneck-1.6.0-cp314-cp314t-win_amd64.whl", hash = "sha256:174b80930ce82bd8456c67f1abb28a5975c68db49d254783ce2cb6983b4fea40", size = 117611, upload-time = "2025-09-08T16:30:37.055Z" }, +] + +[[package]] +name = "bottleneck" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/af/b8/efcaada1e935c510846dc9a57ba8795dc427b4744ef6826b106b2422d36e/bottleneck-1.6.1.tar.gz", hash = "sha256:d87fd88e01132b7211131c3d12c242e6f30e36fc95786c97d97c74ae26d4c421", size = 107030, upload-time = "2026-11-12T23:44:03.346Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/df/2955fd391ff628d50eb852497f7d728a4f48149aaf0c1645c3a67a7bbdde/bottleneck-1.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a04babeb1d97962cd0885a2db4e8edac0fa3a6c7fcb64621c720682bad349528", size = 122957, upload-time = "2026-11-12T23:42:39.807Z" }, + { url = "https://files.pythonhosted.org/packages/67/93/9e9c230667f61f02abed2e1ff3bc45ba61e042490f376326c6a7c3174b2d/bottleneck-1.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c9dc4c7b2d35e069423d2e67be2f805ce3267b820d1f1de527483d7ad7218639", size = 110667, upload-time = "2026-11-12T23:42:41.438Z" }, + { url = "https://files.pythonhosted.org/packages/8e/99/38c7788cd244bb68cd264fab0f0a2f7bca2592c1fc72b77438ccb0f5f22a/bottleneck-1.6.1-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ff54edec6ebb9263ed42653e6cb311853befe6f206c3163bc30de5715fa2481b", size = 386370, upload-time = "2026-11-12T23:42:42.829Z" }, + { url = "https://files.pythonhosted.org/packages/f9/05/e6591a9746939d3c57c4c259f569e4a6a06b3d8f1dec5a298abc90a49f0a/bottleneck-1.6.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f40e7fe5bd0d97b5de5a5353cc3d9035067f373b4c30da103ce4e6c31a626ecd", size = 379967, upload-time = "2026-11-12T23:42:44.536Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9f/40f1e9ee9344a71e2c2686257a5cc8c69f312a990c4619108769e23ab5ca/bottleneck-1.6.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b08e0f1b1a0317d623a58bba443d86ce5dafadb083fce067cf9a9f4a91247745", size = 373756, upload-time = "2026-11-12T23:42:46.075Z" }, + { url = "https://files.pythonhosted.org/packages/2c/d8/494a31e1729d2fe2e94837f33c241de409f35434233ab878cf5a0df9f199/bottleneck-1.6.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0f145a43d77e63ac877343a96feecc6bbd50d27563423285d64d431ac558ca9e", size = 382570, upload-time = "2026-11-12T23:42:47.521Z" }, + { url = "https://files.pythonhosted.org/packages/8b/ee/b9e18d9f8c635c3024898614db77dfddfbb6bdc0e2475f176d2cdd8ddf23/bottleneck-1.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:108d292e33e89573d3933db160f8f424b01cdeee02d322af724e6ea7b32c5867", size = 118642, upload-time = "2026-11-12T23:42:48.917Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ad/5698971917afa9756da3f61d8d35ae81f8c72472b12f988d40ec9331403d/bottleneck-1.6.1-cp311-cp311-win_arm64.whl", hash = "sha256:46bd2d04e0d823d5197a334bf67f04744161ca0287efb4a1230bd1c69a0c2e70", size = 104395, upload-time = "2026-11-12T23:42:50.74Z" }, + { url = "https://files.pythonhosted.org/packages/52/23/9f3d9c2935e1a57c6e40dd19710f5f4898c7d756ac0c12dd6a8b8a197cbc/bottleneck-1.6.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8b68ee11fc509c8536af6266d6cfd98c1437a1573e5dd3af2f23ca96cdc62cb8", size = 123212, upload-time = "2026-11-12T23:42:52.001Z" }, + { url = "https://files.pythonhosted.org/packages/46/30/d5bb73788422368fb328dcffcbdd7b0accedaa3caccf609d8a7d4ee8a20f/bottleneck-1.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b04ea71a0ff6ed3543aee0409d947a9418b462f58a15bef523cf59f1a57193f7", size = 108870, upload-time = "2026-11-12T23:42:53.304Z" }, + { url = "https://files.pythonhosted.org/packages/c6/9b/cbdf09996870a9777782df2843f990a6462855cb5bf87710307f23d0855a/bottleneck-1.6.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:80efa32021fe3d7978b7e37f8ae99fa26e95309736b4ad7c5c983598c3534c9a", size = 394603, upload-time = "2026-11-12T23:42:54.893Z" }, + { url = "https://files.pythonhosted.org/packages/41/aa/f82630d530449e7d8607b3f5a6c5bb8499b7dfa3ee56c87c552613e80c00/bottleneck-1.6.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef9ebab87e72a0ac5ff464d8e368f4934fde9958fad5010fe069d9f0711b28fd", size = 386943, upload-time = "2026-11-12T23:42:56.753Z" }, + { url = "https://files.pythonhosted.org/packages/39/f2/492d3af23db36688489f328f6d2283703aa11167e88f9f8b502a48663e50/bottleneck-1.6.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5d0f25598dd514cb5853a2bf59bb94bf1c1e7181d912817cfd7ce532eed03c08", size = 379929, upload-time = "2026-11-12T23:42:58.749Z" }, + { url = "https://files.pythonhosted.org/packages/c7/34/9a53275f2c41956758b3e0ae752105ba24f97a0700b0aee1abf1b199d581/bottleneck-1.6.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb1614312977ecb64a5633f748d4be4e1312a2622773bda01258c5a94ce75df0", size = 389763, upload-time = "2026-11-12T23:43:00.446Z" }, + { url = "https://files.pythonhosted.org/packages/de/e2/019ac28f760fa6f77f83604d9f7089624b67a73bf6f49ff5dae58069bc4b/bottleneck-1.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:af7cea3552f186e12b7ba29431a551e1a00f5bea979d5df132a6e57a29643a8e", size = 119374, upload-time = "2026-11-12T23:43:02.295Z" }, + { url = "https://files.pythonhosted.org/packages/5b/67/35ffac8441f064af743adf60a9f9546e2e8eca5b89d6235210d8a9bc3466/bottleneck-1.6.1-cp312-cp312-win_arm64.whl", hash = "sha256:5248a65e4848e6ce5d710193a1581037481facdee563489783a52be76ce6580e", size = 104534, upload-time = "2026-11-12T23:43:03.863Z" }, + { url = "https://files.pythonhosted.org/packages/a1/31/c9854c9f556a1fbdde9f357b26511b7f0af559ff5677223e9b5baf0ee987/bottleneck-1.6.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1f6d3a811330ad7051f0c59aa112aaacdd5b885bad7f3be150a4273c1a7891c6", size = 123224, upload-time = "2026-11-12T23:43:05.163Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cf/2795573b47fa0287d78c6aac6e9655e26d0a87432a3af7a3d529361af851/bottleneck-1.6.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4b7713d9bb341af24e27a93c3b792c5ad21e5dbdea32f47fe7c07af5aa8c48aa", size = 108866, upload-time = "2026-11-12T23:43:06.534Z" }, + { url = "https://files.pythonhosted.org/packages/a2/c7/c686bdeeb5641009c2870c9c5963181d995cdb55460704d59d3b8613c3a0/bottleneck-1.6.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:49208f9180a4375424784a18854cef8e93d931100cab1999dbb447df43acadce", size = 395014, upload-time = "2026-11-12T23:43:07.973Z" }, + { url = "https://files.pythonhosted.org/packages/79/9f/72eaedcddad0b2e7d99b3828633b24d8e191be23e8afa338d59f8bd1123f/bottleneck-1.6.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b7d62a2059ddcc1c47dfd1310829bf8e67e9f2ddc718374084546651d9380554", size = 387331, upload-time = "2026-11-12T23:43:09.484Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ae/f1b4dc2a62bb6b6f6f7ba6593c4a299fd7cbc2685f3ef0d1964255676610/bottleneck-1.6.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e686257ec853c6dfffcbf61091d11f03c8e8157d34c5a98fef5fe2b87e97f1af", size = 380217, upload-time = "2026-11-12T23:43:11.218Z" }, + { url = "https://files.pythonhosted.org/packages/00/2d/5c9c82270235f676d62ef4d1a17fdca6251674c5664562ba8b37f1a78091/bottleneck-1.6.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:806f643f5aaea5d6568fc38b219c97cc27d64f02a2a8baad58763c4624ab998c", size = 390052, upload-time = "2026-11-12T23:43:12.673Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ad/fcc4a0f09cab468032007a4a2ba87f00e826fbcce4e0f5db3d7510016a4b/bottleneck-1.6.1-cp313-cp313-win_amd64.whl", hash = "sha256:adbc1bced052eac6f0f412b3104ffe3b249d40e95319f529420ec86a1443ee26", size = 119378, upload-time = "2026-11-12T23:43:14.209Z" }, + { url = "https://files.pythonhosted.org/packages/58/8f/955be246ea7302bc2fa254295a2706d059915e54f3d002b8b44c66dd8c76/bottleneck-1.6.1-cp313-cp313-win_arm64.whl", hash = "sha256:068ff20b07996dee74239a700d3f04082aa0bc81267bf1d74ff53eb9f00749cf", size = 104555, upload-time = "2026-11-12T23:43:15.852Z" }, + { url = "https://files.pythonhosted.org/packages/92/9b/aeafab3d96db1e298b29c51b3bf01c0912b30c9fc6ced3a1d1b892d97d4c/bottleneck-1.6.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:e10d0887b5369265a8638863078d162ecc0a8f7959f1c56bddd204f0a2982eab", size = 123522, upload-time = "2026-11-12T23:43:17.122Z" }, + { url = "https://files.pythonhosted.org/packages/6c/69/ee63727b2e3d422cd5d39b4b52dbe14658da6d3002cb6d5e2bab7529918c/bottleneck-1.6.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7071b8cb4dce4d1f0ba40b4ac19f6ddfb12047109ace31e658ebb3835781daf1", size = 108850, upload-time = "2026-11-12T23:43:18.287Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b8/8b6c8f8aa379b744a2ed5684d0c027357cb7eeb92158bdfb9b2cc6dc8dcf/bottleneck-1.6.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3aa25f81eb19862f0899ba381e3aa321cbd2629b9b1c5cfc2168e3c744b59c51", size = 395148, upload-time = "2026-11-12T23:43:19.596Z" }, + { url = "https://files.pythonhosted.org/packages/96/69/90a21d5279c9892574a6a51d66f481f0c703358fe1a30b5511f00e736b3b/bottleneck-1.6.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eeb669951ffd13a156c9b745e98454aefb7f8d3eb560c76357ddffecfcbd00d3", size = 387789, upload-time = "2026-11-12T23:43:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/30/b9/1a8b458c717a34a0f7233f7a91fb768d131dfc33bff9137c3f1189dbbe42/bottleneck-1.6.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9aead9b5ac0a5bc4c702cc05920bc0fd49f6fcd0c57d4a22d2d49fefa4cbdb96", size = 380951, upload-time = "2026-11-12T23:43:22.705Z" }, + { url = "https://files.pythonhosted.org/packages/53/f1/270e0670de68bbcaaf1f55f3f9822b9766372d894c4368cb759881af0964/bottleneck-1.6.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:168a1bc53439735c54994861ef98487422a95a83195d2f2b2772fd1364f9066d", size = 390370, upload-time = "2026-11-12T23:43:24.552Z" }, + { url = "https://files.pythonhosted.org/packages/59/3e/38ced61062e75c65690ec95ddaf61d9f96d3561eab8c16ca2ed17fd65a47/bottleneck-1.6.1-cp314-cp314-win_amd64.whl", hash = "sha256:5259d260370ee7b1dae20c97928e100023785875d2cfecc0fb11b33693d3cc23", size = 121366, upload-time = "2026-11-12T23:43:25.926Z" }, + { url = "https://files.pythonhosted.org/packages/f4/4a/1977df19c9121cc8c2af364b46243debd6182722f7e9699baa2ffe86add0/bottleneck-1.6.1-cp314-cp314-win_arm64.whl", hash = "sha256:05e5079d487c9f7fa1768db0a008c3f831c5e102c61a1fb16e6b1d7118f0d522", size = 107093, upload-time = "2026-11-12T23:43:27.202Z" }, + { url = "https://files.pythonhosted.org/packages/5e/04/505056c66f3c27465a62d1b9a0852b227d2590a2db5cbe5c8873d1f2396a/bottleneck-1.6.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e06cfed4a880562fcd7f6cccf3a59d9b15651ac68bf7f8d3b28a43d7827fc19a", size = 124489, upload-time = "2026-11-12T23:43:28.51Z" }, + { url = "https://files.pythonhosted.org/packages/a6/42/351f07bcd1cf8ac79c7801fc34b84766a5e7502029bcee5304178688ade0/bottleneck-1.6.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1c2614633a136601c9035c26ff1cf93cc6c59090f96317dfbc6b81f18e35dec2", size = 110051, upload-time = "2026-11-12T23:43:29.803Z" }, + { url = "https://files.pythonhosted.org/packages/23/32/2a611421b98246580f7b6ba51c7155d87a5ddca556a87cdf27a515b9b670/bottleneck-1.6.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6aa06ea952d83a896f0b09c2a4a014a1886f724fb011f2db38caf78d5d106f35", size = 414743, upload-time = "2026-11-12T23:43:31.128Z" }, + { url = "https://files.pythonhosted.org/packages/f1/88/93338519eb3d85cc60bffe5e35afb9980697dc3bf129d2e388479bad3fd7/bottleneck-1.6.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d3e0620854be668642ac6ef3e5f020b5285f821217a1dfe7d7697b3d18417c83", size = 407061, upload-time = "2026-11-12T23:43:32.739Z" }, + { url = "https://files.pythonhosted.org/packages/f5/25/e5589e47bd6a1065c418f57ee1488925f3fa9bcb13a6a44c6bb74882767e/bottleneck-1.6.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:dc34e0285b29e0aeb43f66b72f115a7740366b1cb04be0f1c6ac831608b1420f", size = 398092, upload-time = "2026-11-12T23:43:34.297Z" }, + { url = "https://files.pythonhosted.org/packages/32/a4/2982d34adb17107e21bc681cc7e7ee53e7f6c6dd23aa16db15133e146fae/bottleneck-1.6.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cb376e577ad6031dc866d67693d6240cec184b2df87d2d5141592c786551c20a", size = 408380, upload-time = "2026-11-12T23:43:35.859Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c6/31d7d0da33bf2bbd09f5d789f425433c3464b980428ea390d37f95d07d5c/bottleneck-1.6.1-cp314-cp314t-win_amd64.whl", hash = "sha256:40e6dfd53ee3260b03e7b27885721fc20d84fbb422e8c1cc3296bd5a68dd198b", size = 122849, upload-time = "2026-11-12T23:43:37.488Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2c/d7b1012c7237f39ed92db6827267c47077989db052148a6e56ea466f85df/bottleneck-1.6.1-cp314-cp314t-win_arm64.whl", hash = "sha256:04ec89568fb7cf309882e32fb3a583be77283ebe5caf05c416e47d23f0161923", size = 108112, upload-time = "2026-11-12T23:43:38.747Z" }, + { url = "https://files.pythonhosted.org/packages/0c/36/6883c1402306c264dbff8e9f5467a83a610209d2cbdc206cf907dc97d3b5/bottleneck-1.6.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a5b37d60200e95fd5dfafba868eea3338cc274d888b84994a8c32ef2a90b8e5e", size = 123521, upload-time = "2026-11-12T23:43:40.25Z" }, + { url = "https://files.pythonhosted.org/packages/af/4e/31ebf054f85a485ffe235dc50bfe478cb6c15d741629dd79aa6e351b4b6e/bottleneck-1.6.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:13330ac172a1b00609f554737672624285be4d4981545618d43eb2a120589016", size = 108894, upload-time = "2026-11-12T23:43:41.63Z" }, + { url = "https://files.pythonhosted.org/packages/c0/51/f4e788f20a0c6db6fe14173656b7007a536986eb0d621e379f91e83e14ad/bottleneck-1.6.1-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2cc3ed43a68620e933b30ec18fa19d2a3cb5a7ed3707083d14dfd2431257ee3c", size = 397211, upload-time = "2026-11-12T23:43:43.224Z" }, + { url = "https://files.pythonhosted.org/packages/4e/ed/114ab7b0dc2afbdfb370be13283a0ba97cbcade2afcf97153acfa8c9aab3/bottleneck-1.6.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:80c78b184139bd76bfaaee0b991e0daf4a5415a1bf21b2c03dae513a0dfaaedd", size = 389497, upload-time = "2026-11-12T23:43:44.754Z" }, + { url = "https://files.pythonhosted.org/packages/0e/88/13bf4e6e813b41f3e20be28337eb2439c00e294ce219affb5a6fbb5c1384/bottleneck-1.6.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:2bfde1e628c3fa6a974b078ca8839222fb686b40e136fff13bcbb8b06574a4b6", size = 382490, upload-time = "2026-11-12T23:43:46.177Z" }, + { url = "https://files.pythonhosted.org/packages/fd/e3/d2ac62526e2b29229440215710413b30c5a065f99ac52788de40251c181f/bottleneck-1.6.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:52cc1759f686e5eb90831cc0a700f3397cfcd663199160648141299145e982a5", size = 392122, upload-time = "2026-11-12T23:43:47.629Z" }, + { url = "https://files.pythonhosted.org/packages/64/70/8614930a37e2c7e04bbbeba1ad551731ec1e7b16088a4cd410a9b902c762/bottleneck-1.6.1-cp315-cp315-win_amd64.whl", hash = "sha256:b4da13d8631ca6bcadb23e83c28582dbbc47c26bb00d816ff34905b6de505da9", size = 121363, upload-time = "2026-11-12T23:43:49.236Z" }, + { url = "https://files.pythonhosted.org/packages/dc/ed/340802471cc39487dd008496dbee10e89ce1a51062b8704920556a382a3f/bottleneck-1.6.1-cp315-cp315-win_arm64.whl", hash = "sha256:c377453ae43558100bcec571e3e64da5e6a23eab3c5aecb26116221a3266e248", size = 107092, upload-time = "2026-11-12T23:43:50.553Z" }, + { url = "https://files.pythonhosted.org/packages/7f/48/283ee19dcba6c0bb5bcfbedf125f1b8b9a8ff43ad1c1c66a25f27a893735/bottleneck-1.6.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:963958ceeb33c735b91222ad6817771b876d79025a8b36c422bfdb1cb627c6ab", size = 124497, upload-time = "2026-11-12T23:43:51.962Z" }, + { url = "https://files.pythonhosted.org/packages/9a/1f/2d54d9e96d94372e7b854436e343b01a0ac9a2152fd1b71629bc5cfc070f/bottleneck-1.6.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1bb03af0b98f7478ad6bed1deedc510182147612a6448ba4e7d924820e93b409", size = 110116, upload-time = "2026-11-12T23:43:53.244Z" }, + { url = "https://files.pythonhosted.org/packages/75/37/998fb0b5e87a0b13446799b2712f27f0b7a8a3e663ee843552796eedcbb9/bottleneck-1.6.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:aa34bfa55af4f91650853fe65883e188f2088ef6244cee21735e39725d6d4250", size = 416309, upload-time = "2026-11-12T23:43:54.566Z" }, + { url = "https://files.pythonhosted.org/packages/18/41/5bf185165830170483df9f5f58dda3641f9ee2f2a90d9b1e0c9b569a12cf/bottleneck-1.6.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fb63e8885c2ba8083e37eca7db798be448b0aee6e9b6349ec57872eed7885c92", size = 408499, upload-time = "2026-11-12T23:43:56.149Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b6/37d9c3986fcb142f9e10c642998d893e4c6af8cfdbd713d1e1fc6e14ea2c/bottleneck-1.6.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:55ce169dc3f635d83d83502a0f3908e003214c2bbb1a176cb11e3ac319892681", size = 399758, upload-time = "2026-11-12T23:43:57.572Z" }, + { url = "https://files.pythonhosted.org/packages/4e/9a/d7d0208b6f1833534a0df3c4799f8c518670eeec29fa478edb59f2a30120/bottleneck-1.6.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:01b61550829e459acd1f0b650ccc822d257e87217f9f43841e73efda1190bafc", size = 409562, upload-time = "2026-11-12T23:43:59.109Z" }, + { url = "https://files.pythonhosted.org/packages/e1/88/abb80e28ee966a79d975ca38299a68c1304f2e5fc74026517e77e9809c93/bottleneck-1.6.1-cp315-cp315t-win_amd64.whl", hash = "sha256:6f389a9c00a855694cdf61b955fb32b5f62744efd178a8e7838418781479e61b", size = 122839, upload-time = "2026-11-12T23:44:00.493Z" }, + { url = "https://files.pythonhosted.org/packages/f9/b3/4488d8bb735d44e5d151ed5d5dc3f7ca140bf26dcadddb7dcb136a8e8ff2/bottleneck-1.6.1-cp315-cp315t-win_arm64.whl", hash = "sha256:73eca199ee0d50de4c1f5a77b0496f3d3216058d605c973b32e32c5d86c53278", size = 108112, upload-time = "2026-11-12T23:44:02.02Z" }, +] + +[[package]] +name = "certifi" +version = "2026.11.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c2/c3/cae6d3bdefd96a941ffc247c714ac4babc488a69012e11c058f6c17c6c47/charset_normalizer-3.5.3.tar.gz", hash = "sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff", size = 189359, upload-time = "2026-11-23T02:46:51.755Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/60/b6b70cc6e45cf77ac0a743f47f199080eb18e824f4c28e53dd63edbd8039/charset_normalizer-3.5.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:885f202d6e4e2298bea9802ffc6d8c7dc45394199a8dd9e1492f05fe32dce311", size = 411630, upload-time = "2026-11-23T02:43:14.895Z" }, + { url = "https://files.pythonhosted.org/packages/78/60/6a73c07dfefc15b909895383e1d01ea98ebb064d57621f6b9d8d4e606e4e/charset_normalizer-3.5.3-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b6dad86d938104f9d43404029e5fc8392f82762d171933be4f192a6008bffa53", size = 263930, upload-time = "2026-11-23T02:43:16.539Z" }, + { url = "https://files.pythonhosted.org/packages/03/40/9e6333fbb8e6237ebfbf9f0f8bc8db0de43d40c5373853d189cd4b16679e/charset_normalizer-3.5.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92ddc32b6a1508ea145f4f7995e00666db454b8fd3e2cae6c2ecbde4f4d44616", size = 246432, upload-time = "2026-11-23T02:43:17.787Z" }, + { url = "https://files.pythonhosted.org/packages/83/58/75783a43672907e938223c5b5a217284261de73404261da579ee0cd38df5/charset_normalizer-3.5.3-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:fc540d1618c5638fcf5aea97060cf011467918b010bf682a84ecc0c9474e6cd0", size = 249817, upload-time = "2026-11-23T02:43:18.973Z" }, + { url = "https://files.pythonhosted.org/packages/39/55/615f134c354fd90f47ffe6c6a884c1eb2587f25113651f603ec7034443fd/charset_normalizer-3.5.3-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9510da88bdebc903be7844f31523ac8d7b3f63e167db54b6045104a2354afa6a", size = 293095, upload-time = "2026-11-23T02:43:20.417Z" }, + { url = "https://files.pythonhosted.org/packages/c6/24/d70b990089fe54839cae31ce5ef267614039a62cb0ed8dd7949e9c696b81/charset_normalizer-3.5.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f5a5c311e5de6954c36230a37863b5ca58ce232589bd637ad2881c4056897b12", size = 290128, upload-time = "2026-11-23T02:43:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a6/e3f17fb7fc63db3647b3e2ba5a9aa678893d178da9038dfda864bf0dd3b6/charset_normalizer-3.5.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4a991dbd7aec868fe10802b02bddbf898173a47ba236f2d6afb4ab1f98243534", size = 272037, upload-time = "2026-11-23T02:43:23.318Z" }, + { url = "https://files.pythonhosted.org/packages/c6/d0/770f8e143ff0a6b2b1256af515e585d83b454d75cfb8dda484aac5d92484/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:256b434b2860ef9da1cb6a5fd4ebb5d600936668e50e2035858948b96b068ecd", size = 248179, upload-time = "2026-11-23T02:43:24.712Z" }, + { url = "https://files.pythonhosted.org/packages/0f/56/cae2c9f8584eae51da90da38170d48ccf4cfe9d429f0ce5f85a06900b501/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:806e72ebaeef54d7faa03414be9e8409eb3dcae49fba089d62063a60c0b5a4e5", size = 252278, upload-time = "2026-11-23T02:43:25.996Z" }, + { url = "https://files.pythonhosted.org/packages/a6/e3/14aca06dae6d429401214c61157d23f2526b20b39cea4d8c170fd67e7469/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:326a7a0e3715c3ac24c21e7a3b831d6799cc795bff260aa49c23b69025852f99", size = 292581, upload-time = "2026-11-23T02:43:27.311Z" }, + { url = "https://files.pythonhosted.org/packages/93/ad/150c0142f8da5cda0a42238f48f2cdd903389b54131c7939756bcdc9a223/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d57f1b6affc3581fbf0bc6d783cc60e7c9957adfd9c7b89f8a9f3573ad1cd49a", size = 271620, upload-time = "2026-11-23T02:43:28.543Z" }, + { url = "https://files.pythonhosted.org/packages/a4/7d/523a40378a79d61746340f4392866f7e67174fe9e344d8c389718789741e/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:73b4ddf1230df56c9e7017a16e3f5171b6ef0e4ff554a418a370d7ac7245bd84", size = 289557, upload-time = "2026-11-23T02:43:29.931Z" }, + { url = "https://files.pythonhosted.org/packages/cc/71/513af750987adfe3478dd0a9a3dd33a2f665c6c77e8ad74f81c907eeae87/charset_normalizer-3.5.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:2b7797a5b0cb197f118fd13b41c14c5a3c38dd625a87c1da58a3066cf53254fd", size = 265756, upload-time = "2026-11-23T02:43:31.084Z" }, + { url = "https://files.pythonhosted.org/packages/b4/73/90912621bb04d36f7df20ebc0bc6edd7d05ad57a8ca9313a37525d657e45/charset_normalizer-3.5.3-cp310-cp310-win32.whl", hash = "sha256:277b72183b96879887f0c3aa0bdac1fee08a6c7e67bad53145c4fd416d99dfd3", size = 191223, upload-time = "2026-11-23T02:43:32.66Z" }, + { url = "https://files.pythonhosted.org/packages/0c/06/ce199f4ecf05475e3a900e0083c0037e966c8234edae29d6d1b850e45597/charset_normalizer-3.5.3-cp310-cp310-win_amd64.whl", hash = "sha256:2246873913d7db43ed5a3d98ace398b989b2ae20b77c8d761a7bef5fdb9bed42", size = 213382, upload-time = "2026-11-23T02:43:33.898Z" }, + { url = "https://files.pythonhosted.org/packages/db/7b/14d6f8ea93d6a44875a13234d34ad74e562a6caae981c50f8cdc392fb15d/charset_normalizer-3.5.3-cp310-cp310-win_arm64.whl", hash = "sha256:5970d148182b6b7c22b8290a81f02fb521c4e7aee6747743b3e645db58d5001a", size = 198702, upload-time = "2026-11-23T02:43:35.089Z" }, + { url = "https://files.pythonhosted.org/packages/20/f2/fe2bc8a01ed1f3ede348d8afb8e416e81abe801a4ad789a8c5276d95b370/charset_normalizer-3.5.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2", size = 409498, upload-time = "2026-11-23T02:43:36.288Z" }, + { url = "https://files.pythonhosted.org/packages/98/ff/6b85c4ee2809f4dbfcee89d128f64d2e5141f2d4c3191cb00048bb93b150/charset_normalizer-3.5.3-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2a6f937e0b70133d1f826d0a253331b6fe1a4c874808cc12e16f2fb8177042f4", size = 263382, upload-time = "2026-11-23T02:43:37.485Z" }, + { url = "https://files.pythonhosted.org/packages/45/16/fcd396b14758f491a8dcb6c81373f0d2e3ba8a28d3cec4c1dea24ec0bea0/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90b1ff6cb9c7a204a3b79b1b0ed6ac8a1d8fed3b6dc69e50ae5de0f358ee81d4", size = 245172, upload-time = "2026-11-23T02:43:38.714Z" }, + { url = "https://files.pythonhosted.org/packages/b7/49/7fb9fba79adf9b29c19f9d0ff5cc9633a5f59b5f4ed0af2eab6be1fdbbf7/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:139aeb8ca63946dc79364c37f2c9cfe5c1b7f3882f2c47484d0e54bf14b921b0", size = 248633, upload-time = "2026-11-23T02:43:40.119Z" }, + { url = "https://files.pythonhosted.org/packages/b9/58/4c7e8cb06d3a158f0d3f5d9c83b9048db30077b078dd7b13b49a412ad0dc/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f7a841170fde40b0e1345884bee09ceca7db49a9291fa340089bec66a366c243", size = 291866, upload-time = "2026-11-23T02:43:41.34Z" }, + { url = "https://files.pythonhosted.org/packages/f9/6a/ea6c3a53861c624ade21df448f28091f1f809bb87c56359e27f78eba680a/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:56405211fa124c393eea14b3aeacf5b90de72b1f69b0a60c9bc40b01dfe71a42", size = 289387, upload-time = "2026-11-23T02:43:42.746Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/8b76a30025bb27f32eb1d6684fda8ae95789848e02cc94e25d058a72b883/charset_normalizer-3.5.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0cf4cb8d75090a8da3bd30c0963b2c6c6114e791c6fc060c3cef8971497b1f04", size = 270972, upload-time = "2026-11-23T02:43:43.969Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6f/95e3df1908c796c8ddb02302b48d49b91d9a1791c32eaf04425239154abd/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0ca2da4a505fae7ef95922f8d48235b2e49ff8f10f4edcc0481e5f6526ba3841", size = 247844, upload-time = "2026-11-23T02:43:45.264Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b7/e72956933c09a72e2ae0c6aa75ec2689aa3f8297625a037772146bc6433e/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:09833ba78c91f0d1fd06387c69dae9f079428b77ea05eaaf1553eecead31fb68", size = 251932, upload-time = "2026-11-23T02:43:46.573Z" }, + { url = "https://files.pythonhosted.org/packages/30/b2/78a30d82ac9c712c2cf64ad95983c2ff7ebcf05830ff319d9f77827c4969/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:28d954a437bfa5fcdfe7ad8902cf4347a8486f34a86c5f39003bc1288eb67d72", size = 292201, upload-time = "2026-11-23T02:43:47.878Z" }, + { url = "https://files.pythonhosted.org/packages/ff/3f/49bb7c3f23ae35cbc3d419721cbf65505c3f8a69edd3b56dfdc4c67d9363/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8", size = 270702, upload-time = "2026-11-23T02:43:49.02Z" }, + { url = "https://files.pythonhosted.org/packages/3d/5e/dbae2c2caf099dfcd5cb4b62800e9c39ce39f6595fae5fc7a34077e66fbd/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a43831574e14423103d69fb1357e76e4f2347041c98e8357ab88ef21812e80d9", size = 290015, upload-time = "2026-11-23T02:43:50.243Z" }, + { url = "https://files.pythonhosted.org/packages/f0/99/2f765df40b47605479c3d38a0ccb093e9e3b56baece1f0fbe2ebe37b8ac8/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96387278c3b17bc1170f80693398d0babac7b41df128ced8e27588a7155d95b2", size = 265450, upload-time = "2026-11-23T02:43:51.459Z" }, + { url = "https://files.pythonhosted.org/packages/fa/f5/000bc674f132ea23e06ea8eee6b9b4fdad020774b242cda32eb2dbe70026/charset_normalizer-3.5.3-cp311-cp311-win32.whl", hash = "sha256:6eea31136fd924ecbb4e7c4f3df4b18230409629a22b3896f38a6754d5857794", size = 190318, upload-time = "2026-11-23T02:43:52.686Z" }, + { url = "https://files.pythonhosted.org/packages/50/92/529dd4a3af41874d0cac3c495ec9622c1457cbe7b8276fa8b767235ab8d2/charset_normalizer-3.5.3-cp311-cp311-win_amd64.whl", hash = "sha256:cd5422fd4f8a7859846c9289e310dd95c0d1890c31819667942753e510f88f69", size = 212879, upload-time = "2026-11-23T02:43:53.855Z" }, + { url = "https://files.pythonhosted.org/packages/78/9d/2a2cb4843dc8b2a84b1a97e0a8423d00d41b4bf065c8bf0f7549c572a226/charset_normalizer-3.5.3-cp311-cp311-win_arm64.whl", hash = "sha256:d3c9d5284d64f4c1015d95b751577b260fd6d14e3f8edf21710f4436e7ac4c49", size = 198117, upload-time = "2026-11-23T02:43:55.058Z" }, + { url = "https://files.pythonhosted.org/packages/c6/3b/df144a2ee54de30605fb046b80c5948dca47499383e5efecfbca3c46c2f7/charset_normalizer-3.5.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:92bf85ecec3ad6374ae50d870bd1deb34de12bc1158b5fd09036d4c435c6f58c", size = 388675, upload-time = "2026-11-23T02:43:56.285Z" }, + { url = "https://files.pythonhosted.org/packages/67/92/6db11254f4009dd980e17473a0ee4a4b54945df4d8346af4bef8999ab85a/charset_normalizer-3.5.3-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6", size = 257134, upload-time = "2026-11-23T02:43:57.512Z" }, + { url = "https://files.pythonhosted.org/packages/12/9b/2e28514323a452c444c0c0f27a6aae1d6d74a5b255e2cb6d09dbea3c06c5/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f65dd0c2ed79ea2d9776096e9c7d25e398c2c03eb31877753598d201d91784", size = 239885, upload-time = "2026-11-23T02:43:58.827Z" }, + { url = "https://files.pythonhosted.org/packages/a7/02/9133fb797235f0e46fd0e13792e1cf2dda23ddc7fc58ff55b4a1556b98d6/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b702d36c565f6c650f4b479488f475b2982132ab8d0840d42b1442462c21056", size = 240385, upload-time = "2026-11-23T02:44:00.268Z" }, + { url = "https://files.pythonhosted.org/packages/d4/0f/190e230562c2d6bdbd86d1f310fd2f0ac6989c0a80ce42b71dd97f27a661/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dbdd407104ebf2360464ce02c7933c6ffac58bd5b64cdf6ef7dc0e787e782aaf", size = 275901, upload-time = "2026-11-23T02:44:01.527Z" }, + { url = "https://files.pythonhosted.org/packages/39/a4/d0994111d32d5b0b91284aca5c63d0f5c718811a79827c1d55a230d16e37/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61f3258f700412c68fde407e7c749ed6930e795ea8f5ead9a40afddefbec12c4", size = 273855, upload-time = "2026-11-23T02:44:02.939Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0a/099a0cc4078c2411e4d7f6d9bd71289d69e3095e157c301dc4cf4b2e92bc/charset_normalizer-3.5.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa2476abf8669be493689634bdb79f468a6fe57b005a5126db7e9f61d1954fe2", size = 256145, upload-time = "2026-11-23T02:44:04.216Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8b/9db93b3aca912fe1ca5babf4b68376b74940dc23bec67e80f1b4c9ec3886/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1b2704f4651539eab50ba104a975b96c3cd5246011aa0755d2dd71ac12546644", size = 241112, upload-time = "2026-11-23T02:44:05.412Z" }, + { url = "https://files.pythonhosted.org/packages/bc/9b/cb69867d3ad8c6d177b65cbd716c006dbfeebb09890bf48eb77e162799c6/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:2c4e0050b732ee3dca3676a5f5cf7fbd0c131761c194f1bb1d24c055fad071cf", size = 244503, upload-time = "2026-11-23T02:44:06.677Z" }, + { url = "https://files.pythonhosted.org/packages/54/e1/706d79ce618c4731068ae958c43cf2123ed80b41e378f2dd2fed0956e497/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f06e257ee0cc85a7e4ec44f171ae2595fd901c34212f3c9e7ab8fd8621401e99", size = 276842, upload-time = "2026-11-23T02:44:08.076Z" }, + { url = "https://files.pythonhosted.org/packages/ac/fb/1f42f866d6f9e15817017c1495bbd90a3ca99e5af7057828d5c07cb98f69/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:396fdf2d4367674531a7c8d54ecabbc8e5131e3a1a06270285eb99f3140143df", size = 255982, upload-time = "2026-11-23T02:44:09.328Z" }, + { url = "https://files.pythonhosted.org/packages/3f/b0/a145cebd7a3b787638e64e12a15d2b227f6830a65294d137c70ea4b51482/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:b6ea5bf7e3c39f6e56957d82274ac7cfab469590085883fdbc86e754cde76b11", size = 274691, upload-time = "2026-11-23T02:44:10.546Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a1/172b880e2666371817666fff6b9e43cf0e50e8be91e38158fab8c83c29ba/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9", size = 259298, upload-time = "2026-11-23T02:44:11.73Z" }, + { url = "https://files.pythonhosted.org/packages/2a/66/ac0ae9f9bdd82fd619c61763115c6aad5cc537234923bb4fc131749545ca/charset_normalizer-3.5.3-cp312-cp312-win32.whl", hash = "sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3", size = 185505, upload-time = "2026-11-23T02:44:12.862Z" }, + { url = "https://files.pythonhosted.org/packages/82/78/7913aa5816c1606298274f47caf208efdd4245a0da1e309a13e518cc007b/charset_normalizer-3.5.3-cp312-cp312-win_amd64.whl", hash = "sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13", size = 214472, upload-time = "2026-11-23T02:44:14.041Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/59a418223401d7e85ac15d4a0ae978d2fe802f8acdef50d6b55724edc75f/charset_normalizer-3.5.3-cp312-cp312-win_arm64.whl", hash = "sha256:948fb3649416a70bcdbb267d79c7048e8aa16e989ab9da09f416e67cdd3d6b8c", size = 201366, upload-time = "2026-11-23T02:44:15.264Z" }, + { url = "https://files.pythonhosted.org/packages/6c/b8/9aa05e4bb709dc3f70fe040ca5af4a0bf13064b5a24238988f585f6a98c1/charset_normalizer-3.5.3-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:7fd816f466883dcaac196ac77271d0292eee4a81f4db1191b95d15328f335937", size = 230514, upload-time = "2026-11-23T02:44:16.444Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cb/b42344c84f48204ba696e75424eca12b33f0f046dbe8290bfd2917dffde3/charset_normalizer-3.5.3-cp313-cp313-android_24_x86_64.whl", hash = "sha256:af217012cfdaf6ea5dc0c538aac29b7bd030eb865056cc60f1d973b982b7917b", size = 244366, upload-time = "2026-11-23T02:44:17.675Z" }, + { url = "https://files.pythonhosted.org/packages/a3/08/fb0a6bdbfee82133f43d5c506b865bc9bbef785eefc355b86374ae87f943/charset_normalizer-3.5.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d12571adb9ceeb9ba0640db46433430062f5f1dec89e39713a2a5a8ce3016c37", size = 222552, upload-time = "2026-11-23T02:44:18.941Z" }, + { url = "https://files.pythonhosted.org/packages/59/16/77d291a7b6bc0784a567ef7b00aa3267efa645ace0abf38a30cf3bea0d63/charset_normalizer-3.5.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:183aee7e84789391e547ec1609f8269332b9b123d21e97f7ef79eaa474c47e08", size = 226639, upload-time = "2026-11-23T02:44:20.168Z" }, + { url = "https://files.pythonhosted.org/packages/75/59/47eca4000f8367014c2e1be786aa82bd8702120f24749853e6297eb8217b/charset_normalizer-3.5.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:499e4bbeb1e79b14756311a1d12cb88112f244423e152d80981d9bcaff3279fa", size = 386082, upload-time = "2026-11-23T02:44:21.363Z" }, + { url = "https://files.pythonhosted.org/packages/21/59/0a22abdaa8c34c1daa886001c3f238e9b09dbaeaa75febf7f8f203520774/charset_normalizer-3.5.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:656b9744bac4493561d28b56d7d646afd7a8471254ef7004d849aa8368020037", size = 256179, upload-time = "2026-11-23T02:44:22.674Z" }, + { url = "https://files.pythonhosted.org/packages/c2/22/f1d08fb14f5a7cc6ea88cde946136bb58c3d83038385268e541f424544fa/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fd0341b9dea133d187d7c5a2cd7e21ae6449a7b68ea8c2454f9cf77def11ec1b", size = 238899, upload-time = "2026-11-23T02:44:23.917Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f1/f910dfdeb3c32ba767f8f9b7290ec3aed1fc44998935255d572551168bed/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9d1f467d121b33b06865c94ed5ed8388a9ef76f5e1acc1c8a854ac653493f5d", size = 237042, upload-time = "2026-11-23T02:44:25.138Z" }, + { url = "https://files.pythonhosted.org/packages/f2/1c/7916607074b99e7d5c5d53e88b76fe1a06328864536d3c7228819b7d9cf4/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0810592b80dc5a97f8103443460264b588f31c6baa8a20abae7c683435d8117a", size = 272418, upload-time = "2026-11-23T02:44:26.432Z" }, + { url = "https://files.pythonhosted.org/packages/ce/8f/1d97b6b3287d80b7b961019dcdfb66d917ff3063d46ab0ded635e7615484/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:db2eedef732424346f98d0aba5c6ad688b648bc79847f4cc70dfca830130b1e6", size = 270735, upload-time = "2026-11-23T02:44:27.711Z" }, + { url = "https://files.pythonhosted.org/packages/c6/3c/e51672360b768d7af7a56e00e39f93752489d0dd668034ea14f3d58898e2/charset_normalizer-3.5.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:caefc441edff6070a9f9749ca880a22731a1715d9e74b24304a546eec44bfc16", size = 252692, upload-time = "2026-11-23T02:44:29.013Z" }, + { url = "https://files.pythonhosted.org/packages/a5/1c/569563a1d2cf0a4f7f798a6736acb15f6ea9764382e036e37d8ac7ab9bc2/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3ce4e4587e451ebc7d9899a7a1f539ea30a3c712d7bc8e0d256923c697fd5dcc", size = 240591, upload-time = "2026-11-23T02:44:30.138Z" }, + { url = "https://files.pythonhosted.org/packages/8a/64/7e7181b347948740211351c6d41dd5b78cf3bb81e44ab10f83128a80ed82/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:0b3fc6f7dd9db4a7782e65dc98eb80b2a91a854cf54a03dd93649be2f7ca638d", size = 242946, upload-time = "2026-11-23T02:44:31.33Z" }, + { url = "https://files.pythonhosted.org/packages/c7/03/5f2f94a3289330678689c0af2da8c31f3e10a8bd77ac8b1a68c97239dc5e/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:bed05639ae1bc23df7996a4fd13ea5064ddf60dc7dabd754f8badf060daec63f", size = 273418, upload-time = "2026-11-23T02:44:32.535Z" }, + { url = "https://files.pythonhosted.org/packages/3c/8b/854724ee0da7d44e33fa42cc9a355a5422ef78ad0fe294d7812d8f1bac06/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a36bba41dc7fd263417688c4daf95a1091f93e1f6957c0f71ad7798907c5a10c", size = 253644, upload-time = "2026-11-23T02:44:33.728Z" }, + { url = "https://files.pythonhosted.org/packages/45/45/4f98894509fd63f8d366e68faa60c268492b1476ef468d0a5397055b6972/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b013417037c931583578639cab2523d5a2efc35a584c192d07f4c909b133f6b0", size = 272406, upload-time = "2026-11-23T02:44:34.917Z" }, + { url = "https://files.pythonhosted.org/packages/08/09/c62783ce9f70a78dcab2b63c6079ee978a0f74f22a732eff9bc585c151ac/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8baddc6349faf49edae4d1322f12b681b9e86acacd01874457c997437ef4ccaa", size = 258180, upload-time = "2026-11-23T02:44:36.164Z" }, + { url = "https://files.pythonhosted.org/packages/60/b3/30ac20e447638738c8714c9e893450ed577a7c76ddf5459f461da2f27a42/charset_normalizer-3.5.3-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:6dde7edd9ba5005389bc7c0ab461411f281dbacb2b06e52bd23592eba42bb503", size = 145567, upload-time = "2026-11-23T02:44:37.27Z" }, + { url = "https://files.pythonhosted.org/packages/aa/de/c352e4d1d7aa85956db646cc6873fb7e81c12cdda3446401c554b50ca5e9/charset_normalizer-3.5.3-cp313-cp313-win32.whl", hash = "sha256:b30e5496e453ac971bb17f5e096b84fbaae16d09e2613f6148ff528c08a54a0c", size = 185084, upload-time = "2026-11-23T02:44:38.431Z" }, + { url = "https://files.pythonhosted.org/packages/6c/53/c56cbbee8fc51fef0a8e775488c4ef5205047a190ad850c43ad4b2ae7b35/charset_normalizer-3.5.3-cp313-cp313-win_amd64.whl", hash = "sha256:cb18428af7399e0a6f7e3b45f110d57a1a47cf07fd4b3ce50e2366d99a38959a", size = 213792, upload-time = "2026-11-23T02:44:39.613Z" }, + { url = "https://files.pythonhosted.org/packages/b4/02/9c2209835e8767fefe1d91c22ae700bee5e6105e0e820debdf3e4fd07e86/charset_normalizer-3.5.3-cp313-cp313-win_arm64.whl", hash = "sha256:8b969f0309de905101bc3d2471c112e9ccbba711a7590b12d51f372b4163688a", size = 200777, upload-time = "2026-11-23T02:44:40.757Z" }, + { url = "https://files.pythonhosted.org/packages/9c/19/171fbc8735d20f22891d7f48ebb7ab5bd16e329726920d4c47ca6a520aab/charset_normalizer-3.5.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:c39a4fe28a16e8fa667c55c154f62c6c3cd9ca2491cca9f16330dd7360d05b76", size = 230746, upload-time = "2026-11-23T02:44:41.982Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6e/dd550464337918ade1b01ff3f232f9f9c5374df2cc784044616e5e42d1ca/charset_normalizer-3.5.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:9c1bd8321a840729a6b2620774cf4000fafe66c54cac9064972a10c4f607794b", size = 244366, upload-time = "2026-11-23T02:44:43.197Z" }, + { url = "https://files.pythonhosted.org/packages/43/9d/0a283271f4c7857bb6669228fcc4c92e73b6b6029cf1762344eb9830628e/charset_normalizer-3.5.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:5f86753952f7de3abc7ce871f8239ce4e0d32a91c84d22f3a667e669907c3897", size = 224040, upload-time = "2026-11-23T02:44:44.437Z" }, + { url = "https://files.pythonhosted.org/packages/96/8f/f084960593eaa570230bd847c198531ea5d0df7580a9d43dfac48f746f62/charset_normalizer-3.5.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:581d6e7df9b58d34147e21efde42a480b5087fe54f31e42550c26321566ba1e4", size = 227968, upload-time = "2026-11-23T02:44:45.792Z" }, + { url = "https://files.pythonhosted.org/packages/de/f4/8a4dd59b77e505ce3fbfd27bf3cafedf27ef946bfd6b4c074f0d4a705fc9/charset_normalizer-3.5.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8231365b03b702b516aad35c9515694177ac31c9dc6240326f07308a4c45c708", size = 388599, upload-time = "2026-11-23T02:44:47.076Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a8/0fed9cde3b8197c99b0981bc53ee7f84cc38a3805a4c5f1c1003cda50588/charset_normalizer-3.5.3-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ee9de080e8d6221bbe4ba2667367b1cee0f47a53f60ffc5e431b698cd2f2b214", size = 257076, upload-time = "2026-11-23T02:44:48.32Z" }, + { url = "https://files.pythonhosted.org/packages/ea/4d/3025852264de946fd2c559ea445bd8600c7b76ce9e0a9774e08ec243311d/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61e32fdbf56f4cd25a1efa451c8b5fe886fc5e00143ccaacafdf21f301fad059", size = 240721, upload-time = "2026-11-23T02:44:49.495Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7c/324b9b9354fb779d88ae14a3e5b8d16ab4e2c535fc7af609c647215a8c29/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:826d82356907350f345cf0aa744d43a69ac7948bd60f460f997cde86928beadf", size = 236682, upload-time = "2026-11-23T02:44:50.704Z" }, + { url = "https://files.pythonhosted.org/packages/2e/5d/ede4f860c14369e599b9eaea27277faa6b799e4205037dcdea9ba70482f9/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a312fedd182357f2c22f066d17dcd7413b6a205ee3d063d36950e94e3019d3de", size = 276116, upload-time = "2026-11-23T02:44:52.196Z" }, + { url = "https://files.pythonhosted.org/packages/55/04/156d80f0d51fb1edbb04969d5127fe34eff9721374cd4f02b822a4ea787b/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:249bf0b6f43985c33c83adbbab0ca71246ec24c82d960fa00c4ddb2cfed25db9", size = 273001, upload-time = "2026-11-23T02:44:53.499Z" }, + { url = "https://files.pythonhosted.org/packages/c9/53/2ebca72cbea022292180ee0a5cedb65c4cafbdffeee4142910bf70d0f454/charset_normalizer-3.5.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ea880ae1a692ae694c11bca7be74864614ff1a58bdfff4605f36d1956b4b1588", size = 254524, upload-time = "2026-11-23T02:44:54.678Z" }, + { url = "https://files.pythonhosted.org/packages/d4/32/fb3d20d2bb50071c6370d03c24fbd7fa7c49a5d4170d00a9029b6851c44d/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e34f591669498a03cd70993b0a79b9f0ef40c4e6f8232466bac33c42f0c15742", size = 242520, upload-time = "2026-11-23T02:44:55.846Z" }, + { url = "https://files.pythonhosted.org/packages/01/0e/9f259d7b12c7d707c2784deef221cef368b10a37b5dc56bc49f818116ddf/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:ddea089587432e3df6771a4a405ef249cc9727f7becb1de3f00ab571b2432002", size = 240962, upload-time = "2026-11-23T02:44:57.08Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/d1916a27c54a67730104da1fee1218d3a476954b3ed2e47a1c28569ec720/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f160f03e15bd1e3c35db9bfc20c42ff83155d37f9b0c79806cb10051ca725f13", size = 276468, upload-time = "2026-11-23T02:44:58.303Z" }, + { url = "https://files.pythonhosted.org/packages/17/96/c72352c6bdd9251e979731bdee97fb88dcb9574b0baf9df4d519dc124546/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:6651fecdac146ecfa52700e02a5fa3b3677bddf5fced4983b43e904244de3f6a", size = 254535, upload-time = "2026-11-23T02:44:59.853Z" }, + { url = "https://files.pythonhosted.org/packages/25/d8/5d22ba93705c0ae58ea135f3e4a914953348cf6e50d4a40d638dace152e8/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:45aa4ccf5a6caba138dd0f8bf36fa3e26654585d534881b62ce5e4fea2487772", size = 274514, upload-time = "2026-11-23T02:45:01.002Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/997607e03b4a79f3ac2074f0519bebe35b88b874139c9a98e96e0711bfac/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9eba4613d45b49196af04a5cbadfc5e9379ba94aac85184b72cb1107ad31af0d", size = 258968, upload-time = "2026-11-23T02:45:02.207Z" }, + { url = "https://files.pythonhosted.org/packages/d7/1b/c3a6b94a46302aeb20e5cbbcefbb18cfec59abf235f031409bd15f555ff4/charset_normalizer-3.5.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:2e7fbd98443f28a5ed8004f0b058edcc4720a3d344adf007c0b7f1adbff2f59f", size = 145526, upload-time = "2026-11-23T02:45:03.786Z" }, + { url = "https://files.pythonhosted.org/packages/fd/82/0e4c6c596fd0ec4615255d05cab0c8fa42cec62e3b2be51bdcabab4a0215/charset_normalizer-3.5.3-cp314-cp314-win32.whl", hash = "sha256:d8f85e019c9f08ec134648a378ddd3f6f073c1e4b5ce9bdacd9a9e7b60749cd2", size = 187860, upload-time = "2026-11-23T02:45:05.079Z" }, + { url = "https://files.pythonhosted.org/packages/a0/4e/0d31216be12c3146dd282b043957805d4dda8806cd7b99c90273d251f0f2/charset_normalizer-3.5.3-cp314-cp314-win_amd64.whl", hash = "sha256:b66a0e045cf859d7418f26a554509b65f21ebb6d90a95152460781939e8264f4", size = 218705, upload-time = "2026-11-23T02:45:06.207Z" }, + { url = "https://files.pythonhosted.org/packages/68/5c/8c8f2202314b8918d51146ab2337af9721c9e7c74867c86f625556f657b9/charset_normalizer-3.5.3-cp314-cp314-win_arm64.whl", hash = "sha256:b8fc4fe56992b089d6177021fe6db641321bb2bc2fc7a1abf815c29a80ca2137", size = 205681, upload-time = "2026-11-23T02:45:07.379Z" }, + { url = "https://files.pythonhosted.org/packages/a8/52/01e5da4f7d4d10195f745c37b0daacd83a0fe112e9b6d959663a775ce489/charset_normalizer-3.5.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:6c80b4e83e2fbddd25fe27804cdfc45ef71bb387522caa575af42118d72dc970", size = 413919, upload-time = "2026-11-23T02:45:08.58Z" }, + { url = "https://files.pythonhosted.org/packages/67/49/277767bc060dfcb0788103acd67ec3831cbcc671f5a7b12b4935e733e09a/charset_normalizer-3.5.3-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7a7e5bb8974842ad747d4a2b9fb928f84c3cdbe2c2fd7e405197fc1a1badaeaa", size = 260695, upload-time = "2026-11-23T02:45:10.005Z" }, + { url = "https://files.pythonhosted.org/packages/e1/33/f017126fd88ad2e39d947044af196b28dc91633f23dded8754ae944e2f03/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ba8e6361e0f319641707484994096ceb77e05c29eaad2919756218c0c89001", size = 246771, upload-time = "2026-11-23T02:45:11.143Z" }, + { url = "https://files.pythonhosted.org/packages/32/0d/c147965a1989b0e85f5aabf29a309ee7deb34ac7d89442c0fd51c8055981/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e405cce4170de1fe520d9a92de9d7ececc23dfcf6888c62ab608a21be50838eb", size = 235360, upload-time = "2026-11-23T02:45:12.501Z" }, + { url = "https://files.pythonhosted.org/packages/55/f9/48509fa40ce22ce10497dd6689818b6676a482d7b3eaad02a558744d08c6/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:81132eaffa984f0a399233df4cd383caad18e8cadc6c24c568cf9324732a9768", size = 273351, upload-time = "2026-11-23T02:45:13.717Z" }, + { url = "https://files.pythonhosted.org/packages/8e/9e/3090f8b88f300b71c5d45bfe214f7a9e156de76cf37d12345338f1b63f5f/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c43d9737c3b85ccd16b1862b1e7aa5c4bf30a6033068403713c0a2bba5bda979", size = 274795, upload-time = "2026-11-23T02:45:14.991Z" }, + { url = "https://files.pythonhosted.org/packages/e1/93/171bf6dd9bfbbc21be219fdab5213bb7ee8a8edff9b4acc982cb905e5687/charset_normalizer-3.5.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c9d5d91c16554f6397b823d9e47181ba100d830ab16b5d720adc229e17b2e2", size = 254931, upload-time = "2026-11-23T02:45:16.454Z" }, + { url = "https://files.pythonhosted.org/packages/aa/6a/e5a41dbffdc064c635b487debd32944e19777e6d938ebbc88fca1996e231/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0c0fe07631dce6dae788a59c20ed927adc6feeb2d9ed440747eb367d89822a45", size = 249689, upload-time = "2026-11-23T02:45:18.096Z" }, + { url = "https://files.pythonhosted.org/packages/d5/3c/0b7869da44ab5fbae135df0f9a12a9325c42e37c221353dc194a01b3b3df/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:0ca25f1b1167e9fb94d93d3708df0b631de241bf8440947b0cb9f8c4cb66fed0", size = 242935, upload-time = "2026-11-23T02:45:19.215Z" }, + { url = "https://files.pythonhosted.org/packages/4b/59/c6fd64ab23eb58bd42e940be294864b7d197ea2a2bebe572f3e6600c2d34/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:fcb17f1d40c38912a2cdb56ea47aadac3527cd0b06fe24f3a0c4896febbea063", size = 275394, upload-time = "2026-11-23T02:45:20.373Z" }, + { url = "https://files.pythonhosted.org/packages/c3/d6/208641f89b848dbe842b37175f9cbd56183dedca850377c5d03ae77a5215/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:39e019884c8f857393df954d35f42bf99c5ab85af226fe74d1410188c6fec31f", size = 255552, upload-time = "2026-11-23T02:45:21.529Z" }, + { url = "https://files.pythonhosted.org/packages/f2/a0/04609cb3fe13091be9c8e24c75b55e12cb35882db5d4377c86c58dd09913/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:e282983b8def5ada758fa1f18bf9060bb8ce6cdd73be32f62a2de59820d3286d", size = 273420, upload-time = "2026-11-23T02:45:22.736Z" }, + { url = "https://files.pythonhosted.org/packages/2d/45/c8c27b6e00e6a39175a5b7b0df73d787a84d320012a882647f8c81ce915f/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cbd09b22b340f846671e79e8d832167fac60c1884be4c71fd667211486a3b58e", size = 263761, upload-time = "2026-11-23T02:45:23.812Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c0/51435f05b16daf627d5525de00334f869707aead4e9214e004809b7840f2/charset_normalizer-3.5.3-cp314-cp314t-win32.whl", hash = "sha256:a8f92cc9080bff47555c79b88e7fb8655438ce3bcf29c5f01ed2ed5efdf174a4", size = 200709, upload-time = "2026-11-23T02:45:24.92Z" }, + { url = "https://files.pythonhosted.org/packages/63/14/93634f18a4d3f17b90b0f40852ee9ef45834dde21112f7be5b28c25062ad/charset_normalizer-3.5.3-cp314-cp314t-win_amd64.whl", hash = "sha256:1a34385837db59d5de814c9f1e0f4157b571f9ce0eabdaeace410aa93bf5df62", size = 218684, upload-time = "2026-11-23T02:45:26.194Z" }, + { url = "https://files.pythonhosted.org/packages/57/78/f70f630a2a6af3a09fb82403425576b3c1c366c4e766bdb624b56c4a3d24/charset_normalizer-3.5.3-cp314-cp314t-win_arm64.whl", hash = "sha256:a094178c51530c9ebd1775e72d160af0eac4be244fb06ff1b6f182128c71903c", size = 209276, upload-time = "2026-11-23T02:45:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/7d/63/99fe455c382b9ae254baa0eac2b252d83d174d42ff39557083cc6d1a6e85/charset_normalizer-3.5.3-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:f7fb9a3275f1a1528e542a0f5a3d2c89fcaf68e797fc5c6530434cbd92a852c4", size = 388433, upload-time = "2026-11-23T02:45:29.061Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0b/2cca2599ccb85cb31c60d8d19fcd9f89bc113696b2be2fd774288bc78691/charset_normalizer-3.5.3-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ef8b925f2b331a1f17d6fb32625e09fd571cf41844f578379f934dab0067cf0d", size = 257397, upload-time = "2026-11-23T02:45:30.196Z" }, + { url = "https://files.pythonhosted.org/packages/e2/fc/7f46bdf26bed47cee8f053dda462b9e00dc56cf767f99a88b077ebfdf30b/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:390ef7c7e018c0abb8c0ec2d28ee137567ff50c3706facf6d115cac832ac993b", size = 241315, upload-time = "2026-11-23T02:45:31.352Z" }, + { url = "https://files.pythonhosted.org/packages/8e/55/a6be3d284ea45451d700d1fb58fd9db7155dbbfff7799b7c6351e419c528/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:106b9d0438e2ff0a0e8ebd869273fcb3640af28323bba8651c714c57efb38e51", size = 249109, upload-time = "2026-11-23T02:45:32.508Z" }, + { url = "https://files.pythonhosted.org/packages/57/5a/5cd92437895d67c77add5adebc512a00fe06b7146dd679cdb8b146b94a9f/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6bfbbb9414dd0f5b81c259deb7e50b4b44e65e05879eee482351bdabed49d7f4", size = 276158, upload-time = "2026-11-23T02:45:33.752Z" }, + { url = "https://files.pythonhosted.org/packages/02/b3/18750413345158ae3223fb083c68b497756f7e5b187e216a2b30e51aab70/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:11ad35a0b856ad8bbd0c9e900c069461a4661694714aa17b6e6e2e8621e1c373", size = 273314, upload-time = "2026-11-23T02:45:34.936Z" }, + { url = "https://files.pythonhosted.org/packages/54/b6/d790397b7742c37379942d46816287d90b102aded0f9d48b6418d96403d8/charset_normalizer-3.5.3-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6118055f4ad0d94e016eadbb86caed9caf2c9033631ed70964ba631c1336984f", size = 261077, upload-time = "2026-11-23T02:45:36.46Z" }, + { url = "https://files.pythonhosted.org/packages/a3/da/fd1e0c83475fe7f8dfbf4c0f9308a122963972a81a5507351f6079a47770/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:a09ca76391f6e17b12d55c1068b4b5f8f6c9b44b432d936075372fa12782292d", size = 243097, upload-time = "2026-11-23T02:45:37.891Z" }, + { url = "https://files.pythonhosted.org/packages/9d/00/a8e73fd75e0f6bc5127bb49065a585fcc12b0bb9643b54b25b20375e0782/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:acaa0e100f39287dc5d13de96e33ba0786f1cdfb5b4ca28918913ab0eec3af72", size = 252349, upload-time = "2026-11-23T02:45:39.407Z" }, + { url = "https://files.pythonhosted.org/packages/06/96/dc3e6ce15bf01c3e3a98769fb3cd2bda57661521eba22e2b9f3b55e4ee3b/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:a3f4044dd5d2f7b958be6b9903cb432e6a0fd944d673707ca5cab68137d0592c", size = 276520, upload-time = "2026-11-23T02:45:40.608Z" }, + { url = "https://files.pythonhosted.org/packages/67/65/437f58102ffd405f05b7e00e6ee1fa9b97536e4fc71b518b917b847cf1db/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:d1b7a3fe4cf679eb3870b91b86b8ce12cacd5cf4d74bc114864a5cd65319ddac", size = 260666, upload-time = "2026-11-23T02:45:41.736Z" }, + { url = "https://files.pythonhosted.org/packages/72/06/5113ebc19322267ab243a0cb972cc03af89e31665a6318f711cb410b2906/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:323d5cf6df3ea724afcc3bfb07c73be06d2e8200a8b6b37979a300ae1e7836d0", size = 274614, upload-time = "2026-11-23T02:45:43.227Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b1/41062ab95a6b6806ba9b175dfe33496a5e8b3a9b1cf50096fbf53beac472/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:67bb767a8de7a2b1164c74fdbe5cdc32b9c15d7142efd9a6dc77ff63da94e846", size = 259557, upload-time = "2026-11-23T02:45:44.491Z" }, + { url = "https://files.pythonhosted.org/packages/6c/4a/9ea96a756aa9884b6bd4bbdcd0293c23cc198b0a986831078593a98d61fc/charset_normalizer-3.5.3-cp315-cp315-win32.whl", hash = "sha256:d93403a13c8f6f2d027185d90ab695e81d95e3ebd000f0078e201a1c3159d4d1", size = 187747, upload-time = "2026-11-23T02:45:45.711Z" }, + { url = "https://files.pythonhosted.org/packages/4b/16/c6cdbdf7f3b92c43fdacc074202db46e4f85af1be7fb2fa3fc015167c8a8/charset_normalizer-3.5.3-cp315-cp315-win_amd64.whl", hash = "sha256:2978c799237eb66619d8951d2ab7efd317414cb6682160e05614ce1c8b5c905f", size = 218469, upload-time = "2026-11-23T02:45:47.225Z" }, + { url = "https://files.pythonhosted.org/packages/73/4e/10d9b92b827dab4e333af2e3bfb4955b5504fa04953e7d83862383ac844b/charset_normalizer-3.5.3-cp315-cp315-win_arm64.whl", hash = "sha256:9a6b95b1737f9b5942c35676c52db0c302d60fa806efde3fc2d9f54247ecf4be", size = 206254, upload-time = "2026-11-23T02:45:48.429Z" }, + { url = "https://files.pythonhosted.org/packages/34/86/e0945f37d12630d50e96ba7d8d6935efceb168fc4a58fe26b2f4b80972f5/charset_normalizer-3.5.3-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:06d07272f70d9880fba32d4876e966ae4dc9961134bc989066a0901509dfd8cf", size = 411657, upload-time = "2026-11-23T02:45:49.713Z" }, + { url = "https://files.pythonhosted.org/packages/49/3e/d4c3e4f3b4a63cbdb1215746d2d9e87d890d36a4967a53e50b04d5e4e261/charset_normalizer-3.5.3-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:da606e3015dbd4b9a31c0468898a0c4c998846197ddfda78308821dc8c9e9be3", size = 260078, upload-time = "2026-11-23T02:45:50.953Z" }, + { url = "https://files.pythonhosted.org/packages/3b/43/91b08f37f5561e4e356533f103fb3c60367378871ee730480dbf05571e3e/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6423accb6ecd1456bf824bbac98ba919398523a69ee5f1680dd1da88769de866", size = 246616, upload-time = "2026-11-23T02:45:52.141Z" }, + { url = "https://files.pythonhosted.org/packages/5a/25/29ea27a18f5b84baf2c12b9ec5ecd2f44770ba11fa9431f736b641a47c5e/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ad1becd776f5a41a4d91cb9ee51778f4fd687ef15e4919779e00a33c6cff6948", size = 245190, upload-time = "2026-11-23T02:45:53.322Z" }, + { url = "https://files.pythonhosted.org/packages/81/d0/ab1609490f8bf70a2de391abf6897a22410ea6639c5c62e5085b4791ca0c/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7fdd11094a0b07bce306b359fa7311c71d93466d967b3b345f2e9f03d8b2c959", size = 272663, upload-time = "2026-11-23T02:45:54.53Z" }, + { url = "https://files.pythonhosted.org/packages/a9/34/d898562f7733b7479aacb9b1bfa7d3953472a5ac2d7799c5b7cc10b15860/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:87d5a237d6531c654e7b9b319be9ba7e368665c466e02a03cfd4d3d77730782e", size = 273912, upload-time = "2026-11-23T02:45:55.697Z" }, + { url = "https://files.pythonhosted.org/packages/34/13/952195e0a1eb774cfacdac376ccbd45ee5f062ff1ebbce13f16a3cd61f56/charset_normalizer-3.5.3-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4a0f2adf29a69dd8fe58e42bb191f3c87067b05fcc63279983e8c9ce5092abd", size = 262197, upload-time = "2026-11-23T02:45:56.819Z" }, + { url = "https://files.pythonhosted.org/packages/7f/64/57a0b74ef74e8fbc72eb534074d927b6cfde7c636d7a130c01ea363c38f4/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:643724071b01cc0369026e259850791212cc187c6031d0e930abcd253f128e0c", size = 249293, upload-time = "2026-11-23T02:45:58.069Z" }, + { url = "https://files.pythonhosted.org/packages/03/2d/c85f799904ba58873292482777877ad7f8de59432acd19798bcd333dd379/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:94b595e64bc2927f679774de50df340b7828dc1c07c99149ba7c2d0828dd8bf3", size = 253017, upload-time = "2026-11-23T02:45:59.293Z" }, + { url = "https://files.pythonhosted.org/packages/3b/b3/094707e46822715358296d9240b5bda6d9c3d22492dc9e90a72b2e32d1cf/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:e86a27ab632d2e888c22b79263864eaff8b7dea9e87328a9bb0ea04eff24786f", size = 274884, upload-time = "2026-11-23T02:46:00.405Z" }, + { url = "https://files.pythonhosted.org/packages/29/ea/86c082d940bd103d9c3a55b426c0c63d7042c2d43c1c35afd8cb6470b735/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:48f7c7f537246bb3af2b3139f44716a30b21e78c2fd1cff0f3e392fbd55d8044", size = 262028, upload-time = "2026-11-23T02:46:01.547Z" }, + { url = "https://files.pythonhosted.org/packages/96/5d/b41c750bda9b9eb354a802b4c399c0960f33b06555d1dd265bd29eade5cf/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:085a5d1f49eaf96596d79494fcab18d9a32db6e345da15d6debfc90110b20679", size = 272487, upload-time = "2026-11-23T02:46:02.747Z" }, + { url = "https://files.pythonhosted.org/packages/cf/08/d1968a27a29aa0338329dcf0462272a4f4335e5255d7a7f5bea9689d5c84/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6c8abe7d59bbc891e5080b8b142c36db93154f840c4baf7c83ad6273a1a15397", size = 263202, upload-time = "2026-11-23T02:46:04.239Z" }, + { url = "https://files.pythonhosted.org/packages/b3/77/5abae54c1eeba13ace198119b514ff66c6b07ba0fe8b56f4fb96a299a651/charset_normalizer-3.5.3-cp315-cp315t-win32.whl", hash = "sha256:02b1abf64742b2d0782172cd2542616e462c201c829c23aff833390babe2967f", size = 199993, upload-time = "2026-11-23T02:46:05.377Z" }, + { url = "https://files.pythonhosted.org/packages/36/04/171d1d5352713792d8eebc14ff461625cb6cb0517bf57e0c4e95c1663480/charset_normalizer-3.5.3-cp315-cp315t-win_amd64.whl", hash = "sha256:dfbde696fb427301ec40cd82b8eec0b528e44c6af8239f33ede2b2552d9a085a", size = 217514, upload-time = "2026-11-23T02:46:06.784Z" }, + { url = "https://files.pythonhosted.org/packages/5f/5f/cb8485f62fec625bebab015874df0eb9d8332015b4462fd1da41d1ab1c54/charset_normalizer-3.5.3-cp315-cp315t-win_arm64.whl", hash = "sha256:aa9390d89822dd06f9920ae3038819cb121643a72f4753b2eee1a79b2f1215f8", size = 208602, upload-time = "2026-11-23T02:46:07.978Z" }, + { url = "https://files.pythonhosted.org/packages/64/57/146cbf75a34eb50a27ca6daf4841a4a13a0726fa05db6f7fe97c8f14f383/charset_normalizer-3.5.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:84356c7b7ddf090e3e4692cb99fc820e6189b5f6662ca7e8589f41095cc8efca", size = 376114, upload-time = "2026-11-23T02:46:09.155Z" }, + { url = "https://files.pythonhosted.org/packages/5f/02/b01868added37f27a6b0fd29e7fa19d0ae52b3fdbfc6fde6b9c98ef377ec/charset_normalizer-3.5.3-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6", size = 234407, upload-time = "2026-11-23T02:46:10.528Z" }, + { url = "https://files.pythonhosted.org/packages/9b/9c/a8dddbe4ca722fac44bcbb17c08670bd9f1e9d26a481f7129aa2215eff80/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4e7ecaa25f0dae672ac783c2e5aa9054a62e011749d64ff47b887af360a3e82", size = 222474, upload-time = "2026-11-23T02:46:11.939Z" }, + { url = "https://files.pythonhosted.org/packages/3f/28/b9d955132ca12845bf4d498cac4cad731d88f7dffcfe9ab26182ba19b9b9/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ba26e4d073a4f7f2594676f2ff20ab80a7f03332b81c3f9964e9e53bf2305329", size = 234588, upload-time = "2026-11-23T02:46:13.175Z" }, + { url = "https://files.pythonhosted.org/packages/75/87/5c957d23953540fd53f8bf99f25aca4a73ffaa2621e0c199fa33bea68670/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4831fb33e98e92140fa17d4d673a9f49f9c0ddd056115b722858793e4b86b0c5", size = 264230, upload-time = "2026-11-23T02:46:14.634Z" }, + { url = "https://files.pythonhosted.org/packages/2e/33/94e72d80177dfc1c68d4250bcfc0ac81c7fffb6fb7692eaba1050839c822/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1714ff1ba001da5241a585fbd17a7742a61ad34efb4be8404aca5679f51e53ea", size = 259027, upload-time = "2026-11-23T02:46:15.803Z" }, + { url = "https://files.pythonhosted.org/packages/22/52/2c903fb577eb4fecd1c6e0f426daa4f0af5ae2e2b453985e1995317deeb6/charset_normalizer-3.5.3-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8c4dfcd3269f13dff7f29f9c332d54a4a21f17be818b49e769e111befd4d39e6", size = 252786, upload-time = "2026-11-23T02:46:17.024Z" }, + { url = "https://files.pythonhosted.org/packages/a9/6b/f8c6680edbaa937982c3f0e9a9cbc7634135bed7a6633cbccbdefd8e64b7/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87f7d6c595465a25d33fa3d5215a571a98c4cad00ead3ad18ebfb62adb3d3e6e", size = 223576, upload-time = "2026-11-23T02:46:18.245Z" }, + { url = "https://files.pythonhosted.org/packages/37/24/5ca15b50e452d0b689c152b27ff525b417dde009f0daea1805767a683a3f/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:7c313b46730b4a68bb31450973467313b2c496fefa42ae316b86c186cba74613", size = 235893, upload-time = "2026-11-23T02:46:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/e1/c7/4857928626613d6991d3cc045de5d101ebf04dad1b5786facd5bd9d843e3/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:d313494077f849d8199f36166947785da1eeb36335fda15fde2e8f801ef271b6", size = 263887, upload-time = "2026-11-23T02:46:20.811Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/c6ddeafc6301f7675089d093219f923db0311bd99c7c6e21cd6f10e97884/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:c08e06fc69750827d7ccebba63ebc97a85e479cd5c9dbdb80f5e08a77b774fdb", size = 250628, upload-time = "2026-11-23T02:46:22.044Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1e/2536f55939d911bd638982aba11a2a26d8b5a49926d2d93e3d6cd236e180/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:29ac44f5878142128ffe4fa7e041ddc4cc5fafe43983245b9a141908c40b515d", size = 261092, upload-time = "2026-11-23T02:46:23.382Z" }, + { url = "https://files.pythonhosted.org/packages/3a/fe/aa2706988f2e4e46e79a488383dfd2f4d166728e046d8ae29cf8466d38e2/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d", size = 236268, upload-time = "2026-11-23T02:46:24.607Z" }, + { url = "https://files.pythonhosted.org/packages/6a/79/9264b6a1411dcaf0daa0d58e6915545ddc8b056b53ece56375bcf9776c88/charset_normalizer-3.5.3-cp37-abi3-win32.whl", hash = "sha256:4ff5e27478681ef1b13b036baaf9beaf9b4c6990e903c752ad3b8764692c6d6c", size = 177808, upload-time = "2026-11-23T02:46:26.059Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a5/cc188879ab8e8a36d295f888335f0a2875e39bcdacc6fe3207427c14036f/charset_normalizer-3.5.3-cp37-abi3-win_amd64.whl", hash = "sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527", size = 200667, upload-time = "2026-11-23T02:46:27.221Z" }, + { url = "https://files.pythonhosted.org/packages/d5/a3/4a6047c40414f170ad09a6d44c1a0663914924619304817c2e33d19fae75/charset_normalizer-3.5.3-cp37-abi3-win_arm64.whl", hash = "sha256:e4f85c34f9be32ec5568a0668fb8bc029d3e729285fb8fccc38695e185379a9b", size = 290628, upload-time = "2026-11-23T02:46:29.06Z" }, + { url = "https://files.pythonhosted.org/packages/d2/0d/07ab8eb9b7015274353eac2add4067bde1ab1b51912bbae505392905eedd/charset_normalizer-3.5.3-py3-none-any.whl", hash = "sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132", size = 68878, upload-time = "2026-11-23T02:46:50.665Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/59/df/0bf7ef6c2534c140bb4c3d787e1557542e50a96b393659efaa4f39f9a45a/cloudpickle-3.1.3.tar.gz", hash = "sha256:cbe9fde14429a5db009ea05ce94e5182cf998c97b96918d50c10f73f9c2f4f33", size = 22576, upload-time = "2026-11-18T10:27:18.82Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/42/3b121b42b114919ffc6195a81c1c7065a465f62f46477fbdb87a07699e51/cloudpickle-3.1.3-py3-none-any.whl", hash = "sha256:1654f4f18e416447210a63c5c25a135d65a292156aa5fa519dfa4baf7726dddb", size = 22399, upload-time = "2026-11-18T10:27:17.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "comm" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/54/eb9bfc647b19f2009dd5c7f5ec51c4e6ca831725f1aea7a993034f483147/contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54", size = 13466130, upload-time = "2025-04-15T17:47:53.79Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/a3/da4153ec8fe25d263aa48c1a4cbde7f49b59af86f0b6f7862788c60da737/contourpy-1.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ba38e3f9f330af820c4b27ceb4b9c7feee5fe0493ea53a8720f4792667465934", size = 268551, upload-time = "2025-04-15T17:34:46.581Z" }, + { url = "https://files.pythonhosted.org/packages/2f/6c/330de89ae1087eb622bfca0177d32a7ece50c3ef07b28002de4757d9d875/contourpy-1.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:dc41ba0714aa2968d1f8674ec97504a8f7e334f48eeacebcaa6256213acb0989", size = 253399, upload-time = "2025-04-15T17:34:51.427Z" }, + { url = "https://files.pythonhosted.org/packages/c1/bd/20c6726b1b7f81a8bee5271bed5c165f0a8e1f572578a9d27e2ccb763cb2/contourpy-1.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9be002b31c558d1ddf1b9b415b162c603405414bacd6932d031c5b5a8b757f0d", size = 312061, upload-time = "2025-04-15T17:34:55.961Z" }, + { url = "https://files.pythonhosted.org/packages/22/fc/a9665c88f8a2473f823cf1ec601de9e5375050f1958cbb356cdf06ef1ab6/contourpy-1.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8d2e74acbcba3bfdb6d9d8384cdc4f9260cae86ed9beee8bd5f54fee49a430b9", size = 351956, upload-time = "2025-04-15T17:35:00.992Z" }, + { url = "https://files.pythonhosted.org/packages/25/eb/9f0a0238f305ad8fb7ef42481020d6e20cf15e46be99a1fcf939546a177e/contourpy-1.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e259bced5549ac64410162adc973c5e2fb77f04df4a439d00b478e57a0e65512", size = 320872, upload-time = "2025-04-15T17:35:06.177Z" }, + { url = "https://files.pythonhosted.org/packages/32/5c/1ee32d1c7956923202f00cf8d2a14a62ed7517bdc0ee1e55301227fc273c/contourpy-1.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad687a04bc802cbe8b9c399c07162a3c35e227e2daccf1668eb1f278cb698631", size = 325027, upload-time = "2025-04-15T17:35:11.244Z" }, + { url = "https://files.pythonhosted.org/packages/83/bf/9baed89785ba743ef329c2b07fd0611d12bfecbedbdd3eeecf929d8d3b52/contourpy-1.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cdd22595308f53ef2f891040ab2b93d79192513ffccbd7fe19be7aa773a5e09f", size = 1306641, upload-time = "2025-04-15T17:35:26.701Z" }, + { url = "https://files.pythonhosted.org/packages/d4/cc/74e5e83d1e35de2d28bd97033426b450bc4fd96e092a1f7a63dc7369b55d/contourpy-1.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b4f54d6a2defe9f257327b0f243612dd051cc43825587520b1bf74a31e2f6ef2", size = 1374075, upload-time = "2025-04-15T17:35:43.204Z" }, + { url = "https://files.pythonhosted.org/packages/0c/42/17f3b798fd5e033b46a16f8d9fcb39f1aba051307f5ebf441bad1ecf78f8/contourpy-1.3.2-cp310-cp310-win32.whl", hash = "sha256:f939a054192ddc596e031e50bb13b657ce318cf13d264f095ce9db7dc6ae81c0", size = 177534, upload-time = "2025-04-15T17:35:46.554Z" }, + { url = "https://files.pythonhosted.org/packages/54/ec/5162b8582f2c994721018d0c9ece9dc6ff769d298a8ac6b6a652c307e7df/contourpy-1.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:c440093bbc8fc21c637c03bafcbef95ccd963bc6e0514ad887932c18ca2a759a", size = 221188, upload-time = "2025-04-15T17:35:50.064Z" }, + { url = "https://files.pythonhosted.org/packages/b3/b9/ede788a0b56fc5b071639d06c33cb893f68b1178938f3425debebe2dab78/contourpy-1.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6a37a2fb93d4df3fc4c0e363ea4d16f83195fc09c891bc8ce072b9d084853445", size = 269636, upload-time = "2025-04-15T17:35:54.473Z" }, + { url = "https://files.pythonhosted.org/packages/e6/75/3469f011d64b8bbfa04f709bfc23e1dd71be54d05b1b083be9f5b22750d1/contourpy-1.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b7cd50c38f500bbcc9b6a46643a40e0913673f869315d8e70de0438817cb7773", size = 254636, upload-time = "2025-04-15T17:35:58.283Z" }, + { url = "https://files.pythonhosted.org/packages/8d/2f/95adb8dae08ce0ebca4fd8e7ad653159565d9739128b2d5977806656fcd2/contourpy-1.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6658ccc7251a4433eebd89ed2672c2ed96fba367fd25ca9512aa92a4b46c4f1", size = 313053, upload-time = "2025-04-15T17:36:03.235Z" }, + { url = "https://files.pythonhosted.org/packages/c3/a6/8ccf97a50f31adfa36917707fe39c9a0cbc24b3bbb58185577f119736cc9/contourpy-1.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:70771a461aaeb335df14deb6c97439973d253ae70660ca085eec25241137ef43", size = 352985, upload-time = "2025-04-15T17:36:08.275Z" }, + { url = "https://files.pythonhosted.org/packages/1d/b6/7925ab9b77386143f39d9c3243fdd101621b4532eb126743201160ffa7e6/contourpy-1.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65a887a6e8c4cd0897507d814b14c54a8c2e2aa4ac9f7686292f9769fcf9a6ab", size = 323750, upload-time = "2025-04-15T17:36:13.29Z" }, + { url = "https://files.pythonhosted.org/packages/c2/f3/20c5d1ef4f4748e52d60771b8560cf00b69d5c6368b5c2e9311bcfa2a08b/contourpy-1.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3859783aefa2b8355697f16642695a5b9792e7a46ab86da1118a4a23a51a33d7", size = 326246, upload-time = "2025-04-15T17:36:18.329Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e5/9dae809e7e0b2d9d70c52b3d24cba134dd3dad979eb3e5e71f5df22ed1f5/contourpy-1.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:eab0f6db315fa4d70f1d8ab514e527f0366ec021ff853d7ed6a2d33605cf4b83", size = 1308728, upload-time = "2025-04-15T17:36:33.878Z" }, + { url = "https://files.pythonhosted.org/packages/e2/4a/0058ba34aeea35c0b442ae61a4f4d4ca84d6df8f91309bc2d43bb8dd248f/contourpy-1.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d91a3ccc7fea94ca0acab82ceb77f396d50a1f67412efe4c526f5d20264e6ecd", size = 1375762, upload-time = "2025-04-15T17:36:51.295Z" }, + { url = "https://files.pythonhosted.org/packages/09/33/7174bdfc8b7767ef2c08ed81244762d93d5c579336fc0b51ca57b33d1b80/contourpy-1.3.2-cp311-cp311-win32.whl", hash = "sha256:1c48188778d4d2f3d48e4643fb15d8608b1d01e4b4d6b0548d9b336c28fc9b6f", size = 178196, upload-time = "2025-04-15T17:36:55.002Z" }, + { url = "https://files.pythonhosted.org/packages/5e/fe/4029038b4e1c4485cef18e480b0e2cd2d755448bb071eb9977caac80b77b/contourpy-1.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:5ebac872ba09cb8f2131c46b8739a7ff71de28a24c869bcad554477eb089a878", size = 222017, upload-time = "2025-04-15T17:36:58.576Z" }, + { url = "https://files.pythonhosted.org/packages/34/f7/44785876384eff370c251d58fd65f6ad7f39adce4a093c934d4a67a7c6b6/contourpy-1.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4caf2bcd2969402bf77edc4cb6034c7dd7c0803213b3523f111eb7460a51b8d2", size = 271580, upload-time = "2025-04-15T17:37:03.105Z" }, + { url = "https://files.pythonhosted.org/packages/93/3b/0004767622a9826ea3d95f0e9d98cd8729015768075d61f9fea8eeca42a8/contourpy-1.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:82199cb78276249796419fe36b7386bd8d2cc3f28b3bc19fe2454fe2e26c4c15", size = 255530, upload-time = "2025-04-15T17:37:07.026Z" }, + { url = "https://files.pythonhosted.org/packages/e7/bb/7bd49e1f4fa805772d9fd130e0d375554ebc771ed7172f48dfcd4ca61549/contourpy-1.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:106fab697af11456fcba3e352ad50effe493a90f893fca6c2ca5c033820cea92", size = 307688, upload-time = "2025-04-15T17:37:11.481Z" }, + { url = "https://files.pythonhosted.org/packages/fc/97/e1d5dbbfa170725ef78357a9a0edc996b09ae4af170927ba8ce977e60a5f/contourpy-1.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d14f12932a8d620e307f715857107b1d1845cc44fdb5da2bc8e850f5ceba9f87", size = 347331, upload-time = "2025-04-15T17:37:18.212Z" }, + { url = "https://files.pythonhosted.org/packages/6f/66/e69e6e904f5ecf6901be3dd16e7e54d41b6ec6ae3405a535286d4418ffb4/contourpy-1.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:532fd26e715560721bb0d5fc7610fce279b3699b018600ab999d1be895b09415", size = 318963, upload-time = "2025-04-15T17:37:22.76Z" }, + { url = "https://files.pythonhosted.org/packages/a8/32/b8a1c8965e4f72482ff2d1ac2cd670ce0b542f203c8e1d34e7c3e6925da7/contourpy-1.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26b383144cf2d2c29f01a1e8170f50dacf0eac02d64139dcd709a8ac4eb3cfe", size = 323681, upload-time = "2025-04-15T17:37:33.001Z" }, + { url = "https://files.pythonhosted.org/packages/30/c6/12a7e6811d08757c7162a541ca4c5c6a34c0f4e98ef2b338791093518e40/contourpy-1.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c49f73e61f1f774650a55d221803b101d966ca0c5a2d6d5e4320ec3997489441", size = 1308674, upload-time = "2025-04-15T17:37:48.64Z" }, + { url = "https://files.pythonhosted.org/packages/2a/8a/bebe5a3f68b484d3a2b8ffaf84704b3e343ef1addea528132ef148e22b3b/contourpy-1.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3d80b2c0300583228ac98d0a927a1ba6a2ba6b8a742463c564f1d419ee5b211e", size = 1380480, upload-time = "2025-04-15T17:38:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/db/fcd325f19b5978fb509a7d55e06d99f5f856294c1991097534360b307cf1/contourpy-1.3.2-cp312-cp312-win32.whl", hash = "sha256:90df94c89a91b7362e1142cbee7568f86514412ab8a2c0d0fca72d7e91b62912", size = 178489, upload-time = "2025-04-15T17:38:10.338Z" }, + { url = "https://files.pythonhosted.org/packages/01/c8/fadd0b92ffa7b5eb5949bf340a63a4a496a6930a6c37a7ba0f12acb076d6/contourpy-1.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:8c942a01d9163e2e5cfb05cb66110121b8d07ad438a17f9e766317bcb62abf73", size = 223042, upload-time = "2025-04-15T17:38:14.239Z" }, + { url = "https://files.pythonhosted.org/packages/2e/61/5673f7e364b31e4e7ef6f61a4b5121c5f170f941895912f773d95270f3a2/contourpy-1.3.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:de39db2604ae755316cb5967728f4bea92685884b1e767b7c24e983ef5f771cb", size = 271630, upload-time = "2025-04-15T17:38:19.142Z" }, + { url = "https://files.pythonhosted.org/packages/ff/66/a40badddd1223822c95798c55292844b7e871e50f6bfd9f158cb25e0bd39/contourpy-1.3.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3f9e896f447c5c8618f1edb2bafa9a4030f22a575ec418ad70611450720b5b08", size = 255670, upload-time = "2025-04-15T17:38:23.688Z" }, + { url = "https://files.pythonhosted.org/packages/1e/c7/cf9fdee8200805c9bc3b148f49cb9482a4e3ea2719e772602a425c9b09f8/contourpy-1.3.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71e2bd4a1c4188f5c2b8d274da78faab884b59df20df63c34f74aa1813c4427c", size = 306694, upload-time = "2025-04-15T17:38:28.238Z" }, + { url = "https://files.pythonhosted.org/packages/dd/e7/ccb9bec80e1ba121efbffad7f38021021cda5be87532ec16fd96533bb2e0/contourpy-1.3.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de425af81b6cea33101ae95ece1f696af39446db9682a0b56daaa48cfc29f38f", size = 345986, upload-time = "2025-04-15T17:38:33.502Z" }, + { url = "https://files.pythonhosted.org/packages/dc/49/ca13bb2da90391fa4219fdb23b078d6065ada886658ac7818e5441448b78/contourpy-1.3.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:977e98a0e0480d3fe292246417239d2d45435904afd6d7332d8455981c408b85", size = 318060, upload-time = "2025-04-15T17:38:38.672Z" }, + { url = "https://files.pythonhosted.org/packages/c8/65/5245ce8c548a8422236c13ffcdcdada6a2a812c361e9e0c70548bb40b661/contourpy-1.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:434f0adf84911c924519d2b08fc10491dd282b20bdd3fa8f60fd816ea0b48841", size = 322747, upload-time = "2025-04-15T17:38:43.712Z" }, + { url = "https://files.pythonhosted.org/packages/72/30/669b8eb48e0a01c660ead3752a25b44fdb2e5ebc13a55782f639170772f9/contourpy-1.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c66c4906cdbc50e9cba65978823e6e00b45682eb09adbb78c9775b74eb222422", size = 1308895, upload-time = "2025-04-15T17:39:00.224Z" }, + { url = "https://files.pythonhosted.org/packages/05/5a/b569f4250decee6e8d54498be7bdf29021a4c256e77fe8138c8319ef8eb3/contourpy-1.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8b7fc0cd78ba2f4695fd0a6ad81a19e7e3ab825c31b577f384aa9d7817dc3bef", size = 1379098, upload-time = "2025-04-15T17:43:29.649Z" }, + { url = "https://files.pythonhosted.org/packages/19/ba/b227c3886d120e60e41b28740ac3617b2f2b971b9f601c835661194579f1/contourpy-1.3.2-cp313-cp313-win32.whl", hash = "sha256:15ce6ab60957ca74cff444fe66d9045c1fd3e92c8936894ebd1f3eef2fff075f", size = 178535, upload-time = "2025-04-15T17:44:44.532Z" }, + { url = "https://files.pythonhosted.org/packages/12/6e/2fed56cd47ca739b43e892707ae9a13790a486a3173be063681ca67d2262/contourpy-1.3.2-cp313-cp313-win_amd64.whl", hash = "sha256:e1578f7eafce927b168752ed7e22646dad6cd9bca673c60bff55889fa236ebf9", size = 223096, upload-time = "2025-04-15T17:44:48.194Z" }, + { url = "https://files.pythonhosted.org/packages/54/4c/e76fe2a03014a7c767d79ea35c86a747e9325537a8b7627e0e5b3ba266b4/contourpy-1.3.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0475b1f6604896bc7c53bb070e355e9321e1bc0d381735421a2d2068ec56531f", size = 285090, upload-time = "2025-04-15T17:43:34.084Z" }, + { url = "https://files.pythonhosted.org/packages/7b/e2/5aba47debd55d668e00baf9651b721e7733975dc9fc27264a62b0dd26eb8/contourpy-1.3.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c85bb486e9be652314bb5b9e2e3b0d1b2e643d5eec4992c0fbe8ac71775da739", size = 268643, upload-time = "2025-04-15T17:43:38.626Z" }, + { url = "https://files.pythonhosted.org/packages/a1/37/cd45f1f051fe6230f751cc5cdd2728bb3a203f5619510ef11e732109593c/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:745b57db7758f3ffc05a10254edd3182a2a83402a89c00957a8e8a22f5582823", size = 310443, upload-time = "2025-04-15T17:43:44.522Z" }, + { url = "https://files.pythonhosted.org/packages/8b/a2/36ea6140c306c9ff6dd38e3bcec80b3b018474ef4d17eb68ceecd26675f4/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:970e9173dbd7eba9b4e01aab19215a48ee5dd3f43cef736eebde064a171f89a5", size = 349865, upload-time = "2025-04-15T17:43:49.545Z" }, + { url = "https://files.pythonhosted.org/packages/95/b7/2fc76bc539693180488f7b6cc518da7acbbb9e3b931fd9280504128bf956/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c6c4639a9c22230276b7bffb6a850dfc8258a2521305e1faefe804d006b2e532", size = 321162, upload-time = "2025-04-15T17:43:54.203Z" }, + { url = "https://files.pythonhosted.org/packages/f4/10/76d4f778458b0aa83f96e59d65ece72a060bacb20cfbee46cf6cd5ceba41/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc829960f34ba36aad4302e78eabf3ef16a3a100863f0d4eeddf30e8a485a03b", size = 327355, upload-time = "2025-04-15T17:44:01.025Z" }, + { url = "https://files.pythonhosted.org/packages/43/a3/10cf483ea683f9f8ab096c24bad3cce20e0d1dd9a4baa0e2093c1c962d9d/contourpy-1.3.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:d32530b534e986374fc19eaa77fcb87e8a99e5431499949b828312bdcd20ac52", size = 1307935, upload-time = "2025-04-15T17:44:17.322Z" }, + { url = "https://files.pythonhosted.org/packages/78/73/69dd9a024444489e22d86108e7b913f3528f56cfc312b5c5727a44188471/contourpy-1.3.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e298e7e70cf4eb179cc1077be1c725b5fd131ebc81181bf0c03525c8abc297fd", size = 1372168, upload-time = "2025-04-15T17:44:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/0f/1b/96d586ccf1b1a9d2004dd519b25fbf104a11589abfd05484ff12199cca21/contourpy-1.3.2-cp313-cp313t-win32.whl", hash = "sha256:d0e589ae0d55204991450bb5c23f571c64fe43adaa53f93fc902a84c96f52fe1", size = 189550, upload-time = "2025-04-15T17:44:37.092Z" }, + { url = "https://files.pythonhosted.org/packages/b0/e6/6000d0094e8a5e32ad62591c8609e269febb6e4db83a1c75ff8868b42731/contourpy-1.3.2-cp313-cp313t-win_amd64.whl", hash = "sha256:78e9253c3de756b3f6a5174d024c4835acd59eb3f8e2ca13e775dbffe1558f69", size = 238214, upload-time = "2025-04-15T17:44:40.827Z" }, + { url = "https://files.pythonhosted.org/packages/33/05/b26e3c6ecc05f349ee0013f0bb850a761016d89cec528a98193a48c34033/contourpy-1.3.2-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:fd93cc7f3139b6dd7aab2f26a90dde0aa9fc264dbf70f6740d498a70b860b82c", size = 265681, upload-time = "2025-04-15T17:44:59.314Z" }, + { url = "https://files.pythonhosted.org/packages/2b/25/ac07d6ad12affa7d1ffed11b77417d0a6308170f44ff20fa1d5aa6333f03/contourpy-1.3.2-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:107ba8a6a7eec58bb475329e6d3b95deba9440667c4d62b9b6063942b61d7f16", size = 315101, upload-time = "2025-04-15T17:45:04.165Z" }, + { url = "https://files.pythonhosted.org/packages/8f/4d/5bb3192bbe9d3f27e3061a6a8e7733c9120e203cb8515767d30973f71030/contourpy-1.3.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ded1706ed0c1049224531b81128efbd5084598f18d8a2d9efae833edbd2b40ad", size = 220599, upload-time = "2025-04-15T17:45:08.456Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c0/91f1215d0d9f9f343e4773ba6c9b89e8c0cc7a64a6263f21139da639d848/contourpy-1.3.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:5f5964cdad279256c084b69c3f412b7801e15356b16efa9d78aa974041903da0", size = 266807, upload-time = "2025-04-15T17:45:15.535Z" }, + { url = "https://files.pythonhosted.org/packages/d4/79/6be7e90c955c0487e7712660d6cead01fa17bff98e0ea275737cc2bc8e71/contourpy-1.3.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49b65a95d642d4efa8f64ba12558fcb83407e58a2dfba9d796d77b63ccfcaff5", size = 318729, upload-time = "2025-04-15T17:45:20.166Z" }, + { url = "https://files.pythonhosted.org/packages/87/68/7f46fb537958e87427d98a4074bcde4b67a70b04900cfc5ce29bc2f556c1/contourpy-1.3.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:8c5acb8dddb0752bf252e01a3035b21443158910ac16a3b0d20e7fed7d534ce5", size = 221791, upload-time = "2025-04-15T17:45:24.794Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" }, + { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" }, + { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" }, + { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" }, + { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" }, + { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" }, + { url = "https://files.pythonhosted.org/packages/be/45/adfee365d9ea3d853550b2e735f9d66366701c65db7855cd07621732ccfc/contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb", size = 293419, upload-time = "2025-07-26T12:01:21.16Z" }, + { url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" }, + { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" }, + { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" }, + { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" }, + { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" }, + { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8f/5847f44a7fddf859704217a99a23a4f6417b10e5ab1256a179264561540e/contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69", size = 185018, upload-time = "2025-07-26T12:01:35.64Z" }, + { url = "https://files.pythonhosted.org/packages/19/e8/6026ed58a64563186a9ee3f29f41261fd1828f527dd93d33b60feca63352/contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b", size = 226567, upload-time = "2025-07-26T12:01:36.804Z" }, + { url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" }, + { url = "https://files.pythonhosted.org/packages/68/35/0167aad910bbdb9599272bd96d01a9ec6852f36b9455cf2ca67bd4cc2d23/contourpy-1.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:177fb367556747a686509d6fef71d221a4b198a3905fe824430e5ea0fda54eb5", size = 293257, upload-time = "2025-07-26T12:01:39.367Z" }, + { url = "https://files.pythonhosted.org/packages/96/e4/7adcd9c8362745b2210728f209bfbcf7d91ba868a2c5f40d8b58f54c509b/contourpy-1.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d002b6f00d73d69333dac9d0b8d5e84d9724ff9ef044fd63c5986e62b7c9e1b1", size = 274034, upload-time = "2025-07-26T12:01:40.645Z" }, + { url = "https://files.pythonhosted.org/packages/73/23/90e31ceeed1de63058a02cb04b12f2de4b40e3bef5e082a7c18d9c8ae281/contourpy-1.3.3-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:348ac1f5d4f1d66d3322420f01d42e43122f43616e0f194fc1c9f5d830c5b286", size = 334672, upload-time = "2025-07-26T12:01:41.942Z" }, + { url = "https://files.pythonhosted.org/packages/ed/93/b43d8acbe67392e659e1d984700e79eb67e2acb2bd7f62012b583a7f1b55/contourpy-1.3.3-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:655456777ff65c2c548b7c454af9c6f33f16c8884f11083244b5819cc214f1b5", size = 381234, upload-time = "2025-07-26T12:01:43.499Z" }, + { url = "https://files.pythonhosted.org/packages/46/3b/bec82a3ea06f66711520f75a40c8fc0b113b2a75edb36aa633eb11c4f50f/contourpy-1.3.3-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:644a6853d15b2512d67881586bd03f462c7ab755db95f16f14d7e238f2852c67", size = 385169, upload-time = "2025-07-26T12:01:45.219Z" }, + { url = "https://files.pythonhosted.org/packages/4b/32/e0f13a1c5b0f8572d0ec6ae2f6c677b7991fafd95da523159c19eff0696a/contourpy-1.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4debd64f124ca62069f313a9cb86656ff087786016d76927ae2cf37846b006c9", size = 362859, upload-time = "2025-07-26T12:01:46.519Z" }, + { url = "https://files.pythonhosted.org/packages/33/71/e2a7945b7de4e58af42d708a219f3b2f4cff7386e6b6ab0a0fa0033c49a9/contourpy-1.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a15459b0f4615b00bbd1e91f1b9e19b7e63aea7483d03d804186f278c0af2659", size = 1332062, upload-time = "2025-07-26T12:01:48.964Z" }, + { url = "https://files.pythonhosted.org/packages/12/fc/4e87ac754220ccc0e807284f88e943d6d43b43843614f0a8afa469801db0/contourpy-1.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ca0fdcd73925568ca027e0b17ab07aad764be4706d0a925b89227e447d9737b7", size = 1403932, upload-time = "2025-07-26T12:01:51.979Z" }, + { url = "https://files.pythonhosted.org/packages/a6/2e/adc197a37443f934594112222ac1aa7dc9a98faf9c3842884df9a9d8751d/contourpy-1.3.3-cp313-cp313-win32.whl", hash = "sha256:b20c7c9a3bf701366556e1b1984ed2d0cedf999903c51311417cf5f591d8c78d", size = 185024, upload-time = "2025-07-26T12:01:53.245Z" }, + { url = "https://files.pythonhosted.org/packages/18/0b/0098c214843213759692cc638fce7de5c289200a830e5035d1791d7a2338/contourpy-1.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:1cadd8b8969f060ba45ed7c1b714fe69185812ab43bd6b86a9123fe8f99c3263", size = 226578, upload-time = "2025-07-26T12:01:54.422Z" }, + { url = "https://files.pythonhosted.org/packages/8a/9a/2f6024a0c5995243cd63afdeb3651c984f0d2bc727fd98066d40e141ad73/contourpy-1.3.3-cp313-cp313-win_arm64.whl", hash = "sha256:fd914713266421b7536de2bfa8181aa8c699432b6763a0ea64195ebe28bff6a9", size = 193524, upload-time = "2025-07-26T12:01:55.73Z" }, + { url = "https://files.pythonhosted.org/packages/c0/b3/f8a1a86bd3298513f500e5b1f5fd92b69896449f6cab6a146a5d52715479/contourpy-1.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:88df9880d507169449d434c293467418b9f6cbe82edd19284aa0409e7fdb933d", size = 306730, upload-time = "2025-07-26T12:01:57.051Z" }, + { url = "https://files.pythonhosted.org/packages/3f/11/4780db94ae62fc0c2053909b65dc3246bd7cecfc4f8a20d957ad43aa4ad8/contourpy-1.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:d06bb1f751ba5d417047db62bca3c8fde202b8c11fb50742ab3ab962c81e8216", size = 287897, upload-time = "2025-07-26T12:01:58.663Z" }, + { url = "https://files.pythonhosted.org/packages/ae/15/e59f5f3ffdd6f3d4daa3e47114c53daabcb18574a26c21f03dc9e4e42ff0/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e4e6b05a45525357e382909a4c1600444e2a45b4795163d3b22669285591c1ae", size = 326751, upload-time = "2025-07-26T12:02:00.343Z" }, + { url = "https://files.pythonhosted.org/packages/0f/81/03b45cfad088e4770b1dcf72ea78d3802d04200009fb364d18a493857210/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ab3074b48c4e2cf1a960e6bbeb7f04566bf36b1861d5c9d4d8ac04b82e38ba20", size = 375486, upload-time = "2025-07-26T12:02:02.128Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ba/49923366492ffbdd4486e970d421b289a670ae8cf539c1ea9a09822b371a/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6c3d53c796f8647d6deb1abe867daeb66dcc8a97e8455efa729516b997b8ed99", size = 388106, upload-time = "2025-07-26T12:02:03.615Z" }, + { url = "https://files.pythonhosted.org/packages/9f/52/5b00ea89525f8f143651f9f03a0df371d3cbd2fccd21ca9b768c7a6500c2/contourpy-1.3.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50ed930df7289ff2a8d7afeb9603f8289e5704755c7e5c3bbd929c90c817164b", size = 352548, upload-time = "2025-07-26T12:02:05.165Z" }, + { url = "https://files.pythonhosted.org/packages/32/1d/a209ec1a3a3452d490f6b14dd92e72280c99ae3d1e73da74f8277d4ee08f/contourpy-1.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4feffb6537d64b84877da813a5c30f1422ea5739566abf0bd18065ac040e120a", size = 1322297, upload-time = "2025-07-26T12:02:07.379Z" }, + { url = "https://files.pythonhosted.org/packages/bc/9e/46f0e8ebdd884ca0e8877e46a3f4e633f6c9c8c4f3f6e72be3fe075994aa/contourpy-1.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:2b7e9480ffe2b0cd2e787e4df64270e3a0440d9db8dc823312e2c940c167df7e", size = 1391023, upload-time = "2025-07-26T12:02:10.171Z" }, + { url = "https://files.pythonhosted.org/packages/b9/70/f308384a3ae9cd2209e0849f33c913f658d3326900d0ff5d378d6a1422d2/contourpy-1.3.3-cp313-cp313t-win32.whl", hash = "sha256:283edd842a01e3dcd435b1c5116798d661378d83d36d337b8dde1d16a5fc9ba3", size = 196157, upload-time = "2025-07-26T12:02:11.488Z" }, + { url = "https://files.pythonhosted.org/packages/b2/dd/880f890a6663b84d9e34a6f88cded89d78f0091e0045a284427cb6b18521/contourpy-1.3.3-cp313-cp313t-win_amd64.whl", hash = "sha256:87acf5963fc2b34825e5b6b048f40e3635dd547f590b04d2ab317c2619ef7ae8", size = 240570, upload-time = "2025-07-26T12:02:12.754Z" }, + { url = "https://files.pythonhosted.org/packages/80/99/2adc7d8ffead633234817ef8e9a87115c8a11927a94478f6bb3d3f4d4f7d/contourpy-1.3.3-cp313-cp313t-win_arm64.whl", hash = "sha256:3c30273eb2a55024ff31ba7d052dde990d7d8e5450f4bbb6e913558b3d6c2301", size = 199713, upload-time = "2025-07-26T12:02:14.4Z" }, + { url = "https://files.pythonhosted.org/packages/72/8b/4546f3ab60f78c514ffb7d01a0bd743f90de36f0019d1be84d0a708a580a/contourpy-1.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fde6c716d51c04b1c25d0b90364d0be954624a0ee9d60e23e850e8d48353d07a", size = 292189, upload-time = "2025-07-26T12:02:16.095Z" }, + { url = "https://files.pythonhosted.org/packages/fd/e1/3542a9cb596cadd76fcef413f19c79216e002623158befe6daa03dbfa88c/contourpy-1.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:cbedb772ed74ff5be440fa8eee9bd49f64f6e3fc09436d9c7d8f1c287b121d77", size = 273251, upload-time = "2025-07-26T12:02:17.524Z" }, + { url = "https://files.pythonhosted.org/packages/b1/71/f93e1e9471d189f79d0ce2497007731c1e6bf9ef6d1d61b911430c3db4e5/contourpy-1.3.3-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22e9b1bd7a9b1d652cd77388465dc358dafcd2e217d35552424aa4f996f524f5", size = 335810, upload-time = "2025-07-26T12:02:18.9Z" }, + { url = "https://files.pythonhosted.org/packages/91/f9/e35f4c1c93f9275d4e38681a80506b5510e9327350c51f8d4a5a724d178c/contourpy-1.3.3-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a22738912262aa3e254e4f3cb079a95a67132fc5a063890e224393596902f5a4", size = 382871, upload-time = "2025-07-26T12:02:20.418Z" }, + { url = "https://files.pythonhosted.org/packages/b5/71/47b512f936f66a0a900d81c396a7e60d73419868fba959c61efed7a8ab46/contourpy-1.3.3-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:afe5a512f31ee6bd7d0dda52ec9864c984ca3d66664444f2d72e0dc4eb832e36", size = 386264, upload-time = "2025-07-26T12:02:21.916Z" }, + { url = "https://files.pythonhosted.org/packages/04/5f/9ff93450ba96b09c7c2b3f81c94de31c89f92292f1380261bd7195bea4ea/contourpy-1.3.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f64836de09927cba6f79dcd00fdd7d5329f3fccc633468507079c829ca4db4e3", size = 363819, upload-time = "2025-07-26T12:02:23.759Z" }, + { url = "https://files.pythonhosted.org/packages/3e/a6/0b185d4cc480ee494945cde102cb0149ae830b5fa17bf855b95f2e70ad13/contourpy-1.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:1fd43c3be4c8e5fd6e4f2baeae35ae18176cf2e5cced681cca908addf1cdd53b", size = 1333650, upload-time = "2025-07-26T12:02:26.181Z" }, + { url = "https://files.pythonhosted.org/packages/43/d7/afdc95580ca56f30fbcd3060250f66cedbde69b4547028863abd8aa3b47e/contourpy-1.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6afc576f7b33cf00996e5c1102dc2a8f7cc89e39c0b55df93a0b78c1bd992b36", size = 1404833, upload-time = "2025-07-26T12:02:28.782Z" }, + { url = "https://files.pythonhosted.org/packages/e2/e2/366af18a6d386f41132a48f033cbd2102e9b0cf6345d35ff0826cd984566/contourpy-1.3.3-cp314-cp314-win32.whl", hash = "sha256:66c8a43a4f7b8df8b71ee1840e4211a3c8d93b214b213f590e18a1beca458f7d", size = 189692, upload-time = "2025-07-26T12:02:30.128Z" }, + { url = "https://files.pythonhosted.org/packages/7d/c2/57f54b03d0f22d4044b8afb9ca0e184f8b1afd57b4f735c2fa70883dc601/contourpy-1.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:cf9022ef053f2694e31d630feaacb21ea24224be1c3ad0520b13d844274614fd", size = 232424, upload-time = "2025-07-26T12:02:31.395Z" }, + { url = "https://files.pythonhosted.org/packages/18/79/a9416650df9b525737ab521aa181ccc42d56016d2123ddcb7b58e926a42c/contourpy-1.3.3-cp314-cp314-win_arm64.whl", hash = "sha256:95b181891b4c71de4bb404c6621e7e2390745f887f2a026b2d99e92c17892339", size = 198300, upload-time = "2025-07-26T12:02:32.956Z" }, + { url = "https://files.pythonhosted.org/packages/1f/42/38c159a7d0f2b7b9c04c64ab317042bb6952b713ba875c1681529a2932fe/contourpy-1.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:33c82d0138c0a062380332c861387650c82e4cf1747aaa6938b9b6516762e772", size = 306769, upload-time = "2025-07-26T12:02:34.2Z" }, + { url = "https://files.pythonhosted.org/packages/c3/6c/26a8205f24bca10974e77460de68d3d7c63e282e23782f1239f226fcae6f/contourpy-1.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ea37e7b45949df430fe649e5de8351c423430046a2af20b1c1961cae3afcda77", size = 287892, upload-time = "2025-07-26T12:02:35.807Z" }, + { url = "https://files.pythonhosted.org/packages/66/06/8a475c8ab718ebfd7925661747dbb3c3ee9c82ac834ccb3570be49d129f4/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d304906ecc71672e9c89e87c4675dc5c2645e1f4269a5063b99b0bb29f232d13", size = 326748, upload-time = "2025-07-26T12:02:37.193Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a3/c5ca9f010a44c223f098fccd8b158bb1cb287378a31ac141f04730dc49be/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ca658cd1a680a5c9ea96dc61cdbae1e85c8f25849843aa799dfd3cb370ad4fbe", size = 375554, upload-time = "2025-07-26T12:02:38.894Z" }, + { url = "https://files.pythonhosted.org/packages/80/5b/68bd33ae63fac658a4145088c1e894405e07584a316738710b636c6d0333/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ab2fd90904c503739a75b7c8c5c01160130ba67944a7b77bbf36ef8054576e7f", size = 388118, upload-time = "2025-07-26T12:02:40.642Z" }, + { url = "https://files.pythonhosted.org/packages/40/52/4c285a6435940ae25d7410a6c36bda5145839bc3f0beb20c707cda18b9d2/contourpy-1.3.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b7301b89040075c30e5768810bc96a8e8d78085b47d8be6e4c3f5a0b4ed478a0", size = 352555, upload-time = "2025-07-26T12:02:42.25Z" }, + { url = "https://files.pythonhosted.org/packages/24/ee/3e81e1dd174f5c7fefe50e85d0892de05ca4e26ef1c9a59c2a57e43b865a/contourpy-1.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2a2a8b627d5cc6b7c41a4beff6c5ad5eb848c88255fda4a8745f7e901b32d8e4", size = 1322295, upload-time = "2025-07-26T12:02:44.668Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b2/6d913d4d04e14379de429057cd169e5e00f6c2af3bb13e1710bcbdb5da12/contourpy-1.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fd6ec6be509c787f1caf6b247f0b1ca598bef13f4ddeaa126b7658215529ba0f", size = 1391027, upload-time = "2025-07-26T12:02:47.09Z" }, + { url = "https://files.pythonhosted.org/packages/93/8a/68a4ec5c55a2971213d29a9374913f7e9f18581945a7a31d1a39b5d2dfe5/contourpy-1.3.3-cp314-cp314t-win32.whl", hash = "sha256:e74a9a0f5e3fff48fb5a7f2fd2b9b70a3fe014a67522f79b7cca4c0c7e43c9ae", size = 202428, upload-time = "2025-07-26T12:02:48.691Z" }, + { url = "https://files.pythonhosted.org/packages/fa/96/fd9f641ffedc4fa3ace923af73b9d07e869496c9cc7a459103e6e978992f/contourpy-1.3.3-cp314-cp314t-win_amd64.whl", hash = "sha256:13b68d6a62db8eafaebb8039218921399baf6e47bf85006fd8529f2a08ef33fc", size = 250331, upload-time = "2025-07-26T12:02:50.137Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8c/469afb6465b853afff216f9528ffda78a915ff880ed58813ba4faf4ba0b6/contourpy-1.3.3-cp314-cp314t-win_arm64.whl", hash = "sha256:b7448cb5a725bb1e35ce88771b86fba35ef418952474492cf7c764059933ff8b", size = 203831, upload-time = "2025-07-26T12:02:51.449Z" }, + { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" }, + { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" }, + { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" }, + { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" }, +] + +[[package]] +name = "contourpy" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/ba/01bde9753bdbba04a6da9d2bff3881f021bc708f654655e95fae26d3b3a3/contourpy-1.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b", size = 297302, upload-time = "2026-09-11T19:02:45.103Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f5/c5bf67522d49a2222f3154fe46879451d26f0e35ece41770758a64ea78cb/contourpy-1.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8", size = 284921, upload-time = "2026-09-11T19:02:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cc/cb989599eec12fda312e127eb8e04a8b21a7a6c94bf7ff1bc68273334a42/contourpy-1.4.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0", size = 356332, upload-time = "2026-09-11T19:02:51.408Z" }, + { url = "https://files.pythonhosted.org/packages/47/fb/6f620d7602507817b0b4c21dd790ed68688f1f4ae9c29aacf21f08db5cf1/contourpy-1.4.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b", size = 405878, upload-time = "2026-09-11T19:02:54.093Z" }, + { url = "https://files.pythonhosted.org/packages/32/4e/693c6d6bdece679f0953775eef3a1b66d56be55478d936e7deb1f3004422/contourpy-1.4.0-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c", size = 408296, upload-time = "2026-09-11T19:02:56.528Z" }, + { url = "https://files.pythonhosted.org/packages/78/f9/b6831508960d559581c448532ba4df312217072975486dbf2b24fcc5b76f/contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591", size = 383243, upload-time = "2026-09-11T19:02:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/f2/21/52903825a0ae7bb625e8bd30a09816d4c3c5d6174a469c10a616166cf780/contourpy-1.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3", size = 1357306, upload-time = "2026-09-11T19:03:01.036Z" }, + { url = "https://files.pythonhosted.org/packages/d8/79/d68b1ce8539e4071518fed9523f558398f34dcd078b8927b109c72dad2ef/contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f", size = 1427243, upload-time = "2026-09-11T19:03:03.866Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f0/b75a10e9d0616b97a30de277b6dfe83f1879880854c7330337309530eb48/contourpy-1.4.0-cp312-cp312-win32.whl", hash = "sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2", size = 347345, upload-time = "2026-09-11T19:03:06.192Z" }, + { url = "https://files.pythonhosted.org/packages/50/a9/dab08786bb4d77ef9a046b3c1be923be4e73c5d07d91f5a54e8ea9b09e41/contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c", size = 234083, upload-time = "2026-09-11T19:03:08.122Z" }, + { url = "https://files.pythonhosted.org/packages/47/b9/3ba509755a970dbde5948e7142ac21f266be72f38017cc4087a05fdceee1/contourpy-1.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c", size = 559521, upload-time = "2026-09-11T19:03:10.047Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8b/62a6eacea08ea0b6ab0159a7783df7ed421ff9c1ff58fef7c31f58fa5e52/contourpy-1.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea", size = 297330, upload-time = "2026-09-11T19:03:11.809Z" }, + { url = "https://files.pythonhosted.org/packages/3f/2f/103cdc5b7077cd569989d3ddb99ee3d4e96ee31bde8df2a6e426b2dc6195/contourpy-1.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814", size = 285037, upload-time = "2026-09-11T19:03:13.781Z" }, + { url = "https://files.pythonhosted.org/packages/bf/25/97001d1fdf940e6f5adfc592d4f5899fff95daf7dceead3988fe09987d2d/contourpy-1.4.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5", size = 356675, upload-time = "2026-09-11T19:03:15.374Z" }, + { url = "https://files.pythonhosted.org/packages/a6/5e/9a7241a89e2f74402aefa2569e1349ad2750ff77823c04c788eaaedb7fdd/contourpy-1.4.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561", size = 406990, upload-time = "2026-09-11T19:03:17.44Z" }, + { url = "https://files.pythonhosted.org/packages/36/81/3a4fbbf6a806eada5453a6d16f6c7d96b9f4b3e57a3127368fb545986b8a/contourpy-1.4.0-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b", size = 407271, upload-time = "2026-09-11T19:03:19.523Z" }, + { url = "https://files.pythonhosted.org/packages/68/77/8f93ecbde1a4d11dfd460cd19a0c159f5487352e751fa87f5d78cc9db08e/contourpy-1.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70", size = 384707, upload-time = "2026-09-11T19:03:21.208Z" }, + { url = "https://files.pythonhosted.org/packages/05/07/e5cdf94d68961ee464de6b4fedd3d2f666584f59ccd124bb1290597122ab/contourpy-1.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28", size = 1356741, upload-time = "2026-09-11T19:03:23.621Z" }, + { url = "https://files.pythonhosted.org/packages/fd/8a/2301d07accb257ac08daeb631875fada06fedd019c20ff7b00ee07e9d211/contourpy-1.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67", size = 1426793, upload-time = "2026-09-11T19:03:25.955Z" }, + { url = "https://files.pythonhosted.org/packages/7d/5d/a62648f06259d15c139b14eb8cf3c58fe53cb970a55f2bb77d1070e80a41/contourpy-1.4.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b", size = 117961, upload-time = "2026-09-11T19:03:27.713Z" }, + { url = "https://files.pythonhosted.org/packages/71/31/c5b7771ba6982f319ec90c0cf5c425b36891adfeee2d9f667f90b2d0c166/contourpy-1.4.0-cp313-cp313-win32.whl", hash = "sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599", size = 347438, upload-time = "2026-09-11T19:03:29.829Z" }, + { url = "https://files.pythonhosted.org/packages/68/c1/a59df0754bf83a6f3e153cc19d550a5b01f607e389b1c4d57f436f9139e0/contourpy-1.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4", size = 234084, upload-time = "2026-09-11T19:03:31.657Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/97224f5decb1efa5a610f912195deb45321f73ec9b9dac485cd6fe2d5a6a/contourpy-1.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b", size = 559559, upload-time = "2026-09-11T19:03:33.528Z" }, + { url = "https://files.pythonhosted.org/packages/75/b0/b548628c8dddf6e5e0a981b7fa8e4c008024df09c7d17c6a9e271edfa0b3/contourpy-1.4.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a3e67bc1a6a4618a1dac7c3053a9ffece5ddfa2046b2670b342cf430bb0b87d1", size = 297354, upload-time = "2026-09-11T19:03:35.017Z" }, + { url = "https://files.pythonhosted.org/packages/04/5a/513484208742f65af2648c519f0b7ab034616e183c4403538024c136a1ab/contourpy-1.4.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:072a702e2e178f4fcf96f04775d0c059e4c917925abf0d3208ebb6865df3c23d", size = 283729, upload-time = "2026-09-11T19:03:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/35/da/5a6562febc994b2c4bf9d01e57a50458ef8a2051bb3e7b35a00333e0fc26/contourpy-1.4.0-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:404dbcd9233513dfd1323b66ea593fef90e899f658f6b8a9ed8e93bd0ca669db", size = 357819, upload-time = "2026-09-11T19:03:39.058Z" }, + { url = "https://files.pythonhosted.org/packages/6d/99/7b358ce888aaa426f755daa096c99c59d17c352037344e836f20e5d3b957/contourpy-1.4.0-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:61624f6722480aa7e168fd746164e7bfdf48f8ccb6542f1613741200dc37e2b1", size = 407795, upload-time = "2026-09-11T19:03:41.293Z" }, + { url = "https://files.pythonhosted.org/packages/be/02/34d7548adf08c60967435d79d7a90882eacc84f5093435287974c7e99943/contourpy-1.4.0-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e741a39dfc96babe1722561e81351aeec104526c57dbe91c167c1db606c2d55", size = 408552, upload-time = "2026-09-11T19:03:42.728Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8c/9677dad226e5aaac5b823d5b09d881ebc32ff1648af417597649841e516c/contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e439ab450c93455feb0218532ded3e946ec7a9b5f459069f122cfa44b89229f6", size = 384850, upload-time = "2026-09-11T19:03:44.402Z" }, + { url = "https://files.pythonhosted.org/packages/08/f5/e3fbeaa489c223629fbb434737cb3de4ecaca9cae4825e77b92490f640f8/contourpy-1.4.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:417be048f7e122cefbe2a34c51a1f2b0410f8eb35796f794d45475ddb7872d9d", size = 1357601, upload-time = "2026-09-11T19:03:46.746Z" }, + { url = "https://files.pythonhosted.org/packages/88/be/55fec293d342c222ed58a5d4056df4362e192af2e59527a3d5d822de8828/contourpy-1.4.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:43d80072a32299bf945de0a6dd4e034ea0162e832261de2e07a274a5adbba9c9", size = 1427340, upload-time = "2026-09-11T19:03:48.745Z" }, + { url = "https://files.pythonhosted.org/packages/86/40/0faabf453edf59b0e3633381d7ca72c3414fb9b72b5cbb08b06ed792d3e5/contourpy-1.4.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:fa1b787362a3856e63dd2b89449f6c384d55ee1beb8f94f4bcc871b40f02462c", size = 118355, upload-time = "2026-09-11T19:03:50.047Z" }, + { url = "https://files.pythonhosted.org/packages/38/0c/7ea75aa3559ae8a6805015e15a19c92b6480752ecc92526361e5776e88c5/contourpy-1.4.0-cp314-cp314-win32.whl", hash = "sha256:738c44fa71735a617f36da58e32810512407d283d5d1bb5b1cecb00d7eeba7cf", size = 356977, upload-time = "2026-09-11T19:04:11.401Z" }, + { url = "https://files.pythonhosted.org/packages/15/41/3df8cc14bb572c8b447f9dfbc876703f0f2f2896058285b5c87a1d4a638d/contourpy-1.4.0-cp314-cp314-win_amd64.whl", hash = "sha256:181bea01bc742734ae672fa00c717d855dd35e1f029536406538c52e7b0cd73d", size = 240101, upload-time = "2026-09-11T19:04:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/66/01/ee6830a5aa4565662a345172f6f35eeeed625d20f1c9d4ecd35318fe4ade/contourpy-1.4.0-cp314-cp314-win_arm64.whl", hash = "sha256:64039341e2d8804f1a13bda8c69083eab935167bbd7e856cf096241f17d5bd45", size = 576359, upload-time = "2026-09-11T19:04:14.983Z" }, + { url = "https://files.pythonhosted.org/packages/51/af/49ee9c9cf012699e505c1b63c531cc99f19df50f205173092c4d541e3ec7/contourpy-1.4.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ef47fef9a912c77e3d84b014f701e5a9340f25703e9ed3bcebe37f91fb69dc49", size = 313601, upload-time = "2026-09-11T19:03:51.452Z" }, + { url = "https://files.pythonhosted.org/packages/ad/59/ce411ab2be0f805038626d8f4ca9ce563487ff51ff6c363e7512271564ed/contourpy-1.4.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:96019f059bcb3774acc0104be3360a57b36d33eaaa2e1d7f77c800ca8e07618b", size = 302812, upload-time = "2026-09-11T19:03:53.022Z" }, + { url = "https://files.pythonhosted.org/packages/95/b0/390915f9af14c1e2d3b2a9ad99d85b98df4352346a51e368cbb825f813c3/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ddf5a2596d716fd3793434844caf31abc7a40b1e8718431420c89858268fb909", size = 348996, upload-time = "2026-09-11T19:03:54.594Z" }, + { url = "https://files.pythonhosted.org/packages/c7/85/e0952576d54322f3e9983b1e049a7a31f42ce82c5c29d01821e6dd3780d7/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dd59df9e2fb0aff8bd7fd1adb9f349b7c835245a9d0f18c2f2deeb537190f2b1", size = 400272, upload-time = "2026-09-11T19:03:56.822Z" }, + { url = "https://files.pythonhosted.org/packages/d6/7d/f13543a5e1598e4a4ad01d9d5e2d65f9c09c37660616429913d606c5977d/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b7794ea07cab575633daad8d6e963b662053391022294d3aacc1d9ba9ef54114", size = 412895, upload-time = "2026-09-11T19:03:58.487Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a8/6e5eaff53507dfd2dfc428240eecda32453067277d4b3e7ca71210b2d611/contourpy-1.4.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1c8a74744fa746eeaa12f0f9ed7f8b4add9d8f1b14d95e3b5e133675eac888f", size = 377060, upload-time = "2026-09-11T19:04:00.122Z" }, + { url = "https://files.pythonhosted.org/packages/16/a3/d00e44d35511b3cead5bd794ee672d4eecf30d9de4ceac57a49d6204064f/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:107ec46f7aa1664266d69b1181aadc953d58d39f7d8d648fa5b795d4a060b0de", size = 1345688, upload-time = "2026-09-11T19:04:02.705Z" }, + { url = "https://files.pythonhosted.org/packages/1e/01/1e533b0cae32c8edd63fe40435ec3b29345dab87321afcd28722d7f957d1/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5a4c89c7f38a0d7a94356d74e3391073c4325c4d47ad2fd065c3fe7dbae16c0c", size = 1416140, upload-time = "2026-09-11T19:04:04.77Z" }, + { url = "https://files.pythonhosted.org/packages/6d/0c/4ee66759f00d6a5d6909782f14f441d639fa18a4a43142e334351efc47f8/contourpy-1.4.0-cp314-cp314t-win32.whl", hash = "sha256:912c6afaa106e2f74ba22b30416b77ef7eb94e3bdc5a4df51ab147845dba9b6d", size = 371982, upload-time = "2026-09-11T19:04:06.233Z" }, + { url = "https://files.pythonhosted.org/packages/e6/ac/b3e5324138c3e3741f526663f4f265f4f69dfdf26415a39428940864a5f6/contourpy-1.4.0-cp314-cp314t-win_amd64.whl", hash = "sha256:ef9440f6f8506246269a82734f5ff9e2e4c5e775b3996fc883cc491c5257eca6", size = 262907, upload-time = "2026-09-11T19:04:07.882Z" }, + { url = "https://files.pythonhosted.org/packages/19/37/c9aa45e47819dc15a38fc5c81a2fb987fde55e9d3b991fbde514e3b6b5f5/contourpy-1.4.0-cp314-cp314t-win_arm64.whl", hash = "sha256:fc9feef8f1f001c5b87decadc67c4a5d1eebb62ca39c4763d1237ff62cf2b707", size = 587071, upload-time = "2026-09-11T19:04:09.898Z" }, + { url = "https://files.pythonhosted.org/packages/cc/74/66d4e6fbea3bcb3fd4e5ae21c039ba31b8fc408b35884b4bc09b88016dce/contourpy-1.4.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:79b06c60d5e569ce12c5da8f0c51217cdc484386e2349fa717c30fafb56d2871", size = 297358, upload-time = "2026-09-11T19:04:16.718Z" }, + { url = "https://files.pythonhosted.org/packages/2e/8d/8f7f25e71d73f15d7859943189900d2d348e740388c9ef52a0180d284762/contourpy-1.4.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6f963ea9f0d68d2b6a02d861e3c0aae09ae25ba21f243fcf281e9fed468b078d", size = 283732, upload-time = "2026-09-11T19:04:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/f0/90/957549e3b03c407c670e3e191db63f4aef60dab6605bc967af3a806b543e/contourpy-1.4.0-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5545ff38229c15d11d822fc6f7415b932da9f4975f53e305b7b96ebfb01f889c", size = 357820, upload-time = "2026-09-11T19:04:20.077Z" }, + { url = "https://files.pythonhosted.org/packages/56/4c/fa8de87d907b41b05d03f4945a51675cd67319650d01b4c927d209ffa6ee/contourpy-1.4.0-cp315-cp315-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:630d32f06cedf37b7f1dd2b6a12e4492826bd477a4c9c7b2e2fee6ce3a2cea76", size = 407804, upload-time = "2026-09-11T19:04:21.781Z" }, + { url = "https://files.pythonhosted.org/packages/04/e7/96bd4f4a4ae285727befbdb4b332d53a2654cc5da4585d2525b47a063e1f/contourpy-1.4.0-cp315-cp315-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:be85d160e7c795113c2a93254dde2fc7e86b375322570eee78b420969426973c", size = 408559, upload-time = "2026-09-11T19:04:23.432Z" }, + { url = "https://files.pythonhosted.org/packages/ae/94/39660e8dc309f96bf7971eb4ec5659f272f84e42b34c9990a96ecce8442c/contourpy-1.4.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:018227e134b73090b06f911e773a526c77c9af426be29065500ce096a5accd4c", size = 384861, upload-time = "2026-09-11T19:04:25.198Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7b/411dccbf73d5d19da49bf7735786b3baf4ddb1456412d48ae4d4ab1fc761/contourpy-1.4.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:4bffcb2e8cc5c0e837631acab59dd04265fdac376550e7c3e310523877c68cb7", size = 1357612, upload-time = "2026-09-11T19:04:27.614Z" }, + { url = "https://files.pythonhosted.org/packages/a0/39/bf2442130e7d5aae75a4de4504f0c8aca3ef3da3feac3940ee27ca985d83/contourpy-1.4.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc87f2ffa84a49a77d76cb792f28a48ff3b05a222aa0b2bddbd839ba78e1d5ca", size = 1427345, upload-time = "2026-09-11T19:04:29.646Z" }, + { url = "https://files.pythonhosted.org/packages/96/60/e5d9196dd83ccd7dd103762982b10ef19a4f72e8ef67ae7157699b9be0bb/contourpy-1.4.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:c8be3392b84cf43373a488874dc1ebf46f60784a70977f92586e18019d71c7ed", size = 118157, upload-time = "2026-09-11T19:04:31.091Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b2/ae3d90f08ba2ed82189d93b55ffbd41e559760e89af4f9ef54d51869f41d/contourpy-1.4.0-cp315-cp315-win32.whl", hash = "sha256:618137ec5778fb76d494c9ec854b104a377fddba0d128bef7136cce2c3bf0df8", size = 356982, upload-time = "2026-09-11T19:04:52.913Z" }, + { url = "https://files.pythonhosted.org/packages/02/a0/36648fff407dcf8b8482985d33367ffc0fe90be72383869312cd0bd00a1b/contourpy-1.4.0-cp315-cp315-win_amd64.whl", hash = "sha256:ea09dc704029930cbd097f75cb0cc1db9852adbcf1a151fac7e9559f7bcbfd19", size = 240101, upload-time = "2026-09-11T19:04:54.587Z" }, + { url = "https://files.pythonhosted.org/packages/07/09/49e987a96706b8f877596cee00d558d7880793a833addc6b33f80805e5dc/contourpy-1.4.0-cp315-cp315-win_arm64.whl", hash = "sha256:a5e2bb871b90cd7a52bdee63bf80ef7acb46398d27efc66d7679240016efc5aa", size = 576375, upload-time = "2026-09-11T19:04:56.515Z" }, + { url = "https://files.pythonhosted.org/packages/e3/18/820ba24a070fe2a834af73e52245c501960746f5c1777ebc64ec0c0dec12/contourpy-1.4.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:432e89f835cf01f8d2123a130a3126b17ee6e0348e4d62c0973872b30aa873bf", size = 313543, upload-time = "2026-09-11T19:04:32.582Z" }, + { url = "https://files.pythonhosted.org/packages/d3/4c/f61a63d8107e0c1c3fa47d30ce45abad90b2ad48a1a9a4510332db7e0176/contourpy-1.4.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e0a2392533e5e2abdf277c951047516acc8d2f3c42b2dd9dc34c907c9ebabf2", size = 302702, upload-time = "2026-09-11T19:04:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/9d/93/5af95cb5113ecc6e780ca0c6c79756a2cea8833f971bbae112dd4ad73ded/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:758e7496cec3195fc28a28945eab3ceef348c47fb95c7afc2eca2f3901209c8c", size = 354370, upload-time = "2026-09-11T19:04:36.158Z" }, + { url = "https://files.pythonhosted.org/packages/47/75/5a9942446647202beb7b4d150891bfcb78fb112c73862484bbe4cc031092/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bee6ff96653e0807cd0f8eaef00174a031e3a2effa5c20f49a5a8d574b05af23", size = 402340, upload-time = "2026-09-11T19:04:37.914Z" }, + { url = "https://files.pythonhosted.org/packages/c3/4f/bfdb0c67775a584f957211936661289789c4d0ec3e988bca2c8c02f8090e/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a58b5f130afec61a093d743cdda435cc4047748b6791627e34a68f41ec3a9b07", size = 410721, upload-time = "2026-09-11T19:04:39.925Z" }, + { url = "https://files.pythonhosted.org/packages/65/d3/dddf13d6bb26e145c99debd1f2695018b5f3e24452dd9bfc9904c9d2ec89/contourpy-1.4.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9dc493e7924e5aa32d89d0b8e50986280f3d4b284968a792787bd7bcffd3cad", size = 382604, upload-time = "2026-09-11T19:04:41.793Z" }, + { url = "https://files.pythonhosted.org/packages/37/b4/89f0a5f6c6ccd322eae2704c7e933c82a4e594a61773933b4b0a18646866/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:c927ec747633e68c9920bcaad48b0bcefe648812b822f18c34e2d0e2270a3d2a", size = 1354996, upload-time = "2026-09-11T19:04:43.856Z" }, + { url = "https://files.pythonhosted.org/packages/5d/29/fc91cc1ac6f3b591a269f4357b656d6ed0c39eb17c148f41f6da2f9729b9/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:80c7fc8e7ac217777ce7ba2db3cf8478652b5a4b335283111012ff9eaac9d842", size = 1425030, upload-time = "2026-09-11T19:04:45.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b8/bb129f524210c5d3eb8616876e02af280fba8b5554e0ac1afad80b51e06b/contourpy-1.4.0-cp315-cp315t-win32.whl", hash = "sha256:90feb8da006803a95ba573fddc9536357d0c3faddc3a4c9e22816ca49af52878", size = 371854, upload-time = "2026-09-11T19:04:48.106Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b1/bc774d9d200cfc4f073bba78b1bb1cb3b55bf1c8c345eae41fc2db510459/contourpy-1.4.0-cp315-cp315t-win_amd64.whl", hash = "sha256:de503609fdb71f597634ca64fb4bd2f13d27c97f140e912b1e8ed93544840df0", size = 262450, upload-time = "2026-09-11T19:04:49.502Z" }, + { url = "https://files.pythonhosted.org/packages/54/bf/eb4ff492e1c3d027617b5a20e4e6d63a035b41b8cf77a95950159556a3a5/contourpy-1.4.0-cp315-cp315t-win_arm64.whl", hash = "sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184", size = 587064, upload-time = "2026-09-11T19:04:51.148Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.4.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "cuda-pathfinder", version = "1.8.3", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/1e/d90a8af3d589776c70e92d43d7a0234260709a1d552d105f4dd3bdf48fa3/cuda_bindings-13.4.4-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90f85a00fc89dd4a8f7c4beb0a2f3f788b845c8496fe84adc1217830206db9e0", size = 6512106, upload-time = "2026-10-14T12:35:04.07Z" }, + { url = "https://files.pythonhosted.org/packages/70/62/8c23958012acc7558cdc3d453b3078742c3e6051cc8be2860e6bfbdf00fd/cuda_bindings-13.4.4-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:85d961133658fff3167cfcf69de1beac8e46453c15fd4bcaa4a96d3ef1110c69", size = 7160770, upload-time = "2026-10-14T12:35:06.501Z" }, + { url = "https://files.pythonhosted.org/packages/a1/15/0277326dd1a2d619ea8a85b790fc9e43cb67897d3a3377eb783f5bc2a33a/cuda_bindings-13.4.4-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b8b2e4235b552edb42cdbe39de7a9259ceec631e21c7344b76177db9cc6c58b4", size = 6494096, upload-time = "2026-10-14T12:35:11.314Z" }, + { url = "https://files.pythonhosted.org/packages/97/36/3bfb7b74817a0a78f80340fae742a27d166e8fcdffa459b79d5be66e077a/cuda_bindings-13.4.4-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e1cef1eaf5a08cc3bf3675ca9d3f97f3fc7085998556c848b4053e74ba4ba392", size = 7160763, upload-time = "2026-10-14T12:35:13.773Z" }, + { url = "https://files.pythonhosted.org/packages/d7/38/87909f62598d02d9e5c536326aed1755f6bfa190285507b962bb601e0005/cuda_bindings-13.4.4-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b346bfe1dda49537537c06cc4727b2210d949d8aee883cb591bca46581629d00", size = 6488222, upload-time = "2026-10-14T12:35:20.703Z" }, + { url = "https://files.pythonhosted.org/packages/c2/f8/332443cf969734551891cdbd93657eaeaf747ac2b7dd73feb3422701b02b/cuda_bindings-13.4.4-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:433efa31e33c2868621b5f6036bd3bf5de9c45c5546cb1361a5f6ff3415b8bb5", size = 7172184, upload-time = "2026-10-14T12:35:22.817Z" }, + { url = "https://files.pythonhosted.org/packages/a7/97/7d75105a92ee18b7764f5cf60672d6a966842348a2a049e663fe690902ff/cuda_bindings-13.4.4-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c3f4cc887eac0d5edb5d7396cc78b336bee151a97e2ba7acf59e8b9380132d0", size = 6316532, upload-time = "2026-10-14T12:35:30.291Z" }, + { url = "https://files.pythonhosted.org/packages/ba/8f/aedec367fea64267594a26ede3704f241e1bee465962f3a92d6186c774b7/cuda_bindings-13.4.4-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d6adc44f098472d8ac2d6211923eea6081830521852dc77f8c9237bf9320a59", size = 6929120, upload-time = "2026-10-14T12:35:32.508Z" }, + { url = "https://files.pythonhosted.org/packages/e6/f0/d71d1dd45caa358a39c6898dcc9f1bd22a9f22b92376b967835c047b50bc/cuda_bindings-13.4.4-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a429132f06d0c3a853aa419aabe4c0a7bfc3f3886fb4c336d81729f63754d31", size = 6407946, upload-time = "2026-10-14T12:35:39.826Z" }, + { url = "https://files.pythonhosted.org/packages/15/65/0b8f2f2509e5f1a8e556a2e083ac0287fe4af79afdba3153454229306f39/cuda_bindings-13.4.4-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:680e70dcb8b61fdae16d3bb4876c41d55aadc9fe8b3825ea567f2f2c85606b0a", size = 6978954, upload-time = "2026-10-14T12:35:42.892Z" }, + { url = "https://files.pythonhosted.org/packages/f1/dd/81903887199ffd90f9ee29eee8ecd497b734007e78b80689e0dd2f904bd8/cuda_bindings-13.4.4-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:03a8fd2a25530dbae26ecd4462d418156028e35b3f3b081440ff6368506e10eb", size = 6314269, upload-time = "2026-10-14T12:35:50.607Z" }, + { url = "https://files.pythonhosted.org/packages/90/44/f6325a6061f1fc619e216dd6c7cbd9a0b475d3937bb32296c84cc27e6eeb/cuda_bindings-13.4.4-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ce9208c7cf03a947ac11553b08ee2fca594ac63d34360639a9060980f546a62", size = 6865978, upload-time = "2026-10-14T12:35:52.874Z" }, + { url = "https://files.pythonhosted.org/packages/c2/26/00d628420ac318a6a6d559fe6602e08a0156e7f4b5bf9dc6ea20c63789bc/cuda_bindings-13.4.4-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:50bc70ef3b225f4794f5b374773629836bbfdf4a21fc975ac25e7daad67494b8", size = 6414169, upload-time = "2026-10-14T14:12:29.952Z" }, + { url = "https://files.pythonhosted.org/packages/63/88/5b50b13cef9ae8baadcca03a47cf0e9146c0b52ca6aeabaf50fc17e18445/cuda_bindings-13.4.4-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6781fe08ed5f4b5163a3c6577e079bc28955811382d35995c916bf052ee0994e", size = 7012626, upload-time = "2026-10-14T14:12:32.224Z" }, + { url = "https://files.pythonhosted.org/packages/63/cb/013d9fd501dc1b05c3f467f28ad3adeed9e4d39318a4668a7a75fc5b19da/cuda_bindings-13.4.4-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a4c97f8430d7f7c4a4d0f245510d26647dd81ea3fc65941f7a815ad395cbc30e", size = 6302110, upload-time = "2026-10-14T14:12:39.47Z" }, + { url = "https://files.pythonhosted.org/packages/c8/5d/ca0d5c1d9c09a9de15f474c1fa6abe801761e75cdc1be9a03431063f2af5/cuda_bindings-13.4.4-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:baa0f5f1f9a05032e7deb97051e85aa18b4e3c6db914f1c813bb2f02e5c72db4", size = 6878099, upload-time = "2026-10-14T14:12:41.504Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "cuda-pathfinder", version = "1.9.1", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/09/74e159fbe67b081cca842871addce6d2b493f9bb48ce85124f023eb5f1c9/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71c15ed97099a8ef416515d80ddd10770e0f6339234e16855a526d2896516631", size = 7434875, upload-time = "2026-11-05T12:05:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0d/ca24317a31118b90fd60126aec5c0a92a191a7fdd39524032d43328b49b5/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:08b7e8d674c3266facb00453a7e34ea7d3ea965c2f594bb728f269f45f39fbe2", size = 8390178, upload-time = "2026-11-05T12:05:52.653Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a6/13d14600381bdbfe55dfc35564e4bf4a208f169ee9f6cbeb356564268aff/cuda_bindings-13.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40eadfad6ae1554f8c1aa456620a85a49a275fc902f2c6dd93ee8c488b2c5e9f", size = 7354398, upload-time = "2026-11-05T12:06:03.542Z" }, + { url = "https://files.pythonhosted.org/packages/27/68/14bf44f386672b03fcc0799be8d18df3e1c45847ee23b95721f6022abbaf/cuda_bindings-13.5.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a46a8cc84112d769d0f57bf3ae3fedc115cf09348f14da85a1a8200968b6f262", size = 8378158, upload-time = "2026-11-05T12:06:05.253Z" }, + { url = "https://files.pythonhosted.org/packages/89/94/e90cb85fbe77d6d9b0d3d3d60c0964a59e7fbcc5b21be64a2fda6aff9e21/cuda_bindings-13.5.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cf525b2c2113fdfd2b10899a3e5d280520e970aa13c6ca021e83d9d02f895ed1", size = 7388832, upload-time = "2026-11-05T12:06:11.458Z" }, + { url = "https://files.pythonhosted.org/packages/66/05/6a2ab20fefb584d469d2daaf9d8cb65661a8fe938b850cb2534c016f1ae2/cuda_bindings-13.5.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d47b6f6d0398f97c82e2525eefb02e7252848e48c902824f6a6b6467a5902894", size = 8385548, upload-time = "2026-11-05T12:06:13.46Z" }, + { url = "https://files.pythonhosted.org/packages/ab/2c/d293e815d9203a1ac0429eaaac9bafc404abc54a0211992a6145fa2c4392/cuda_bindings-13.5.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da7fafa0eb222b980dc931281d1b53f822c34efb33e72ae14b0e1ce216232afd", size = 7471124, upload-time = "2026-11-05T12:06:19.966Z" }, + { url = "https://files.pythonhosted.org/packages/b9/fc/220c4d23f2675d237fb3a1fb5b35a77b82825c5a5097451b3d0da55d5160/cuda_bindings-13.5.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99746f2928150042191edf7952323bb22e8f104f7bcee787bd7e2001a8bba70b", size = 8443163, upload-time = "2026-11-05T12:06:21.695Z" }, + { url = "https://files.pythonhosted.org/packages/3d/1f/9473a7391c8f2be4c0d04dedffb187c47f8695c8a13f3a4604ab9cc45434/cuda_bindings-13.5.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:643ed0f6aae2bec657a7ad8872a62912178c28e94bb533ce60dbc46c1c0950dc", size = 7557151, upload-time = "2026-11-05T12:06:27.603Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7c/e26e5d9e5ab339cd34d089c759b348e6a82ae48d513fa35641a1c55b527e/cuda_bindings-13.5.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9b69fdaa27b1f69746bb23b7fa6a458c88dffcb4d7cf27062ad2f1b6245a18c0", size = 8322122, upload-time = "2026-11-05T12:06:29.286Z" }, + { url = "https://files.pythonhosted.org/packages/d9/d1/0b6a66341a6caa7b39245cde2a43db2bf27c62405c2ccb5e328cf46cda16/cuda_bindings-13.5.0-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92baf83790a1c7f33cce41d89d7e4b5bea67d683f08007c781d88d5e55a9cb33", size = 7478864, upload-time = "2026-11-05T12:06:35.078Z" }, + { url = "https://files.pythonhosted.org/packages/88/08/f82b39f219ac875c5d544fbbfe251d5cb639b3fe4dcd9354281074db0ee7/cuda_bindings-13.5.0-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:991ace38a09fc664228209fd023d1394f5209aeee4728f14c1f7647908cb5a70", size = 8447167, upload-time = "2026-11-05T12:06:36.87Z" }, + { url = "https://files.pythonhosted.org/packages/45/e6/c33e51f4158868b76d53be64a476d6700e0f5280d855b1588ef5b4136ec4/cuda_bindings-13.5.0-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f1faaea572a382e903d8bfe2a066de2879d04775198c0fb28f3791bf1221b8a1", size = 7580891, upload-time = "2026-11-05T12:06:43.706Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e1/7df5d56759d894c1c88da9d018f7d8fc1ea467876c5bdf26ca4855880697/cuda_bindings-13.5.0-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fb26fb0532d9bb0f5d5469493530c71fe6dce8614e20006beaa546408a97e4bc", size = 8352712, upload-time = "2026-11-05T12:06:45.489Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/fb/f8e1890428f9f590b4beebd63b068aac1ce32a3331510c847b9f9a78f261/cuda_pathfinder-1.8.3-py3-none-any.whl", hash = "sha256:e29e59829c297a7a5233bd9cc71094fc5bddbd076951482670178f9eade39b1f", size = 62561, upload-time = "2026-10-02T03:20:23.712Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.9.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/8e/e6101ff068e7e78b362879ffc0c7cbfe68c9742943c9b034f009fe19f88f/cuda_pathfinder-1.9.1-py3-none-any.whl", hash = "sha256:b743c132f90ad2d1e71d43fd28f31ebcde518f943e50fd44aca62b2a80d5230d", size = 63462, upload-time = "2026-11-19T04:26:29.241Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", version = "13.1.1.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-nvrtc", version = "13.0.88", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", version = "13.0.96", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufft = [ + { name = "nvidia-cufft", version = "12.0.0.61", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufile = [ + { name = "nvidia-cufile", version = "1.15.1.6", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", version = "13.0.85", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +curand = [ + { name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusolver = [ + { name = "nvidia-cublas", version = "13.1.1.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusolver", version = "12.0.4.66", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusparse", version = "12.6.3.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusparse = [ + { name = "nvidia-cusparse", version = "12.6.3.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", version = "13.0.88", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvtx = [ + { name = "nvidia-nvtx", version = "13.0.85", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.2.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/3d/62/854e4a141f5e87e5425513bad2a742a6260acfe06ef148001b5362148f31/cuda_toolkit-13.2.2-py2.py3-none-any.whl", hash = "sha256:d12edc1aad1356236a2ee10c0d794b1aff5d3e79bfeca54867c3bb8e5afd87b0", size = 2607, upload-time = "2026-07-16T10:13:01.07Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", version = "13.4.1.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-nvrtc", version = "13.2.86", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", version = "13.2.86", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufft = [ + { name = "nvidia-cufft", version = "12.2.0.57", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufile = [ + { name = "nvidia-cufile", version = "1.17.1.22", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", version = "13.2.86", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusolver = [ + { name = "nvidia-cublas", version = "13.4.1.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusolver", version = "12.2.0.11", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusparse", version = "12.7.10.12", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusparse = [ + { name = "nvidia-cusparse", version = "12.7.10.12", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", version = "13.2.86", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvtx = [ + { name = "nvidia-nvtx", version = "13.2.86", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "dask" +version = "2026.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "cloudpickle" }, + { name = "fsspec" }, + { name = "importlib-metadata", version = "9.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "importlib-metadata", version = "10.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "packaging" }, + { name = "partd" }, + { name = "pyyaml" }, + { name = "toolz" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/49/6b/417e5397929c0b798bc006021d0996291d7bfc141228248b86c2cee8074f/dask-2026.11.0.tar.gz", hash = "sha256:75448e361e733aff98a57e2075a2a2398329c60eb6c567a3aa35de91970f1c7e", size = 11627641, upload-time = "2026-11-23T14:49:30.446Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/a1/49cd0780d5a1adffc29d0062eafcc2447156a2d64d49634f201ef19e7497/dask-2026.11.0-py3-none-any.whl", hash = "sha256:3d826d9448c6834ccd1e0a9c932caa249e5a138aee254db791a0153c0a357f6d", size = 1497453, upload-time = "2026-11-23T14:49:28.679Z" }, +] + +[[package]] +name = "decorator" +version = "5.3.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4e/a2/dc08c667e7e51cb035ffab38ae98d7d0f249092591130db4f67dc26b0021/decorator-5.3.2.tar.gz", hash = "sha256:d9883f1b8259e3bfc42565d0bc6fdc760012008552aa449f75efd2d48319b82b", size = 62733, upload-time = "2026-11-21T05:12:51.05Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/bb/03ad4489fe19a410fe0065bbfb5424d28455eac9115e9cee7a56b6b1ec37/decorator-5.3.2-py3-none-any.whl", hash = "sha256:d3fb2a434ac31e231d14175ecbda823d83f26b7e45270cd7cd4d0350264b79e2", size = 11830, upload-time = "2026-11-21T05:12:50.003Z" }, +] + +[[package]] +name = "docutils" +version = "0.21.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", size = 2204444, upload-time = "2024-04-23T18:57:18.24Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", size = 587408, upload-time = "2024-04-23T18:57:14.835Z" }, +] + +[[package]] +name = "docutils" +version = "0.22.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/b6/03bb70946330e88ffec97aefd3ea75ba575cb2e762061e0e62a213befee8/docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968", size = 2291750, upload-time = "2025-12-18T19:00:26.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/10/5da547df7a391dcde17f59520a231527b8571e6f46fc8efb02ccb370ab12/docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de", size = 633196, upload-time = "2025-12-18T19:00:18.077Z" }, +] + +[[package]] +name = "docutils" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/aa/ff/f2b6db8d41a56842f480de6ee43f5112f5b40981d99327d3733731b1c376/docutils-0.23.1.tar.gz", hash = "sha256:8a83ac8810e41228b6f20e96a183abd2460a1757f78e2603e3d4b31fe7d29622", size = 2304939, upload-time = "2026-12-01T15:56:28.485Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/fd/feddc9e9b09e73ae49bca0e684b3ac24527e8d14b19acdebb5d9ca25599d/docutils-0.23.1-py3-none-any.whl", hash = "sha256:08633ce67a7bf227823a363043f0b0e7b6d731e473276349f3a44f5cba39b0e4", size = 634982, upload-time = "2026-12-01T15:56:22.876Z" }, +] + +[[package]] +name = "donfig" +version = "0.8.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/71/80cc718ff6d7abfbabacb1f57aaa42e9c1552bfdd01e64ddd704e4a03638/donfig-0.8.1.post1.tar.gz", hash = "sha256:3bef3413a4c1c601b585e8d297256d0c1470ea012afa6e8461dc28bfb7c23f52", size = 19506, upload-time = "2024-05-23T14:14:31.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, +] + +[[package]] +name = "exceptiongroup" +version = "1.3.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/ac/f882fe3234606340c8729372da0fb98c634b97a560c9d375d9afea21496b/exceptiongroup-1.3.2.tar.gz", hash = "sha256:ca82e69f0cb535fbde934885744b67669a3efddd50fe7bc00d3398839fcaddec", size = 34687, upload-time = "2026-11-19T22:10:16.815Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/7d/0fb19ccdf794c448141461180d5992c50402f69f8515a801bfac7ad65f45/exceptiongroup-1.3.2-py3-none-any.whl", hash = "sha256:41c6a70dfec22050d3d8b43386b059a4dc0bca3f3d40a40971cb206fff1785af", size = 16854, upload-time = "2026-11-19T22:10:15.746Z" }, +] + +[[package]] +name = "executing" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/92/8a611141e42930c0f194f7504063ab87dfe970cf1a5af28e7703df448734/executing-2.3.0.tar.gz", hash = "sha256:15919cb5d667e5cb4e099511971d00d659573fff2dd5c4e6cd8b71636c7858d2", size = 1338003, upload-time = "2026-10-10T14:06:04.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/dd/8bc67e7d5ffc1d88aa5af511189dfb76dc4e1e5b808fab186146ef2663e5/executing-2.3.0-py3-none-any.whl", hash = "sha256:736e859c9f8701f11fcf516856f26f562e04776387824b43a35a1dfe21c84122", size = 29393, upload-time = "2026-10-10T14:06:02.777Z" }, +] + +[[package]] +name = "fasteners" +version = "0.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/18/7881a99ba5244bfc82f06017316ffe93217dbbbcfa52b887caa1d4f2a6d3/fasteners-0.20.tar.gz", hash = "sha256:55dce8792a41b56f727ba6e123fcaee77fd87e638a6863cec00007bfea84c8d8", size = 25087, upload-time = "2025-08-11T10:19:37.785Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/ac/e5d886f892666d2d1e5cb8c1a41146e1d79ae8896477b1153a21711d3b44/fasteners-0.20-py3-none-any.whl", hash = "sha256:9422c40d1e350e4259f509fb2e608d6bc43c0136f79a00db1b49046029d0b3b7", size = 18702, upload-time = "2025-08-11T10:19:35.716Z" }, +] + +[[package]] +name = "filelock" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/4c/58/6fd434bec86eff7c38a3168454cb132b762b2bea9b3ac094101a2f7bc32a/filelock-4.1.0.tar.gz", hash = "sha256:ad7f724afef953e731b1cc39bcd3a09166d72ed7fcdf29e6e88b1c3235c6715d", size = 561277, upload-time = "2026-10-09T19:57:20.34Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/86/032133892a5de43b5a98200b01aadcad68cc255e274a762f08b8a76d2912/filelock-4.1.0-py3-none-any.whl", hash = "sha256:2ce9818e3e2d8f284c1a964414447ef148d42a5fd5e2a477a7118e574b293ec1", size = 133003, upload-time = "2026-10-09T19:57:18.716Z" }, +] + +[[package]] +name = "filelock" +version = "4.3.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/b2/de/99f4266dc2b97503fe35af46d4bf54ea4d434bc322992103145c9de7da95/filelock-4.3.2.tar.gz", hash = "sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3", size = 744182, upload-time = "2026-11-27T22:58:32.45Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/4f/6429bb372197194e65bb33885cd112c7008c2b9cf7496285874aa274e506/filelock-4.3.2-py3-none-any.whl", hash = "sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b", size = 244905, upload-time = "2026-11-27T22:58:31.01Z" }, +] + +[[package]] +name = "flake8" +version = "7.4.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "mccabe" }, + { name = "pycodestyle" }, + { name = "pyflakes", version = "4.0.3", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c2/94/85870fc02dfe4ab0885c440e7e41f6a986b10e43eca6717e90f8ce1215cc/flake8-7.4.1.tar.gz", hash = "sha256:84ea5afcaf344487b0ea5baaebb8100f4cfaebc01f755998f75876664029f587", size = 47897, upload-time = "2026-09-23T12:21:59.283Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/d4/8e58a7221419bf8cb194f362ab26abf504c983135975e4c785fac0852886/flake8-7.4.1-py2.py3-none-any.whl", hash = "sha256:78480274a6d7289d9cb8eafeda241fac57d4ea687d26e32dfdca37b72cdeddad", size = 57449, upload-time = "2026-09-23T12:21:58.085Z" }, +] + +[[package]] +name = "flake8" +version = "7.5.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "mccabe" }, + { name = "pycodestyle" }, + { name = "pyflakes", version = "4.1.0", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9a/da/b0d00f8c4c676212284edd3cc3d371588ce0e36a349373c3a01e188b5639/flake8-7.5.0.tar.gz", hash = "sha256:0dab7566341aca0d80aa29b5812bdadf256caa6a63e6068e49ac2649918236a4", size = 47811, upload-time = "2026-10-28T20:17:22.128Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/57/a3adc5f380f50ef3d01014cb9d3b8c17b25de9b89def20d559def4fc3c4e/flake8-7.5.0-py2.py3-none-any.whl", hash = "sha256:637ea1a443a78ed6ee461725cdf71ca93bc5cde0abf25436dbebdc3880b4e078", size = 57487, upload-time = "2026-10-28T20:17:21.061Z" }, +] + +[[package]] +name = "fonttools" +version = "4.65.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/77/51/d63c7e52163ac14393a35bd14bd7c0da95f8f74be5d7cc988092f9965129/fonttools-4.65.0.tar.gz", hash = "sha256:762ba5431358d0dbd4a01982484a1d494fb267e91f974cdcf20b80eab8560f6f", size = 3674467, upload-time = "2026-09-10T15:35:54.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/d9/1caaa015dd207da7ccd3feba87289997bd88334ea3e74a367cdc7b0e50a3/fonttools-4.65.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:93a73af2075036d36d7fbf856779c56a1b3b86ffcdae6abede7596604c42c156", size = 3095449, upload-time = "2026-09-10T15:33:04.814Z" }, + { url = "https://files.pythonhosted.org/packages/20/d6/988cd9b33ae2d92b15a51d73eb77c991f7a0fe90a7bc74526e9669247789/fonttools-4.65.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c130be2232e3caf8d2b476854ea78421ec1642917ff5ab695284bac31bbb072b", size = 2587697, upload-time = "2026-09-10T15:33:07.653Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6a/36f465a1c277131f9569f6a56fe99cf135391b4860b9c4f4b23e5b1cd5df/fonttools-4.65.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e3944e0bdba42effb71959e43d91b599326b02b59c78310d5675e8a75525e7d8", size = 5313308, upload-time = "2026-09-10T15:33:09.975Z" }, + { url = "https://files.pythonhosted.org/packages/ee/56/151b5e81d20c63834f48ad37a0cbbbe2f9b248e38f8d10387f0cf5219244/fonttools-4.65.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fb53892b570f7f1f0055e75fc4de32673e32f749c4c8a606b63d5c436650e634", size = 5253649, upload-time = "2026-09-10T15:33:12.225Z" }, + { url = "https://files.pythonhosted.org/packages/c8/22/6389215da9d4f98623aacdca9479c1030bbd516cb658e893bc54b61098ce/fonttools-4.65.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a6c8d184e523580a7c55d21cde37176a3c91cb539cf06c2aa36ffc634fd75296", size = 5277745, upload-time = "2026-09-10T15:33:14.783Z" }, + { url = "https://files.pythonhosted.org/packages/89/e3/c1037a1dfb7c8efe6f2a7d1951ebdde40cbbf82e9c5d796fcb03077e4790/fonttools-4.65.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:e5ceccaf2e57d83b753a2b5db5d94aa0a8071886d4afebd2d520c9683e6bef0e", size = 5413259, upload-time = "2026-09-10T15:33:17.619Z" }, + { url = "https://files.pythonhosted.org/packages/44/b9/7dd72330168d39635c329f23a98279393b1e825e42a6db362e09897aad7b/fonttools-4.65.0-cp310-cp310-win32.whl", hash = "sha256:aff640a4fcb021fa83f9879d5bfa115b6931522dae991a24faa75888bd6aeff6", size = 1577124, upload-time = "2026-09-10T15:33:19.864Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c2/e959385b4626989b25b82b9f4f99e7c3ac68377d6846b376239b6f126966/fonttools-4.65.0-cp310-cp310-win_amd64.whl", hash = "sha256:5c1700a60e4ff23a0425d5a64abf43d092e6b55071354825781faf255904dcb4", size = 1633354, upload-time = "2026-09-10T15:33:21.963Z" }, + { url = "https://files.pythonhosted.org/packages/62/9e/58250cdc54d96fcfacb544e12997a6390fa4e6b71ae2241cfcfe5b341803/fonttools-4.65.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06273c71e692caf5989c0437ca50875a5e49e216ddf653228fe9bb35bdc82c0f", size = 3089141, upload-time = "2026-09-10T15:33:24.509Z" }, + { url = "https://files.pythonhosted.org/packages/3e/67/0f0416069e38da0a1327a847a2e8dd1edb425d0043d8a3e63eb940070209/fonttools-4.65.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ca2b02d74e9ad7e21a1d11e4701425800a4b0c63cf90486e60258262feccbcbf", size = 2584298, upload-time = "2026-09-10T15:33:26.598Z" }, + { url = "https://files.pythonhosted.org/packages/99/0d/7e40e9957359afc0bab081131c215370a6d2d203361bb6f945ab595e924c/fonttools-4.65.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7830e9fa3bebc44dbc27ff44d8201def30ea5c48a773696d58e69e6bcd9cd5d4", size = 5498163, upload-time = "2026-09-10T15:33:29.071Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e6/e48cf0a272a5d4d17a09d44f92727e67f975ddfa94acc8464763d19a654d/fonttools-4.65.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a3991732c87b3f054a2a8cf86dd0d602833fa8cb37c911503173771646e1013d", size = 5457456, upload-time = "2026-09-10T15:33:31.918Z" }, + { url = "https://files.pythonhosted.org/packages/e4/8a/a5c67ddeda82ee5e4ec3bc52ac1cbb685f0bb7a0516badc55643b454ab0d/fonttools-4.65.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6031e77b3fb8c765055ba2b8bd8dcb17030f3bf2484c448b472fdedf4460ba80", size = 5464334, upload-time = "2026-09-10T15:33:34.605Z" }, + { url = "https://files.pythonhosted.org/packages/d7/16/294e77383b2d39c9f8f25144a7ba23fe1cbbc05227cc72545097785ff07c/fonttools-4.65.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6813cc1e2e883bd6c15b3e04f72c78dc65fdc4ca861063adf5f341fbaec2ca62", size = 5595597, upload-time = "2026-09-10T15:33:37.591Z" }, + { url = "https://files.pythonhosted.org/packages/80/01/8e74ce8626c734959c782f2d89af8e9f14d078fd3d4ddf8b5a51401ae475/fonttools-4.65.0-cp311-cp311-win32.whl", hash = "sha256:4a5db8442453da4b6f43ad325879381b726bf2238a2253efd9584be21a2cefc2", size = 2441114, upload-time = "2026-09-10T15:33:40.592Z" }, + { url = "https://files.pythonhosted.org/packages/37/3e/835dc6c658426e2670b7f38c38295492fcbaeb06080e9dce89ce8105993c/fonttools-4.65.0-cp311-cp311-win_amd64.whl", hash = "sha256:9f201796c8e24e657be77c16fa664e798a46122144217f90838982937a964f0a", size = 2498823, upload-time = "2026-09-10T15:33:43.402Z" }, + { url = "https://files.pythonhosted.org/packages/58/db/242fa4fce7f632c5f7ab15585343393b25792510c0c32bd218ad24d59f1c/fonttools-4.65.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e844a45c9e5ced6536f184cf1a65b5d65e8f7e711993b413e10500a8223622e5", size = 3097120, upload-time = "2026-09-10T15:33:46Z" }, + { url = "https://files.pythonhosted.org/packages/a0/b6/42fa4d373416675f74446421cf0b2badb82a4245c60745f05f424f75c649/fonttools-4.65.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b30e953de049bf43fc0a63c7d0c44d205c923e4bbf24716aae1518c0e65f977c", size = 2584658, upload-time = "2026-09-10T15:33:48.473Z" }, + { url = "https://files.pythonhosted.org/packages/75/6f/d589b9d62280a846c77a2c383d852c6dcb79ae8aa02bf0fa46c8577af145/fonttools-4.65.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09c34bdeed8915bfb53bee0c8ed2254dbd8ec69c0014b7f3702f347c049bf358", size = 5425737, upload-time = "2026-09-10T15:33:51.473Z" }, + { url = "https://files.pythonhosted.org/packages/b5/09/de2c0c20a42c18e565a2617932beb08c06697bbdd0d3f62b108262e11583/fonttools-4.65.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:05595385ae99f4b9626cebb973bf171b8fe38a8f40708e6e42abba0ed7537778", size = 5402463, upload-time = "2026-09-10T15:33:54.907Z" }, + { url = "https://files.pythonhosted.org/packages/79/2e/bc0f5c9dce21821454bb5812d3b23410bca33c8bbd5468386d0327aa0cff/fonttools-4.65.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d95b34dd68fbfc0e4a1740c421597656117f979ed8dc85de66e08f9f9981806e", size = 5362168, upload-time = "2026-09-10T15:33:57.481Z" }, + { url = "https://files.pythonhosted.org/packages/1f/0d/2116763ade7e71e0e5d421babe1785d745be9b3d605bf914792ce1c97f79/fonttools-4.65.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:924d06e6130429168318db71c40174a765ad016fc4b56ca811287e3d7373b3a6", size = 5524117, upload-time = "2026-09-10T15:34:00.021Z" }, + { url = "https://files.pythonhosted.org/packages/e2/5e/f9600553b9f645e3068553831685ff1dab6259536a23b38d2e048de38f17/fonttools-4.65.0-cp312-cp312-win32.whl", hash = "sha256:04f73dd01005752a6e75cf4a8dc6b70dc724d1d4bc34cc89522153f4a2f07680", size = 2432089, upload-time = "2026-09-10T15:34:02.803Z" }, + { url = "https://files.pythonhosted.org/packages/3a/02/e436a6a1863b9862bab9f82d6da33055dd7aa3738017edd902a163525dc2/fonttools-4.65.0-cp312-cp312-win_amd64.whl", hash = "sha256:3b5d9ba89edf778b376e669b879ae33a198bf45cf5a23c3f6514f935cf9d0d9d", size = 2483475, upload-time = "2026-09-10T15:34:05.09Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5c/343a4225e83eb06f82c1d8bf41fc5e5f71eab2f62bc7ca215c764722c0a9/fonttools-4.65.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8b7bb52817a24731d2e4f4df0e71fdde05e6c806c8f8f1517b015d142fdacfa5", size = 3094663, upload-time = "2026-09-10T15:34:07.235Z" }, + { url = "https://files.pythonhosted.org/packages/9b/c9/49b2401be932741d9218181c08948c96db32eab21ecaaf79283b752e13e7/fonttools-4.65.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e2c21772fcf70325189707b19f346812690bb1b0bd7e207e6ac205244806b303", size = 2584521, upload-time = "2026-09-10T15:34:09.648Z" }, + { url = "https://files.pythonhosted.org/packages/51/c9/48b07e6c5cf44fa56f758a04c3772a66c0e9ba82bbe22077e4076746a62b/fonttools-4.65.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:64c9b26816415b5e3d899e9077109d327b22140fe3c4066644d8cdbad5bb1569", size = 5395399, upload-time = "2026-09-10T15:34:12.38Z" }, + { url = "https://files.pythonhosted.org/packages/fa/2d/5cc5a10c8ed56079d6c2e9e3e5920622529a2ae045c9f47a6055ccb1a319/fonttools-4.65.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6dd6243f60e2d6160c2966e1e14020dc261ffd741b69a2e4ca8bfd051592e4b7", size = 5376659, upload-time = "2026-09-10T15:34:15.239Z" }, + { url = "https://files.pythonhosted.org/packages/ab/6f/ccf33739d936bb3afa1655a225be7ee5d63d6d3c8b7d0e570bc5a2a7b899/fonttools-4.65.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:834962fd7cf21c58e81ac50a59e6ed2306f9df5e3dd481dad1cd7d2c4c60b773", size = 5336795, upload-time = "2026-09-10T15:34:17.817Z" }, + { url = "https://files.pythonhosted.org/packages/7e/c1/ffd17483f2094f0f4118974295b514b5b82afd4f6e3c80c23f01684e97a6/fonttools-4.65.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:580eb68ff7bd6954a7a76afddd864bfc66eaaf5f5c20dd6ead9186d0055a4ffe", size = 5496530, upload-time = "2026-09-10T15:34:20.241Z" }, + { url = "https://files.pythonhosted.org/packages/b1/19/9aca7712d0676ba5f8d1530ce20478a9bb09cccd0153d56693337379cdcf/fonttools-4.65.0-cp313-cp313-win32.whl", hash = "sha256:7a18b2ffd44249fe84289253197aa65ad4f2de554c0d381f18b1f5939bc6bc60", size = 2430392, upload-time = "2026-09-10T15:34:22.906Z" }, + { url = "https://files.pythonhosted.org/packages/1f/6f/f015dea0f4354e0798751b657cea2dee482914737f88bf1a078349ce92cf/fonttools-4.65.0-cp313-cp313-win_amd64.whl", hash = "sha256:8ae1846b0f192fd485d26a455af19b8f5cf05aff08f9836f533913d8fcea133c", size = 2481620, upload-time = "2026-09-10T15:34:25.816Z" }, + { url = "https://files.pythonhosted.org/packages/64/29/606365ef601668bfebed14cfe3dc72bb7fcd1e23011bbb2833f17fea3065/fonttools-4.65.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:dc87a9f846bec83c3795804f62b4632716d46e3522869a3dd9cd44a5d245b006", size = 3098393, upload-time = "2026-09-10T15:34:28.472Z" }, + { url = "https://files.pythonhosted.org/packages/c7/61/11412939d6b7abf5ac7ce0d61d7f94a0a4fbabc9f1ab0a04fa622e0fc11c/fonttools-4.65.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:aa50dd7b9baf75e2bbd43401fc0d237f7a94a8ad2e0c57ea97160fc631af5eb0", size = 2585766, upload-time = "2026-09-10T15:34:31.207Z" }, + { url = "https://files.pythonhosted.org/packages/db/17/734921d8aee8309801da42590375d32d4d46f771b73373ec9520d5d4220b/fonttools-4.65.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d2a9892fdb3b7e2d0f4174e3b907d226ff83698249762eeefce08ec5b2de1dd", size = 5380679, upload-time = "2026-09-10T15:34:33.933Z" }, + { url = "https://files.pythonhosted.org/packages/cf/eb/2a4d78d60d978e694cfa04c98e4d8ddbf7f028fd768ddef470bb9da5d69e/fonttools-4.65.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6d815734e7fede0ad1f233f23f0f191cbe8fc64762ff041e589bc0f78e0b2397", size = 5321833, upload-time = "2026-09-10T15:34:36.295Z" }, + { url = "https://files.pythonhosted.org/packages/d9/ca/1cd48b5c11ef9658732787bf2362e1bf3871dad5945d2f6cc8f675ca769c/fonttools-4.65.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:71e4c67b6196a2f447f46476fd2302604721617f5e0a21b0988bdd87b6bb9687", size = 5320938, upload-time = "2026-09-10T15:34:38.992Z" }, + { url = "https://files.pythonhosted.org/packages/c6/0d/90e6051bded926cccabe9dd0bce3b6ca012f4d5779d61167afbf4989ceb6/fonttools-4.65.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b11d8a4a0c3ca74bbd4c105b7ef82501945c939e6096d9934ec7d288cdf5aaa9", size = 5451747, upload-time = "2026-09-10T15:34:41.387Z" }, + { url = "https://files.pythonhosted.org/packages/18/74/23e0268e48029ff0752083f69312c49b738163d5af919add9dc4ac81e907/fonttools-4.65.0-cp314-cp314-win32.whl", hash = "sha256:8e44a34d91b3c793879767eb115867ced74d2eb94974e64e72fe9e2eea71cf1a", size = 2434246, upload-time = "2026-09-10T15:34:44.385Z" }, + { url = "https://files.pythonhosted.org/packages/a1/2d/ee69affecd4bc81cb932a213438d4199fb48bf8ca6d664438ccc7f623c2a/fonttools-4.65.0-cp314-cp314-win_amd64.whl", hash = "sha256:0aa8901db22875c831d6a91796549590d7e747da37438f38b69d771b668be445", size = 2486706, upload-time = "2026-09-10T15:34:46.842Z" }, + { url = "https://files.pythonhosted.org/packages/8e/9c/edee5f785198ce3327e1ddeace91c773122d47f086a67e0a84b800f4a940/fonttools-4.65.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:2e4a380ca40d3a5372e31b340f0da0d53b4583aadbb8e41f6a516afa69c509a4", size = 3172027, upload-time = "2026-09-10T15:34:49.269Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c6/252ec9884381089bc30da75978b072593920249de60219817f16cbc9145f/fonttools-4.65.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:661bd91c4be13721408b2d4b67a9b3fa7736713adc9a6c9780c9c60fc7959f90", size = 2619020, upload-time = "2026-09-10T15:34:51.453Z" }, + { url = "https://files.pythonhosted.org/packages/42/79/f71b0d202b8473bb45b07876c08a474de9fe560ed2c0cde642812a81e22a/fonttools-4.65.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62c5e42c79449def957adf8a9a65a43018efa7e2a6bc6baa3afe955e0d5fb2ab", size = 5545942, upload-time = "2026-09-10T15:34:54.804Z" }, + { url = "https://files.pythonhosted.org/packages/4a/bd/52e1bf33e0aebfe22ecc9a85c634db707c1dd9f6b1b438efeed98c55b959/fonttools-4.65.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:36fca8efc46b5adfca327c666e739fc05b7a7a6ef17840230f81b22f53230f61", size = 5351477, upload-time = "2026-09-10T15:34:57.514Z" }, + { url = "https://files.pythonhosted.org/packages/5c/76/8c6b2ad20beec95cd446f3a8bdc753c7e4a4fd69ef3e66704c0f7c8cb0b5/fonttools-4.65.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8aa1291e4c767abf1b0b79ca2d6895f7c0b661d9d95d03b5791c883a9d1e1f08", size = 5412271, upload-time = "2026-09-10T15:35:00.895Z" }, + { url = "https://files.pythonhosted.org/packages/79/49/fadbf11bbbd2d699d88a5498a0634280206e01e3bd5da9a4e0c504953ce9/fonttools-4.65.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fcf39949f56911348514b466714efa9118bec3d2be249e1c487263f7cda6edab", size = 5446450, upload-time = "2026-09-10T15:35:03.369Z" }, + { url = "https://files.pythonhosted.org/packages/df/77/5fda646d3a6d5ee26465865c00319cc0925cf484a3b42dd8232d5b39f973/fonttools-4.65.0-cp314-cp314t-win32.whl", hash = "sha256:ffc918702661f1d74d2fbb2f5551036b64f6d2d743139e105289b694bcd16f54", size = 2467858, upload-time = "2026-09-10T15:35:05.744Z" }, + { url = "https://files.pythonhosted.org/packages/ae/0f/afa0f3de70ebe02bba46b32cccb30b1de52624472b14ac2e7cd403d08db9/fonttools-4.65.0-cp314-cp314t-win_amd64.whl", hash = "sha256:5a977e3645dbffaee924209828aa702a215f7ff68bc08010740c10c723787e62", size = 2518248, upload-time = "2026-09-10T15:35:07.846Z" }, + { url = "https://files.pythonhosted.org/packages/86/54/b273cf5712b36a381c13284fbf244e811e1e1d7081aed20f200f0a191ffa/fonttools-4.65.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:7aa0518b45ff5286ad56f063938db3add3816e899aab58d782b3f9a252523caa", size = 3092770, upload-time = "2026-09-10T15:35:10.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/1d/d3e4511475954d4ec4f3c254e81f0fcc1ade504cb7381eeca48b8c44b8a6/fonttools-4.65.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:673e2b3ac4ac8e4f3607d390ecc5a606e5db5c4e88fb4cb2999593efb65afea2", size = 2584364, upload-time = "2026-09-10T15:35:13.54Z" }, + { url = "https://files.pythonhosted.org/packages/e5/3f/7cfaba467bdd1d3d04be21ba7b5bd75c6ca58ba280e0519707ca96a43c4d/fonttools-4.65.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a03cff943b204a90bf3d1c04c97b9509a8aa0ee99e2e544084ca43ad995975b", size = 5377819, upload-time = "2026-09-10T15:35:15.839Z" }, + { url = "https://files.pythonhosted.org/packages/25/17/a68d9b19a97bb2ee37e8098fea50657073df97c7e5392afbe1b9d7c0c581/fonttools-4.65.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:41f684ee6212e411196ab054f8308faf6605f154950e6f4686fb8f2103d624b0", size = 5341296, upload-time = "2026-09-10T15:35:18.527Z" }, + { url = "https://files.pythonhosted.org/packages/ad/8d/d744653ed607a241339015d4af6743ca3d85a74a2045a02cc06ea0383c71/fonttools-4.65.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:52ea9d2a8385075770db74d5e5718fa80b2222bb4fc62856a377dd2865ca8848", size = 5315310, upload-time = "2026-09-10T15:35:20.853Z" }, + { url = "https://files.pythonhosted.org/packages/f0/c8/1ca6dc69cbaa0e394ff70d9e266777124d3ce3c6433026a6b4de50b890ae/fonttools-4.65.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:d0d25027ade65ec46b13c0436e51bcb7c5171a4ea255a5e7a8d0d1d3ab4cffd7", size = 5463840, upload-time = "2026-09-10T15:35:24.022Z" }, + { url = "https://files.pythonhosted.org/packages/07/97/d374df38a14f2ac04ba9ed96bca89d4988e7d63aa5ed85c54fd8f2badd7d/fonttools-4.65.0-cp315-cp315-win32.whl", hash = "sha256:22cb846d35d278235ef3b7e947c6040b2057d72e8305a314f21d5342eca49040", size = 2433149, upload-time = "2026-09-10T15:35:26.59Z" }, + { url = "https://files.pythonhosted.org/packages/62/c5/eb8f7506faf6a70c5a8f2eccbeea3cd826c748a6fd78c7b4b3effb5a3a11/fonttools-4.65.0-cp315-cp315-win_amd64.whl", hash = "sha256:aecc899fdbf9ecbf728f8977977e2e1043ee4d70c257124c8fa4cbcf796fcd83", size = 2485725, upload-time = "2026-09-10T15:35:28.945Z" }, + { url = "https://files.pythonhosted.org/packages/f1/a4/2df0d97514feb8d857d5de854cd8d660d9a7ee1fd081bc98497124f515a8/fonttools-4.65.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:6275863dad195ee34b6e0ca3fc61c74096bc37e5d6fb8e049f4d68d65865a2b7", size = 3164065, upload-time = "2026-09-10T15:35:31.197Z" }, + { url = "https://files.pythonhosted.org/packages/15/33/e09661c09e6c8a3b0bd50da0e72918df7576dede31f39c948cc245011434/fonttools-4.65.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:d8ffd2f62b402180b0edae8f86a071f583970e2177143117db5cf4c52da60079", size = 2615195, upload-time = "2026-09-10T15:35:33.569Z" }, + { url = "https://files.pythonhosted.org/packages/64/d7/114b05f4193679d0935272220083ec43de7f918b5a777018c5ac5c1ae39e/fonttools-4.65.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:830f91327ca83bfc1278e7060068a498938f84d05dc4869675486f84f55d4fe1", size = 5521239, upload-time = "2026-09-10T15:35:36.291Z" }, + { url = "https://files.pythonhosted.org/packages/ba/10/67d615939f859ffe75663a67bca3593966febbcd0109ec72f20f73cbb4cc/fonttools-4.65.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9db2cb95847c18eef74a4ef0fe257a893ae3f4b0395f4866e2f426ab07f3d804", size = 5343802, upload-time = "2026-09-10T15:35:38.82Z" }, + { url = "https://files.pythonhosted.org/packages/d1/06/faa793a806da03acce862fbed353f76026b28103d43860d69be9a6a1f0fd/fonttools-4.65.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:be9b9a95ed0af03375e99020e921c4bc6b41fad10e053dea7acad370521a3c46", size = 5388482, upload-time = "2026-09-10T15:35:41.616Z" }, + { url = "https://files.pythonhosted.org/packages/53/d2/eb7258df60e634db60c9a8cd72bc9eaf8dea409d1b1ceec3b9fb49531ad2/fonttools-4.65.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:bbd9faf777a9deb6790df4f2b0be611857c45fe86605e840d7154a028d828af7", size = 5435088, upload-time = "2026-09-10T15:35:44.639Z" }, + { url = "https://files.pythonhosted.org/packages/00/6a/58597f16e1265fe9205de3069e338a339e3eef0b1daf049ee08269458091/fonttools-4.65.0-cp315-cp315t-win32.whl", hash = "sha256:c779d838815b91889c95ed64c9be5950ad5a683279f91aeb23384cb757ddc6a3", size = 2464925, upload-time = "2026-09-10T15:35:47.224Z" }, + { url = "https://files.pythonhosted.org/packages/4b/95/122fc172006db747f4968e08c710f52a94f55eb007173b859b3f80b5b810/fonttools-4.65.0-cp315-cp315t-win_amd64.whl", hash = "sha256:d9484b7ee1b49b6b8a0231c849f3983723dec29e3a7366d9b1b02f4036f71944", size = 2513945, upload-time = "2026-09-10T15:35:49.895Z" }, + { url = "https://files.pythonhosted.org/packages/e6/35/f894ceb867118c0261d0f69a9bd516b045a3754238f76c88a49513ac7a83/fonttools-4.65.0-py3-none-any.whl", hash = "sha256:3060b8c1fc2329fa20265b7c138614143ea7c1624e26c5c180c76aeb74deae6f", size = 1196441, upload-time = "2026-09-10T15:35:52.347Z" }, +] + +[[package]] +name = "fonttools" +version = "4.69.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/06/7a/83dd380d74b56a57c3eafce90265035d8727469d05ca4d2942d14367a6c7/fonttools-4.69.1.tar.gz", hash = "sha256:d09a2ea8ed4c71ac52e789ba9313da3e26cee3f812400d7e8a8b3a38d0f98dfe", size = 3958958, upload-time = "2026-11-25T17:04:21.285Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d3/32/d07b479e0180a5da8a1478fa1cc1042bda04c6afe489ee400161f552e2c3/fonttools-4.69.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1b7a214d39cd38e9904c4302ef3f3987c72c1a36577d91c04efa718cb61252b2", size = 3745253, upload-time = "2026-11-25T17:02:12.827Z" }, + { url = "https://files.pythonhosted.org/packages/84/5a/110fe2738174bf5f8dabd5baa50aacba0cf6b85b7d8feda615082e65dd00/fonttools-4.69.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:02f39e7bafb18cdf77aa918501d8176c7abb085cf5caa8c6700daf37f80405a3", size = 3090638, upload-time = "2026-11-25T17:02:15.141Z" }, + { url = "https://files.pythonhosted.org/packages/04/9c/dd8b07ce30419a99edf63b2b360f5352c0960e45671cff427ed0c9428915/fonttools-4.69.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4197b60631b02a633ce99870a61817db1065e4e000f65d2747833acb0da54ea6", size = 6879397, upload-time = "2026-11-25T17:02:17.12Z" }, + { url = "https://files.pythonhosted.org/packages/36/73/2e685084251b7b5724d20a4caddcb4e60b027d0b3a60cec7d78a3bc9f98f/fonttools-4.69.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d1f2c6857c79609d3680efb63f8de06d4604752a8a57f6d684e8651b13d424f5", size = 6789594, upload-time = "2026-11-25T17:02:19.352Z" }, + { url = "https://files.pythonhosted.org/packages/9e/60/80950696191a3a53ce966365b5a8a05e13174d323ad871e166c2b49ae19d/fonttools-4.69.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:deb1a0444dc2b460b946a0be91ce917d814ac82d830677475bb8bec9eaddcf3f", size = 6837481, upload-time = "2026-11-25T17:02:21.297Z" }, + { url = "https://files.pythonhosted.org/packages/b4/43/44f2e470fc0f5eba90758d9a98ee2a5916e94b64803439870686d03bd19b/fonttools-4.69.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fb1d0f41d7b1c1fe5f50586ae72c19d7fc801a58095c45db7eceac50c2d8c5e", size = 7010922, upload-time = "2026-11-25T17:02:23.223Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ee/d5a04dd6361f596d3555699c82988cdd195fa7bc7b9c2c03c6e91f729a23/fonttools-4.69.1-cp311-cp311-win32.whl", hash = "sha256:2c1af38f6865e04303c469db43ede638a75b001103495254e7ad702f1ba43230", size = 1783491, upload-time = "2026-11-25T17:02:25.274Z" }, + { url = "https://files.pythonhosted.org/packages/b4/cc/75327e90a05b203871a602f014cd0bcdebda1636cbbc1f5fe2e0879e7377/fonttools-4.69.1-cp311-cp311-win_amd64.whl", hash = "sha256:0bac72578753c83e902f44be7c881b8b415569da7ce815a192603729ef30eba8", size = 1862650, upload-time = "2026-11-25T17:02:26.845Z" }, + { url = "https://files.pythonhosted.org/packages/0d/1b/092f11671982eb5c9e64a6928df429180240f519bf0a70cc38f199190e86/fonttools-4.69.1-cp311-cp311-win_arm64.whl", hash = "sha256:b0cb2e51c290ef0b9b997746745d518f611887b688eb7b5356b50cf1ed3b98ed", size = 1816267, upload-time = "2026-11-25T17:02:28.514Z" }, + { url = "https://files.pythonhosted.org/packages/34/4c/9cb1be468c036994a719e5c42cb31c0fdc452c99051a3c4e3ce9a23948f8/fonttools-4.69.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:42d8b7c35023553e4adeaab89266fbcf47871675bea53111c93c030e733c3160", size = 3755790, upload-time = "2026-11-25T17:02:31.286Z" }, + { url = "https://files.pythonhosted.org/packages/bc/96/0a894f670237772d17d09a7584b2dc31befd15d134af177b0ea025a9184c/fonttools-4.69.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ddd3fe4dbcfad028944eabf123fa848780180bd5c52381a7b448edbe2d98062e", size = 3094053, upload-time = "2026-11-25T17:02:33.391Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f9/b6c12bc0f666a8c87bafc57c2213e76179a14578e5845e039a7b38e05b8c/fonttools-4.69.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1a5db60afd86a933a755e62bef2dcdd2156ea0d7b5c501ecfaf1fbf29d733b4a", size = 6800900, upload-time = "2026-11-25T17:02:35.607Z" }, + { url = "https://files.pythonhosted.org/packages/ba/5e/f81d7eb69048a5216b28b32f24c85f4ec6d3502cef7e2ebcb968b6a8e1fb/fonttools-4.69.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b5d90b9fac1989a85661c3e4b2a9d482f98b62b7fdc817178f117a26e7329118", size = 6740113, upload-time = "2026-11-25T17:02:37.708Z" }, + { url = "https://files.pythonhosted.org/packages/39/09/15b4b649983519b04ed60d7941342d0e6000c3e480f11fca6503b6cc80fb/fonttools-4.69.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:168b7389527bae9c585277270714a5c733d8b1905287ab686672351379cee2a0", size = 6712560, upload-time = "2026-11-25T17:02:39.485Z" }, + { url = "https://files.pythonhosted.org/packages/9e/60/5ab23ba66101d4afd5861b75d894183eeb309902a141190c6a22c3db85e1/fonttools-4.69.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41130f24b457d09faaa038cb770956146ebef8040b05c17914c97ba0e864be0c", size = 6921767, upload-time = "2026-11-25T17:02:41.273Z" }, + { url = "https://files.pythonhosted.org/packages/75/10/251781c9e490b34bcf03fe26b01e88d39c0c424c6c86672c72b52b146f7d/fonttools-4.69.1-cp312-cp312-win32.whl", hash = "sha256:ad1a471e2bf87980df95671fdf299a2d31aa8a61a44b2e8b577d062de3cd412e", size = 2893390, upload-time = "2026-11-25T17:02:43.217Z" }, + { url = "https://files.pythonhosted.org/packages/37/a4/c64ac8a6259a43b00e1690898d25df897cc6ccdd61b3336c49048ed7e5bc/fonttools-4.69.1-cp312-cp312-win_amd64.whl", hash = "sha256:fc373eed76df520e33cdc37709f0e86c2b519a54faa0e84e7d9f772ce88d063a", size = 2969315, upload-time = "2026-11-25T17:02:45.826Z" }, + { url = "https://files.pythonhosted.org/packages/37/42/7d41bff435615b5e930896913ffd026b78898cf8294985e13a6122539f76/fonttools-4.69.1-cp312-cp312-win_arm64.whl", hash = "sha256:56dae8593a36baead9c3aedf8e4f06a3f0a508dfe12eeaeca47bd4f1fa26e1ba", size = 2923284, upload-time = "2026-11-25T17:02:47.454Z" }, + { url = "https://files.pythonhosted.org/packages/71/66/1724ed27d9e7a3ef3a59706fe94c64bdf207344329f9191248cb910af138/fonttools-4.69.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:c3b749eb66ee30072e35948cdc1b4653eb7dd8bbc155406acfea65e9579a0e1f", size = 3754055, upload-time = "2026-11-25T17:02:49.042Z" }, + { url = "https://files.pythonhosted.org/packages/5d/15/29831762760501240c56e6b61e0de87fb6dfef953daaa86f90e6df7f19da/fonttools-4.69.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:880c714c885d03be2059a1ea514be11f92ee2eb54ab9b641e701a79d72b86348", size = 3094811, upload-time = "2026-11-25T17:02:50.67Z" }, + { url = "https://files.pythonhosted.org/packages/7e/2c/d2f98fa2f01f7001b596d98e869574312de605cf96db6a9aaa5efcd6d13b/fonttools-4.69.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eecfdfc4ebd28fdc8938536516c50ebc241b5520ac4adede6fdd498defe1a829", size = 6762222, upload-time = "2026-11-25T17:02:52.733Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/5f331aaaa041a10e63e7bf171ab7002f2f8ee9c07f3a35f2907193d36e20/fonttools-4.69.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:845682da756e7d04f194778a9bdde667f34ab12da9d51068fbc752043d125150", size = 6700953, upload-time = "2026-11-25T17:02:54.941Z" }, + { url = "https://files.pythonhosted.org/packages/c8/9f/4aadb58b57cc98b670aa1ba7d1254c115e1886167274c35211aed55b4d06/fonttools-4.69.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20df01aebde8c1a7da627f3ece9587d544814c092a4e0beb3e6ec1745f451892", size = 6675476, upload-time = "2026-11-25T17:02:56.617Z" }, + { url = "https://files.pythonhosted.org/packages/db/df/3b7432817644101870086c29d46a14b8ae5c94bc7de351b5fb388f8552d0/fonttools-4.69.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:267dbdc676f388b241899d3b8475264f41cffa6cf41330b46eabe0242363e37d", size = 6880086, upload-time = "2026-11-25T17:02:59.073Z" }, + { url = "https://files.pythonhosted.org/packages/ea/33/5721727271d8b8c4c14748653964c421d4e97ee98e83c8b08a55c30f304b/fonttools-4.69.1-cp313-cp313-win32.whl", hash = "sha256:2a77c569b5556ac9222bbec70330bf647f5d63279d70fc6a5b21dd13e36600db", size = 2891622, upload-time = "2026-11-25T17:03:00.932Z" }, + { url = "https://files.pythonhosted.org/packages/4e/ea/c23aa74379403076715fe3ba0b30528b0eed177c8003ad92c98fd881cafe/fonttools-4.69.1-cp313-cp313-win_amd64.whl", hash = "sha256:a1dedfe496cf57d0ff5f3874aaa87f618a61062e39d9cb6a8b809b87a8fe2ee9", size = 2966198, upload-time = "2026-11-25T17:03:02.559Z" }, + { url = "https://files.pythonhosted.org/packages/2b/e0/bc81080adbb5a9494cd5600406134b324e94f64506e41bab4b079e418ccc/fonttools-4.69.1-cp313-cp313-win_arm64.whl", hash = "sha256:6186fc88e6d2a899bf5dfc4a9f959beb4d19e6e8e1b0d64617909706851a03c9", size = 2920187, upload-time = "2026-11-25T17:03:04.662Z" }, + { url = "https://files.pythonhosted.org/packages/6f/dd/b08f1c88bd171d113220502036ed36c0ecdbc4a137aa15893fe2d5363403/fonttools-4.69.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:10a0effa186298c2ad6f5e743d85387b7ccee3692d57c5c8a33258177f07fb8e", size = 3757431, upload-time = "2026-11-25T17:03:06.863Z" }, + { url = "https://files.pythonhosted.org/packages/10/f0/731ea65fabf2c663f254e661321f0d68302597386b3fec7b8e81b76148a0/fonttools-4.69.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a939ef8b4bf65cbb8e7de316700e4dd0d4151c6a18882599a6f13b5c7b071c63", size = 3095750, upload-time = "2026-11-25T17:03:09.29Z" }, + { url = "https://files.pythonhosted.org/packages/4a/36/09ce1d45f49b0ab691c7b29ba7e6fc95fb23f774ab5926cff12d823cac1e/fonttools-4.69.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bdb61f68ab0eec23c7bfd8b21ada1f81a65f0bcb82a7140b3f5b63a293265b2f", size = 6744292, upload-time = "2026-11-25T17:03:11.382Z" }, + { url = "https://files.pythonhosted.org/packages/1b/d2/c1833090bc2598fd907bd30ead74d40460542232e4962a416590880262ca/fonttools-4.69.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b8049f31d648732458a4b1c7b2e68b5ce90c7f033961990bf3dbfecfe688343c", size = 6634523, upload-time = "2026-11-25T17:03:13.253Z" }, + { url = "https://files.pythonhosted.org/packages/e3/28/db59c21bd2d322e7f3e199ac8a8aca0e86234393e3f8e8530379edbc29e0/fonttools-4.69.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:6e57b734b6e53b04995a202bc85bd6b1055c83f501e17abca61ce9ef1b4e9d37", size = 6665393, upload-time = "2026-11-25T17:03:15.301Z" }, + { url = "https://files.pythonhosted.org/packages/9e/b5/01e95164bff8e7c8cbf56d9eb1445f5c35fd8a67caa812b417530b33a343/fonttools-4.69.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:62f4c1a2162fb29c615c4eca17de5afda4069baa34ad7ecf679ce0da07cba672", size = 6831805, upload-time = "2026-11-25T17:03:17.127Z" }, + { url = "https://files.pythonhosted.org/packages/fb/54/4c8fe90c9816ef73d9dc9c99632df119fcf669a8a522f219d60e2d8af9ec/fonttools-4.69.1-cp314-cp314-win32.whl", hash = "sha256:ef194c7d1be37b12201b427e6efb58bcb9479c1d1086acd67fccfda5c7a2f05d", size = 2895216, upload-time = "2026-11-25T17:03:19.045Z" }, + { url = "https://files.pythonhosted.org/packages/18/63/0057e999a328987a9be98418d2c9e8dbffafe79bd3237976b59dab60e046/fonttools-4.69.1-cp314-cp314-win_amd64.whl", hash = "sha256:84f2d9610b216bd13d2b9a2a26f0e7d31791f4564a7d5a8bc3048919ec2b678a", size = 2974412, upload-time = "2026-11-25T17:03:20.754Z" }, + { url = "https://files.pythonhosted.org/packages/d2/4e/411b2194a06567b2fa310bbe03f89b7af704f5fafd7ae8c3a935c58e5689/fonttools-4.69.1-cp314-cp314-win_arm64.whl", hash = "sha256:702578c858ee25a1ddd9b95411a7ce0cf134263e06e230a553ab2b56b96862aa", size = 2930529, upload-time = "2026-11-25T17:03:22.692Z" }, + { url = "https://files.pythonhosted.org/packages/30/ce/7fb0561998b2bef8badf72e3f5459e7a7e16566fc8a5547f185fd7120d03/fonttools-4.69.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4b2b7fb2fb7003adcab018bca2601bdf4597df782fffe8dcdf2ba9188a1662d0", size = 3849762, upload-time = "2026-11-25T17:03:24.401Z" }, + { url = "https://files.pythonhosted.org/packages/fe/53/30c2213768900a6d20b2a8cdc15ced8d457d1dfde481d2af5ab36a716536/fonttools-4.69.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0c5bd43871a8b763ed7c3e19320e7293cb758bf0cc3f38dfa9621e45be415f07", size = 3136935, upload-time = "2026-11-25T17:03:26.469Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f9/bc377ed14c0c82edbb80f0ecb85b257061eae129585eb174a9d8309aaa0d/fonttools-4.69.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:16360f39bff8f5180ff6fc5b1db069aeb5a5ad34f310e65703a37051974bd92e", size = 6981290, upload-time = "2026-11-25T17:03:28.907Z" }, + { url = "https://files.pythonhosted.org/packages/40/58/161cf90de31188a5abfbf965555e2f3aae6c1077224672cbbe33188755ef/fonttools-4.69.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2dbfc4666c94f45c573c9b55b17dca57173e3d872041bf10eed03ae719a6d134", size = 6711627, upload-time = "2026-11-25T17:03:31.044Z" }, + { url = "https://files.pythonhosted.org/packages/8e/25/1a53cd77809f0ae93b674060429fce7a8acf405062ac4bc2ee3e55d19233/fonttools-4.69.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fd54bec546f8aefa27433ede1fa351aa1d659010afba77a4051636ea3ffdb384", size = 6814046, upload-time = "2026-11-25T17:03:32.911Z" }, + { url = "https://files.pythonhosted.org/packages/f5/92/85493c245f12eeed5fe89de95f277e127fc9c28ed5105607fe88e549b321/fonttools-4.69.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3c1f2c17f7b6f87abcbb89cb200386bbb48bd106483ad4250e669f5022b2460c", size = 6855360, upload-time = "2026-11-25T17:03:34.815Z" }, + { url = "https://files.pythonhosted.org/packages/6f/97/741402faf4baf87ce8f3bd2f2b21706e81a8b0ab9e8ffe5fa1b3b8c77fc7/fonttools-4.69.1-cp314-cp314t-win32.whl", hash = "sha256:67e94b0be5657a62ee5f96fe9eaca69eaac9e7d671574fb5fcb6f6ac3facd35f", size = 2939262, upload-time = "2026-11-25T17:03:36.811Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7b/92b3f920ca567f80812efe9148f5f777f13d070dd574b5a8eb9eb003bf59/fonttools-4.69.1-cp314-cp314t-win_amd64.whl", hash = "sha256:16547febc419641e57d3630c9027db42d1d4d87870c9398d6195a643171b79f6", size = 3015069, upload-time = "2026-11-25T17:03:38.933Z" }, + { url = "https://files.pythonhosted.org/packages/36/5e/223b6d058881bf638bc79cc7e81d3dfcb8b51b72ba638ac75b6023b40dec/fonttools-4.69.1-cp314-cp314t-win_arm64.whl", hash = "sha256:1cc82d3dc7bbd22f5413f5f106d9bfce90e77d9eca0ae5a73d8f5bdb91476efd", size = 2962010, upload-time = "2026-11-25T17:03:41.014Z" }, + { url = "https://files.pythonhosted.org/packages/a2/6d/93278d29716c2217bc72ff7b6ff9614c9ff73a28eb8f2bebedbe935c9bff/fonttools-4.69.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:ce2489d42524fecd5880eaf33a845099dfa31cf255a3b409bb0e0fbe24503b38", size = 3750982, upload-time = "2026-11-25T17:03:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/60/22/dc6d71b97686b0fae3b5cfddd00230ea721b9c52030719cfe73cad6ab8fd/fonttools-4.69.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:de09446b2cc483b04b86230f3e1d3733f044372c438a6561b523c128a9939c20", size = 3094103, upload-time = "2026-11-25T17:03:44.634Z" }, + { url = "https://files.pythonhosted.org/packages/c3/8a/e33cff6ebbeb44f8347968c454eede89f00ffd4a6255629ab46fd03d36d9/fonttools-4.69.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:44d291b5ad3b142d3a10d39b9acb04da1e9e20bcc3732c543f15fd37fd8b413c", size = 6737607, upload-time = "2026-11-25T17:03:46.335Z" }, + { url = "https://files.pythonhosted.org/packages/85/08/22ed1792d74d93df1f31d16a9fc7107a99e6737f1ec90417e90acfe7b62d/fonttools-4.69.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f3e90a720ea5dcfb26fe604aba49250a174620b3fc08d7c0350e6fa999e7d5df", size = 6650409, upload-time = "2026-11-25T17:03:48.654Z" }, + { url = "https://files.pythonhosted.org/packages/1d/52/089e5ee950e1d2617aab007fd16ef8bd849b9cc4d26c3927fe9d22592733/fonttools-4.69.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:aefc016b617d7e860aeb139656d31382fd5239a8ac714780cdabd1f0a8ca6d96", size = 6654229, upload-time = "2026-11-25T17:03:51.162Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d9/4e4ba7bda40a194d4c7d499a8c624fbc2ace6ed0d4d3a77276d76a336858/fonttools-4.69.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1761f85fb01fbea8fee9f7d1addbcef4b4ea145941a7a371f475a62e8aa96cdc", size = 6839720, upload-time = "2026-11-25T17:03:53.044Z" }, + { url = "https://files.pythonhosted.org/packages/85/b1/4d2ed1ebb2ca4f92975124273af0f30e0c2cd6315b2f2cd62407de624347/fonttools-4.69.1-cp315-cp315-win32.whl", hash = "sha256:ae2e9c0d727b2d0a5f8a02318107d49bb7169687f47c123eaaa665d61b5e45e5", size = 2893142, upload-time = "2026-11-25T17:03:55.257Z" }, + { url = "https://files.pythonhosted.org/packages/4e/a6/ec05ec4ca564b56d2b5c12a0cad6d3a3a71795744d342bca26db13caeb86/fonttools-4.69.1-cp315-cp315-win_amd64.whl", hash = "sha256:bd0ab3278a88b8da248086236e4babc8b8b7e5a2293b47d2042323d60d7890da", size = 2972955, upload-time = "2026-11-25T17:03:57.429Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ad/5bbe03a6af7d47b34635dfe6e050e544fc5e61154f739e5c34646c6bdcbb/fonttools-4.69.1-cp315-cp315-win_arm64.whl", hash = "sha256:634d7302bd50476e9d4b880db62e4a97d93a1ff516b37ade75bd12d0284af50a", size = 2928918, upload-time = "2026-11-25T17:03:59.146Z" }, + { url = "https://files.pythonhosted.org/packages/61/a6/a698ccf1c6d9487ce1613c6cbe17d34bb31dbc3e9ba824e32eacc109c5b9/fonttools-4.69.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:017ef6361db599dd1f16c6508cc929607d690abdb66824997582819a21457b9d", size = 3838920, upload-time = "2026-11-25T17:04:01.112Z" }, + { url = "https://files.pythonhosted.org/packages/8b/81/aeedc33cd915c8c00e823a978f9815d298b3ab119f41124c6176099730a9/fonttools-4.69.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:a489f75c71414a4c845a924a61bfdae6196e7847aa33c62f1d517c8670c3d80a", size = 3132679, upload-time = "2026-11-25T17:04:02.884Z" }, + { url = "https://files.pythonhosted.org/packages/98/fb/e96626f8eabb786d67048c3a519c8ec59643f2196bed4a7c98b4122b64a6/fonttools-4.69.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cb69f5a28fc736befee9ee6fc12c23681fcd6fc8b35fe3bde59861adf77dd8d", size = 6945330, upload-time = "2026-11-25T17:04:05.032Z" }, + { url = "https://files.pythonhosted.org/packages/1f/d5/082959f670b96b1553d5d01c8611561cc78a6102d65c1ef05c127ea16ec6/fonttools-4.69.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1de071656a22f564cc1d2a4268120336478948ec361af9d14535fa8cf5a15975", size = 6701668, upload-time = "2026-11-25T17:04:07.153Z" }, + { url = "https://files.pythonhosted.org/packages/ad/1c/c1d718db6265c5b8abbb3dc010d5fd387e4911c5b4258ccfa1f616804e6a/fonttools-4.69.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:ccf9f1afad6f0cf485f23322a100ece3c0bf12bd673d5ce9c007a2a0c766729f", size = 6779664, upload-time = "2026-11-25T17:04:09.207Z" }, + { url = "https://files.pythonhosted.org/packages/39/3c/2f09629983cfd19fbc1365144da6744b0e5b4323781635d638fa18efba96/fonttools-4.69.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:d8867ec31e3e6c35a877317414999243bb9d827fca44c6cc53dcfdffed1ad6d2", size = 6837898, upload-time = "2026-11-25T17:04:11.698Z" }, + { url = "https://files.pythonhosted.org/packages/e7/50/1494495cfd09c02d3c5e008047ea26ae5a3f2b6c5f7e9a03020411d02552/fonttools-4.69.1-cp315-cp315t-win32.whl", hash = "sha256:d8421685945c228b9e43634a017bec8912ee43408aef5cf0d419333e9aab03d5", size = 2936012, upload-time = "2026-11-25T17:04:13.675Z" }, + { url = "https://files.pythonhosted.org/packages/5f/19/69ccf8e483762f8d62778d82b090128f052c1804b35054276dc47985a67c/fonttools-4.69.1-cp315-cp315t-win_amd64.whl", hash = "sha256:922bb6d9c8113f8320d111c1e7d138ce80d32d7aeb290e766a9ff8c3bfb966c1", size = 3009060, upload-time = "2026-11-25T17:04:15.379Z" }, + { url = "https://files.pythonhosted.org/packages/4f/07/8c8da7e679df42213c77dad8c41d6f1ba7b605ad0e27ed88a8ab65aad7fb/fonttools-4.69.1-cp315-cp315t-win_arm64.whl", hash = "sha256:4724852d6b2e613782286f247153f0a77bcb06c2a291b129400de582f208cb4d", size = 2957194, upload-time = "2026-11-25T17:04:17.007Z" }, + { url = "https://files.pythonhosted.org/packages/43/ef/3575cacafe63d7d78b639e815bb3637cd0a66c6365efc5aed636a92cdb12/fonttools-4.69.1-py3-none-any.whl", hash = "sha256:20e9dfac71694d9eeae48bb53c877bdf43b914794d69a769940728a1929cc835", size = 1301769, upload-time = "2026-11-25T17:04:19.256Z" }, +] + +[[package]] +name = "freetype-py" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/9c/61ba17f846b922c2d6d101cc886b0e8fb597c109cedfcb39b8c5d2304b54/freetype-py-2.5.1.zip", hash = "sha256:cfe2686a174d0dd3d71a9d8ee9bf6a2c23f5872385cf8ce9f24af83d076e2fbd", size = 851738, upload-time = "2024-08-29T18:32:26.37Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/a8/258dd138ebe60c79cd8cfaa6d021599208a33f0175a5e29b01f60c9ab2c7/freetype_py-2.5.1-py3-none-macosx_10_9_universal2.whl", hash = "sha256:d01ded2557694f06aa0413f3400c0c0b2b5ebcaabeef7aaf3d756be44f51e90b", size = 1747885, upload-time = "2024-08-29T18:32:17.604Z" }, + { url = "https://files.pythonhosted.org/packages/a2/93/280ad06dc944e40789b0a641492321a2792db82edda485369cbc59d14366/freetype_py-2.5.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d2f6b3d68496797da23204b3b9c4e77e67559c80390fc0dc8b3f454ae1cd819", size = 1051055, upload-time = "2024-08-29T18:32:19.153Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/853cad240ec63e21a37a512ee19c896b655ce1772d803a3dd80fccfe63fe/freetype_py-2.5.1-py3-none-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:289b443547e03a4f85302e3ac91376838e0d11636050166662a4f75e3087ed0b", size = 1043856, upload-time = "2024-08-29T18:32:20.565Z" }, + { url = "https://files.pythonhosted.org/packages/93/6f/fcc1789e42b8c6617c3112196d68e87bfe7d957d80812d3c24d639782dcb/freetype_py-2.5.1-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:cd3bfdbb7e1a84818cfbc8025fca3096f4f2afcd5d4641184bf0a3a2e6f97bbf", size = 1108180, upload-time = "2024-08-29T18:32:21.871Z" }, + { url = "https://files.pythonhosted.org/packages/2a/1b/161d3a6244b8a820aef188e4397a750d4a8196316809576d015f26594296/freetype_py-2.5.1-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:3c1aefc4f0d5b7425f014daccc5fdc7c6f914fb7d6a695cc684f1c09cd8c1660", size = 1106792, upload-time = "2024-08-29T18:32:23.134Z" }, + { url = "https://files.pythonhosted.org/packages/93/6e/bd7fbfacca077bc6f34f1a1109800a2c41ab50f4704d3a0507ba41009915/freetype_py-2.5.1-py3-none-win_amd64.whl", hash = "sha256:0b7f8e0342779f65ca13ef8bc103938366fecade23e6bb37cb671c2b8ad7f124", size = 814608, upload-time = "2024-08-29T18:32:24.648Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/77/cd/9be253869fc42e764de7f3dedd6969af7d44ff9c3375214a3442a6f3fc08/fsspec-2026.9.0.tar.gz", hash = "sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe", size = 333545, upload-time = "2026-09-18T17:50:42.825Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", hash = "sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", size = 221738, upload-time = "2026-09-18T17:50:41.341Z" }, +] + +[[package]] +name = "furo" +version = "2025.12.19" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "accessible-pygments" }, + { name = "beautifulsoup4" }, + { name = "pygments" }, + { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, + { name = "sphinx-basic-ng" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ec/20/5f5ad4da6a5a27c80f2ed2ee9aee3f9e36c66e56e21c00fde467b2f8f88f/furo-2025.12.19.tar.gz", hash = "sha256:188d1f942037d8b37cd3985b955839fea62baa1730087dc29d157677c857e2a7", size = 1661473, upload-time = "2025-12-19T17:34:40.889Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/b2/50e9b292b5cac13e9e81272c7171301abc753a60460d21505b606e15cf21/furo-2025.12.19-py3-none-any.whl", hash = "sha256:bb0ead5309f9500130665a26bee87693c41ce4dbdff864dbfb6b0dae4673d24f", size = 339262, upload-time = "2025-12-19T17:34:38.905Z" }, +] + +[[package]] +name = "giant-python" +source = { editable = "." } +dependencies = [ + { name = "bottleneck", version = "1.6.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "bottleneck", version = "1.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "h5py" }, + { name = "joblib" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "opencv-python" }, + { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pandas", version = "3.1.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "scikit-image", version = "0.25.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scikit-image", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "slap2-utils" }, + { name = "tifffile", version = "2025.5.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "tifffile", version = "2026.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "tifffile", version = "2026.11.26", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "torch", version = "2.14.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "torch", version = "2.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "tqdm" }, +] + +[package.dev-dependencies] +dev = [ + { name = "black" }, + { name = "flake8", version = "7.4.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "flake8", version = "7.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "furo" }, + { name = "interrogate" }, + { name = "isort" }, + { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, +] + +[package.metadata] +requires-dist = [ + { name = "bottleneck" }, + { name = "h5py" }, + { name = "joblib" }, + { name = "numpy" }, + { name = "opencv-python" }, + { name = "pandas" }, + { name = "scikit-image" }, + { name = "scipy" }, + { name = "slap2-utils", git = "https://github.com/m-xie/SLAP2_Utils.git?rev=multidatafiles" }, + { name = "tifffile" }, + { name = "torch" }, + { name = "tqdm" }, +] + +[package.metadata.requires-dev] +dev = [ + { name = "black" }, + { name = "flake8" }, + { name = "furo" }, + { name = "interrogate" }, + { name = "isort" }, + { name = "sphinx" }, +] + +[[package]] +name = "google-crc32c" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fa/25/9cb0c1c31c45b893eb8f11ae70b3f4309432d59b5acaebca5dbe791729a4/google_crc32c-1.9.0.tar.gz", hash = "sha256:7b8c84c3d159ab6817fe3f74e6e6cef099c3f95dcec3abc0d8afb1404642efbe", size = 14857, upload-time = "2026-09-24T21:39:32.067Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/7c/e89a13c971bcab4a0464ecc78f8dc162c5c7ec8986a54dd867fc093b2c6f/google_crc32c-1.9.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:e6b529a6a287104ec79d281c411685231200ce954a29c28ab8e5093cb6e130fb", size = 31959, upload-time = "2026-09-24T21:19:00.091Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/510062c2acbdbf602d759b7b0086032c487126106bb25197b9da1ff1047f/google_crc32c-1.9.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:51cb4e23a38ad4f495f35f87c233ca3ea6b9c4559e7ac383cdef786fab0f7977", size = 31801, upload-time = "2026-09-24T21:22:24.222Z" }, + { url = "https://files.pythonhosted.org/packages/9a/c6/53eaa12dc62625f4605760b09854a0814ef6afebdc0e611a38c7b15aa6d1/google_crc32c-1.9.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8535e75dfead304f30e9122b9ea2c0a570dbaa52c176a0a591540c7914c1e46d", size = 37203, upload-time = "2026-09-24T21:38:04.791Z" }, + { url = "https://files.pythonhosted.org/packages/dd/92/770c2713df471df73998f79758739da83e410ef576bfafd05e5e845959ff/google_crc32c-1.9.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:280f3a3e47af0eeba3a3e5aa7d311af77001812b8df80fb8beafcd0b40eaf7f1", size = 35816, upload-time = "2026-09-24T21:38:05.798Z" }, + { url = "https://files.pythonhosted.org/packages/b8/f3/181945217690644aa502220a3ec9bf0d2ef9af930bbfffee555fe5236e2f/google_crc32c-1.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:56610f548f1b35c9568b9d1de30423480f505dae4991556072d5802820ff35c4", size = 35097, upload-time = "2026-09-24T21:39:27.402Z" }, + { url = "https://files.pythonhosted.org/packages/0e/55/a2f07f15e624f0de79359b1a6c1deb59ec5061bd3b38744b3b2849400662/google_crc32c-1.9.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:457d0d9a4718fd52b1494eac5c200ad25beeadbdc91843d550a003910838589f", size = 31958, upload-time = "2026-09-24T21:19:00.994Z" }, + { url = "https://files.pythonhosted.org/packages/f8/b3/923743597b774bbcf12a7c3e00e48d745e15fd616ad7489a40a63fff8f2f/google_crc32c-1.9.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:ccfe40021fd6afe23361175cf7551e3cef5fd34dc1ebe319f14993a83579e0eb", size = 31805, upload-time = "2026-09-24T21:22:25.019Z" }, + { url = "https://files.pythonhosted.org/packages/df/a6/4d0352fe889663e0d81cea7fc664ec9158727384de4a44ab10e9967a7682/google_crc32c-1.9.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fbef61a3794e011c65fb4396a196cf123a7f474fe5a443db8e5dd7d751b9e6d4", size = 38119, upload-time = "2026-09-24T21:38:06.634Z" }, + { url = "https://files.pythonhosted.org/packages/aa/e3/26685384e4b66ff0928d9566ef6110a7df76029175a1842329d7e3515f10/google_crc32c-1.9.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:86764b99e7a607830d93cb5b75e0ec3ff6cb06d3c274624418473cee701900d4", size = 36677, upload-time = "2026-09-24T21:38:08.082Z" }, + { url = "https://files.pythonhosted.org/packages/cb/ce/4e90102e84880e97d3cf935f2672ecd29191bdeacf57f01740f92debda00/google_crc32c-1.9.0-cp311-cp311-win_amd64.whl", hash = "sha256:43a2dc26f9be213fbe0b4fc4a1088c5d45cbfcb3247420ccc820f0fc3edeea86", size = 35096, upload-time = "2026-09-24T21:39:28.201Z" }, + { url = "https://files.pythonhosted.org/packages/e4/5d/0730e1b3a14d054d1466f2fec88dadf978509c749a3d96d8b069cc56d38a/google_crc32c-1.9.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:53fdafef58e230d0c946ab5f8446d123d9f548230a73b29c8b41c9546f268bc1", size = 31961, upload-time = "2026-09-24T21:19:01.724Z" }, + { url = "https://files.pythonhosted.org/packages/dd/32/d085abaf2fd907121975b92245bb3480fb8be40c37d03f9d6c41857f84c3/google_crc32c-1.9.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:8b91f41645b15a720357183fa5716682ada441873e3c462c15f9714be36f146b", size = 31804, upload-time = "2026-09-24T21:22:25.81Z" }, + { url = "https://files.pythonhosted.org/packages/94/78/dd1935432337e5da7af391a6fc9f161c1c8e9b9002a402b9190135fe1b59/google_crc32c-1.9.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:16865b477d7941712cb0e0aad8ad4815e984fb5fc16d3fdaef7d986e26e53c95", size = 37775, upload-time = "2026-09-24T21:38:09.249Z" }, + { url = "https://files.pythonhosted.org/packages/9e/43/9db03635bb10188d93dcbab9baa2a8670a0da4e868b4370cdbd98d65fed8/google_crc32c-1.9.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3abb18297d9ef0ab120531838be0e6d68c9fa876570e11c229c48f2edac23ce7", size = 36347, upload-time = "2026-09-24T21:38:10.141Z" }, + { url = "https://files.pythonhosted.org/packages/cf/eb/94dee516c846bd9382c3f566d8f8e5fb9e90599e45afeb697f9fc2533528/google_crc32c-1.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:fb63a8d7fa2e95dcff1ca16af2f4d88b526fa5ff72d1696285884ac2d49b6963", size = 35097, upload-time = "2026-09-24T21:39:28.934Z" }, + { url = "https://files.pythonhosted.org/packages/3f/34/cb484e8b6174f130f8c6dc79c733a9dd8869b410ad6511fb6104c46b973a/google_crc32c-1.9.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:f1dc17d987ddcc5eba12a7ce48f0eb93141dea236b170c1101151396edf2f0cf", size = 31960, upload-time = "2026-09-24T21:19:02.454Z" }, + { url = "https://files.pythonhosted.org/packages/af/25/3e8e567bd48448e225ea27318ccf2b94e05124e7b8b97b13eaec9e127199/google_crc32c-1.9.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:f894a2877650b56201d26a012a257b76d54a68834dc3913a93830ca8a047b075", size = 31803, upload-time = "2026-09-24T21:22:27.008Z" }, + { url = "https://files.pythonhosted.org/packages/f0/18/bee0dd59ae622482dc6463636c79e4bde7c954d061c859c9256362c9931a/google_crc32c-1.9.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:4488f1553a9ab7e86cdedc833374a7e904031803b995dc0bd0be48c271fa6556", size = 37776, upload-time = "2026-09-24T21:38:11.056Z" }, + { url = "https://files.pythonhosted.org/packages/fd/b6/e76e80fed5f2558273c7839e622f98095c9b36c719c7147e38e3c055cb70/google_crc32c-1.9.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0568b17ed90ac596f29400d99e243fd0cc6276766183def888d1bf8d1dc13827", size = 36350, upload-time = "2026-09-24T21:38:12.138Z" }, + { url = "https://files.pythonhosted.org/packages/87/34/165542bfa99dfef91a76471cc48cce74b8ff4e295722896087ab2b8e8611/google_crc32c-1.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:8583ec21d56b565d68ab2963cc7e21b3b271247c29b04286068255ef65f221bd", size = 35090, upload-time = "2026-09-24T21:39:29.764Z" }, + { url = "https://files.pythonhosted.org/packages/8f/eb/43ea41f4061a1cad87b2b6559c98e960e45bf551fe66f83d833b98aaf0c9/google_crc32c-1.9.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:6a3b2c8a343c570ed8100a7627c20badfd92c6caa2067093a86be45af27f5b1b", size = 31963, upload-time = "2026-09-24T21:19:03.208Z" }, + { url = "https://files.pythonhosted.org/packages/45/d2/a968c0c29ccd2b0c980ff4f9e3f7035cee28c23a1c57541825cc8221858c/google_crc32c-1.9.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:13179f7e3282617923e957b8e54b8f9c3968030f48640a9f47fd7c5c38c4a215", size = 31805, upload-time = "2026-09-24T21:22:27.917Z" }, + { url = "https://files.pythonhosted.org/packages/03/73/388e493d6c3e252e37165d22efe5a1361f872a24425391b999822861b23a/google_crc32c-1.9.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:265233aff33d835f5b909584fe36ab29647b598c271b661a300001099109e53e", size = 37925, upload-time = "2026-09-24T21:38:13.32Z" }, + { url = "https://files.pythonhosted.org/packages/98/36/190d32caa363ef25d685f422ed1bbf93ff1140fb22fd4d90f24cec209977/google_crc32c-1.9.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:dee799544cae42a42b17a88e38b59cf2c271051dc001da2117a8ff240ffa0548", size = 36495, upload-time = "2026-09-24T21:38:14.211Z" }, + { url = "https://files.pythonhosted.org/packages/d3/fd/81cefea6adae7bd92abb23d4567d199f6485a20ec0a305ca5fa04c52b9c5/google_crc32c-1.9.0-cp314-cp314-win_amd64.whl", hash = "sha256:af73200fa9791ccd380f3598235dba8d82b8af0905df045b3dc60b59836e8ddd", size = 35535, upload-time = "2026-09-24T21:39:30.52Z" }, + { url = "https://files.pythonhosted.org/packages/c5/18/19d4f17f3f33f8fdffcb3e1e69219d6f7ec2c359c160867b04dac1d0a64d/google_crc32c-1.9.0-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:e6e8be8a94436079cb5340f6d495d9d7ba30124d8b952703994c739c7c06e236", size = 31977, upload-time = "2026-09-24T21:19:03.976Z" }, + { url = "https://files.pythonhosted.org/packages/81/b4/8010372c4b46f2ee2352dfdb630c397570cd85522a315df024ad2f9459aa/google_crc32c-1.9.0-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:f2b64641bca27497b986b9d87883014035aa904cb4fa333407c6752b3afee9ba", size = 31809, upload-time = "2026-09-24T21:22:29.1Z" }, + { url = "https://files.pythonhosted.org/packages/c5/f8/7e33845d6b90ce1cf37cfabf25cb859277c7d3533ef1b6b1e1ca58581549/google_crc32c-1.9.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f97c3806dcea41c29c04965347b0e12481561b75e0045dc7a4f69d75dec5d9b1", size = 38359, upload-time = "2026-09-24T21:38:14.983Z" }, + { url = "https://files.pythonhosted.org/packages/36/ff/556b2423f449a7515af6b8222a4d7833cbe09ff3e8d2f0b80471f5f6d02e/google_crc32c-1.9.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0abe7e202c25909869c35672ab0f2fe748a7acf276eb78577332a7c38999740f", size = 36858, upload-time = "2026-09-24T21:38:15.799Z" }, + { url = "https://files.pythonhosted.org/packages/40/71/4733f1b7c921d04a2bb9b9916cf66498bf7ad0860a06289413830da83192/google_crc32c-1.9.0-cp315-cp315-win_amd64.whl", hash = "sha256:5695c8b9327e040b2aba12c6659b0acb5995314ef0af0192da66e662e011103b", size = 35534, upload-time = "2026-09-24T21:39:31.337Z" }, +] + +[[package]] +name = "h5py" +version = "3.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/33/acd0ce6863b6c0d7735007df01815403f5589a21ff8c2e1ee2587a38f548/h5py-3.16.0.tar.gz", hash = "sha256:a0dbaad796840ccaa67a4c144a0d0c8080073c34c76d5a6941d6818678ef2738", size = 446526, upload-time = "2026-03-06T13:49:08.07Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3a/6b/231413e58a787a89b316bb0d1777da3c62257e4797e09afd8d17ad3549dc/h5py-3.16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e06f864bedb2c8e7c1358e6c73af48519e317457c444d6f3d332bb4e8fa6d7d9", size = 3724137, upload-time = "2026-03-06T13:47:35.242Z" }, + { url = "https://files.pythonhosted.org/packages/74/f9/557ce3aad0fe8471fb5279bab0fc56ea473858a022c4ce8a0b8f303d64e9/h5py-3.16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ec86d4fffd87a0f4cb3d5796ceb5a50123a2a6d99b43e616e5504e66a953eca3", size = 3090112, upload-time = "2026-03-06T13:47:37.634Z" }, + { url = "https://files.pythonhosted.org/packages/7a/f5/e15b3d0dc8a18e56409a839e6468d6fb589bc5207c917399c2e0706eeb44/h5py-3.16.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:86385ea895508220b8a7e45efa428aeafaa586bd737c7af9ee04661d8d84a10d", size = 4844847, upload-time = "2026-03-06T13:47:39.811Z" }, + { url = "https://files.pythonhosted.org/packages/cb/92/a8851d936547efe30cc0ce5245feac01f3ec6171f7899bc3f775c72030b3/h5py-3.16.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:8975273c2c5921c25700193b408e28d6bdd0111c37468b2d4e25dcec4cd1d84d", size = 5065352, upload-time = "2026-03-06T13:47:41.489Z" }, + { url = "https://files.pythonhosted.org/packages/2b/ae/f2adc5d0ca9626db3277a3d87516e124cbc5d0eea0bd79bc085702d04f2c/h5py-3.16.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:1677ad48b703f44efc9ea0c3ab284527f81bc4f318386aaaebc5fede6bbae56f", size = 4839173, upload-time = "2026-03-06T13:47:43.586Z" }, + { url = "https://files.pythonhosted.org/packages/64/0b/e0c8c69da1d8838da023a50cd3080eae5d475691f7636b35eff20bb6ef20/h5py-3.16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7c4dd4cf5f0a4e36083f73172f6cfc25a5710789269547f132a20975bfe2434c", size = 5076216, upload-time = "2026-03-06T13:47:45.315Z" }, + { url = "https://files.pythonhosted.org/packages/66/35/d88fd6718832133c885004c61ceeeb24dbd6397ef877dbed6b3a64d6a286/h5py-3.16.0-cp310-cp310-win_amd64.whl", hash = "sha256:bdef06507725b455fccba9c16529121a5e1fbf56aa375f7d9713d9e8ff42454d", size = 3183639, upload-time = "2026-03-06T13:47:47.041Z" }, + { url = "https://files.pythonhosted.org/packages/ba/95/a825894f3e45cbac7554c4e97314ce886b233a20033787eda755ca8fecc7/h5py-3.16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:719439d14b83f74eeb080e9650a6c7aa6d0d9ea0ca7f804347b05fac6fbf18af", size = 3721663, upload-time = "2026-03-06T13:47:49.599Z" }, + { url = "https://files.pythonhosted.org/packages/bf/3b/38ff88b347c3e346cda1d3fc1b65a7aa75d40632228d8b8a5d7b58508c24/h5py-3.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c3f0a0e136f2e95dd0b67146abb6668af4f1a69c81ef8651a2d316e8e01de447", size = 3087630, upload-time = "2026-03-06T13:47:51.249Z" }, + { url = "https://files.pythonhosted.org/packages/98/a8/2594cef906aee761601eff842c7dc598bea2b394a3e1c00966832b8eeb7c/h5py-3.16.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:a6fbc5367d4046801f9b7db9191b31895f22f1c6df1f9987d667854cac493538", size = 4823472, upload-time = "2026-03-06T13:47:53.085Z" }, + { url = "https://files.pythonhosted.org/packages/52/a0/c1f604538ff6db22a0690be2dc44ab59178e115f63c917794e529356ab23/h5py-3.16.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:fb1720028d99040792bb2fb31facb8da44a6f29df7697e0b84f0d79aff2e9bd3", size = 5027150, upload-time = "2026-03-06T13:47:55.043Z" }, + { url = "https://files.pythonhosted.org/packages/2e/fd/301739083c2fc4fd89950f9bcfce75d6e14b40b0ca3d40e48a8993d1722c/h5py-3.16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:314b6054fe0b1051c2b0cb2df5cbdab15622fb05e80f202e3b6a5eee0d6fe365", size = 4814544, upload-time = "2026-03-06T13:47:56.893Z" }, + { url = "https://files.pythonhosted.org/packages/4c/42/2193ed41ccee78baba8fcc0cff2c925b8b9ee3793305b23e1f22c20bf4c7/h5py-3.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ffbab2fedd6581f6aa31cf1639ca2cb86e02779de525667892ebf4cc9fd26434", size = 5034013, upload-time = "2026-03-06T13:47:59.01Z" }, + { url = "https://files.pythonhosted.org/packages/f7/20/e6c0ff62ca2ad1a396a34f4380bafccaaf8791ff8fccf3d995a1fc12d417/h5py-3.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:17d1f1630f92ad74494a9a7392ab25982ce2b469fc62da6074c0ce48366a2999", size = 3191673, upload-time = "2026-03-06T13:48:00.626Z" }, + { url = "https://files.pythonhosted.org/packages/f2/48/239cbe352ac4f2b8243a8e620fa1a2034635f633731493a7ff1ed71e8658/h5py-3.16.0-cp311-cp311-win_arm64.whl", hash = "sha256:85b9c49dd58dc44cf70af944784e2c2038b6f799665d0dcbbc812a26e0faa859", size = 2673834, upload-time = "2026-03-06T13:48:02.579Z" }, + { url = "https://files.pythonhosted.org/packages/c8/c0/5d4119dba94093bbafede500d3defd2f5eab7897732998c04b54021e530b/h5py-3.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c5313566f4643121a78503a473f0fb1e6dcc541d5115c44f05e037609c565c4d", size = 3685604, upload-time = "2026-03-06T13:48:04.198Z" }, + { url = "https://files.pythonhosted.org/packages/b0/42/c84efcc1d4caebafb1ecd8be4643f39c85c47a80fe254d92b8b43b1eadaf/h5py-3.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:42b012933a83e1a558c673176676a10ce2fd3759976a0fedee1e672d1e04fc9d", size = 3061940, upload-time = "2026-03-06T13:48:05.783Z" }, + { url = "https://files.pythonhosted.org/packages/89/84/06281c82d4d1686fde1ac6b0f307c50918f1c0151062445ab3b6fa5a921d/h5py-3.16.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:ff24039e2573297787c3063df64b60aab0591980ac898329a08b0320e0cf2527", size = 5198852, upload-time = "2026-03-06T13:48:07.482Z" }, + { url = "https://files.pythonhosted.org/packages/9e/e9/1a19e42cd43cc1365e127db6aae85e1c671da1d9a5d746f4d34a50edb577/h5py-3.16.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:dfc21898ff025f1e8e67e194965a95a8d4754f452f83454538f98f8a3fcb207e", size = 5405250, upload-time = "2026-03-06T13:48:09.628Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8e/9790c1655eabeb85b92b1ecab7d7e62a2069e53baefd58c98f0909c7a948/h5py-3.16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:698dd69291272642ffda44a0ecd6cd3bda5faf9621452d255f57ce91487b9794", size = 5190108, upload-time = "2026-03-06T13:48:11.26Z" }, + { url = "https://files.pythonhosted.org/packages/51/d7/ab693274f1bd7e8c5f9fdd6c7003a88d59bedeaf8752716a55f532924fbb/h5py-3.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2b2c02b0a160faed5fb33f1ba8a264a37ee240b22e049ecc827345d0d9043074", size = 5419216, upload-time = "2026-03-06T13:48:13.322Z" }, + { url = "https://files.pythonhosted.org/packages/03/c1/0976b235cf29ead553e22f2fb6385a8252b533715e00d0ae52ed7b900582/h5py-3.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:96b422019a1c8975c2d5dadcf61d4ba6f01c31f92bbde6e4649607885fe502d6", size = 3182868, upload-time = "2026-03-06T13:48:15.759Z" }, + { url = "https://files.pythonhosted.org/packages/14/d9/866b7e570b39070f92d47b0ff1800f0f8239b6f9e45f02363d7112336c1f/h5py-3.16.0-cp312-cp312-win_arm64.whl", hash = "sha256:39c2838fb1e8d97bcf1755e60ad1f3dd76a7b2a475928dc321672752678b96db", size = 2653286, upload-time = "2026-03-06T13:48:17.279Z" }, + { url = "https://files.pythonhosted.org/packages/0f/9e/6142ebfda0cb6e9349c091eae73c2e01a770b7659255248d637bec54a88b/h5py-3.16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:370a845f432c2c9619db8eed334d1e610c6015796122b0e57aa46312c22617d9", size = 3671808, upload-time = "2026-03-06T13:48:19.737Z" }, + { url = "https://files.pythonhosted.org/packages/b0/65/5e088a45d0f43cd814bc5bec521c051d42005a472e804b1a36c48dada09b/h5py-3.16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:42108e93326c50c2810025aade9eac9d6827524cdccc7d4b75a546e5ab308edb", size = 3045837, upload-time = "2026-03-06T13:48:21.854Z" }, + { url = "https://files.pythonhosted.org/packages/da/1e/6172269e18cc5a484e2913ced33339aad588e02ba407fafd00d369e22ef3/h5py-3.16.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:099f2525c9dcf28de366970a5fb34879aab20491589fa89ce2863a84218bb524", size = 5193860, upload-time = "2026-03-06T13:48:24.071Z" }, + { url = "https://files.pythonhosted.org/packages/bd/98/ef2b6fe2903e377cbe870c3b2800d62552f1e3dbe81ce49e1923c53d1c5c/h5py-3.16.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:9300ad32dea9dfc5171f94d5f6948e159ed93e4701280b0f508773b3f582f402", size = 5400417, upload-time = "2026-03-06T13:48:25.728Z" }, + { url = "https://files.pythonhosted.org/packages/bc/81/5b62d760039eed64348c98129d17061fdfc7839fc9c04eaaad6dee1004e4/h5py-3.16.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:171038f23bccddfc23f344cadabdfc9917ff554db6a0d417180d2747fe4c75a7", size = 5185214, upload-time = "2026-03-06T13:48:27.436Z" }, + { url = "https://files.pythonhosted.org/packages/28/c4/532123bcd9080e250696779c927f2cb906c8bf3447df98f5ceb8dcded539/h5py-3.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e420b539fb6023a259a1b14d4c9f6df8cf50d7268f48e161169987a57b737ff", size = 5414598, upload-time = "2026-03-06T13:48:29.49Z" }, + { url = "https://files.pythonhosted.org/packages/c3/d9/a27997f84341fc0dfcdd1fe4179b6ba6c32a7aa880fdb8c514d4dad6fba3/h5py-3.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:18f2bbcd545e6991412253b98727374c356d67caa920e68dc79eab36bf5fedad", size = 3175509, upload-time = "2026-03-06T13:48:31.131Z" }, + { url = "https://files.pythonhosted.org/packages/a5/23/bb8647521d4fd770c30a76cfc6cb6a2f5495868904054e92f2394c5a78ff/h5py-3.16.0-cp313-cp313-win_arm64.whl", hash = "sha256:656f00e4d903199a1d58df06b711cf3ca632b874b4207b7dbec86185b5c8c7d4", size = 2647362, upload-time = "2026-03-06T13:48:33.411Z" }, + { url = "https://files.pythonhosted.org/packages/48/3c/7fcd9b4c9eed82e91fb15568992561019ae7a829d1f696b2c844355d95dd/h5py-3.16.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9c9d307c0ef862d1cd5714f72ecfafe0a5d7529c44845afa8de9f46e5ba8bd65", size = 3678608, upload-time = "2026-03-06T13:48:35.183Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b7/9366ed44ced9b7ef357ab48c94205280276db9d7f064aa3012a97227e966/h5py-3.16.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8c1eff849cdd53cbc73c214c30ebdb6f1bb8b64790b4b4fc36acdb5e43570210", size = 3054773, upload-time = "2026-03-06T13:48:37.139Z" }, + { url = "https://files.pythonhosted.org/packages/58/a5/4964bc0e91e86340c2bbda83420225b2f770dcf1eb8a39464871ad769436/h5py-3.16.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:e2c04d129f180019e216ee5f9c40b78a418634091c8782e1f723a6ca3658b965", size = 5198886, upload-time = "2026-03-06T13:48:38.879Z" }, + { url = "https://files.pythonhosted.org/packages/f1/16/d905e7f53e661ce2c24686c38048d8e2b750ffc4350009d41c4e6c6c9826/h5py-3.16.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:e4360f15875a532bc7b98196c7592ed4fc92672a57c0a621355961cafb17a6dd", size = 5404883, upload-time = "2026-03-06T13:48:41.324Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f2/58f34cb74af46d39f4cd18ea20909a8514960c5a3e5b92fd06a28161e0a8/h5py-3.16.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:3fae9197390c325e62e0a1aa977f2f62d994aa87aab182abbea85479b791197c", size = 5192039, upload-time = "2026-03-06T13:48:43.117Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ca/934a39c24ce2e2db017268c08da0537c20fa0be7e1549be3e977313fc8f5/h5py-3.16.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:43259303989ac8adacc9986695b31e35dba6fd1e297ff9c6a04b7da5542139cc", size = 5421526, upload-time = "2026-03-06T13:48:44.838Z" }, + { url = "https://files.pythonhosted.org/packages/3e/14/615a450205e1b56d16c6783f5ccd116cde05550faad70ae077c955654a75/h5py-3.16.0-cp314-cp314-win_amd64.whl", hash = "sha256:fa48993a0b799737ba7fd21e2350fa0a60701e58180fae9f2de834bc39a147ab", size = 3183263, upload-time = "2026-03-06T13:48:47.117Z" }, + { url = "https://files.pythonhosted.org/packages/7b/48/a6faef5ed632cae0c65ac6b214a6614a0b510c3183532c521bdb0055e117/h5py-3.16.0-cp314-cp314-win_arm64.whl", hash = "sha256:1897a771a7f40d05c262fc8f37376ec37873218544b70216872876c627640f63", size = 2663450, upload-time = "2026-03-06T13:48:48.707Z" }, + { url = "https://files.pythonhosted.org/packages/5d/32/0c8bb8aedb62c772cf7c1d427c7d1951477e8c2835f872bc0a13d1f85f86/h5py-3.16.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:15922e485844f77c0b9d275396d435db3baa58292a9c2176a386e072e0cf2491", size = 3760693, upload-time = "2026-03-06T13:48:50.453Z" }, + { url = "https://files.pythonhosted.org/packages/1d/1f/fcc5977d32d6387c5c9a694afee716a5e20658ac08b3ff24fdec79fb05f2/h5py-3.16.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:df02dd29bd247f98674634dfe41f89fd7c16ba3d7de8695ec958f58404a4e618", size = 3181305, upload-time = "2026-03-06T13:48:52.221Z" }, + { url = "https://files.pythonhosted.org/packages/f5/a1/af87f64b9f986889884243643621ebbd4ac72472ba8ec8cec891ac8e2ca1/h5py-3.16.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:0f456f556e4e2cebeebd9d66adf8dc321770a42593494a0b6f0af54a7567b242", size = 5074061, upload-time = "2026-03-06T13:48:54.089Z" }, + { url = "https://files.pythonhosted.org/packages/cc/d0/146f5eaff3dc246a9c7f6e5e4f42bd45cc613bce16693bcd4d1f7c958bf5/h5py-3.16.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:3e6cb3387c756de6a9492d601553dffea3fe11b5f22b443aac708c69f3f55e16", size = 5279216, upload-time = "2026-03-06T13:48:56.75Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/12a13424f1e604fc7df9497b73c0356fb78c2fb206abd7465ce47226e8fd/h5py-3.16.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8389e13a1fd745ad2856873e8187fd10268b2d9677877bb667b41aebd771d8b7", size = 5070068, upload-time = "2026-03-06T13:48:59.169Z" }, + { url = "https://files.pythonhosted.org/packages/41/8c/bbe98f813722b4873818a8db3e15aa3e625b59278566905ac439725e8070/h5py-3.16.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:346df559a0f7dcb31cf8e44805319e2ab24b8957c45e7708ce503b2ec79ba725", size = 5300253, upload-time = "2026-03-06T13:49:02.033Z" }, + { url = "https://files.pythonhosted.org/packages/32/9e/87e6705b4d6890e7cecdf876e2a7d3e40654a2ae37482d79a6f1b87f7b92/h5py-3.16.0-cp314-cp314t-win_amd64.whl", hash = "sha256:4c6ab014ab704b4feaa719ae783b86522ed0bf1f82184704ed3c9e4e3228796e", size = 3381671, upload-time = "2026-03-06T13:49:04.351Z" }, + { url = "https://files.pythonhosted.org/packages/96/91/9fad90cfc5f9b2489c7c26ad897157bce82f0e9534a986a221b99760b23b/h5py-3.16.0-cp314-cp314t-win_arm64.whl", hash = "sha256:faca8fb4e4319c09d83337adc80b2ca7d5c5a343c2d6f1b6388f32cfecca13c1", size = 2740706, upload-time = "2026-03-06T13:49:06.347Z" }, +] + +[[package]] +name = "hsluv" +version = "5.0.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/81/af16607fa045724e515579d312577261b436f36f419e7c677e7e88fcc943/hsluv-5.0.4.tar.gz", hash = "sha256:2281f946427a882010042844a38c7bbe9e0d0aaf9d46babe46366ed6f169b72e", size = 543090, upload-time = "2023-09-11T21:46:52.022Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/36/5bddefea3d7adf22a64f9aa9701492f8a9fe6948223f5cf2602c22ec9be7/hsluv-5.0.4-py2.py3-none-any.whl", hash = "sha256:0138bd10038e2ee1b13eecae9a7d49d4ec8c320b1d7eb4f860832c792e3e4567", size = 5252, upload-time = "2023-09-11T21:46:50.407Z" }, +] + +[[package]] +name = "hsluv" +version = "5.0.5" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/c7/6f/139a4b35fa329a855d3a2af2f8e1351b133bca13a3fa2731bbd8a5273f95/hsluv-5.0.5.tar.gz", hash = "sha256:fe9891df52ff78ddc9fc9cdba0fd0de49a4378d41e30a3901a1d716ec0c14163", size = 541586, upload-time = "2026-10-21T23:50:05.347Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/f2/84ae3176b3ccbc26ed470d599499c85170d378bf27bfd2db6aa9eaff7d98/hsluv-5.0.5-py3-none-any.whl", hash = "sha256:ac1caa7837ad0ca94b48a574a19778f2303fce7f4a34ce5eafe751a40ec143db", size = 5656, upload-time = "2026-10-21T23:50:04.005Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "imageio" +version = "2.38.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/81/c8/2b56274457e4fadcfa86bf7c0fb93f19e124ab8f38f4bfa4372423052046/imageio-2.38.0.tar.gz", hash = "sha256:fe1d406862f6bc2930e8ec662d7bc40d4370cb76e3390dcd33819560d2708531", size = 403333, upload-time = "2026-09-28T07:44:08.101Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/4b/87a794e51d150f62a55715c453c9afbf6103fe24afef6db26a929a8480b7/imageio-2.38.0-py3-none-any.whl", hash = "sha256:474ea3a39e36e0e8e02d81d7f10412aaecec7a2825e5fbc4f44cbcd7bb7cebfc", size = 328055, upload-time = "2026-09-28T07:44:06.169Z" }, +] + +[[package]] +name = "imageio" +version = "2.38.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/be/027f866037034c8ccc1791a3df6d630d2e454233f7ba09fbff76ce5aed81/imageio-2.38.2.tar.gz", hash = "sha256:62e338ea5c19a5547521b3b590a8a9ed1177e5d6c3fd1df076029053eacc73ca", size = 404125, upload-time = "2026-11-16T08:43:45.488Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/30/34/7fb055831d4dd5aa9994cc296b61e341f4cd5221c8119b15b0617c721c61/imageio-2.38.2-py3-none-any.whl", hash = "sha256:d71174e7af8369a4f73525c5b1c0d2621eb2827ed3cfd7327560be02ac1b4084", size = 328689, upload-time = "2026-11-16T08:43:43.569Z" }, +] + +[[package]] +name = "imagesize" +version = "2.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fb/5e/513ff06670c84e7b9887c1fdf61b2d42b4f574a831f2f1d2222023049d8a/imagesize-2.0.1.tar.gz", hash = "sha256:b2ba6a4dea487a7ebcd53248d3476aca449d30db12a2dde5e0c5ca9624fd77e5", size = 1883774, upload-time = "2026-08-24T12:35:19.13Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/01/f9/575c8d760eae1fc99651b7cc5efd96ad5379ca4d6b53750b0fb4fe983f34/imagesize-2.0.1-py3-none-any.whl", hash = "sha256:ea0c9a0384df69ed86a943a15cde37d0360b82491b3910dc2215e202e62b5b02", size = 14794, upload-time = "2026-08-24T12:35:12.548Z" }, +] + +[[package]] +name = "importlib-metadata" +version = "9.0.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" }, +] + +[[package]] +name = "importlib-metadata" +version = "10.2.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "lazy-importer" }, + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/91/0ef39e4ef4407de276289a3759977ac3a8cc546f59c55d725750eae3f41b/importlib_metadata-10.2.0.tar.gz", hash = "sha256:9413a2029fd9ca5669d27f1386071bbfe3c7ebca0545692ec975088241fe1d79", size = 72457, upload-time = "2026-11-09T19:09:10.915Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/61/0c0fae37eb561d8fddb788cbae0f227051628d70d67498a8a116c1f547d7/importlib_metadata-10.2.0-py3-none-any.whl", hash = "sha256:c7a4bf1c7479601f6b8e437cfc14f4f77028ba62a8f34ae95cd93d9774dfba51", size = 34109, upload-time = "2026-11-09T19:09:09.942Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "interrogate" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "click" }, + { name = "colorama" }, + { name = "py" }, + { name = "tabulate" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8b/22/74f7fcc96280eea46cf2bcbfa1354ac31de0e60a4be6f7966f12cef20893/interrogate-1.7.0.tar.gz", hash = "sha256:a320d6ec644dfd887cc58247a345054fc4d9f981100c45184470068f4b3719b0", size = 159636, upload-time = "2024-04-07T22:30:46.217Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/c9/6869a1dcf4aaf309b9543ec070be3ec3adebee7c9bec9af8c230494134b9/interrogate-1.7.0-py3-none-any.whl", hash = "sha256:b13ff4dd8403369670e2efe684066de9fcb868ad9d7f2b4095d8112142dc9d12", size = 46982, upload-time = "2024-04-07T22:30:44.277Z" }, +] + +[[package]] +name = "ipython" +version = "8.39.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "exceptiongroup" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl", hash = "sha256:bb3c51c4fa8148ab1dea07a79584d1c854e234ea44aa1283bcb37bc75054651f", size = 831849, upload-time = "2026-03-27T10:02:07.846Z" }, +] + +[[package]] +name = "ipython" +version = "9.19.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/00/7e/26321a87b91702b94b62a8d90acdbff90d7d928e0216457c24a30dc25b86/ipython-9.19.1.tar.gz", hash = "sha256:8d717edbe293adcb1b9fdeaad7ccfb1573f62d91bc10f0ae62604dbf31e6acac", size = 4438506, upload-time = "2026-11-23T09:06:30.123Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/1f/e56e6060d8607af0ef806d026914dd8e9ba77c8abd633eef94ce6d9eb529/ipython-9.19.1-py3-none-any.whl", hash = "sha256:06158707d8bb83f0bb0f03cc358de185dcf2fe99187bbce03e9971c22616a7c5", size = 649865, upload-time = "2026-11-23T09:06:28.274Z" }, +] + +[[package]] +name = "ipython-pygments-lexers" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, +] + +[[package]] +name = "ipywidgets" +version = "8.1.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "comm" }, + { name = "ipython", version = "8.39.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "ipython", version = "9.19.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jupyterlab-widgets" }, + { name = "traitlets" }, + { name = "widgetsnbextension" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c9/7c/6db60eddf38547353b06d57941f5eee22a990640ce30479fd71a810507f2/ipywidgets-8.1.9.tar.gz", hash = "sha256:bcccba38a6ec3253f7a39c943cea5b9ad01999ce071396171adbc51c6a6a8613", size = 117252, upload-time = "2026-08-18T08:54:24.123Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/55/298e9b3b864a198234997e87a1471c1b17d7f3546ace6d18fb5cf1ce24b2/ipywidgets-8.1.9-py3-none-any.whl", hash = "sha256:f2b8cbcaae10252b809fbe4d7470db75c09b769a32cbf816d20e5ca6d3c5a79d", size = 140101, upload-time = "2026-08-18T08:54:22.339Z" }, +] + +[[package]] +name = "isort" +version = "9.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mypy-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/cf/068066b8fdab91cd40bcd63e483137908710a3d25a4d3a01b538be45d9d6/isort-9.0.2.tar.gz", hash = "sha256:d2298980ce44350f11d9d24c8150eaef1883431ec203dddbb4e9b5c3ceb54c70", size = 685196, upload-time = "2026-09-28T19:21:58.07Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/16/02099475d03310b0a209ca4928bb0779fb273b97c8924a94a32c38cc1eeb/isort-9.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b3e81cae981a52f94d5b31a474e1cbb033ea9cc850bc4c922117c0534a1864dd", size = 1070114, upload-time = "2026-09-28T19:20:58.339Z" }, + { url = "https://files.pythonhosted.org/packages/f1/36/60423264e176965fc0002bbb0a0a8b4ac21d4ee32dfef9a490767d5a7eb4/isort-9.0.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cd67d39c3501d7227e8b229476da1d8679c03e0af97bd295876cf7070e5b709", size = 1625659, upload-time = "2026-09-28T19:21:00.076Z" }, + { url = "https://files.pythonhosted.org/packages/20/75/b008785e61ccd53f6964501ef26a65c17ccc1c5ed9676dec6ebd2662cdb1/isort-9.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:288a320e6d52ba2d3447345390c8a8400591e4033ffbe4ce6bc3e50e5b4818e1", size = 1611889, upload-time = "2026-09-28T19:21:01.732Z" }, + { url = "https://files.pythonhosted.org/packages/db/a1/da35cd0cf273d560c844f94e92f2b266e23b416edc8dd6b6db0934543863/isort-9.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:67b12d9504e5bc6359bb3bb4493f36cf1093d15477c61c349f52f7d04209fb5d", size = 872900, upload-time = "2026-09-28T19:21:03.597Z" }, + { url = "https://files.pythonhosted.org/packages/19/e2/73251e82fec4218d278c63be8de6d79de99dc04cd6219746d18502108079/isort-9.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4a54aed1bb731d7cf80ef5dfbae5b960f777cea70523b751ee6049bcb604371", size = 1057035, upload-time = "2026-09-28T19:21:05.383Z" }, + { url = "https://files.pythonhosted.org/packages/d1/04/dfa9686e44bb8e8a41ebbb77fae0b5bd7e3acbdd30c73c0dfef396ab54ca/isort-9.0.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b34a165cd4e25726930ed2eed8cf2fe46fb1a5ebacd9b28eaf566b343a6457ca", size = 1593851, upload-time = "2026-09-28T19:21:07.062Z" }, + { url = "https://files.pythonhosted.org/packages/99/af/347958db3d7705116f7cadb718a37fddb24b52cf854032585cfae340208a/isort-9.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5c929e8ec9d9fb83f034d5f50895503f40c624605f552b97ad090a37e62407ca", size = 1579176, upload-time = "2026-09-28T19:21:08.815Z" }, + { url = "https://files.pythonhosted.org/packages/d8/03/b323bf130ce480bd5ef9c90b874c03f1a10126b583b26b7be2b1dbebd5f3/isort-9.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:5f448510ef0a92fa626a975759d76bdbe3b721c3d615da6d1010cc451de5610d", size = 873698, upload-time = "2026-09-28T19:21:10.34Z" }, + { url = "https://files.pythonhosted.org/packages/41/c3/3cd3e0f66af21e1bf917f50b45d3389de3d9a25661f2e7f74e51c7fb37a8/isort-9.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a05dc63cb6ae2a8e62ec4184153f424b1650593e00a24e6138184c46193891e9", size = 1062138, upload-time = "2026-09-28T19:21:11.782Z" }, + { url = "https://files.pythonhosted.org/packages/ab/36/512c41f0d9f4c2a61d56d383db21d42a9b82b4f768827f7e852139d14123/isort-9.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:af8be0b5cac101202c8255360e5de832ebbb84b2e863dc0f65dbb1a3d63dd40a", size = 1680120, upload-time = "2026-09-28T19:21:13.474Z" }, + { url = "https://files.pythonhosted.org/packages/84/6f/44fa0de7eb71d576d08d0ad3a1d5d401d6cc0c4f908d76159c52b690e6de/isort-9.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3fe693c1e56781de387a6c206306e9e5e560cfeb4acdfd85f0c46122afd48792", size = 1669955, upload-time = "2026-09-28T19:21:15.095Z" }, + { url = "https://files.pythonhosted.org/packages/b1/cc/89e9a499612665321a1f05e3bb1f4ff6f99e170568cff5c0162bd5d82ae6/isort-9.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:f7a9efeb3689c7327a0d637eb4e12691e8d5ab1297caee997b144dc595ccb93f", size = 880360, upload-time = "2026-09-28T19:21:16.534Z" }, + { url = "https://files.pythonhosted.org/packages/99/44/b51a78a2aee3bc14b91d5f071aea2fe35d9acde5f65f0ac5cb77800616a3/isort-9.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f65ff614632ddc3306c40f619717b3b3ca69938ffee21d97110056d52472c79a", size = 1038192, upload-time = "2026-09-28T19:21:18.25Z" }, + { url = "https://files.pythonhosted.org/packages/28/54/0ac6f7cf254c29bde0832dc655b0327d84752c4511f9f56fbd0778251542/isort-9.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e5f11c7ccd5f079ac0431fe52c7b38ea5d9f4e31a1889746de81dac0e7b0a766", size = 1670286, upload-time = "2026-09-28T19:21:19.895Z" }, + { url = "https://files.pythonhosted.org/packages/65/0c/22a3f073415110f95a9fcfd9aaee72144545c66e5fd99a3ed15c8634e8f1/isort-9.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:810561edf6f1f5f3600f02aa709603a4360d5290c5fff2ae4b370090dd1a5445", size = 1660662, upload-time = "2026-09-28T19:21:21.599Z" }, + { url = "https://files.pythonhosted.org/packages/5f/da/c357996945d7fcd653281e2b53cf5f16ec7c540d86bac045581ecff5ed63/isort-9.0.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:e2636222848a48cadbd712280058b5da19fa147c501132e04a486a5bddcc9e28", size = 465149, upload-time = "2026-09-28T19:21:23.392Z" }, + { url = "https://files.pythonhosted.org/packages/99/fc/3f477cb8ac91b116773bd0682d072c0bcf2bcf5d77ee288c1e46a95b0c8a/isort-9.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:71870ac3b1afdf3c259b8404c05076d3ab874122fec6f78339f1c92d2c29b012", size = 884875, upload-time = "2026-09-28T19:21:25.403Z" }, + { url = "https://files.pythonhosted.org/packages/53/25/b0dae3025157f020d9010bc126120e703b50ed74ebfb5ca56be81e064d0c/isort-9.0.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bd8c4fb9829a5e7117d9f71f540ff1e8caafb471e574012057ce6dc35fda2d7b", size = 1039110, upload-time = "2026-09-28T19:21:27.024Z" }, + { url = "https://files.pythonhosted.org/packages/7e/da/f97a4905cf8212c31d584f0222ae8b1deed391e42db910e8e908eb89002e/isort-9.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6eb3e714d64de6eba78ee29051f7fc80613c74e90c6f54f84082f59c429c0a0b", size = 1674555, upload-time = "2026-09-28T19:21:28.645Z" }, + { url = "https://files.pythonhosted.org/packages/90/f4/df11f0de3a2796ef1a74071d1331158b67961770c8066850d60f362ba7cc/isort-9.0.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:bf3ef0a91974f29f406e25eef0e04781fd5c2254b8ab55e7655b20d8cd7c5514", size = 1666034, upload-time = "2026-09-28T19:21:30.35Z" }, + { url = "https://files.pythonhosted.org/packages/15/f0/0007f037135659de11f6ef29563b75c8080eeb51d67f37e82128d66613dc/isort-9.0.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:cd1e0e5e61497e95a4e5be269088e6a1013f530aeccf6ebd6134f403285ecd63", size = 464424, upload-time = "2026-09-28T19:21:31.98Z" }, + { url = "https://files.pythonhosted.org/packages/ae/5c/f64d0cc97abbdf6f7902b0e38171e5101842ba75ac22212fd6d254156bb3/isort-9.0.2-cp314-cp314-win_amd64.whl", hash = "sha256:11da67a30f5a88383c71db075488ca3d081f427f53368f90bb1d74e958a9b040", size = 903922, upload-time = "2026-09-28T19:21:33.412Z" }, + { url = "https://files.pythonhosted.org/packages/14/8a/c0bdd165c6cfcb7c87b3acdee5ebc03e10da5317482017084cdf92a2a076/isort-9.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f7c2fa33e1c9fbcf9fd639997e4550515c0b712b52ed70a059124a5247825480", size = 1106274, upload-time = "2026-09-28T19:21:35.13Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ec/4ab29f699d58baa7c00840bc66328ce8f06be31cd36250aef8d4f71bd24e/isort-9.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:85e859fd72e50c27306d05185f9472ed97fae9e1cce91c0e891260d16f2ecece", size = 1887727, upload-time = "2026-09-28T19:21:37.015Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ec/12f58041288e08c35dc9a719108482c2c599b157ce0913454d57d32c7b5c/isort-9.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2a960e4252ac5b00f78adc0f731529e122657ee642e650896b36e1ff83028023", size = 1905479, upload-time = "2026-09-28T19:21:38.789Z" }, + { url = "https://files.pythonhosted.org/packages/56/ea/69fd476d07e5dddea5b41d6b3adfad4d2f5d251362f2fb594f2cfd0f5308/isort-9.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:91b60ce3d96fcb0730d61fc5ab84ee5b56d676fbb92550f7ea333f58778f2f20", size = 928154, upload-time = "2026-09-28T19:21:40.745Z" }, + { url = "https://files.pythonhosted.org/packages/93/93/ed3f1894ec261381abbdc22a3216fa86ad8fb2ec5f5d1f414f1d56c94ffe/isort-9.0.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:aa810daf72ff5d8ade462b2190dad9c0e16d6d428a3f9aea210f14cca2487d58", size = 1038495, upload-time = "2026-09-28T19:21:42.41Z" }, + { url = "https://files.pythonhosted.org/packages/2c/fd/4a911a73beb68a746a2f827a842f71030c3118a056585400023e37b5c8ec/isort-9.0.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8dde4e2d9cfb35390437353f0861ec41378f91ff958d8cd3051fb95cae59315a", size = 1686028, upload-time = "2026-09-28T19:21:44.107Z" }, + { url = "https://files.pythonhosted.org/packages/7e/3e/6fb9ab0f5a89e174d45ae2809970fcb908f2b261e1b77993101e52a20869/isort-9.0.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:4315e23e701bb1fcdfd364da59da61d78c3332c554318b7eb635ea3924d24c5e", size = 1675313, upload-time = "2026-09-28T19:21:45.6Z" }, + { url = "https://files.pythonhosted.org/packages/74/a2/e73c430847408ae900bf0fb7627daa87e939c80c2f0713fb9a163ec48663/isort-9.0.2-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:1c134ef9d94943eae14bf31c634db1904dd875e6e7280a60baee10ca06132db6", size = 464361, upload-time = "2026-09-28T19:21:47.142Z" }, + { url = "https://files.pythonhosted.org/packages/08/29/236939344dc87499299f36469527fc01a516a51abcf0d82ba5b7644f5966/isort-9.0.2-cp315-cp315-win_amd64.whl", hash = "sha256:d4da51a99dfd00e5c51e507ed91ebad6aafd44dc65135c17e2ef37355cd9fa98", size = 904023, upload-time = "2026-09-28T19:21:48.583Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ec/14dfd5e8e20a1500043d50053d899527c742dcebeaba2fb2633abfad2ec1/isort-9.0.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:16436aefeebe3aa2d5d7ae1ca895b2278f770fc4a41d95c22569a30f7413ec45", size = 1105456, upload-time = "2026-09-28T19:21:50.162Z" }, + { url = "https://files.pythonhosted.org/packages/5a/f7/c0e4d16a17f742b459397be8570af4edce4173e91d64ccf16c1ecd7826d8/isort-9.0.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a36f30b6b85d9726f79c7623d35f3e966d5d7d9d0a005af91ba19988fccd038b", size = 1874501, upload-time = "2026-09-28T19:21:51.786Z" }, + { url = "https://files.pythonhosted.org/packages/c3/98/226855cb96275e7df63167ed8fae3b65e0c94e38c9d63a6a80458da919b1/isort-9.0.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:d03c68e9d0a83b51ed381d04b0919f2d918fb66c1ca1766761157ff44149366f", size = 1890469, upload-time = "2026-09-28T19:21:53.42Z" }, + { url = "https://files.pythonhosted.org/packages/bb/e5/3a1c4748483a05533a065b49dcf64039a68162e84175e08d1d70db7e7413/isort-9.0.2-cp315-cp315t-win_amd64.whl", hash = "sha256:29669ea6c410528ffe3b632a41835757f08282257e4ddac892a5e6d01bd35201", size = 927256, upload-time = "2026-09-28T19:21:55.063Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c9/0849e74b868ef10312eecfc24278710e97dd14bc49c1df629d7df142d318/isort-9.0.2-py3-none-any.whl", hash = "sha256:6c29deeb39698a8717823b7f75b2ac58c5e8ab8dcf6cf31205a72a6617fb454e", size = 105052, upload-time = "2026-09-28T19:21:56.512Z" }, +] + +[[package]] +name = "jedi" +version = "0.20.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "parso" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "jupyterlab-widgets" +version = "3.0.17" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/8b/e739cf9066ad5037a2d4b0a403f06da374fdccb9748221661c8b492d3dbc/jupyterlab_widgets-3.0.17.tar.gz", hash = "sha256:6e61fe21ca8a66039180a5cc52a433e07279d2fee79c8be963e00d55193f17a8", size = 213919, upload-time = "2026-08-18T08:52:17.511Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/ef/6d27fc118f58cb24886da413545a7efb0853d405fddbfd8b2d9ac09fbed4/jupyterlab_widgets-3.0.17-py3-none-any.whl", hash = "sha256:40ac1e9955acf116c4d995d9bfa082d86ad9ec6d91c4f134827cf5e0a5eb75e0", size = 217292, upload-time = "2026-08-18T08:52:15.47Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/54/1b8d2bc580414cc75b3a5b3d195981a6facacd8a8d986e589d0a3b51a709/kiwisolver-1.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:1acc7e5b7ef05e9da8bb70cd6c7c4513090213d2e1ad9720f599f0bf6c52aec5", size = 123362, upload-time = "2026-08-28T10:24:43.402Z" }, + { url = "https://files.pythonhosted.org/packages/57/19/92c30f540dcfff86ff625389427c39b53a9aaea16420ddcc09b2ab8d1073/kiwisolver-1.5.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bad20d4c69c851c982a1e3606f4c293edfd5a87885786c50082412240c4b1ffd", size = 66551, upload-time = "2026-08-28T10:24:44.768Z" }, + { url = "https://files.pythonhosted.org/packages/30/ae/30b94088722e7bce8b821cd5ee935a87f80023e7243125f1accf98e39bf7/kiwisolver-1.5.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0a4faea5c6db201c6a21391d2ac926ea97acf7dacdbc3c417189e1adb1a00837", size = 64076, upload-time = "2026-08-28T10:24:46.184Z" }, + { url = "https://files.pythonhosted.org/packages/f1/0e/9f394d693be549fa3fab62498c2778294595991047adc3dcf10aa99b91c0/kiwisolver-1.5.1-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e05c2f7925f1d88778e53cb44f14e0223204a3bdd09a41664750363acfb1f2ef", size = 1628782, upload-time = "2026-08-28T10:24:47.91Z" }, + { url = "https://files.pythonhosted.org/packages/64/96/26efc04348c0f332b6e6c471dff132bb8b18b2df494a1b65826601674e62/kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c3a4e41e3096bf1f0f1b76e2ffd6d828d6547f574f702d59bdbef7acfa59db9c", size = 1228112, upload-time = "2026-08-28T10:24:49.503Z" }, + { url = "https://files.pythonhosted.org/packages/5a/ac/df9ddc19ec972cd97b60b262dd2c4be28c6192b5a779cad429c6657ee680/kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f1d56ec54d257d05e0b50f5780d967540cd07beeaf9e5f645b26d50cce79f4d8", size = 1246756, upload-time = "2026-08-28T10:24:51.225Z" }, + { url = "https://files.pythonhosted.org/packages/cf/de/c38a246b8a4f4b293c7291aa650917b05c5549b0d532749bc523296e90c4/kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8de6f2a4ce7e7bd27d23dd94abf0ccafe0e0e5cc9c764b0577191f2c25f08f26", size = 1295555, upload-time = "2026-08-28T10:24:52.953Z" }, + { url = "https://files.pythonhosted.org/packages/b6/48/3c95a5232d8b5783050d8c8089b58bf1f57018f9135232d72c5aa6b0c01b/kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:16895f553ee6620a827d2da56b871f835fb70b9216cca5d188e885caf6e3bd23", size = 2179476, upload-time = "2026-08-28T10:24:54.568Z" }, + { url = "https://files.pythonhosted.org/packages/e6/e9/b9e999336afc561b154e93682f597832bdc7446f2ee18b467c5b0e924867/kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:6b92f60017dda7d877fdc546438b5e28f31c523264f49cf5a48c1d0ce1a0dfbc", size = 2275258, upload-time = "2026-08-28T10:24:56.186Z" }, + { url = "https://files.pythonhosted.org/packages/76/cd/c1c550796ada4a59644b8264b425fe332686d2a086c4729fcc640ececdfe/kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:7824b5e8bdbf0bccb4ccd37bbb115849a1dc45437fb4de8351385ed07c437ee0", size = 2443424, upload-time = "2026-08-28T10:24:58.093Z" }, + { url = "https://files.pythonhosted.org/packages/b2/d4/30f641eb8e10f6ad5bb9af8a15ec8eea386162a6ef491e68995b8680ef4e/kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:aa7d00b1700966d2917e54d278aba86897890ca9276dd8b76cf6446b6c181b92", size = 2249457, upload-time = "2026-08-28T10:25:00.223Z" }, + { url = "https://files.pythonhosted.org/packages/1c/d9/211e016f8aa5b5bf496dd3bd7ebab4b73b22d91f025f25e20156a44a77fc/kiwisolver-1.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:96c30002424670b5e1e46495c2b8cbffef39cf77c1d79e76462029d50339785b", size = 70643, upload-time = "2026-08-28T10:25:01.888Z" }, + { url = "https://files.pythonhosted.org/packages/9e/8e/ae7007266dea1fd93fcc48541042c1f6583958055de3b424a59ec16def25/kiwisolver-1.5.1-cp310-cp310-win_arm64.whl", hash = "sha256:f0f4a42db92d6ec7677ab9d12830a2a8ec145a9c6d15db2b593466bc875c78d7", size = 68215, upload-time = "2026-08-28T10:25:03.136Z" }, + { url = "https://files.pythonhosted.org/packages/94/7b/2de6908edc668427c149af5f93112e931f87e1fa4cab80bac32c5844dccc/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6", size = 123364, upload-time = "2026-08-28T10:25:04.359Z" }, + { url = "https://files.pythonhosted.org/packages/8a/24/e70914415c77c97be7e22c80a0740869cb7428768cc380fdcdf6703e7084/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55", size = 66558, upload-time = "2026-08-28T10:25:05.506Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2b/8b08b11833db4d475b8ef1f36174f8d8a7abd31bedd7e794be78e8814b48/kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839", size = 64071, upload-time = "2026-08-28T10:25:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/89/00/05c2d0369ac322d22d5c05f84b5c4a6856fa6207fbae42869108a28f0383/kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720", size = 1438206, upload-time = "2026-08-28T10:25:08.254Z" }, + { url = "https://files.pythonhosted.org/packages/c0/05/c941a139f27438c1910d630fdc3ccfdab7c8407c72052299ead12ece086e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225", size = 1248975, upload-time = "2026-08-28T10:25:10.053Z" }, + { url = "https://files.pythonhosted.org/packages/58/a1/2669ee5512e39b9d4de25faacaedf788c957f93730c5f7c63993ec4f5933/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404", size = 1266301, upload-time = "2026-08-28T10:25:11.754Z" }, + { url = "https://files.pythonhosted.org/packages/28/b8/353f52f2c7f861a9e90cd2e8f90f85b3ad03060835f823e08298d094c463/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6", size = 1319708, upload-time = "2026-08-28T10:25:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/21/0e/14b83200eadc2c1d63b76bac01c1813bf072aecf567429f303e00b70258e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c", size = 971720, upload-time = "2026-08-28T10:25:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/86/91/9d43d84d23b1cbff72a142d387ead1ea03db0cba8ff86ed5335addad3cc9/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052", size = 2200119, upload-time = "2026-08-28T10:25:16.636Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7c/f2bd9616f27ffb5e17cecc0baa5d0bbcee7e55aeddc0ccc871d69e2fc3ee/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7", size = 2295005, upload-time = "2026-08-28T10:25:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/ee671b72bf8f46a08379d4392c65582541759a542428197562f2898294ad/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e", size = 1960982, upload-time = "2026-08-28T10:25:19.893Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f7/0e26b4c05bee3bdb0f048dfa305e4fe701999ea17b51e9c616ef91035bbe/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7", size = 2464918, upload-time = "2026-08-28T10:25:21.65Z" }, + { url = "https://files.pythonhosted.org/packages/ae/62/6eb431133d30ce656ac1e5ff72fac70dd34d54c3984f4011b9ac8bf77d54/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d", size = 2270967, upload-time = "2026-08-28T10:25:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/bf/9f/6f9e489c188200e6fb3193935501894811e8c97577c8ffe9033589bf3521/kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071", size = 70744, upload-time = "2026-08-28T10:25:25.061Z" }, + { url = "https://files.pythonhosted.org/packages/c6/6d/dfc430d1d43957061599adea3f08ea982bb6f4ab601a8c974bedcf2ba850/kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3", size = 68404, upload-time = "2026-08-28T10:25:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/6b/9b/65b302742389c6f96f2956bef5decf26011309feb2fc5d79613af18adea4/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:63fb7294b768f444eb4b068965f2662f28c2fd4161e23bd60fcf3ff27b74c046", size = 123876, upload-time = "2026-08-28T10:25:27.44Z" }, + { url = "https://files.pythonhosted.org/packages/71/74/c21f339956f6f691b2ed7e31d5f3ae767304df6c460192739fc830853051/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ebdef3eae5336568147c39a55be6a2036ffde53faa9ca2d978989ae7c2da12c", size = 66487, upload-time = "2026-08-28T10:25:28.728Z" }, + { url = "https://files.pythonhosted.org/packages/84/e5/bdb34e21523e01dceda064d63713f3bdec91388af24fba1eca7ea5e85864/kiwisolver-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1798e83840c3f627246104c4d8a9639c60fa068adf9ce92b61791781fa8a68c1", size = 64660, upload-time = "2026-08-28T10:25:30.071Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" }, + { url = "https://files.pythonhosted.org/packages/6f/35/09c58daac34e6f6ea5c6dee0094b422118e5a7c265586008a95fd135ac5f/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002", size = 1278499, upload-time = "2026-08-28T10:25:33.375Z" }, + { url = "https://files.pythonhosted.org/packages/19/32/739765e24fbad29d13f83e546ea4abc215a78cea9d677ca09025b027724d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048", size = 1296677, upload-time = "2026-08-28T10:25:35.059Z" }, + { url = "https://files.pythonhosted.org/packages/df/32/03304d1010e2cc45e5b3b52cef7e43fed3a2a5cd6c87a89b4a88e1d85b5d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7", size = 1346037, upload-time = "2026-08-28T10:25:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/3e/57/4c49377bfd274450dd72ecaa13eaac32ea804a03363e4d1db0c5aa999ceb/kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083", size = 988248, upload-time = "2026-08-28T10:25:38.299Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c3/38df144a08b6c5d75ca4504e5cc3141bb3bfef64c04f4ef48204f42711b6/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148", size = 2228722, upload-time = "2026-08-28T10:25:40.038Z" }, + { url = "https://files.pythonhosted.org/packages/e7/11/3221838a89cd64d9b386353e000cd8a296069a20fbe3584507fdfd5bebae/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c", size = 2325216, upload-time = "2026-08-28T10:25:41.699Z" }, + { url = "https://files.pythonhosted.org/packages/83/d4/075c219230697bb5db910d37262b9bacf880f92b4811a02ab81ed073a253/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858", size = 1977689, upload-time = "2026-08-28T10:25:43.559Z" }, + { url = "https://files.pythonhosted.org/packages/bb/08/1d219c3c2dd960983d0d4da623d916e9de6385df2b0bab3d1af0e9b8fccc/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6", size = 2491443, upload-time = "2026-08-28T10:25:45.242Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" }, + { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" }, + { url = "https://files.pythonhosted.org/packages/94/61/ef0daa157c8bb23672f7423e0d14c39db1dc6ef8ed47e6bc54c9c1bef3bf/kiwisolver-1.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:ad8b9671348d7c8716715652ae11f85ed0eb99e265a2df2ca490577d69860b2c", size = 68324, upload-time = "2026-08-28T10:25:49.81Z" }, + { url = "https://files.pythonhosted.org/packages/08/c1/88018321d976f53c421e379c43bc6993e70ce0c8a3ec5edc4bfe102257f6/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b6ae6a0328f0bc035741820fdeecdcd67bf4694eee03972e843663107122f450", size = 62272, upload-time = "2026-08-28T10:25:51.02Z" }, + { url = "https://files.pythonhosted.org/packages/85/d2/712bc17ea4f1d216034928069d612defbc6c95a471c55a7203a39faecb1a/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:886fc26012f0e8b5f69d1cfe6d711f6b11f194621539bf8e6bb1c25c5dc82724", size = 64481, upload-time = "2026-08-28T10:25:52.22Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e6/6c5380d676f43b6d918033962ea5e72360ca69e5a404154bc496b598ffdb/kiwisolver-1.5.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aefe930d113798330e9462f7874542977869c0613cba3262e2de3a8d5dee8f3a", size = 66260, upload-time = "2026-08-28T10:25:53.387Z" }, + { url = "https://files.pythonhosted.org/packages/92/6a/7087f5822cc8bb272679641404b1966a42504dac9ee74e2b33840475a0aa/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a5ca5aebae78a0bc13c1943af4af615d4966c5b650b05d5aa83b50e427196fee", size = 123876, upload-time = "2026-08-28T10:25:54.644Z" }, + { url = "https://files.pythonhosted.org/packages/5c/4b/9f385087ca09ee5ab9c09c6832561a7d2f7c78d3e5661d511e669f70e439/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ed0f5e49d0ceff8b72190824d9e59c062fbbc02c231b853112c78474b3f5ec2", size = 66487, upload-time = "2026-08-28T10:25:55.899Z" }, + { url = "https://files.pythonhosted.org/packages/47/8b/40d33ffd2f378094ed462e9a9a0907e59d4de9845e65a59561272da350d4/kiwisolver-1.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:77a4c8187a5948d7f8795adb765a3c7b553d07d86d88e43038fc32fc1fb9a3f3", size = 64673, upload-time = "2026-08-28T10:25:57.048Z" }, + { url = "https://files.pythonhosted.org/packages/ab/43/86aacc027959108b4c66eeae8b73cedb057dfa6eb3a335d05ad65197081c/kiwisolver-1.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:74ad5c3dad54a4641b4c28cd15ded70899d04459c6c7aeacafea716be97cce6d", size = 1477992, upload-time = "2026-08-28T10:25:58.479Z" }, + { url = "https://files.pythonhosted.org/packages/ed/40/b1d0369048c79733a32c8abb0f2718532e6630641368e33a81384246e844/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e46b23a2da695c364124817bc01d970effd5483147f8d66a6a7167e3f6b851", size = 1278821, upload-time = "2026-08-28T10:26:00.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/a1/fa71c1792272ff9461432715ae60ffb7e11a4d7ac3bf68961b9cab6c60cf/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:75d9b1cf8258462dbdc1eeda718c96ea7f079324c09067f6daabfcf37712b7fe", size = 1296805, upload-time = "2026-08-28T10:26:01.868Z" }, + { url = "https://files.pythonhosted.org/packages/a3/49/3f0bd94af8e06ecc47eb834b195a06f05d48711ceb2352c56d6835160f0e/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fca690b00c4c48f6c2a547b0160ed511357093a4e4c9b47e0fadf3128066d89", size = 1346109, upload-time = "2026-08-28T10:26:03.59Z" }, + { url = "https://files.pythonhosted.org/packages/a4/44/3afe6ef9cf06d61220953a8963e94eca978491be1d9547cb01d82a1efa08/kiwisolver-1.5.1-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:876bbfd276473d3daffe30e8c975df4ed9429967b41a6cb362dbb5155b6f13ad", size = 988252, upload-time = "2026-08-28T10:26:05.306Z" }, + { url = "https://files.pythonhosted.org/packages/e4/30/a12bd7a7285a211e1747c3eec77b8c614dbfcc1dad942f7611a1a6921ae5/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f942903fde7363d1d879057ec5de01310efda2597161784d752fa9953a01a71a", size = 2228846, upload-time = "2026-08-28T10:26:07.312Z" }, + { url = "https://files.pythonhosted.org/packages/a1/6b/233e2958abf0dab7b18d07e52f286e02e519d7651bfbbe97af9347564109/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c90d3022d8a94778939cda8638c6c8da8fa757b8958dad7ec868ce29c87681b8", size = 2325583, upload-time = "2026-08-28T10:26:09.093Z" }, + { url = "https://files.pythonhosted.org/packages/42/8e/7673060a27b01405b580058510adef34687069d229800239f5e44682d4d0/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8a34616dc2521cc8dc1d7d081734da63539f021ac0450ce950908340c6e7aa2f", size = 1978221, upload-time = "2026-08-28T10:26:11.127Z" }, + { url = "https://files.pythonhosted.org/packages/3f/7b/1b882fc1a8b4a0bb8084e7d1d85004116d08c92c0705d31f2928dec607f2/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:8bf4df63592c2a66b4f8edc5df2544998c288aa02f96ce0acd880cd1de8c8127", size = 2491819, upload-time = "2026-08-28T10:26:13.348Z" }, + { url = "https://files.pythonhosted.org/packages/39/9c/426deb49e62c5f69464b64bbeca064d3b758a7506b8913d986ef34f4619c/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d09037ca068d784ebc4aec290ef952ca27ac15dd9c0b5801a88c6e1096b83e6b", size = 2295520, upload-time = "2026-08-28T10:26:15.042Z" }, + { url = "https://files.pythonhosted.org/packages/f5/22/deabbb3ad6d918d74b7831b2d8ae7151b09d21c87974e5ee8a456f58c94c/kiwisolver-1.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:dc23390afe9f4ef9ac3bcc72a03a56eebbde03f4c571a32cb38f859cff9a6524", size = 70758, upload-time = "2026-08-28T10:26:16.504Z" }, + { url = "https://files.pythonhosted.org/packages/b9/71/02fa5c2fd92068bb8952847e70ee6c5cb280e7febe11653d17812acc53dd/kiwisolver-1.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:186884a58486651e3c217b6acea0a53eaa9498fdd472057c46f2f0fb5c25aad5", size = 68329, upload-time = "2026-08-28T10:26:17.658Z" }, + { url = "https://files.pythonhosted.org/packages/dd/87/2d5dfad0daf17dcc18d98c48ed2332fc3f051cf599e60be6182a30dd4cf1/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0324cd2567259b7a095f6cf18a52b0ffc6f3de9e69528ff1bc0e7a37bd43ff1a", size = 62337, upload-time = "2026-08-28T10:26:18.778Z" }, + { url = "https://files.pythonhosted.org/packages/08/c8/83e1624f15d6262b470dbcc80b09979fd4d5b2ea3ddfc6b6e3327e235726/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:74ea337e0ec3f6f342a36a4f1b5cd94dd9affddcd28ba9aae2905af932ee8c6b", size = 64513, upload-time = "2026-08-28T10:26:19.909Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2d/827ec30eb07f528c08d8459ffb318ae91a56d793ee8acbea8b491f0ff906/kiwisolver-1.5.1-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ee9df1f0d77b9c6e94f4ac0fec533fbddd5ea3a327807f18d7b069ae019ded80", size = 66287, upload-time = "2026-08-28T10:26:21.078Z" }, + { url = "https://files.pythonhosted.org/packages/53/11/5c43a562529dad8def4b81e5e1877c612a7e0298105a5939b3b409d2079c/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fc271a6f0a2126958f4090e5507b9da5848927dae331f8f763bd4aa642b3d2cd", size = 123940, upload-time = "2026-08-28T10:26:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/64/db/9bd6c505c95128c258a55236bfbb3a7a3fb6023f863316b6d7d9f3c69052/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9b3092d8992a1d69b7a59c3e39f35e1b9be327a17f68a7c35fc17329e337d6f2", size = 66493, upload-time = "2026-08-28T10:26:23.743Z" }, + { url = "https://files.pythonhosted.org/packages/e1/f4/b3007a3ed5c9be73f81161140684cf7d9bdb9c4b632f5f484d2a1c713fb9/kiwisolver-1.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c2306e8bb53601979fcb3fa09cc65e031876d9ae01eff2fcbcd7a84ef94d5bc1", size = 64720, upload-time = "2026-08-28T10:26:24.95Z" }, + { url = "https://files.pythonhosted.org/packages/a1/13/08188f0cafa3a800403e4ff62b9aad4e7a17f9c4c7e080dc8f18c64794cf/kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:18a0cfb124546a4c2e6087c5f3029c7f44b37c85b142e0ced71f73a7599ac208", size = 1475867, upload-time = "2026-08-28T10:26:26.393Z" }, + { url = "https://files.pythonhosted.org/packages/8a/3e/053bdc3c9abdb8f2606225eda398adca25c0c91ab90add8222a69db65ee0/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34ec467940442c9943016fb2d4c81d1ba84351eeca2f1a78f8bc87f1ba0d414c", size = 1282865, upload-time = "2026-08-28T10:26:28.118Z" }, + { url = "https://files.pythonhosted.org/packages/5e/64/a44c341b36b610588cc2f1e89b3cae072a3119aa8be578e90987cd640751/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a83ee7107df13abe42a54a6654670eef9bb39425cf2e27f65e0007465e1286ab", size = 1300865, upload-time = "2026-08-28T10:26:30.125Z" }, + { url = "https://files.pythonhosted.org/packages/60/5e/7e7d716dca38c714478b741257a5b4a321d9932b8d851551a136dcaf3984/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bebb89489b279b2f5661bbbb2abcc87bcd4a46607bb4a5c966f04f1db6b8df9a", size = 1348071, upload-time = "2026-08-28T10:26:31.829Z" }, + { url = "https://files.pythonhosted.org/packages/10/1a/2b98fdda8bf45b7be317e48ed12393d44334394d315c74b81f4a14c0e31b/kiwisolver-1.5.1-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:509735237ae0d849e8a843551d423d2500d2e0a9ac1611a145658b29c0fb9f85", size = 992191, upload-time = "2026-08-28T10:26:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/b6/55/d893f5ede0e50f9e3fcf01f6015f42ec7d9cd221e26772701fe4a98745f9/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:824c3d763a05ea9e9003610145186b0e9848c7584a5575c79bac5a8e7cd80bad", size = 2233854, upload-time = "2026-08-28T10:26:35.282Z" }, + { url = "https://files.pythonhosted.org/packages/b1/82/f85f6279555a6ee1639fef7bfe83adb037a03e11a6fc9eaa54b8d0380339/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:1fff05e239575b1481b6ed1a782f6fad616efbf1f0b1f44e6e85c4dfe426e483", size = 2330621, upload-time = "2026-08-28T10:26:36.9Z" }, + { url = "https://files.pythonhosted.org/packages/56/31/e11aea078f66fc2fffcc179d38ca90d9da97652a241b64519169742ba46a/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0627b9bceb9c3cdcf12b8a18655eedfed2692b038df27423383c120d0b7dc2d6", size = 1982848, upload-time = "2026-08-28T10:26:39.01Z" }, + { url = "https://files.pythonhosted.org/packages/af/ea/2956b63bf5140ca46aa2c2818e6aa03e2d5754dd2fa41db1c6b28922940c/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:8a708a47ade1fe19e8371d5da076bac0dd4b0a5a7985ad6c637f7f7e361b6baa", size = 2494850, upload-time = "2026-08-28T10:26:40.837Z" }, + { url = "https://files.pythonhosted.org/packages/11/d1/3829542258d8b3fc0898d221e7ef0e2c83eca0d348709bb8dbe54f3d4005/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:007a5553dfc4f4e8d184f588a0200e2cd4b63a59cc8796df3c39909e679dc7a0", size = 2298067, upload-time = "2026-08-28T10:26:42.803Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/49522e1ab5788cbaf63a26fbd3b851f9028616828c961b8a31b35cb96df8/kiwisolver-1.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:f4167e87b397f273dc2356fcf1eaf50a6bac51e6105f45103ef7129c8efb0255", size = 72282, upload-time = "2026-08-28T10:26:44.268Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b6/22e7ca5315d363e6f81c9f37c9472e12e7b298731e77c0428e6a911a2c39/kiwisolver-1.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5c490db2168a508088f59140dd392556a54b8bd1048fc6383c8baff13c359673", size = 69855, upload-time = "2026-08-28T10:26:45.725Z" }, + { url = "https://files.pythonhosted.org/packages/30/8c/03a9cfbe871964c8758a816eb03ac96c806da2795a9a7cd9bf9648bfb594/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4d4ca09bf13cff792b1884f64b98ee6c2467930d632233be25c56b442d99f10e", size = 126289, upload-time = "2026-08-28T10:26:47.023Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e3/14ce3041ca79dff9c9d884ca00c7bf32374e76028a865a9ecd99b4f5a517/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:44b8faef94f1857e77fa0238f3390ff1ac51d2ea20a487e2e452a59fd2b5f5ca", size = 67709, upload-time = "2026-08-28T10:26:48.268Z" }, + { url = "https://files.pythonhosted.org/packages/af/c4/45030471a66ec8ef042e9f96ffe1d522c9ab12da180186a0898966fc1385/kiwisolver-1.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2ae70bc59790d2af72a3f76f24b272403e135070340281108b447cb77ea70819", size = 65909, upload-time = "2026-08-28T10:26:49.523Z" }, + { url = "https://files.pythonhosted.org/packages/42/73/17dce073a6ae259bb32cf9d686c4079d2e538868bc45967462bf33df914a/kiwisolver-1.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:43844c1a7ad6d723d5b5b4c4fc7f5bd399c40e288120d16257c7c9e8765c6e85", size = 1584907, upload-time = "2026-08-28T10:26:50.933Z" }, + { url = "https://files.pythonhosted.org/packages/8c/84/ae3c75909f507283cbfcc7e916c7e822579ef962020b97e6882b27b4478f/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22d5e5aaad6be121f2515765e3b1c444352cb8eb4c86510801db8f2e50757316", size = 1392474, upload-time = "2026-08-28T10:26:52.638Z" }, + { url = "https://files.pythonhosted.org/packages/34/31/8bcc83caad5bce8fa4577152389848bf6bc110e51e573a2b4e7c2aa34c89/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3fa5855898f6d3d01b72ccd48a2d65cbdee301251603fefe34e2025bddba219c", size = 1405246, upload-time = "2026-08-28T10:26:54.248Z" }, + { url = "https://files.pythonhosted.org/packages/55/72/220345537d790cf4ae54f8acfff4b5cc2468e0702a384d651cf7a771c63e/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d66a64dd5dec136040ec2ae94aa026a912ee60fdd45bc28d3db30037fd809e88", size = 1456099, upload-time = "2026-08-28T10:26:56.042Z" }, + { url = "https://files.pythonhosted.org/packages/cd/10/3725fd2398f66d18c34b4e0f81a8d03764cd4f4f089f58a527f0b4428086/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:9e51c119992ea8820706871c30a4642ec76de20ae82f9b50b9a45517d8e9f810", size = 1073695, upload-time = "2026-08-28T10:26:57.658Z" }, + { url = "https://files.pythonhosted.org/packages/86/cb/28d6e09e66b93e4588b2e6b7d84d020ccefea09e2f4de788510a07efeab7/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:70ed9a45c7484d2b30cdacf60d220f494a1763b9fec1ad03285c6553fa0889f2", size = 2335355, upload-time = "2026-08-28T10:26:59.202Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b3/a0f31d5e4e40af7dc97c36b8a74fdd3a36cf3c8bbd098da9a23466ff6a94/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:98b208a7cc42c803445ef551d6753cc42a5ea13e9cab1ee66cd8b9cb70195330", size = 2426524, upload-time = "2026-08-28T10:27:01.181Z" }, + { url = "https://files.pythonhosted.org/packages/2f/c9/728f63bd58c72cafdc79fc306abeeac7391bec03b757a48dadeb30906521/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c6834b92dd2428e2dd85ef3d85f723d3c12f20aaf43a2ddd4f944ca25d833408", size = 2063430, upload-time = "2026-08-28T10:27:03.06Z" }, + { url = "https://files.pythonhosted.org/packages/84/df/ce188b96f92f9a2c958231da140768918cba53c9713dc887b82f85462118/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5d142e352eb13facc7dd047489aebdff6ba78576c239f1ea04931979caaf0567", size = 2597513, upload-time = "2026-08-28T10:27:05.072Z" }, + { url = "https://files.pythonhosted.org/packages/69/d6/76947c8203768968382e5bd74d9cc95654746703a61ea53015f2c74a2e06/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9b1c4900736e489a812c529100de4b8fb617d4db075e931e213c57424b83d9b", size = 2394488, upload-time = "2026-08-28T10:27:07.423Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d4/14b21e4eb203c4d15425e8b6a2c625a320b4a1f2f7557eead63ffc30ffb7/kiwisolver-1.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:5978c3340f16a35c30f8ab2fa7bcf559973c55f1a5ef6970e1f621acf3c4db13", size = 75404, upload-time = "2026-08-28T10:27:08.892Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f5/53157899fc7f45f76421b77b99eb1639dd0f83f26ff9d76300c96bb4a3b0/kiwisolver-1.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ca307d6c259e5c98d3cb9ade55342b47a6839762caf2536f3d7b46ee660cc82e", size = 72946, upload-time = "2026-08-28T10:27:10.944Z" }, + { url = "https://files.pythonhosted.org/packages/75/62/f786c3a27f181fa339d851a77e266d208e776b9883cabc40a5b041a31b5a/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:bb7c99f0673c03017a3ee01e54a5c2617a05468b11eabe513b0080e063ed95b1", size = 62420, upload-time = "2026-08-28T10:27:12.308Z" }, + { url = "https://files.pythonhosted.org/packages/02/cd/58a91ed25fbad0facdf503297b03768efab04bdf3141e5e3b49a34be7443/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:0d8924877ce22e17326a99a418c3c82037da078df3c6a260b13eca677444e6e7", size = 64577, upload-time = "2026-08-28T10:27:13.502Z" }, + { url = "https://files.pythonhosted.org/packages/f6/5c/d501ef5a0958b226eac28306d24d5e5f114be0ace50e19cabae7b6b3b197/kiwisolver-1.5.1-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:534f02c1abb31ed6dbd3515545285c330b2f12d00fdb1fdb71658b9ca5a13a6a", size = 66284, upload-time = "2026-08-28T10:27:14.813Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a6/8fbecaf4fc18c02f31f05e47a84c010a80e3ec391ed2f0bdade1d62b5954/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:cea20da04494e662b83c872683bf4ff2345206043d036315ed0e924b652e7294", size = 124031, upload-time = "2026-08-28T10:27:16.193Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c6/bf3090d2983b4204347cbdbe952116e7c3b2abf62b4e33e50167a13e75ee/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:7fd82debf43c6acd0a94359d232f6bb516ee13f269a7993736a9ac9f988bb5d9", size = 66489, upload-time = "2026-08-28T10:27:17.506Z" }, + { url = "https://files.pythonhosted.org/packages/85/de/562dddef55fdd7c291da8626d6619e72b5fc0870e6ccca0e149a5731e7f3/kiwisolver-1.5.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:18170a77ddfecf40ec60d0928268dc95880c881864e015a8f34094ed18b9b9ad", size = 64806, upload-time = "2026-08-28T10:27:18.673Z" }, + { url = "https://files.pythonhosted.org/packages/89/b1/ba7b9c0164ce1cf62bf2872db63b8483289cf0f3110d6f9390eb09e409ed/kiwisolver-1.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca7f6fe0f37ca978a1e5eb7a3a68e6413f417e78e838324947ffd420202b198b", size = 1482211, upload-time = "2026-08-28T10:27:20.039Z" }, + { url = "https://files.pythonhosted.org/packages/13/dc/34da54efb4976616d45c20aae32d70e89d6e7395ed908029154d1609ef22/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b973887ff782cfd6b67c9904ad8ca542e0bc5e4961503408b423b5a688b4d38", size = 1283739, upload-time = "2026-08-28T10:27:21.82Z" }, + { url = "https://files.pythonhosted.org/packages/5a/3a/30ffb62bee646e266e98a1b5cd276d9c75b6116fbfcb87c1190838c1b6df/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f76fc85bd054c806960f917ec0f329e24e436f1712267d90588e4c39890caa63", size = 1301681, upload-time = "2026-08-28T10:27:23.876Z" }, + { url = "https://files.pythonhosted.org/packages/a9/8d/13c70be22a8506880b35fdc38dca36629613bc493405c79f4037f2cd2bb9/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:828f75af2b0080c8a972e75f649ab46af008e92c6104a57a759157200b835b75", size = 1349159, upload-time = "2026-08-28T10:27:25.899Z" }, + { url = "https://files.pythonhosted.org/packages/82/0e/993972b8ec6767f47cd69818fb3a5ff14510557d29f7d1a839be7574fa1b/kiwisolver-1.5.1-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:431dc224a1a92a5c8f582d96e505196a3b5997a7271076678da2dfde67b77e9a", size = 997613, upload-time = "2026-08-28T10:27:27.507Z" }, + { url = "https://files.pythonhosted.org/packages/36/82/ca26eddd2eda2420dfc56693449c1f821f78b485da9cbde9904c03af3f93/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:61e9a64c7635095a6bfe483e2ff055d437c59bd45f3617a228b37277f0185d62", size = 2235109, upload-time = "2026-08-28T10:27:30.113Z" }, + { url = "https://files.pythonhosted.org/packages/c7/84/97d920881e10840b8d7c7185620298e3e4c88820b05514e3a15a258b08a6/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:3c24cd69455e1b00ddf770c13b6e2c33e07d6dc3f2d34add0bf9277c5c6bbd46", size = 2331207, upload-time = "2026-08-28T10:27:32.795Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ce/34d74b8f25acc58800f4c09268371e8d6159cf0f1206f1e4dc7835629b48/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:27add358abe374ebaa3b8763ef380bc99051b5a4b18d94878366a9e4f59efef0", size = 1986696, upload-time = "2026-08-28T10:27:34.628Z" }, + { url = "https://files.pythonhosted.org/packages/0e/01/f892644014612527aef7031d3306a2ffc60b3cb044f802c1561f8e5e14f3/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:255605693a483db7bd5c79f60437f7bf658f7f520d61aa42722e32257c941951", size = 2496400, upload-time = "2026-08-28T10:27:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/32/6d/d8284e66e697026536e5f418b9cfe56567bffd3c775e3ecfbae373605854/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7d38b0c279c3032e8c9cc013b405c6df8e1668dbf15465779aa7f15f61201812", size = 2302967, upload-time = "2026-08-28T10:27:38.803Z" }, + { url = "https://files.pythonhosted.org/packages/46/0a/69a355e27f32ba50d5b6369949b6a1702e122f5277c89bc76d452b81c1c4/kiwisolver-1.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:958254518717542d02d0688d0d20cbf771da5e415e6f49543f92481c850a4540", size = 72283, upload-time = "2026-08-28T10:27:40.491Z" }, + { url = "https://files.pythonhosted.org/packages/ef/d8/7a95be90c33dcdd52204d4aa6384d731443225b887283bbd8b61e7931f6c/kiwisolver-1.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:da3275833be0edbaf4830fae08bae3dc7219f40ce0c37eaa6c25825957e06612", size = 69860, upload-time = "2026-08-28T10:27:41.835Z" }, + { url = "https://files.pythonhosted.org/packages/31/f8/9bc493e7f5707788ba7f621902c68f82dc3a7ba03c78fbd337b026cef1ed/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:470d420f98d368d6f010633a20659b544c5fdfa5329e6b70219f2ef08fd4a7ef", size = 126336, upload-time = "2026-08-28T10:27:43.379Z" }, + { url = "https://files.pythonhosted.org/packages/d1/82/3aea86b3f99712db825e9ac5631bf99571e818a8b8961ff98cebd798413e/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:83f78128fa28705fa85d01c59771c72fe81c11bd0e6155edbb9f818983a7d761", size = 67698, upload-time = "2026-08-28T10:27:44.613Z" }, + { url = "https://files.pythonhosted.org/packages/84/7d/8daafc5d2e7f9c47a4f78f8865d86d2a9cf399c2a85f86c44a993594410c/kiwisolver-1.5.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:9506e892bcc3b409831d363c6f53e5985e1c8d1f6f6b0256d00358684ff85378", size = 65945, upload-time = "2026-08-28T10:27:45.932Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c9/51dc974d9130da70a8c47a96160123443d387ffe1b6b833d6f91d9429339/kiwisolver-1.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cea90547bfd93807e0013a004dc76552be44fad3bc1cc2b38610a9e889ed098f", size = 1588030, upload-time = "2026-08-28T10:27:47.678Z" }, + { url = "https://files.pythonhosted.org/packages/e6/86/f3e1a730e7a995149d8d3ff9e313b6d8a17b2cf1d98a8eff139dc30463fb/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8e4d953faaded9ec7ede36824e9814082d22d4c7b1eafbfa079ecba8cd0d076", size = 1390760, upload-time = "2026-08-28T10:27:49.676Z" }, + { url = "https://files.pythonhosted.org/packages/4f/3b/8ba25a2b5a0d2375e046f1b72de5179513f0be95aba6e7b094c89303929f/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e9c01d3dd7ceba4d1d436cc021d40d592466e40b9bc7f5d83dc4e98a5c9cd8c", size = 1403279, upload-time = "2026-08-28T10:27:51.242Z" }, + { url = "https://files.pythonhosted.org/packages/18/d0/278d5cb8be812740027d5ca0a7eda0c375488a88d6dce0fa60fcc2591ad2/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37f801b5d7cc0e5a548921308e059fd2b057bb42972b591cfa3049f95423c4ed", size = 1454429, upload-time = "2026-08-28T10:27:53.213Z" }, + { url = "https://files.pythonhosted.org/packages/94/37/bcbab41063ec284c1d200efe5087cf087798c2f8916960aa8a20dd303290/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:e68e151428b5384f766cd25739bf77c7e4a3dc93b5ded7a12118d9fbfdf78ab6", size = 1073225, upload-time = "2026-08-28T10:27:55.089Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c5/ab79dcdf5ae28909a51210ae0a1c579e97ff997b3466414f0d04c0994583/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8f8fddb8e323bd6eee4e54e69a39243beab22689070f4c66b472c4cc88bb89d8", size = 2334335, upload-time = "2026-08-28T10:27:56.78Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/71d047468a189041d9c93f3b76844b924f9793b188c44bd149fa258912da/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:3cc210010fd2f438a3ed430b45f1b501fd13a8618bf984dc2c5ce5b69b78752e", size = 2424982, upload-time = "2026-08-28T10:27:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/7d/37/1347461bbea6d0e1f0580b94ef603b18e72c2be5f667fa1653867361a00b/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:b5664603a253efd3a75716d793d1d3a6a82723b61dc6db767b2460bbbeec4c0f", size = 2062857, upload-time = "2026-08-28T10:28:00.407Z" }, + { url = "https://files.pythonhosted.org/packages/1f/87/c7f0976c9cd0d127643351bc0c9929e0b8899d7f49d4ec238cd909e39c42/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a7b85b2cc6ea45e5f7e8c9a30bc9fabd47cda09106cbb4b967335c3e6c43b69d", size = 2596022, upload-time = "2026-08-28T10:28:02.183Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9a/59a6f6ae6f938c15076be2c21b6cedea973d71bb1349ec84fa485fab82cf/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:ab620eb663952455271ac37f9aaad86b73c969c02f11f53cea405b38e96a4300", size = 2395634, upload-time = "2026-08-28T10:28:03.977Z" }, + { url = "https://files.pythonhosted.org/packages/e9/2d/8982c1fb7926da5bb7ed60318c3665b5c3f941447271ac982960a11b8637/kiwisolver-1.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:cb6fae641357ed2f6e533c0d3c6504a4a5703621a50c89459e46051d56b61140", size = 75379, upload-time = "2026-08-28T10:28:06.307Z" }, + { url = "https://files.pythonhosted.org/packages/07/78/ba7b6dfa1708b82b373ac056928a30c545d5c1a627df9839dcec3c6c1881/kiwisolver-1.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:b390aec180a7c054919c04898835e1c77bced23ea8383eb2c570213bf25d1a86", size = 73011, upload-time = "2026-08-28T10:28:07.578Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c4/1407df7512a5b36cc79840e01710dc575733c461b13ab866cae77eaf87f3/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:482676e5bd48d70ac99d9fc78863469845421e01184fa83f1f9366dc49f7e974", size = 134002, upload-time = "2026-08-28T10:28:08.881Z" }, + { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c1/69f00d627949580e43d57af0aa465df46868d7c29801c137a55374101294/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f", size = 73362, upload-time = "2026-08-28T10:28:12.449Z" }, + { url = "https://files.pythonhosted.org/packages/ba/f1/8bae9fac0f1837679ed59a5dd7e97e7eb943b738defa7cc0117ea0d107dc/kiwisolver-1.5.1-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:a5716a33bfabb2c6ce27b6cf03253467b3804f83e215f4d202685cf93c6c9874", size = 59543, upload-time = "2026-08-28T10:28:13.794Z" }, + { url = "https://files.pythonhosted.org/packages/c3/3e/42e3639d32ef3ac6ede80c39dc1d1df6224927409960d8f762b6cb504efe/kiwisolver-1.5.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:685929988b208a911f1285e2f8ed54210b0d681a3dc0f03e00d599d291986e7e", size = 57504, upload-time = "2026-08-28T10:28:15.074Z" }, + { url = "https://files.pythonhosted.org/packages/e1/12/f4beaaceb740b96c363a8fa6f34dbdf37a58d9e5f15416427d7bf89c552a/kiwisolver-1.5.1-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4e49f7e1a4e7191bdf9dc67a974db714501b1fc52c24324103d06a86abd5c08", size = 79885, upload-time = "2026-08-28T10:28:16.345Z" }, + { url = "https://files.pythonhosted.org/packages/02/24/18d8a755acdae79c37ca2f1a925795aab67b9456c30c8569c377ea3abc77/kiwisolver-1.5.1-pp310-pypy310_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0a887b6565bbfe80efde2b7f6e8890d7d9bbdb11bdb17028a3690c32fe0621f", size = 77582, upload-time = "2026-08-28T10:28:17.719Z" }, + { url = "https://files.pythonhosted.org/packages/df/a9/b86dde4f553ef74db0f9c32398614e24b2e8ec1d29a6ca04ae080d7dd29b/kiwisolver-1.5.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:1983f0974a750a6f6556f368ba11105d1d8369c735b944747c9f12ae5aea7aae", size = 98321, upload-time = "2026-08-28T10:28:19.087Z" }, + { url = "https://files.pythonhosted.org/packages/b5/1d/59ba570b1774e95e97fde3a0981b2e22118a7a495f73bf74cedc538566a0/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1", size = 59450, upload-time = "2026-08-28T10:28:20.383Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/a6849f04dc18b5400e8b98affa2cd8fd86ed583085f036e57b32e571f4fa/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957", size = 57400, upload-time = "2026-08-28T10:28:21.632Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ce/a7dc71353dd06a4cbe02222773f52d4a28c81e5a452a75797f8ed113dc99/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2", size = 79891, upload-time = "2026-08-28T10:28:22.936Z" }, + { url = "https://files.pythonhosted.org/packages/10/b1/d61c61a84ff85d1a36a99df2c152b59ffedb1d356c598902aba44abcdb60/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6", size = 77605, upload-time = "2026-08-28T10:28:24.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/52/5aef56f21a460a6e43ab3cdfc7697d59d7b87deb0ec97a0f7b91aa4a521b/kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f", size = 98465, upload-time = "2026-08-28T10:28:25.696Z" }, +] + +[[package]] +name = "lazy-importer" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/23/d2c8308466a6831043ac3518e480c2e1a06b21a13e0a8f6542ab29cf592a/lazy_importer-0.1.0.tar.gz", hash = "sha256:b2e296716ce015c0cd80e57b940e52727c5b934b34b8656d5ce06bdd0ee5fbdd", size = 84008, upload-time = "2026-10-20T00:36:58.369Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/28/7ded071d0975dcc6d5d106ffbf7b3ca420f7caa3b8a235fa604b6e37032a/lazy_importer-0.1.0-py3-none-any.whl", hash = "sha256:bd93fab7bef18e842eea02b839410954d37889140dc64ca4d9680aec6880c739", size = 12580, upload-time = "2026-10-20T00:36:57.176Z" }, +] + +[[package]] +name = "lazy-loader" +version = "0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/8c/0f2ff2a8b7513e68871a74740c17a504b0488c679b379e6445ebb7bd78dc/lazy_loader-0.6.tar.gz", hash = "sha256:2f4b7824d6401958639008a0cae20c776b61dff619accd6890693e2de8260167", size = 18438, upload-time = "2026-09-21T21:31:32.982Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" }, +] + +[[package]] +name = "locket" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/83/97b29fe05cb6ae28d2dbd30b81e2e402a3eed5f460c26e9eaa5895ceacf5/locket-1.0.0.tar.gz", hash = "sha256:5c0d4c052a8bbbf750e056a8e65ccd309086f4f0f18a2eac306a8dfa4112a632", size = 4350, upload-time = "2022-04-20T22:04:44.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/db/bc/83e112abc66cd466c6b83f99118035867cecd41802f8d044638aa78a106e/locket-1.0.0-py2.py3-none-any.whl", hash = "sha256:b6c819a722f7b6bd955b80781788e4a66a55628b858d347536b7e81325a3a5e3", size = 4398, upload-time = "2022-04-20T22:04:42.23Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/aa/9a65962e364bf19745f6bec7bde398fb1f5ca53ad2e734258e6198cc32ba/markupsafe-3.0.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:dd8ea6ebee7aedbf7c749fa80521d9ccf1ba473e0d1e14805caafbaad281c889", size = 11521, upload-time = "2026-10-02T23:04:20.141Z" }, + { url = "https://files.pythonhosted.org/packages/14/36/927999a34b7d1def6957de89153d327fedc4030061940b5a468584e6c5a8/markupsafe-3.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:dff05cb7016dff1e9fd68f4122c127b65dfc59de5306cfb7ad92f956f230bee2", size = 12066, upload-time = "2026-10-02T23:04:21.275Z" }, + { url = "https://files.pythonhosted.org/packages/17/54/69e7b0db9bd687bfd83451eed5666384d67cfed3be062bfc59a06a15474e/markupsafe-3.0.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cf63c214fe879a65e69a386f915e36104fc84254ab141240f8854602d8e0be2a", size = 22081, upload-time = "2026-10-02T23:04:22.221Z" }, + { url = "https://files.pythonhosted.org/packages/bd/14/f6f5c97903f7d2db76bbfaced31509a47d360a103b3aaf4849f6536591ec/markupsafe-3.0.4-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2a6ef68ae94aed8721934072b27a3b654ea2100b97e4ab864cf1489c90926fbc", size = 26079, upload-time = "2026-10-02T23:04:23.346Z" }, + { url = "https://files.pythonhosted.org/packages/d0/04/c3cc9b75f94f8b54d7e503c44cebd4b4a115ec1d6f1b996b999807daba99/markupsafe-3.0.4-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:fd9f8797427910198f95bced71ddfed61130d7e349213bfb8466c9c99e2c46a8", size = 22611, upload-time = "2026-10-02T23:04:24.401Z" }, + { url = "https://files.pythonhosted.org/packages/00/26/c4708ed3b0f08e8e6d7cbce3314ac130cb5352d1f62951b6fef7878f2b1e/markupsafe-3.0.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d1aca03ede943eb80ab3d63bb082c84b7aab85ea83bd0fd0c200260945fb49d9", size = 20712, upload-time = "2026-10-02T23:04:25.386Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b9/f3894d6aae3d7a52c9363317f4baf2fcadc052163d6dbc871266e32639ed/markupsafe-3.0.4-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0764a13d34cae40db7bbf3a09b7e9b491bf4603e20b263a7a9d6b8e324975d0a", size = 20742, upload-time = "2026-10-02T23:04:26.403Z" }, + { url = "https://files.pythonhosted.org/packages/59/7c/8e248ddbfe286ab6bddb462bdac0851cbb1510d2cbbb815a415fcb0511af/markupsafe-3.0.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:9388003072b95f2f1e3fd908604194d653ba21330d811961a78b7da1a77e9e36", size = 21560, upload-time = "2026-10-02T23:04:27.522Z" }, + { url = "https://files.pythonhosted.org/packages/df/26/2353fef7d4bcf2b18e16bad81979fcecff2915156ca6882447917205b8e2/markupsafe-3.0.4-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:8698d70a8081ee8c090dbb394768b5789a1da8b131b5499f89d071dd3cfaf6be", size = 20973, upload-time = "2026-10-02T23:04:28.573Z" }, + { url = "https://files.pythonhosted.org/packages/67/6f/a9561d98d9a6ee3494b0b970a1c766e58bab128cc84841d56ec009456dbd/markupsafe-3.0.4-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:bf053da3c97a4bc5ecfbb218cdd2983febd91c617be8367d139882aa11e490aa", size = 22036, upload-time = "2026-10-02T23:04:29.568Z" }, + { url = "https://files.pythonhosted.org/packages/55/83/6217df9192eca95af3ff0cad955c9854a93fa43b288cf7411ae24713eb52/markupsafe-3.0.4-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:9438a2648b2195980cb2dd8e53ed7b8df91319e2d0b70ae61a9e1d1bc8d3bec9", size = 20314, upload-time = "2026-10-02T23:04:30.881Z" }, + { url = "https://files.pythonhosted.org/packages/35/7c/9cd8081dae70e17fdab3558121fa618d459c7950c8abd8fc10fc024486d7/markupsafe-3.0.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:88d59b473bfb03259722600839af9bbd7fa13a2eb514beefeedb95997882f69a", size = 20780, upload-time = "2026-10-02T23:04:31.975Z" }, + { url = "https://files.pythonhosted.org/packages/44/37/c5f2f45f4d8f0c24e4af7b9dc711640c888044cbf5f7e2ba2c0bb74cbb55/markupsafe-3.0.4-cp310-cp310-win32.whl", hash = "sha256:4a540e2d3192792fc84eced57bef37851ccb2b41f73291bb17408eea77bcd278", size = 14096, upload-time = "2026-10-02T23:04:33.129Z" }, + { url = "https://files.pythonhosted.org/packages/50/50/394a1c61c9b9972cb4f76875c332af7109bd39bdad09d3a0ec5327a339dc/markupsafe-3.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:5c22873ad1f0532ba40fa1727f3c0fc1bbbaab6d373d4cbe3f0dc74b2e2521c7", size = 14329, upload-time = "2026-10-02T23:04:34.168Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9a/86d03d2f32ba41a57baa124a7bcb76d0a6d39b1622e9bd4d550074e8b61a/markupsafe-3.0.4-cp310-cp310-win_arm64.whl", hash = "sha256:3d23795802fc8bd72534836d64489bbf0f67c088959091bdb22e10735a5107bf", size = 14196, upload-time = "2026-10-02T23:04:35.201Z" }, + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/81/09/4c59d56b8461ae8eb0d8ba34bb25b7e618547044679d58a82ef9b2479fc1/markupsafe-3.0.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6", size = 11658, upload-time = "2026-10-02T23:04:51.876Z" }, + { url = "https://files.pythonhosted.org/packages/a2/f0/d6613774d86fbf6d145751d43c59875e47a6f9f17daee0aef173bd36d90e/markupsafe-3.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f", size = 12050, upload-time = "2026-10-02T23:04:52.931Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f2/8f18e0b806eb13c1f8d07d917a720831ead54253a6dec011fbc78098a6f8/markupsafe-3.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b", size = 24363, upload-time = "2026-10-02T23:04:53.895Z" }, + { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525, upload-time = "2026-10-02T23:04:54.905Z" }, + { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733, upload-time = "2026-10-02T23:04:56.229Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001, upload-time = "2026-10-02T23:04:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f8/bffee5e7d2a3deb59748a797650a48af7e672025cf641a79344a771ad106/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c", size = 23793, upload-time = "2026-10-02T23:04:59.686Z" }, + { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640, upload-time = "2026-10-02T23:05:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074, upload-time = "2026-10-02T23:05:01.813Z" }, + { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563, upload-time = "2026-10-02T23:05:03.239Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" }, + { url = "https://files.pythonhosted.org/packages/c8/52/7632a53360671a9b750cdbabaf9cdd89f18b42248b8e4cb42c0b0296e459/markupsafe-3.0.4-cp312-cp312-win32.whl", hash = "sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237", size = 14108, upload-time = "2026-10-02T23:05:05.513Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/4c24208776a65878d656996945aacfbfe010d3720d1a98fc0eb8491fc03b/markupsafe-3.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9", size = 14174, upload-time = "2026-10-02T23:05:07.617Z" }, + { url = "https://files.pythonhosted.org/packages/6d/18/4bc5ba32499e87bb2b0ef5b3a9bb9c00a131fa961ddf0be548cb550f548b/markupsafe-3.0.4-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1", size = 12786, upload-time = "2026-10-02T23:05:08.709Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6f/17f0c099bf25f3e31e63cc19244d9f6af861a9a4ab778c203997903cfdd0/markupsafe-3.0.4-cp313-cp313-android_24_x86_64.whl", hash = "sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1", size = 12510, upload-time = "2026-10-02T23:05:09.93Z" }, + { url = "https://files.pythonhosted.org/packages/11/af/1a141081b905036ee904ec4bd945e1f70b4e1b32d33c4e59e8cf1d58b247/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96", size = 11583, upload-time = "2026-10-02T23:05:10.884Z" }, + { url = "https://files.pythonhosted.org/packages/e7/0a/a89385ae590232622a03e091805cff12f24fabe6c11e0e8bae096cece81c/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148", size = 11801, upload-time = "2026-10-02T23:05:11.913Z" }, + { url = "https://files.pythonhosted.org/packages/ed/85/ea548dc013962eb73653124bc595635fbf9e0fa41d1f181a967ccb784dfb/markupsafe-3.0.4-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e", size = 11443, upload-time = "2026-10-02T23:05:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/cc/72/15f2e5ec9cf2eb00d5cdfe968d94e4156a7bd7303832c3f3b2c403a36839/markupsafe-3.0.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248", size = 11665, upload-time = "2026-10-02T23:05:13.829Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/4030bea613677e333c8a2c901fd405055f657f9d06acba5b7357984b6ef7/markupsafe-3.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72", size = 12061, upload-time = "2026-10-02T23:05:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/28b76a7449eb702966b88bef599e2360b411fbb3afeee8fe560939be06ec/markupsafe-3.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2", size = 24395, upload-time = "2026-10-02T23:05:15.909Z" }, + { url = "https://files.pythonhosted.org/packages/07/6c/21232811afc3a063b5e934b1ae2efda52f46154ec382f585149c020e61fe/markupsafe-3.0.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85", size = 27183, upload-time = "2026-10-02T23:05:16.976Z" }, + { url = "https://files.pythonhosted.org/packages/14/38/6ccdfa5b59049cb36fb80cbc80aee9cf1fc9bb77d1335ad435f2070b08cf/markupsafe-3.0.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde", size = 24772, upload-time = "2026-10-02T23:05:18.209Z" }, + { url = "https://files.pythonhosted.org/packages/63/e0/cec6865dfe88cb48fedd4b20aed6af5158e41092adcbf3e028bcc6ec2108/markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6", size = 23017, upload-time = "2026-10-02T23:05:19.286Z" }, + { url = "https://files.pythonhosted.org/packages/ee/76/6ed4940bb7648a9aac457c14f870cfdd5105f139a0fb1f29cd61fafa47d1/markupsafe-3.0.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f", size = 22036, upload-time = "2026-10-02T23:05:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/a1/4f/ed476226d4fe46a09090a36025bf319296810028df55eb12f1253b540f3a/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39", size = 23786, upload-time = "2026-10-02T23:05:21.576Z" }, + { url = "https://files.pythonhosted.org/packages/9a/35/66ff30450e35ef5fba9ebc930c9411747e537fd9447b65e44f5007e2b84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee", size = 22672, upload-time = "2026-10-02T23:05:22.922Z" }, + { url = "https://files.pythonhosted.org/packages/32/0b/72f45ce4b4efcbca4b80cf1b06703eff0be8d37e82abb78f66c85a7ead1e/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2", size = 24107, upload-time = "2026-10-02T23:05:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/71776e5fdcba04614b384cc102e8a4198208579d896fd1394cb7cb9aa900/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46", size = 21615, upload-time = "2026-10-02T23:05:25.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/5f/801ce02a02e7aee0f784b1ec7843026178f6adeb9c93ac67eb1992a9a84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17", size = 23076, upload-time = "2026-10-02T23:05:26.423Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/c43776625428f3bb4a61e8633940400e3efe6409e3c6f5bff26de5e45618/markupsafe-3.0.4-cp313-cp313-win32.whl", hash = "sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0", size = 14118, upload-time = "2026-10-02T23:05:27.716Z" }, + { url = "https://files.pythonhosted.org/packages/6f/36/163da64de88a13db79214ef75fa041be7fa13bdb42261cf5b7484de14bfb/markupsafe-3.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5", size = 14313, upload-time = "2026-10-02T23:05:28.749Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/9b662783ffaa1149221432a923cee562f78b9cbbb8baa3df9b3753e63e1e/markupsafe-3.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc", size = 14189, upload-time = "2026-10-02T23:05:29.917Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c3/a944f3b0df22bd129e96915b9f4e98d2eeca6516687d7618304a966c3c74/markupsafe-3.0.4-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed", size = 12787, upload-time = "2026-10-02T23:05:30.971Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d6/a44863f69d88b6c7e27889108f70d47aed259edf89d5df3c5fca1eac87d6/markupsafe-3.0.4-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59", size = 12525, upload-time = "2026-10-02T23:05:32.263Z" }, + { url = "https://files.pythonhosted.org/packages/17/8f/168ba80e532dd6a93f96f8f706f1ad41d7990b6e1aeedc1cc0d211a33497/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453", size = 11589, upload-time = "2026-10-02T23:05:33.251Z" }, + { url = "https://files.pythonhosted.org/packages/32/b3/aa2c95a574d3af39403a469b295886eb9b6d448da568cbebb5a2cbfdc2e5/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b", size = 11801, upload-time = "2026-10-02T23:05:34.315Z" }, + { url = "https://files.pythonhosted.org/packages/60/d0/34b810107d83840e768bf485de795893ebbae35b26ab061b487adfa0a692/markupsafe-3.0.4-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6", size = 11447, upload-time = "2026-10-02T23:05:35.302Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ab/2f8488f0f817a39fca068d2b17daf446bf5cdb3eae28c3720af534d873b4/markupsafe-3.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634", size = 11722, upload-time = "2026-10-02T23:05:36.363Z" }, + { url = "https://files.pythonhosted.org/packages/ad/40/e2d117b048d47282ade906fbfd92814cbee5647afc13fda88a3406039372/markupsafe-3.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f", size = 12061, upload-time = "2026-10-02T23:05:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a8/73a81135e85ba66217f5af7facb03bbb386807e1a729ab64532e4c802652/markupsafe-3.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9", size = 24434, upload-time = "2026-10-02T23:05:38.407Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ca/fa9216dd01efee2dfdacafe7df32b4d0170fbac694b0c258a193d6e53999/markupsafe-3.0.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f", size = 27183, upload-time = "2026-10-02T23:05:39.581Z" }, + { url = "https://files.pythonhosted.org/packages/fa/4e/a469509e538d37af51103b17b073126973f2b1cbf197ff32c7ddf025cfe5/markupsafe-3.0.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c", size = 24813, upload-time = "2026-10-02T23:05:40.671Z" }, + { url = "https://files.pythonhosted.org/packages/8f/db/d7282caf7ab03af44d5d6fdbaa019b35c7d7f1c90588b839c07cba640d6a/markupsafe-3.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300", size = 23049, upload-time = "2026-10-02T23:05:41.864Z" }, + { url = "https://files.pythonhosted.org/packages/30/f3/b6a425206e6964efda6acee544d0eb01d1501784d0b8e2dcc74986f33b17/markupsafe-3.0.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0", size = 22088, upload-time = "2026-10-02T23:05:43.014Z" }, + { url = "https://files.pythonhosted.org/packages/ea/8a/84d3582fc1f0d5bd466cdf2eebf175e172158a6e70701aacec1de1b35430/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977", size = 23846, upload-time = "2026-10-02T23:05:44.098Z" }, + { url = "https://files.pythonhosted.org/packages/1c/65/db101cce51b7ba4864ac491a9859d297dd1adf0e55b103fee9db9c47c527/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7", size = 22674, upload-time = "2026-10-02T23:05:45.23Z" }, + { url = "https://files.pythonhosted.org/packages/e0/49/ddee9813d71db0c7a5c9d97c832125e6758a0c844777f1cf076569bb0e22/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17", size = 24104, upload-time = "2026-10-02T23:05:46.398Z" }, + { url = "https://files.pythonhosted.org/packages/aa/0e/7d8518d726726870a2399d69fd30d0fa36c5e57a2132c336b58d7c491073/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c", size = 21637, upload-time = "2026-10-02T23:05:47.48Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/b505e8a361ba557dbf3b3aa7331ea39b00d2022a26e925ff8463b9714bb3/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4", size = 23081, upload-time = "2026-10-02T23:05:48.611Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ea/9cc3cea873f980c75cbdb6f4277ce30ee955de38be0b3d02f14c108e0698/markupsafe-3.0.4-cp314-cp314-win32.whl", hash = "sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c", size = 14272, upload-time = "2026-10-02T23:05:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/80/f0/5792ff768a410f93ee3f84fc19345295ffc352d2c936b424cb37e514714c/markupsafe-3.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe", size = 14501, upload-time = "2026-10-02T23:05:50.788Z" }, + { url = "https://files.pythonhosted.org/packages/5f/cf/3d074a8edffcc6899355232ff2543ae8d929733239596423b7db79698bc9/markupsafe-3.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a", size = 14364, upload-time = "2026-10-02T23:05:51.857Z" }, + { url = "https://files.pythonhosted.org/packages/d9/31/87ce42159aae2163cf3bbbd0c44bc87780510eecab1ea3859099aed95dcb/markupsafe-3.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2", size = 11759, upload-time = "2026-10-02T23:05:52.951Z" }, + { url = "https://files.pythonhosted.org/packages/5f/53/b047207eeb7752e960aca3eb1df5fb7eefa7dd4c62ac49bb156456c8a702/markupsafe-3.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977", size = 12096, upload-time = "2026-10-02T23:05:54.066Z" }, + { url = "https://files.pythonhosted.org/packages/ee/51/4326c88a13c7b755657d44b4bb986f8c3d9843ecba7e22d98661d87f9a57/markupsafe-3.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289", size = 25699, upload-time = "2026-10-02T23:05:55.15Z" }, + { url = "https://files.pythonhosted.org/packages/f2/bb/990581b7474bfcf2cf34bed6ba5ea23bd87adb9d671213d68e88620e7a6b/markupsafe-3.0.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe", size = 27804, upload-time = "2026-10-02T23:05:56.29Z" }, + { url = "https://files.pythonhosted.org/packages/6b/89/89491878c28e8291f5aa2fffe2c2d57230d10ae366d55dd810b840513d78/markupsafe-3.0.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a", size = 25912, upload-time = "2026-10-02T23:05:57.416Z" }, + { url = "https://files.pythonhosted.org/packages/30/77/680998b54efdea06fc114565cd739b6d059f826a0279219b218dfa750d29/markupsafe-3.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733", size = 23623, upload-time = "2026-10-02T23:05:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/ae/75/2709f5ac5de9467b40b10e2bb8f89cc63dfb74582e09aa734b1124a217de/markupsafe-3.0.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34", size = 23301, upload-time = "2026-10-02T23:05:59.94Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c8/39eadc6c5b14c9c7679bfb98f4d4c6a97863b5beb91839aca4d2d6e16e55/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978", size = 24950, upload-time = "2026-10-02T23:06:01.289Z" }, + { url = "https://files.pythonhosted.org/packages/1a/5e/01037f8a43e8ccb0bffb4fbdc5212db05bf080fdd7286cd392332d58128a/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc", size = 23330, upload-time = "2026-10-02T23:06:02.441Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f4/23e83ce0596bb0cbe670502d31df8f757bbd01a392aa486fa3b40d1ed399/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc", size = 25239, upload-time = "2026-10-02T23:06:03.579Z" }, + { url = "https://files.pythonhosted.org/packages/88/5b/3708897368073cc683d524750474f41a77d2986152c380dcc55b20fdf340/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932", size = 22767, upload-time = "2026-10-02T23:06:04.699Z" }, + { url = "https://files.pythonhosted.org/packages/c6/61/ebda1307864b409e6b3115757a3d4a09cca46cfb6cc65191b5de226b424b/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6", size = 23668, upload-time = "2026-10-02T23:06:05.9Z" }, + { url = "https://files.pythonhosted.org/packages/09/15/98075cceac3b5ba0dbb8e4762a847be967d2befc349a2cf2d0ac77f62c9d/markupsafe-3.0.4-cp314-cp314t-win32.whl", hash = "sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691", size = 14301, upload-time = "2026-10-02T23:06:07.109Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a3/768b560fcc4156685cb563d922b217810cfa7bc135773367f62f1f9d2078/markupsafe-3.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464", size = 14526, upload-time = "2026-10-02T23:06:08.276Z" }, + { url = "https://files.pythonhosted.org/packages/93/63/da554b4c97a6b0ea3229ca7fe8cbfb620be81613d517f482e85958550537/markupsafe-3.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c", size = 14421, upload-time = "2026-10-02T23:06:09.402Z" }, + { url = "https://files.pythonhosted.org/packages/a9/30/54d11c8ca027114898cab97421fb39e4ffd9ddf47cdbc44df2ec76722da9/markupsafe-3.0.4-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65", size = 12791, upload-time = "2026-10-02T23:06:10.485Z" }, + { url = "https://files.pythonhosted.org/packages/10/6d/97c913e253a14bd3cd0e15a5c56d13203b823fa7ee32498342896a072dc4/markupsafe-3.0.4-cp315-cp315-android_24_x86_64.whl", hash = "sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163", size = 12527, upload-time = "2026-10-02T23:06:11.834Z" }, + { url = "https://files.pythonhosted.org/packages/26/f9/b86d032042a4d597d9e1997f0e5f63a3eedaf11258e0a05760b0a0a826ea/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92", size = 11602, upload-time = "2026-10-02T23:06:13.122Z" }, + { url = "https://files.pythonhosted.org/packages/f2/dc/73c14c1eedf0ac5fa3292ba43435e6c49d2c2050f33cebde541f8f4807f1/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a", size = 11817, upload-time = "2026-10-02T23:06:14.227Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/2c2fcaa5fcee22d72c7819c0d536fd181c74a688e6143845419579cd2863/markupsafe-3.0.4-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429", size = 11446, upload-time = "2026-10-02T23:06:15.574Z" }, + { url = "https://files.pythonhosted.org/packages/88/54/9e5ec76c62e6e2834d5a93623018c943e8b3bb41d663e3fd4c03303b9b85/markupsafe-3.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8", size = 11719, upload-time = "2026-10-02T23:06:16.701Z" }, + { url = "https://files.pythonhosted.org/packages/96/24/3ec292b44064c16229e064d770b2625bd8ea941aa61f44905a9fa44942c0/markupsafe-3.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97", size = 12075, upload-time = "2026-10-02T23:06:17.855Z" }, + { url = "https://files.pythonhosted.org/packages/aa/85/b64fdb1f304848518742136983c24e96d967bfb59a0ea160e92736901ab0/markupsafe-3.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b", size = 24656, upload-time = "2026-10-02T23:06:18.963Z" }, + { url = "https://files.pythonhosted.org/packages/9c/18/23997d4c65b355da6390d61cd56e0ab3befd6ba8dda25cb40c602bd0fa6b/markupsafe-3.0.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9", size = 27737, upload-time = "2026-10-02T23:06:20.117Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/35998dead3c6af88c38265a56e58100211f036234ab88eb2283fd4cbce44/markupsafe-3.0.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653", size = 25003, upload-time = "2026-10-02T23:06:21.284Z" }, + { url = "https://files.pythonhosted.org/packages/82/96/ef49135ce260db4ca4a12b119ed468449cd248db6b1468e2112b546d7a2e/markupsafe-3.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369", size = 23111, upload-time = "2026-10-02T23:06:22.524Z" }, + { url = "https://files.pythonhosted.org/packages/50/7d/83126e338bd88c17a220668235368ad719fd4638e426739858cbb8508f77/markupsafe-3.0.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19", size = 22403, upload-time = "2026-10-02T23:06:23.785Z" }, + { url = "https://files.pythonhosted.org/packages/83/dd/daf7e420de23c8206c365204e7b85e1251d8e19d34196a56336f316e5ed2/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e", size = 24083, upload-time = "2026-10-02T23:06:25.037Z" }, + { url = "https://files.pythonhosted.org/packages/19/3c/11eecdc06bc44ad5570350085b572ebf049e8f9a38d1ece6d76640b739cd/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811", size = 22931, upload-time = "2026-10-02T23:06:26.328Z" }, + { url = "https://files.pythonhosted.org/packages/0d/9e/ac0fd77f2a726e56ecc3ca0235d095feace1358d1b822406c2a2ef26a4dc/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea", size = 24299, upload-time = "2026-10-02T23:06:27.742Z" }, + { url = "https://files.pythonhosted.org/packages/d7/09/c6bd842ad58ff5b3bc76eeed7e9a42a6f11adc5d090ec697b72c9672731e/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916", size = 21948, upload-time = "2026-10-02T23:06:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/a3/46/82f586711fed61e86faa1ee1bc317d68cd45a10c8bdbe3f7d1fdf9026ad8/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741", size = 23150, upload-time = "2026-10-02T23:06:30.583Z" }, + { url = "https://files.pythonhosted.org/packages/19/2d/2dfdce99318abbfa26925195fbc17db188c46a1ec6457be121b6f9cfeb42/markupsafe-3.0.4-cp315-cp315-win32.whl", hash = "sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b", size = 14269, upload-time = "2026-10-02T23:06:31.949Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ec/6000fd82e8791e58fcd0456ec20f098957e2b03d5ed02eb73241a577c0ba/markupsafe-3.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214", size = 14496, upload-time = "2026-10-02T23:06:33.258Z" }, + { url = "https://files.pythonhosted.org/packages/bc/66/e73bd5016421d5d6e2fb6de7dd609f9de020942ac8c626526bd8c6eeaf82/markupsafe-3.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67", size = 14361, upload-time = "2026-10-02T23:06:34.539Z" }, + { url = "https://files.pythonhosted.org/packages/90/df/cb8c3dc98d313a951df2f8968f44e4cb5643df6d3cab749a530ce2f7d972/markupsafe-3.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad", size = 11760, upload-time = "2026-10-02T23:06:35.807Z" }, + { url = "https://files.pythonhosted.org/packages/d6/bb/4af9b3ca0753d654ac75f9531d5bd741bb77ca6e696f36807c475ffc099a/markupsafe-3.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99", size = 12108, upload-time = "2026-10-02T23:06:37.089Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d4/b56429313aee5fd59b079c3df5615299959e25e7113eb6d8caadbdd7d38a/markupsafe-3.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002", size = 25762, upload-time = "2026-10-02T23:06:38.419Z" }, + { url = "https://files.pythonhosted.org/packages/65/f5/34c181e891aa4f7d59c918584672e0c5eb7fffe76c1387d1246008bf4081/markupsafe-3.0.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e", size = 28400, upload-time = "2026-10-02T23:06:39.819Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b5/ad14694fd0ac9a5ce30bc6498f2999378f418583dd1679cca5a1b512957e/markupsafe-3.0.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c", size = 25946, upload-time = "2026-10-02T23:06:41.381Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a8/26b606445387d0ceb1eb1f21840094b84e4e3c3c3983d80d10b89823b490/markupsafe-3.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8", size = 23634, upload-time = "2026-10-02T23:06:42.748Z" }, + { url = "https://files.pythonhosted.org/packages/39/a2/b8814de672f1f0094d498bf646f2fec9d6356b503d28ef500b71c5095377/markupsafe-3.0.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe", size = 23488, upload-time = "2026-10-02T23:06:44.176Z" }, + { url = "https://files.pythonhosted.org/packages/db/c7/287223376fb73335a3cc5d6eb22c6ab01358cf33945a9c39c06b9dac3f4b/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2", size = 25037, upload-time = "2026-10-02T23:06:45.646Z" }, + { url = "https://files.pythonhosted.org/packages/f9/29/4df8355e313426d19e62ba33e0253c009ca12a0894ee77d67fa67255361c/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38", size = 23543, upload-time = "2026-10-02T23:06:47.264Z" }, + { url = "https://files.pythonhosted.org/packages/71/e5/8377731e8495668dcc768f645e717df18318c841edaf023a99395f6da9b4/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494", size = 25282, upload-time = "2026-10-02T23:06:48.795Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5f/373456e37ceb1478d657d6fe769cbe0a39f0a8dfc1548eeb19c471eefdd9/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d", size = 22993, upload-time = "2026-10-02T23:06:50.31Z" }, + { url = "https://files.pythonhosted.org/packages/d7/93/2cbd5628435afb6f541bbaced4bce0c2edac4b09a142e6e928b8b0da9858/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894", size = 23712, upload-time = "2026-10-02T23:06:51.759Z" }, + { url = "https://files.pythonhosted.org/packages/81/99/157e10966b033b363aeda5263e82596ee232a0b1d082fdbf90aa417ff083/markupsafe-3.0.4-cp315-cp315t-win32.whl", hash = "sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78", size = 14300, upload-time = "2026-10-02T23:06:53.241Z" }, + { url = "https://files.pythonhosted.org/packages/33/05/55884815414c9706a23deca150b72c25a62109e65b0b6ce232077802c719/markupsafe-3.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c", size = 14522, upload-time = "2026-10-02T23:06:54.729Z" }, + { url = "https://files.pythonhosted.org/packages/92/f9/ecbde7149e95b8a0f18e16d5d747f7dc06049d5da2e4f77f6f5e4a1f46a8/markupsafe-3.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba", size = 14417, upload-time = "2026-10-02T23:06:56.246Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.9" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "contourpy", version = "1.3.2", source = { registry = "https://pypi.org/simple" } }, + { name = "cycler" }, + { name = "fonttools", version = "4.65.0", source = { registry = "https://pypi.org/simple" } }, + { name = "kiwisolver" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyparsing" }, + { name = "python-dateutil", version = "3.0.0", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/63/1b/4be5be87d43d327a0cf4de1a56e86f7f84c89312452406cf122efe2839e6/matplotlib-3.10.9.tar.gz", hash = "sha256:fd66508e8c6877d98e586654b608a0456db8d7e8a546eb1e2600efd957302358", size = 34811233, upload-time = "2026-04-24T00:14:13.539Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/6f/340b04986e67aac6f66c5145ce68bf72c64bed30f92c8913499a6e6b8f99/matplotlib-3.10.9-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:77210dce9cb8153dffc967efaae990543392563d5a376d4dd8539bebcb0ed217", size = 8296625, upload-time = "2026-04-24T00:11:43.376Z" }, + { url = "https://files.pythonhosted.org/packages/bb/2f/127081eb83162053ebb9678ceac64220b93a663e0167432566e9c7c82aab/matplotlib-3.10.9-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1e7698ac9868428e84d2c967424803b2472ff7167d9d6590d4204ed775343c3b", size = 8188790, upload-time = "2026-04-24T00:11:46.556Z" }, + { url = "https://files.pythonhosted.org/packages/fc/b7/d8bcec2626c35f96972bff656299fef4578113ea6193c8fdad324710410c/matplotlib-3.10.9-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1aa972116abb4c9d201bf245620b433726cb6856f3bef6a78f776a00f5c92d37", size = 8769389, upload-time = "2026-04-24T00:11:48.959Z" }, + { url = "https://files.pythonhosted.org/packages/12/49/b78e214a527ea732033b7f4d37f7afb504d74ba9d134bd47938230dfb8b1/matplotlib-3.10.9-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae2f11957b27ce53497dd4d7b235c4d4f1faf383dfb39d0c5beb833bff883294", size = 9589657, upload-time = "2026-04-24T00:11:51.915Z" }, + { url = "https://files.pythonhosted.org/packages/5f/15/5246f7b43beae19c74dfee651d58d6cc8112e06f77adb4e88cc04f2e3a23/matplotlib-3.10.9-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b049278ddce116aaa1c1377ebf58adea909132dfce0281cf7e3a1ea9fc2e2c65", size = 9651983, upload-time = "2026-04-24T00:11:54.766Z" }, + { url = "https://files.pythonhosted.org/packages/75/77/5acecfe672ba0fa1b8c0454f69ce155d1e6fc5852fa7206bf9afaf767121/matplotlib-3.10.9-cp310-cp310-win_amd64.whl", hash = "sha256:82834c3c292d24d3a8aae77cd2d20019de69d692a34a970e4fdb8d33e2ea3dda", size = 8199701, upload-time = "2026-04-24T00:11:58.389Z" }, + { url = "https://files.pythonhosted.org/packages/4c/8c/290f021104741fea63769c31494f5324c0cd249bf536a65a4350767b1f22/matplotlib-3.10.9-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:68cfdcede415f7c8f5577b03303dd94526cdb6d11036cecdc205e08733b2d2bb", size = 8306860, upload-time = "2026-04-24T00:12:01.207Z" }, + { url = "https://files.pythonhosted.org/packages/51/18/325cd32ece1120d1da51cc4e4294c6580190699490183fc2fe8cb6d61ec5/matplotlib-3.10.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dfca0129678bd56379db26c52b5d77ed7de314c047492fbdc763aa7501710cfb", size = 8199254, upload-time = "2026-04-24T00:12:04.239Z" }, + { url = "https://files.pythonhosted.org/packages/79/db/e28c1b83e3680740aa78925f5fb2ae4d16207207419ad75ea9fe604f8676/matplotlib-3.10.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8e436d155fa8a3399dc62683f8f5d0e2e50d25d0144a73edd73f82eec8f4abfb", size = 8777092, upload-time = "2026-04-24T00:12:06.793Z" }, + { url = "https://files.pythonhosted.org/packages/55/fa/3ce7adfe9ba101748f465211660d9c6374c876b671bdb8c2bb6d347e8b94/matplotlib-3.10.9-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56fc0bd271b00025c6edfdc7c2dcd247372c8e1544971d62e1dc7c17367e8bf9", size = 9595691, upload-time = "2026-04-24T00:12:09.706Z" }, + { url = "https://files.pythonhosted.org/packages/36/c4/6960a76686ed668f2c60f84e9799ba4c0d56abdb36b1577b60c1d061d1ec/matplotlib-3.10.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5a6104ed666402ba5106d7f36e0e0cdca4e8d7fa4d39708ca88019e2835a2eb", size = 9659771, upload-time = "2026-04-24T00:12:12.766Z" }, + { url = "https://files.pythonhosted.org/packages/7e/0d/271aace3342157c64700c9ff4c59c7b392f3dbab393692e8db6fbe7ab96c/matplotlib-3.10.9-cp311-cp311-win_amd64.whl", hash = "sha256:d730e984eddf56974c3e72b6129c7ca462ac38dc624338f4b0b23eb23ecba00f", size = 8205112, upload-time = "2026-04-24T00:12:15.773Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ee/cb57ad4754f3e7b9174ce6ce66d9205fb827067e48a9f58ac09d7e7d6b77/matplotlib-3.10.9-cp311-cp311-win_arm64.whl", hash = "sha256:51bf0ddbdc598e060d46c16b5590708f81a1624cefbaaf62f6a81bf9285b8c80", size = 8132310, upload-time = "2026-04-24T00:12:18.645Z" }, + { url = "https://files.pythonhosted.org/packages/35/c6/5581e26c72233ebb2a2a6fed2d24fb7c66b4700120b813f51b0555acf0b6/matplotlib-3.10.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f0c3c28d9fbcc1fe7a03be236d73430cf6409c41fb2383a7ac52fe932b072cb1", size = 8319908, upload-time = "2026-04-24T00:12:21.323Z" }, + { url = "https://files.pythonhosted.org/packages/b7/18/4880dd762e40cd360c1bf06e890c5a97b997e91cb324602b1a19950ad5ce/matplotlib-3.10.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:41cb28c2bd769aa3e98322c6ab09854cbcc52ab69d2759d681bba3e327b2b320", size = 8216016, upload-time = "2026-04-24T00:12:23.4Z" }, + { url = "https://files.pythonhosted.org/packages/32/91/d024616abdba99e83120e07a20658976f6a343646710760c4a51df126029/matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ae20801130378b82d647ff5047c07316295b68dc054ca6b3c13519d0ea624285", size = 8789336, upload-time = "2026-04-24T00:12:26.096Z" }, + { url = "https://files.pythonhosted.org/packages/5c/04/030a2f61ef2158f5e4c259487a92ac877732499fb33d871585d89e03c42d/matplotlib-3.10.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c63ebcd8b4b169eb2f5c200552ae6b8be8999a005b6b507ed76fb8d7d674fe2", size = 9604602, upload-time = "2026-04-24T00:12:29.052Z" }, + { url = "https://files.pythonhosted.org/packages/fc/c2/541e4d09d87bb6b5830fc28b4c887a9a8cf4e1c6cee698a8c05552ae2003/matplotlib-3.10.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d75d11c949914165976c621b2324f9ef162af7ebf4b057ddf95dd1dba7e5edcf", size = 9670966, upload-time = "2026-04-24T00:12:32.131Z" }, + { url = "https://files.pythonhosted.org/packages/04/a1/4571fc46e7702de8d0c2dc54ad1b2f8e29328dea3ee90831181f7353d93c/matplotlib-3.10.9-cp312-cp312-win_amd64.whl", hash = "sha256:d091f9d758b34aaaaa6331d13574bf01891d903b3dec59bfff458ef7551de5d6", size = 8217462, upload-time = "2026-04-24T00:12:35.226Z" }, + { url = "https://files.pythonhosted.org/packages/4b/d0/2269edb12aa30c13c8bcc9382892e39943ce1d28aab4ec296e0381798e81/matplotlib-3.10.9-cp312-cp312-win_arm64.whl", hash = "sha256:10cc5ce06d10231c36f40e875f3c7e8050362a4ee8f0ee5d29a6b3277d57bb42", size = 8136688, upload-time = "2026-04-24T00:12:37.442Z" }, + { url = "https://files.pythonhosted.org/packages/aa/d3/8d4f6afbecb49fc04e060a57c0fce39ea51cc163a6bd87303ccd698e4fa6/matplotlib-3.10.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b580440f1ff81a0e34122051a3dfabb7e4b7f9e380629929bde0eff9af72165f", size = 8320331, upload-time = "2026-04-24T00:12:39.688Z" }, + { url = "https://files.pythonhosted.org/packages/63/d9/9e14bc7564bf92d5ffa801ae5fac819ce74b925dfb55e3ebde61a3bbad3e/matplotlib-3.10.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b1b745c489cd1a77a0dc1120a05dc87af9798faebc913601feb8c73d89bf2d1e", size = 8216461, upload-time = "2026-04-24T00:12:42.494Z" }, + { url = "https://files.pythonhosted.org/packages/8a/17/4402d0d14ccf1dfc70932600b68097fbbf9c898a4871d2cbbe79c7801a32/matplotlib-3.10.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8f3bcac1ca5ed000a6f4337d47ba67dfddf37ed6a46c15fd7f014997f7bf865f", size = 8790091, upload-time = "2026-04-24T00:12:44.789Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0b/322aeec06dd9b91411f92028b37d447342770a24392aa4813e317064dad5/matplotlib-3.10.9-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a8d66a55def891c33147ba3ba9bfcabf0b526a43764c818acbb4525e5ed0838", size = 9605027, upload-time = "2026-04-24T00:12:47.583Z" }, + { url = "https://files.pythonhosted.org/packages/74/88/5f13482f55e7b00bcfc09838b093c2456e1379978d2a146844aae05350ad/matplotlib-3.10.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d843374407c4017a6403b59c6c81606773d136f3259d5b6da3131bc814542cc2", size = 9671269, upload-time = "2026-04-24T00:12:50.878Z" }, + { url = "https://files.pythonhosted.org/packages/c5/e0/0840fd2f93da988ec660b8ad1984abe9f25d2aed22a5e394ff1c68c88307/matplotlib-3.10.9-cp313-cp313-win_amd64.whl", hash = "sha256:f4399f64b3e94cd500195490972ae1ee81170df1636fa15364d157d5bdd7b921", size = 8217588, upload-time = "2026-04-24T00:12:53.784Z" }, + { url = "https://files.pythonhosted.org/packages/47/b9/d706d06dd605c49b9f83a2aed8c13e3e5db70697d7a80b7e3d7915de6b17/matplotlib-3.10.9-cp313-cp313-win_arm64.whl", hash = "sha256:ba7b3b8ef09eab7df0e86e9ae086faa433efbfbdb46afcb3aa16aabf779469a8", size = 8136913, upload-time = "2026-04-24T00:12:56.501Z" }, + { url = "https://files.pythonhosted.org/packages/9b/45/6e32d96978264c8ca8c4b1010adb955a1a49cfaf314e212bbc8908f04a61/matplotlib-3.10.9-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:09218df8a93712bd6ea133e83a153c755448cf7868316c531cffcc43f69d1cc9", size = 8368019, upload-time = "2026-04-24T00:12:58.896Z" }, + { url = "https://files.pythonhosted.org/packages/86/0a/c8e3d3bba245f0f7fc424937f8ff7ef77291a36af3edb97ccd78aa93d84f/matplotlib-3.10.9-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:82368699727bfb7b0182e1aa13082e3c08e092fa1a25d3e1fd92405bff96f6d4", size = 8264645, upload-time = "2026-04-24T00:13:01.406Z" }, + { url = "https://files.pythonhosted.org/packages/3d/aa/5bf5a14fe4fed73a4209a155606f8096ff797aad89c6c35179026571133e/matplotlib-3.10.9-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3225f4e1edcb8c86c884ddf79ebe20ecd0a67d30188f279897554ccd8fded4dc", size = 8802194, upload-time = "2026-04-24T00:13:03.702Z" }, + { url = "https://files.pythonhosted.org/packages/dd/5e/b4be852d6bba6fd15893fadf91ff26ae49cb91aac789e95dde9d342e664f/matplotlib-3.10.9-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de2445a0c6690d21b7eb6ce071cebad6d40a2e9bdf10d039074a96ba19797b99", size = 9622684, upload-time = "2026-04-24T00:13:06.647Z" }, + { url = "https://files.pythonhosted.org/packages/4c/3d/ed428c971139112ef730f62770654d609467346d09d4b62617e1afd68a5a/matplotlib-3.10.9-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:b2b9516251cb89ff618d757daec0e2ed1bf21248013844a853d87ef85ab3081d", size = 9680790, upload-time = "2026-04-24T00:13:10.009Z" }, + { url = "https://files.pythonhosted.org/packages/e7/09/052e884aaf2b985c63cb79f715f1d5b6a3eaa7de78f6a52b9dbc077d5b53/matplotlib-3.10.9-cp313-cp313t-win_amd64.whl", hash = "sha256:e9fae004b941b23ff2edcf1567a857ed77bafc8086ffa258190462328434faf8", size = 8287571, upload-time = "2026-04-24T00:13:13.087Z" }, + { url = "https://files.pythonhosted.org/packages/f4/38/ae27288e788c35a4250491422f3db7750366fc8c97d6f36fbdecfc1f5518/matplotlib-3.10.9-cp313-cp313t-win_arm64.whl", hash = "sha256:6b63d9c7c769b88ab81e10dc86e4e0607cf56817b9f9e6cf24b2a5f1693b8e38", size = 8188292, upload-time = "2026-04-24T00:13:15.546Z" }, + { url = "https://files.pythonhosted.org/packages/d6/e6/3bd8afd04949f02eabc1c17115ea5255e19cacd4d06fc5abdde4eeb0052c/matplotlib-3.10.9-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:172db52c9e683f5d12eaf57f0f54834190e12581fe1cc2a19595a8f5acb4e77d", size = 8321276, upload-time = "2026-04-24T00:13:18.318Z" }, + { url = "https://files.pythonhosted.org/packages/41/86/86231232fff41c9f8e4a1a7d7a597d349a02527109c3af7d618366122139/matplotlib-3.10.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97e35e8d39ccc85859095e01a53847432ba9a53ddf7986f7a54a11b73d0e143f", size = 8218218, upload-time = "2026-04-24T00:13:20.974Z" }, + { url = "https://files.pythonhosted.org/packages/85/8f/becc9722cafc64f5d2eb0b7c1bf5f585271c618a45dbd8fabeb021f898b6/matplotlib-3.10.9-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aba1615dabe83188e19d4f75a253c6a08423e04c1425e64039f800050a69de6b", size = 9608145, upload-time = "2026-04-24T00:13:23.228Z" }, + { url = "https://files.pythonhosted.org/packages/32/5d/f7e914f7d9325abff4057cee62c0fa70263683189f774473cbfb534cd13b/matplotlib-3.10.9-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34cf8167e023ad956c15f36302911d5406bd99a9862c1a8499ea6f7c0e015dc2", size = 9885085, upload-time = "2026-04-24T00:13:25.849Z" }, + { url = "https://files.pythonhosted.org/packages/a5/fd/fa69f2221534e80cc5772ac2b7d222011a2acafc2ec7216d5dd174c864ae/matplotlib-3.10.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:59476c6d29d612b8e9bb6ce8c5b631be6ba8f9e3a2421f22a02b192c7dd28716", size = 9672358, upload-time = "2026-04-24T00:13:28.906Z" }, + { url = "https://files.pythonhosted.org/packages/ab/1a/5a4f747a8b271cbb024946d2dd3c913ab5032ba430626f8c3528ada96b4b/matplotlib-3.10.9-cp314-cp314-win_amd64.whl", hash = "sha256:336b9acc64d309063126edcdaca00db9373af3c476bb94388fe9c5a53ad13e6f", size = 8349970, upload-time = "2026-04-24T00:13:31.904Z" }, + { url = "https://files.pythonhosted.org/packages/64/dc/95d60ecaefe30680a154b52ea96ab4b0dab547f1fd6aa12f5fb655e89cae/matplotlib-3.10.9-cp314-cp314-win_arm64.whl", hash = "sha256:2dc9477819ffd78ad12a20df1d9d6a6bd4fec6aaa9072681465fddca052f1456", size = 8272785, upload-time = "2026-04-24T00:13:34.511Z" }, + { url = "https://files.pythonhosted.org/packages/70/a0/005d68bc8b8418300ce6591f18586910a8526806e2ab663933d9f20a41e9/matplotlib-3.10.9-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:da4e09638420548f31c354032a6250e473c68e5a4e96899b4844cf39ddea23fe", size = 8367999, upload-time = "2026-04-24T00:13:36.962Z" }, + { url = "https://files.pythonhosted.org/packages/22/05/1236cc9290be70b2498af20ca348add76e3fffe7f67b477db5133a84f3ea/matplotlib-3.10.9-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:345f6f68ecc8da0ca56fad2ea08fde1a115eda530079eca185d50a7bc3e146c6", size = 8264543, upload-time = "2026-04-24T00:13:39.851Z" }, + { url = "https://files.pythonhosted.org/packages/cd/c2/071f5a5ff6c5bd63aaaf2f45c811d9bf2ced94bde188d9e1a519e21d0cba/matplotlib-3.10.9-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4edcfbd8565339aa62f1cd4012f7180926fdbe71850f7b0d3c379c175cd6b66c", size = 9622800, upload-time = "2026-04-24T00:13:42.296Z" }, + { url = "https://files.pythonhosted.org/packages/95/57/da7d1f10a85624b9e7db68e069dd94e58dc41dbf9463c5921632ecbe3661/matplotlib-3.10.9-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6be157fe17fc37cb95ac1d7374cf717ce9259616edec911a78d9d26dae8522d4", size = 9888561, upload-time = "2026-04-24T00:13:45.026Z" }, + { url = "https://files.pythonhosted.org/packages/67/b2/ef8d6bb59b0edb6c16c968b70f548aa13b54348972def5aa6ac85df67145/matplotlib-3.10.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4e42042d54db34fda4e95a7bd3e5789c2a995d2dad3eb8850232ee534092fbbf", size = 9680884, upload-time = "2026-04-24T00:13:48.066Z" }, + { url = "https://files.pythonhosted.org/packages/61/1c/d21bfeb9931881ebe96bcfcff27c7ae4b160ae0ec291a714c42641a56d75/matplotlib-3.10.9-cp314-cp314t-win_amd64.whl", hash = "sha256:c27df8b3848f32a83d1767566595e43cfaa4460380974da06f4279a7ec143c39", size = 8432333, upload-time = "2026-04-24T00:13:51.008Z" }, + { url = "https://files.pythonhosted.org/packages/78/23/92493c3e6e1b635ccfff146f7b99e674808787915420373ac399283764c2/matplotlib-3.10.9-cp314-cp314t-win_arm64.whl", hash = "sha256:a49f1eadc84ca85fd72fa4e89e70e61bf86452df6f971af04b12c60761a0772c", size = 8324785, upload-time = "2026-04-24T00:13:53.633Z" }, + { url = "https://files.pythonhosted.org/packages/2c/2b/0e92ad0ac446633f928a1563db4aa8add407e1924faf0ded5b95b35afb27/matplotlib-3.10.9-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:1872fb212a05b729e649754a72d5da61d03e0554d76e80303b6f83d1d2c0552b", size = 8293058, upload-time = "2026-04-24T00:13:56.339Z" }, + { url = "https://files.pythonhosted.org/packages/4b/23/74682fd369f5299ceda438fea2a0662e6383b85c9383fb9cdfcf04713e07/matplotlib-3.10.9-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:985f2238880e2e69093f588f5fe2e46771747febf0649f3cf7f7b7480875317f", size = 8186627, upload-time = "2026-04-24T00:13:58.623Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e8/368aab88f3c4cd8992800f31abfe0670c3e47540ba20a97e9fdbcde594b3/matplotlib-3.10.9-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6640f75af2c6148293caa0a2b39dd806a492dd66c8a8b04035813e33d0fd2585", size = 8764117, upload-time = "2026-04-24T00:14:01.684Z" }, + { url = "https://files.pythonhosted.org/packages/63/e2/9f66ca6a651a52abfe0d4964ce01439ed34f3f1e119de10ff3a07f403043/matplotlib-3.10.9-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:42fb814efabe95c06c1994d8ab5a8385f43a249e23badd3ba931d4308e5bca20", size = 8304420, upload-time = "2026-04-24T00:14:04.57Z" }, + { url = "https://files.pythonhosted.org/packages/e8/e8/467c03568218792906aa87b5e7bb379b605e056ed0c74fe00c051786d925/matplotlib-3.10.9-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:f76e640a5268850bfda54b5131b1b1941cc685e42c5fa98ed9f2d64038308cba", size = 8197981, upload-time = "2026-04-24T00:14:07.233Z" }, + { url = "https://files.pythonhosted.org/packages/6f/87/afead29192170917537934c6aff4b008c805fff7b1ccea0c79120d96beda/matplotlib-3.10.9-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3fc0364dfbe1d07f6d15c5ebd0c5bf89e126916e5a8667dd4a7a6e84c36653d4", size = 8774002, upload-time = "2026-04-24T00:14:09.816Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.11.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "contourpy", version = "1.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "contourpy", version = "1.4.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "cycler" }, + { name = "fonttools", version = "4.69.1", source = { registry = "https://pypi.org/simple" } }, + { name = "kiwisolver" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyparsing" }, + { name = "python-dateutil", version = "4.0.0", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/a9/a7fc5a63c427aeb9a4b99d6a0449f891be0952d3aee2b85229099f7b9f54/matplotlib-3.11.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:5e1e923a3fc3326b99ec0a6ff1ab1338ac6c6cc62ad9d8a9c944197c7f8c6221", size = 9461046, upload-time = "2026-09-11T19:02:59.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d7/59d8ee63e4dee845d953515c50d67e6b8cefa953b453c6b803f197ae556e/matplotlib-3.11.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c27e577ece613ea12a0790e00b4eb80d901c59a3e16cad474f31d8b1529690b9", size = 9290872, upload-time = "2026-09-11T19:03:02.295Z" }, + { url = "https://files.pythonhosted.org/packages/2e/a4/1ca765c63a60e3096ae2ad132eb25f6f7eab0377418cd0472808befd9665/matplotlib-3.11.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:07d9b9fa60cd4c393692f50d0bb03123242ddf61c99bb0e95e75feb354e7c1a8", size = 9854405, upload-time = "2026-09-11T19:03:04.796Z" }, + { url = "https://files.pythonhosted.org/packages/d7/3d/f28ca971a4ad0ed83ebdd60230b09d99de8b91aba47964fac3a81eb2e2ba/matplotlib-3.11.2-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:30ec15d7eefee71de16b7c689b42ba49715a4644650b76a6c7c70d79daf24e91", size = 10660507, upload-time = "2026-09-11T19:03:07.402Z" }, + { url = "https://files.pythonhosted.org/packages/f7/0c/a743556bc64a9b57d2246b14d91b713078adfd2df4199f542df1861737a9/matplotlib-3.11.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:116cdb0eb0eb5644fc98eb2975d4b4dd4ad35e5c8e6b851c22e6976f371f7ab5", size = 10801141, upload-time = "2026-09-11T19:03:11.357Z" }, + { url = "https://files.pythonhosted.org/packages/66/54/91fe3fdfa29100b4668cbf9721577a10acde6e009694618230e4e7a97527/matplotlib-3.11.2-cp311-cp311-win_amd64.whl", hash = "sha256:a24d5fd36e4f0e742c3851dcd20810e56a95633a342e4bf6cb591c678e8fe61f", size = 9329982, upload-time = "2026-09-11T19:03:14.25Z" }, + { url = "https://files.pythonhosted.org/packages/49/c1/13b70871c98d7e93f0d2ed71f226b8d6f873f1372124046068a6b4902fb5/matplotlib-3.11.2-cp311-cp311-win_arm64.whl", hash = "sha256:57b9ea60a835937c2012861923cbb91f47db8565775d326d1c42fc926aa10351", size = 9023542, upload-time = "2026-09-11T19:03:16.878Z" }, + { url = "https://files.pythonhosted.org/packages/cb/ce/1bfcc4873b121597791ad74032943b123218c0613af0b97e8dd05e916fb1/matplotlib-3.11.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef752769cd962f39ea0b6ffc82d1ea43a0012c5a6157c7a075212fa509cfcff2", size = 9476466, upload-time = "2026-09-11T19:03:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c4/7f5f3601ee69baf072c0c7d3ce60c03e0618621c5a56c34a62a460e29d11/matplotlib-3.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ef31985c4dedb5f1424e1aec6849a47dd37689cb7fa3c20b1b82187f26806261", size = 9305583, upload-time = "2026-09-11T19:03:22.39Z" }, + { url = "https://files.pythonhosted.org/packages/b8/90/2b3fd67ee273163faeda6d514be70b5596eaa0fd77b60ffc294ad0b34f5f/matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27", size = 9860353, upload-time = "2026-09-11T19:03:25.049Z" }, + { url = "https://files.pythonhosted.org/packages/f4/84/32549e7a462dc311aed2ab62e5d2538028840b5c53a8be0195c789937c3d/matplotlib-3.11.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b9a7ad579856284135e401ecc918c5f8a017ee30539298862a109f51b971710", size = 10670348, upload-time = "2026-09-11T19:03:28.108Z" }, + { url = "https://files.pythonhosted.org/packages/84/39/02e21b74f7439bd643d717ea846006d46e309e6d29b632b57751265311d6/matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2", size = 10810580, upload-time = "2026-09-11T19:03:31.402Z" }, + { url = "https://files.pythonhosted.org/packages/04/93/0d239bde12b308262265c2d98909b2f0ecad2b5deeae96241642e822e9c7/matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43", size = 9349409, upload-time = "2026-09-11T19:03:34.195Z" }, + { url = "https://files.pythonhosted.org/packages/49/a8/06baf901c02246c8a222b655cc4540ef9c15e1549a04e07927f9cde716c3/matplotlib-3.11.2-cp312-cp312-win_arm64.whl", hash = "sha256:643ff850d8e0f5b8319337f87ed3cb59506afb3df3cc48de777d85871233be7b", size = 9028084, upload-time = "2026-09-11T19:03:37.032Z" }, + { url = "https://files.pythonhosted.org/packages/bf/ce/fc58855a3d17f6cb8a87b6f9ccd100f65432a3a7ffed57309cbf14c78987/matplotlib-3.11.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7d43ff8cebb50840648cb6429b2228621dbd709010f3117b3740abb20abf21c0", size = 9476987, upload-time = "2026-09-11T19:03:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/a9/29/2a47b700545aca050e0ed73c89ba21e08407e11f5f42a567421b220de6c1/matplotlib-3.11.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2a8285cea8ef4d92aa041d1c33788bcae82248503300f93f1ca2136b9049452f", size = 9306050, upload-time = "2026-09-11T19:03:43.103Z" }, + { url = "https://files.pythonhosted.org/packages/a9/df/e7c10292f348cf55178a5b3c0092a38ea68891a3945f199ae8b7b8ac9dc1/matplotlib-3.11.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1944895967f87c84c9b4bad29a707b31f5b36df4a3a2339ea1f8ea3ce5105539", size = 9861060, upload-time = "2026-09-11T19:03:46.044Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b9/b978de6d43d47f1d4d8e653fac32c16d8d2e5f46bbbb822e26d7cb1adece/matplotlib-3.11.2-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af2661f6ac6bbd1d081996f54fdd9385715c625ace8cec0869055c0cfbf38981", size = 10670885, upload-time = "2026-09-11T19:03:48.942Z" }, + { url = "https://files.pythonhosted.org/packages/a3/80/d72f61bb2631ac15d17fada1f17e0f99fecba69d8376d34f17cf93b7eddd/matplotlib-3.11.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e5a90f8a707ebb6004a713b1cff091a40cc5df4c7c1cb165e5a505ebc11c292", size = 10811222, upload-time = "2026-09-11T19:03:51.665Z" }, + { url = "https://files.pythonhosted.org/packages/94/2e/6d1d33f242c705b5c6c6fb3f0fc141add51cb1abb62912e59de0835d28c4/matplotlib-3.11.2-cp313-cp313-win_amd64.whl", hash = "sha256:bc067c462a86f0e57bf52fc6e058d90171a5420007dac00c46e90153050c69a7", size = 9349539, upload-time = "2026-09-11T19:03:54.534Z" }, + { url = "https://files.pythonhosted.org/packages/bb/bb/c0aa86a7f4c0e62f1c3c0711e361f6f23f87eb9018732a5e11994bd1b7ec/matplotlib-3.11.2-cp313-cp313-win_arm64.whl", hash = "sha256:3e8576f7c47e02fd4f21f44171302d2d1d58d4471d46da3d71fe8899d19539d9", size = 9028295, upload-time = "2026-09-11T19:03:57.261Z" }, + { url = "https://files.pythonhosted.org/packages/54/b4/4facdb700bc236e4c676495ca3798d8134ab8668cbfe0f6b2e9ebf962a38/matplotlib-3.11.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c9721f81275499da1feeb36a2cf8192ea086283b3bd16b7dc4c9d7aedb7396d6", size = 9478976, upload-time = "2026-09-11T19:04:00.12Z" }, + { url = "https://files.pythonhosted.org/packages/4c/a0/bba05f0a25bfeb0475c2f2a87958b31103aa6b7a5386017afb1a96212825/matplotlib-3.11.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a3040b209f3968b4e84161df7b174f07a9fad33b0f2d7e48ea3bbd3075e2863", size = 9307932, upload-time = "2026-09-11T19:04:02.976Z" }, + { url = "https://files.pythonhosted.org/packages/d4/42/81d5cba4bb39b41b0998efc880e129f2d7cdb94256ca49678fdcd9c21be5/matplotlib-3.11.2-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf3fe71fbfb8ec0e310e0bc8537c3405a01f38f25f9394ed2135e6202fed542b", size = 10674370, upload-time = "2026-09-11T19:04:06.912Z" }, + { url = "https://files.pythonhosted.org/packages/29/5e/52f56f93d5b20815ee0ae352f7a38eff25580edb180b4fa7df87cfeba68f/matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8c8255de28f986d935a64c9ca71c0ec2d2f41d355691f5ea684725dc91413f71", size = 10954597, upload-time = "2026-09-11T19:04:09.948Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ae/f8918a1b564db49c53cd603eb3c8748c5767e4ce0fb2cf1d7c38653e4c5d/matplotlib-3.11.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a8756cc73d9af9a7fe0deb54ea2e75ef73b01d9e575877e72acad5458e660943", size = 10812583, upload-time = "2026-09-11T19:04:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/ea/61/4315ef0d63937fe56f451887b4a0be3b8e8b22cf1d92a8d157caac54570d/matplotlib-3.11.2-cp314-cp314-win_amd64.whl", hash = "sha256:ecea603dd2fbf8242fd31a305a8b12a4ece2de28096870c65fdd0d1e35b8d9a6", size = 9505972, upload-time = "2026-09-11T19:04:15.788Z" }, + { url = "https://files.pythonhosted.org/packages/d5/00/02398b0a1a62ef73d9af0a957fe1773363eec9a6ca7e433c72ae2790fbce/matplotlib-3.11.2-cp314-cp314-win_arm64.whl", hash = "sha256:01dc8eaaab5a9fce9ff615eca82345728f289e4715b186ee10c6d85272fc26bb", size = 9184534, upload-time = "2026-09-11T19:04:18.691Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c5/1e6ca10baa7e04f113c37856aadb4adc3dbb1c55fc7da6dc830bba1292d7/matplotlib-3.11.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79a258f58253dfa025af80a9e9bb228d75fced007f0e93ae7423fefbde81a74d", size = 9526415, upload-time = "2026-09-11T19:04:21.39Z" }, + { url = "https://files.pythonhosted.org/packages/e0/93/7561727af07ccc84747953c6a33eee3981cc436d04f465032e707ca0e429/matplotlib-3.11.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c0b83f044ce10a98027b105b3931548719a6e8c7ef986b4362651e0b5367c8dc", size = 9361064, upload-time = "2026-09-11T19:04:24.107Z" }, + { url = "https://files.pythonhosted.org/packages/c1/40/ce270ef2a6794d94a409fe28b8dabedffc07c07f9e5dbb89e0f605bd157d/matplotlib-3.11.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e43b188f0a5b75447bcc197728258166aa64365770ed1caa36595a5e1ca4bbba", size = 10684626, upload-time = "2026-09-11T19:04:27.201Z" }, + { url = "https://files.pythonhosted.org/packages/45/46/396e0307dbf1c1f2d0a3654caa6dbc780dd5379f5f11257369cf8d21d9fe/matplotlib-3.11.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3304eb5a59442a8867f6920d484591c0fa09ffc29e9260be2feec3351e25869", size = 10960602, upload-time = "2026-09-11T19:04:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1c/97/4defb84695477340aa88b27c9482cc1ca4de11f36f66b6c8c0ddd685def1/matplotlib-3.11.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:02329432ae5c6af87cf208ee575b701d698bdf0b1a3bb28cc6d53c36e967e575", size = 10822603, upload-time = "2026-09-11T19:04:32.964Z" }, + { url = "https://files.pythonhosted.org/packages/7d/e7/eab54551c1ec6b72dcd678a078b6c6da8d4c85ec1ff0016e81fe52866304/matplotlib-3.11.2-cp314-cp314t-win_amd64.whl", hash = "sha256:f2ac30cf5eb5dff1b584627ae0b0e1186551a4f69ae3c75073911da497a29170", size = 9551206, upload-time = "2026-09-11T19:04:35.811Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/04698032cb4d8fb1e30d8ffec5ded20f6f582b03c8c58b2385c95245f158/matplotlib-3.11.2-cp314-cp314t-win_arm64.whl", hash = "sha256:cf41ecd1b0c0b6f7177ed965a54c2afbe888715c7cf6054dc12d53bc1494002c", size = 9234977, upload-time = "2026-09-11T19:04:38.972Z" }, + { url = "https://files.pythonhosted.org/packages/44/a9/ca827c184b87364378964e36e7c0ae23651d146fdbc4000635205490cf82/matplotlib-3.11.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:894a9cbbecbe30ae6787d464df2e8fc7a8d475cfc68f87c3029f7c11152899b3", size = 9478997, upload-time = "2026-09-11T19:04:41.914Z" }, + { url = "https://files.pythonhosted.org/packages/48/60/01aaafc9c3159f3fae9a65bbcddaa4a6d4d72b0aeffdd636d7f6d00a5c8d/matplotlib-3.11.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:bbf1062991d826ed27e2144f3afa4461afbb8ff56e8f703043e191a8163b1ee9", size = 9307947, upload-time = "2026-09-11T19:04:44.834Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a0/6aa72c7cd7cf4dfac652744d7a3310007cec3ce8e5ab9be607bec7096471/matplotlib-3.11.2-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:399fef672f7046ef7d6a57572b2a6f9845f3f5afcff04e7b2df7a363a9f42190", size = 10674370, upload-time = "2026-09-11T19:04:47.745Z" }, + { url = "https://files.pythonhosted.org/packages/a1/97/d7e90225ac145046787a2ee0fa4cdc7e4d5cb6772ea232130b10f8a4095a/matplotlib-3.11.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc82dde2a0d3e3ad472edce04897ad7146b8d8bfd1df8a32992eebb81af18fdc", size = 10954581, upload-time = "2026-09-11T19:04:50.712Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/89cf056a9d2cae01f4b8baf01c7e809d613244fcdfa2a2acf28c1e0d79fa/matplotlib-3.11.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:930efb28f59fda124e39265d177bab302625297bb147d2910de725a2fc2aef54", size = 10812605, upload-time = "2026-09-11T19:04:53.552Z" }, + { url = "https://files.pythonhosted.org/packages/9d/4d/c61b9f4c34af802d4d84e58803e009013d626b5f468bafe1416131863b5b/matplotlib-3.11.2-cp315-cp315-win_amd64.whl", hash = "sha256:3da3bc0cbf7245e7db72cc6d29d12c5abef72cb73059c73b945f14e3545f3eb2", size = 9506068, upload-time = "2026-09-11T19:04:56.519Z" }, + { url = "https://files.pythonhosted.org/packages/03/7b/047f2fa8708d47430d8e7fa45e9fffb0aee5d4e300f978e087be2ee11fbc/matplotlib-3.11.2-cp315-cp315-win_arm64.whl", hash = "sha256:f25446b2981717dca9786bac841cb3fd7efb568e3e3c755dd980481c5cb9228d", size = 9184576, upload-time = "2026-09-11T19:04:59.318Z" }, + { url = "https://files.pythonhosted.org/packages/03/6e/ad9c5989950785a98642667df265a47c6637e924cb69b5dcf68c3299ae7c/matplotlib-3.11.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:fea03cf56568cc1cba08b470be6a0559e71c3a5b688d54b7179bb35ba23d0821", size = 9525988, upload-time = "2026-09-11T19:05:02.304Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c3/25c61701fb655dd412428b15eee2591ce554cdd593e39a045a153373f428/matplotlib-3.11.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:254d4ddb2fa8df3b4c689c0c306063aee10521df82cfb438185e499c75fe37c1", size = 9360774, upload-time = "2026-09-11T19:05:05.092Z" }, + { url = "https://files.pythonhosted.org/packages/58/5a/4552878fce8f9d249a5e264c16f5c267c27eac08fb039fa3e207a06feff5/matplotlib-3.11.2-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e60cf3047a51edecdc4535a9196bbd6a732936b8e9f8184aabf4d16165884aaf", size = 10685892, upload-time = "2026-09-11T19:05:07.686Z" }, + { url = "https://files.pythonhosted.org/packages/af/dd/b3b19ec0124fc4aafd8a4b3bae859c562a7ff0fd8ae3b2099947f78bde19/matplotlib-3.11.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eb3712dc9b464793de0a4e42a7313d50293c751f94bddaf7332a1bc71bccdda9", size = 10964946, upload-time = "2026-09-11T19:05:10.943Z" }, + { url = "https://files.pythonhosted.org/packages/7b/30/687ccce22f66a57fed85942450e88062773bcbf1a42914e70c7148ec71dc/matplotlib-3.11.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:75b6d88402770e181b5d06a67dda4129c31da7d05004d63a21c310ec78d1b83c", size = 10824960, upload-time = "2026-09-11T19:05:13.9Z" }, + { url = "https://files.pythonhosted.org/packages/d3/34/117fe35a8d05054b4b34d2d29287099927c24c3841d36e06d9fa2f20c1cf/matplotlib-3.11.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a6939df7567114b6bac7f4c5e06c84a67f197c1b2f2e4b234d4eecb3bfec9482", size = 9551204, upload-time = "2026-09-11T19:05:16.48Z" }, + { url = "https://files.pythonhosted.org/packages/63/5a/9f440e7bec8b80d0af2a65d1165b2f4e718982dad785531f62255d9ff19b/matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff", size = 9233946, upload-time = "2026-09-11T19:05:19.063Z" }, + { url = "https://files.pythonhosted.org/packages/0f/d9/a1218a31fa2d8082eb893548990ad09a2005ebda1b2b89dad88a8308e51a/matplotlib-3.11.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:854df8d7dfe9fdffcbaa6f39e44a6c24b409cb4d7561fbc09213b157d833f6a6", size = 9457702, upload-time = "2026-09-11T19:05:22.086Z" }, + { url = "https://files.pythonhosted.org/packages/68/d7/a9fde05d87c3c853f233ec20c5b5c3a1c86035e1ed4bfa397cd54d46ec90/matplotlib-3.11.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:eac4b07d4e3743b172451e122ea964f72f152879d4f9adcf3f3d33e518f12ead", size = 9287753, upload-time = "2026-09-11T19:05:24.677Z" }, + { url = "https://files.pythonhosted.org/packages/ec/79/ea2ae4eab84f011c1dc8145864f78e5a63adda8efb95557ef36cc38e6da2/matplotlib-3.11.2-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ef7a53b66780e5d942923724f08577fbc5be1f7322da0f0f3f9dcaa45dd803d", size = 9848259, upload-time = "2026-09-11T19:05:27.455Z" }, +] + +[[package]] +name = "matplotlib-inline" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, +] + +[[package]] +name = "matplotlib-scalebar" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "matplotlib", version = "3.10.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "matplotlib", version = "3.11.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c5/3d/e76e0e48c96e43b656446c35990824f20136de21940a7436020ab757a54d/matplotlib_scalebar-0.9.0.tar.gz", hash = "sha256:f91adc5e4e67ac920a8fa98a55f904d56e5c2da4d56286748c31ec62146362be", size = 1180588, upload-time = "2025-01-17T22:10:59.349Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a8/c0/2dfab7b319dabe23f5a7b515a797c74b501d15c72e7a03837cf0cf779b9e/matplotlib_scalebar-0.9.0-py3-none-any.whl", hash = "sha256:5140525cd4e0c60bcade541b86571dabaf446fa69192530bd82d60b54601aa79", size = 16411, upload-time = "2025-01-17T22:10:57.319Z" }, +] + +[[package]] +name = "mccabe" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/ff/0ffefdcac38932a54d2b5eed4e0ba8a408f215002cd178ad1df0f2806ff8/mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325", size = 9658, upload-time = "2022-01-24T01:14:51.113Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/1a/1f68f9ba0c207934b35b86a8ca3aad8395a3d6dd7921c0686e23853ff5a9/mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e", size = 7350, upload-time = "2022-01-24T01:14:49.62Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "msgspec" +version = "0.23.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/72/c9d89595763e54800d2c136efadfb65c8ae789bc85b8a0c890358f967667/msgspec-0.23.0.tar.gz", hash = "sha256:a0d57d3ca7734542eb6861e72d974ab051e6cf73ea6b01b263f77170593362be", size = 378550, upload-time = "2026-11-28T19:29:08.14Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/ae/001e3cba00c70ceeaa4239ae5836e002e545996b1fe6cb3862ae7a65e5cf/msgspec-0.23.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:192057d796ee16b245032e80e72e6cf4cc715e14701867aea2bea858f5d88a53", size = 207220, upload-time = "2026-11-28T19:27:19.487Z" }, + { url = "https://files.pythonhosted.org/packages/5e/b9/df5cda06fd1bf4913871922181723dabc9b0ef140b1f93f001fe53dc1864/msgspec-0.23.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:675e2f5c31eb032d4f32eccc3c75741e0349894226c604e8351f7114332b6726", size = 198670, upload-time = "2026-11-28T19:27:21.437Z" }, + { url = "https://files.pythonhosted.org/packages/61/4d/c815ad6b70341fe6c1b81226aa70b57af2ca38d3f080bda0d811ff8b5f65/msgspec-0.23.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45dc8e7024e7e4c67a03fb0880f60c816070d079edf7117bfc5086f6faf676d8", size = 229573, upload-time = "2026-11-28T19:27:22.7Z" }, + { url = "https://files.pythonhosted.org/packages/31/d1/dc3892e855d222abfb17dd65b2db81f59846d371fab1b6b069bf15deeb8d/msgspec-0.23.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b878940013f711c187d346ad931e457bab39d416c33939bc24e22383c9bbfdd", size = 234722, upload-time = "2026-11-28T19:27:24.223Z" }, + { url = "https://files.pythonhosted.org/packages/1d/8f/ece8e42d00b6282593c9353d27f936014657068e230900aba77fe7ffeb1f/msgspec-0.23.0-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c4df43386061dc2898fea9ad52120dabd60e4a14b1e9c7233037e9e289cb0dd9", size = 242688, upload-time = "2026-11-28T19:27:25.914Z" }, + { url = "https://files.pythonhosted.org/packages/12/68/a66df6ea29be70a60eb70c5c70ed75758bb69f7b252e02e2e085714f0653/msgspec-0.23.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:205ba19b98a273247068239ba6444967269f8f4a0537c2c51dd344a6b5dfc153", size = 234239, upload-time = "2026-11-28T19:27:27.176Z" }, + { url = "https://files.pythonhosted.org/packages/7a/ff/4254880dbd2273f1826f861cc9b865601b888699941cc064c03c328736c1/msgspec-0.23.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:b0ac263559e5d4833a1b4a201c85cf5fc5bde714ad7d999d37dee8995e8d7ce5", size = 242472, upload-time = "2026-11-28T19:27:28.45Z" }, + { url = "https://files.pythonhosted.org/packages/30/14/aeee88b5daba05bac57e285c95f20d1fd8a7b8a5843983a1d527ad85df00/msgspec-0.23.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:dc13f7ef9f5d80d672e9ed7aa97c787876416c1212a650a2d9ccd10bd2e9d36f", size = 237534, upload-time = "2026-11-28T19:27:29.741Z" }, + { url = "https://files.pythonhosted.org/packages/83/7c/70d3283e717acbe3ac43e2dcbee06b998e9f1387e308dcd730c685bdbab4/msgspec-0.23.0-cp310-cp310-win_amd64.whl", hash = "sha256:d082a79e0b86639b70b9553694800d6bf23a6690466195ccf65ba9941eb7e1bd", size = 198052, upload-time = "2026-11-28T19:27:30.938Z" }, + { url = "https://files.pythonhosted.org/packages/d1/ab/4b5630c206198cd445747aa561e09893a3f5b2c8082130b71b00c9dce99c/msgspec-0.23.0-cp310-cp310-win_arm64.whl", hash = "sha256:c44574aefa468eb67c63f470452769d9fa6f132570b7a20e794d8000fd97f0eb", size = 193296, upload-time = "2026-11-28T19:27:32.25Z" }, + { url = "https://files.pythonhosted.org/packages/6e/24/268907b971bda07f6e8f9b4f269fb547e5116138c7d055a3031048cd55ec/msgspec-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8546e43bc64c604a9ec8b64d636429f6bb400eab1f9f746f5f3902727650037b", size = 205258, upload-time = "2026-11-28T19:27:33.529Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9e/ee945746966e04dfd45a43dbf0ed09832138b63e8e90c3c7f59955ada7e6/msgspec-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:68adebfc001bb6bafbbfade8d922691e13ac654293435b5e61f1cb38218a1636", size = 196849, upload-time = "2026-11-28T19:27:34.821Z" }, + { url = "https://files.pythonhosted.org/packages/94/ed/96778b68d3609ff05486599e9da166dae5153a51c2e1cd7f0d6ff9b3fd9e/msgspec-0.23.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ce60801cf7c8368819ca755deec31a0da02137544dc5d3ab065aac5e59e7cdb", size = 227482, upload-time = "2026-11-28T19:27:36.167Z" }, + { url = "https://files.pythonhosted.org/packages/5c/79/7844827ee0c6e6bc0bf5546b3b9aa30f0352a2fcc00161ac4285c5a36d5c/msgspec-0.23.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e514e5b2a23e376f545f4962834b7312d9400705627c53330116b46daddfbe3", size = 232334, upload-time = "2026-11-28T19:27:37.509Z" }, + { url = "https://files.pythonhosted.org/packages/25/eb/be7659eb2d1efebdc9e4311dc3e1dac4304385f12cab1d507037ae8847ec/msgspec-0.23.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:45618388dc353565da759be1349f6d8c2d0649954fbf51901662a91b1c8d8a73", size = 240555, upload-time = "2026-11-28T19:27:38.8Z" }, + { url = "https://files.pythonhosted.org/packages/a3/64/4b8906a35c804c91094e2ae3a9fdf6b5063730d187c67c47f344299900a2/msgspec-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:64b4aa9412783913de79a81d12c4aaa0534acd2f17b79dee06d69983389734b9", size = 232253, upload-time = "2026-11-28T19:27:40.053Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ef/3d822357ec06401a9ca90bbb7c61a34ebb3fc7e65e462035ba910115f256/msgspec-0.23.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:b3b00a73f7171edca6118a1375fae8e11636abac67a5dc5e58368f4a8b3b5319", size = 239982, upload-time = "2026-11-28T19:27:41.368Z" }, + { url = "https://files.pythonhosted.org/packages/9b/6a/31d1bb14bacd5659a95c8ad9df5d92706741005f6466ce56a2da64dfbaa7/msgspec-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:46fe4b44555a8a69e5edce0cc44842ee3364b82292cfba291f38bf22ec527fa2", size = 235377, upload-time = "2026-11-28T19:27:42.565Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e5/53d97827886cf835841e6ab2af4eb61d2b7e9a328c211726e760691af7a4/msgspec-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:3f7373410e34db4d186c2a2d8dbe384e059fcad824febabf983c0cd69eaf1f50", size = 198498, upload-time = "2026-11-28T19:27:43.908Z" }, + { url = "https://files.pythonhosted.org/packages/20/27/d7637f630708d7db12ac9068a6ba6453fdbad21b43e52048282a8951d67d/msgspec-0.23.0-cp311-cp311-win_arm64.whl", hash = "sha256:62508294938b64f9dda1663ca18ef16f214e963d281d8d3499fbeb668ad9cd79", size = 194409, upload-time = "2026-11-28T19:27:45.16Z" }, + { url = "https://files.pythonhosted.org/packages/f7/b3/31a7ec58265f9524d964bc5887686f18655f1cf1bf327dff49ff4da140da/msgspec-0.23.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1e96cf442c0c1072cb5f87c9fd061e234ce0faec9d143f849c9e53c96cab69ed", size = 207894, upload-time = "2026-11-28T19:27:46.406Z" }, + { url = "https://files.pythonhosted.org/packages/4f/5f/c468e0b508e0c09ecd61a7aca74edb9302b7482899d8aeb087eec222baca/msgspec-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a58acc6bcb5b528ea400fbd2b362f8a58cd306564636454debf8af029c90f8fb", size = 199553, upload-time = "2026-11-28T19:27:47.653Z" }, + { url = "https://files.pythonhosted.org/packages/7c/51/5389b9be05ce3cf139743ba1d10af3a7bae4917bfcb40a2bae90a0a23b57/msgspec-0.23.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:000abdb9da8b56f53ec2980ed182f00765df4ab07a093785fe9ce5273aa8d4d6", size = 230676, upload-time = "2026-11-28T19:27:48.944Z" }, + { url = "https://files.pythonhosted.org/packages/59/7a/910a8ff19a5e759f6775eb9efc3b27c509d8c3705f142ab18b9ef3ae0c48/msgspec-0.23.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c08f294663135183bd633efd843645687285a445054a876c37506d4e9de7d80b", size = 236624, upload-time = "2026-11-28T19:27:50.272Z" }, + { url = "https://files.pythonhosted.org/packages/c8/0a/5266ede27a6affeb8f1464cf482c3b2476ef8f52803b7095d6b0d37b35c0/msgspec-0.23.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:62887038958440092a165d4541220c3c637c43afb9c038c0c23a7afedb86cca1", size = 243124, upload-time = "2026-11-28T19:27:51.565Z" }, + { url = "https://files.pythonhosted.org/packages/98/cb/497c400eebdcc1cb371664776f9a3a49496dd54145110b3a2b8c4d0d8be3/msgspec-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bddda9fcdc38377edfae92d1b8a282fabe2328924517ebdf37fa6e14e874dd5", size = 234112, upload-time = "2026-11-28T19:27:52.763Z" }, + { url = "https://files.pythonhosted.org/packages/76/a3/d225e6ced293541f6a3acfedaf70a46bd26623994c30a6bba0ec1e6948db/msgspec-0.23.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:61492ae8f47bedae609723804632beaad688d53057151e6fd54b810eb8d542d9", size = 242167, upload-time = "2026-11-28T19:27:54.375Z" }, + { url = "https://files.pythonhosted.org/packages/ad/b3/60af281f93ed9d357f51a648d6ce79fc604100248ba80de42af4a91b87c2/msgspec-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b8a3cf17156120cc845762a98cfa19f0d02297d338ba529a7d403b2c69ed99e", size = 238651, upload-time = "2026-11-28T19:27:55.626Z" }, + { url = "https://files.pythonhosted.org/packages/df/ed/95847e8818bcbba9f838153f65aeafa0819d85c61973605de9b872f47972/msgspec-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:4ea6a15d78dbb61b38ed786913ffde142b2c776c0d8ae517f2419aa3c9e299f9", size = 207534, upload-time = "2026-11-28T19:27:56.889Z" }, + { url = "https://files.pythonhosted.org/packages/00/5f/f470c5f65f9e5fb413d138b8eb47a6fe5f6312564ceb966f3e48958c276d/msgspec-0.23.0-cp312-cp312-win_arm64.whl", hash = "sha256:7db818985fbe9f5b81c71000edd312d987abe7258ae28f01489749f06bcd532b", size = 200060, upload-time = "2026-11-28T19:27:58.116Z" }, + { url = "https://files.pythonhosted.org/packages/eb/12/1b33209749bded16d81a94cc77c383e40aca8c3a2bd3d42656974359d9eb/msgspec-0.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4a3a40bec3559c6fc5fad1f2641f03d59104b2a1f069b5c146ae9fbb857e7c63", size = 207915, upload-time = "2026-11-28T19:27:59.343Z" }, + { url = "https://files.pythonhosted.org/packages/a4/6e/f2ac94a03a1f7fd86a0a890b964d0a30b7f8b1feba770d56e3395c94568c/msgspec-0.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2e852f554a1a8e521f6727da6faa85a6f6d0e2ed34eef29030e51d1991b636b6", size = 199541, upload-time = "2026-11-28T19:28:00.686Z" }, + { url = "https://files.pythonhosted.org/packages/75/b8/99137210e2a95ccdfdce5cf18316f98690d64e5ea2ca768e1a0f5ce2a26e/msgspec-0.23.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff7f32930c370d2982613dff161d6f0fa05d4e0a4a7d3cd7369411c1e44c2635", size = 230724, upload-time = "2026-11-28T19:28:01.879Z" }, + { url = "https://files.pythonhosted.org/packages/31/c3/eb7c8be54416b678286221728e196484b73c6abb47bab8a356d196a71475/msgspec-0.23.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:35bfe3b61fbb966610c4071c02a27ea8c81ace0effce2aa67acc3ea03b93559b", size = 236671, upload-time = "2026-11-28T19:28:03.222Z" }, + { url = "https://files.pythonhosted.org/packages/b1/62/bbad58dc605e95d49f74e68c407690e71be5722652bd5f893cbc1a5a0888/msgspec-0.23.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:16e8be6a4f8addc6af168a07719c2028e1397abcc7b90ec7870b419182bb49c7", size = 243143, upload-time = "2026-11-28T19:28:04.5Z" }, + { url = "https://files.pythonhosted.org/packages/1a/63/c8c8b7dc4a620b319bf504845afbfc14441604da72279c10ffde414c0dbb/msgspec-0.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3966278e188aeb209c827b656170191d25344ca2852eccacaa0856c79230c4ed", size = 234109, upload-time = "2026-11-28T19:28:05.952Z" }, + { url = "https://files.pythonhosted.org/packages/ae/76/d501d4b7bc694d0b8da3d3127d7b24d758a293d2fbf2bc53d16f9345b591/msgspec-0.23.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7e3b36f643594ab9754ffe0006089599815c06a6e5ff8142fc9704a585519c98", size = 242278, upload-time = "2026-11-28T19:28:07.208Z" }, + { url = "https://files.pythonhosted.org/packages/6a/0a/49682eb30167c1b936f96bfe96a936505a7efe99593828087597de35c229/msgspec-0.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4ae9e363c1045c4186245c48c0281dd02e3cd8411748cc33b50b0c4f6e019d57", size = 238794, upload-time = "2026-11-28T19:28:08.503Z" }, + { url = "https://files.pythonhosted.org/packages/8a/a1/3a32fb47b06f5082f36cb334603ff63a1944b59e77f649b0d429a5dd52ca/msgspec-0.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:290624a74fe844a21f01c0b4239561aaea8a7a1fa291c1433d73a40079c4a53f", size = 207486, upload-time = "2026-11-28T19:28:09.759Z" }, + { url = "https://files.pythonhosted.org/packages/d5/af/b51353d95f280ec5eb2bbdda4c9a472bbaff4bf36774167749d805ec9c89/msgspec-0.23.0-cp313-cp313-win_arm64.whl", hash = "sha256:a7bc3d5eb017bd22e6721480022f089db5040439c4e96227a7878c2998cbb75e", size = 200041, upload-time = "2026-11-28T19:28:11.114Z" }, + { url = "https://files.pythonhosted.org/packages/04/e8/c991287d1af017003e5140fc312d15749c54e98ad9849269a2e396dc75cc/msgspec-0.23.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:5e1f845e6eac1a9985e31eec434f57b974a5e19365d175a0434f9864923415c0", size = 207988, upload-time = "2026-11-28T19:28:12.642Z" }, + { url = "https://files.pythonhosted.org/packages/a4/e0/14da7ffff4272e26081fd81c8188284e2f9369d9bbb99d66095942b87534/msgspec-0.23.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f4e62d63f609cf523c658098bd8d54d2e45d169f521649feff2b1855283fd526", size = 200034, upload-time = "2026-11-28T19:28:13.91Z" }, + { url = "https://files.pythonhosted.org/packages/d8/23/9e82922d6450f094814babc17561f55e4ba304d6627a791af46f2c6fc249/msgspec-0.23.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5b4cec4279c717a0c70cdf3d2a750349bbed82152a87a6863909f3724224836", size = 231792, upload-time = "2026-11-28T19:28:15.332Z" }, + { url = "https://files.pythonhosted.org/packages/e4/00/bad5774cf84f78ab7c94f2bfe918b1890e9ea518be89b39cbaa111fbf3c2/msgspec-0.23.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d6df6890bc48a2359172ba38dcdd2a8f4a53013bc68a0a6495f8b3c3d4e4024", size = 236745, upload-time = "2026-11-28T19:28:16.624Z" }, + { url = "https://files.pythonhosted.org/packages/57/0b/18ed7bea89186c765f468cb3b64872ffa28cecad63e18cbd08e729789556/msgspec-0.23.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0bfdc53912b2dfc6a00d6d9d570838a30b7b099f2ce9f43f0484b64a589d9c03", size = 243396, upload-time = "2026-11-28T19:28:17.92Z" }, + { url = "https://files.pythonhosted.org/packages/d6/86/65635e81fc76a6c27ea8db6d494f8784dee17c6ee1db089cad6434a60d4f/msgspec-0.23.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:66381457284204c6a243cbf22f4ac2db92a1cf13f1d00367c53b7f5111e17067", size = 235364, upload-time = "2026-11-28T19:28:19.052Z" }, + { url = "https://files.pythonhosted.org/packages/13/34/dd1c79943c218967339b09b22ce02ee7605b876c0c36612b5c05b123ab66/msgspec-0.23.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:34317aa997dc7634269716a50c7ba4aebfc7ad99f3419a710a35d6a443ce24d6", size = 242305, upload-time = "2026-11-28T19:28:20.307Z" }, + { url = "https://files.pythonhosted.org/packages/1c/5e/2c40267b37e69efa4bacde3216cc59e3a46e0841be5ad5db671aebc84027/msgspec-0.23.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d4eea7b2ad6d38d873dbf4b311f36914a2a1b19742f297f8c1235d5172540b52", size = 238690, upload-time = "2026-11-28T19:28:21.737Z" }, + { url = "https://files.pythonhosted.org/packages/fa/33/67509d508c2ba46e7ddf00237259e4164dcebabc4650930bc432ccf57946/msgspec-0.23.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:1836f50ad87e7c56600b648a1b75c3bbcce62835cb1f489435fc5fee8d068831", size = 141266, upload-time = "2026-11-28T19:28:23.021Z" }, + { url = "https://files.pythonhosted.org/packages/3b/a7/c1edad90f9a0bc986450fe3abece2beb26bbb018b537eea51a599a54912c/msgspec-0.23.0-cp314-cp314-win_amd64.whl", hash = "sha256:2830b00aa61857a306e692ea3579bc6dc59b3957dd3dedac9f143ea922a555cb", size = 212217, upload-time = "2026-11-28T19:28:24.213Z" }, + { url = "https://files.pythonhosted.org/packages/ab/83/a1ac00e31e39f26953061913f6ce8925c57a8893506d35ce39d3a4cdc234/msgspec-0.23.0-cp314-cp314-win_arm64.whl", hash = "sha256:6abeac42c25d5614a228958a7912ff112458daea33f75c5015457f166694cd2f", size = 205483, upload-time = "2026-11-28T19:28:25.485Z" }, + { url = "https://files.pythonhosted.org/packages/94/c2/d807cea3704813993bfda05964361fd61c0801b141920489a14a973358b1/msgspec-0.23.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:cb991f7d12dd8646437dde8975e8c3d1676dea6bda7f0197853df27bb9849cee", size = 211718, upload-time = "2026-11-28T19:28:27.187Z" }, + { url = "https://files.pythonhosted.org/packages/04/83/293950fe10f944f4fcc61ac9a8fd1fcffc752c35dedc525f94488eb80ea0/msgspec-0.23.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2f0475ce77031a14b83ed5c2db583dd8ae3001dd191248484aed4f8f08c78bbb", size = 203926, upload-time = "2026-11-28T19:28:28.428Z" }, + { url = "https://files.pythonhosted.org/packages/d2/6f/be093639aadfec6322a3c04da791e12ad03b93320f01ecbe8e731c3d8b8c/msgspec-0.23.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eee899b5d76ecd1682aaca3e6731fd4f4ceca331702b0625f6fda12090c68121", size = 236410, upload-time = "2026-11-28T19:28:29.702Z" }, + { url = "https://files.pythonhosted.org/packages/37/1c/d384dd55fd8e5568c5cb21da8250b76bff1407185ea85c261c7591fca3c5/msgspec-0.23.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:27ca63a01716dc9f4b261945ec13b66d018db6cdfd2dc2a124129c2e2ec1b369", size = 240296, upload-time = "2026-11-28T19:28:30.938Z" }, + { url = "https://files.pythonhosted.org/packages/f2/a6/ecc0bcdeccefbd66114e0b4a3ed694a7905bb771f8671b4d6564693ca5e8/msgspec-0.23.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e83096f88786933f0ba867df1d3fb1d41e10009d57792b918d84690ddafae1ca", size = 248559, upload-time = "2026-11-28T19:28:32.438Z" }, + { url = "https://files.pythonhosted.org/packages/3e/e0/8c408d7d959b0e1bcf79b5cd3ece7b0e9315a20e83db464c5b9414a74339/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:511c4f83916a369a9afb2abb463c3ddd6774470a0ed1ed049f230702e72679e1", size = 239645, upload-time = "2026-11-28T19:28:33.994Z" }, + { url = "https://files.pythonhosted.org/packages/24/f4/6d31c938cfdee9315abb7c3a8c807afada8d709f0a4289013ef83c3176bf/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:532df6d66c52b9fe7c612da29d042c0eda7cee270eb35ed5235dfc54cfcee831", size = 247413, upload-time = "2026-11-28T19:28:35.34Z" }, + { url = "https://files.pythonhosted.org/packages/90/09/91590d5c78c9ed42c2608277b84f2aa974f0cb4b9875ccd0dcb7bdade600/msgspec-0.23.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:13a25949a469c19d82516fcabbe1cf2babb5a1b2dd997d285644ec5c96316b00", size = 242637, upload-time = "2026-11-28T19:28:36.652Z" }, + { url = "https://files.pythonhosted.org/packages/d9/a7/dc0a519d58cffea5c8baa91eba85081c26e37537510c852213b1be3ff268/msgspec-0.23.0-cp314-cp314t-win_amd64.whl", hash = "sha256:379b6d6e016aee2c004797970936cfb5231dd3bea0ad7fa01637876b35479511", size = 217609, upload-time = "2026-11-28T19:28:37.839Z" }, + { url = "https://files.pythonhosted.org/packages/c3/c8/5f318a77af9087844910de28888d9f0acaccc3cc1d1116d34f2849a69bd1/msgspec-0.23.0-cp314-cp314t-win_arm64.whl", hash = "sha256:c5cd5b4e1a97fcde9b15304226b27a700d1931349a29abec9db0884a42f91497", size = 209521, upload-time = "2026-11-28T19:28:39.09Z" }, + { url = "https://files.pythonhosted.org/packages/11/9d/e80ad799eb149d9b63d5ff4787f674d741ad45d590032bb30ba8ab6a8a38/msgspec-0.23.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:55ca292b386fc63813b524c782c8cbb45497d3ca3d78e4576eac374294d0796b", size = 209043, upload-time = "2026-11-28T19:28:40.377Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1c/89dfd220e9d14da2682ac56eeb61dabd94faa20215c260edf9b37c51671d/msgspec-0.23.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6d02d95225da458a21120606eb06106791f18e9550f206e34b71f9ad8f0a59da", size = 200986, upload-time = "2026-11-28T19:28:41.893Z" }, + { url = "https://files.pythonhosted.org/packages/74/98/04a9ff3eba269e4343302f85fcd1b03c7ceccd41ce5f793417c6bd650027/msgspec-0.23.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d14bc8cfe758d63b8f8376236be434fb53500505c4002b67b9d67a30385c794", size = 233244, upload-time = "2026-11-28T19:28:43.732Z" }, + { url = "https://files.pythonhosted.org/packages/b6/bc/3f5a94b68039d2192a2f8fdf42eef0899da6d640a0aef35de1ca4d5c8fe8/msgspec-0.23.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d366ac1b286e30e2dfdb52a67056ce27ac6fe4d4edff6cf5dd8fac44865d505e", size = 237974, upload-time = "2026-11-28T19:28:45.238Z" }, + { url = "https://files.pythonhosted.org/packages/6f/a9/60eba35d65eb41b0198d8324aee46b803d1ad94b3413926a8b45a42abb75/msgspec-0.23.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2eed0f1d284eafa228fc7174d13ab79f779615993e0627cfed342cb573d39676", size = 248902, upload-time = "2026-11-28T19:28:47.145Z" }, + { url = "https://files.pythonhosted.org/packages/b3/93/b17150d7e50258f0baa454902309afb824041c7892ec4dce1fb11cd1250a/msgspec-0.23.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:3868a8bf5b2b2f36e1b214968423bdd129521ea26b8f77530265b87cb8bab978", size = 236977, upload-time = "2026-11-28T19:28:48.772Z" }, + { url = "https://files.pythonhosted.org/packages/9f/e5/d24bf3cb8d3ac8719d4268bf3d314602b5d9b51390e57bb4c9d68b9e662c/msgspec-0.23.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:2cd244c3e713aa68ab4908385882afb2da6ebaf270bcdf84289d640dc846c2d5", size = 248149, upload-time = "2026-11-28T19:28:50.028Z" }, + { url = "https://files.pythonhosted.org/packages/be/6e/f2a765a71172c5e984eb134debc0a51bc58d8a4c860c4427533fe08dd23d/msgspec-0.23.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:ee58dff142359dedf8e2b4da67eea47189d9c161bca26816a4ded4fb18658946", size = 240310, upload-time = "2026-11-28T19:28:51.23Z" }, + { url = "https://files.pythonhosted.org/packages/b9/59/1029072e0307604b9c77c5170d2f83b4a8d5aa3e2fbbe7d2d50320ac3ff4/msgspec-0.23.0-cp315-cp315-win_amd64.whl", hash = "sha256:492870aa884ca02361a35f7f8d4bb6c31b38ed69ea91dadbf676e24176ec2aa4", size = 212785, upload-time = "2026-11-28T19:28:52.406Z" }, + { url = "https://files.pythonhosted.org/packages/39/d0/31dac480f6bef20a8338d1444f52f11cdf1e2617bc57f2bb82bd868f5b6c/msgspec-0.23.0-cp315-cp315-win_arm64.whl", hash = "sha256:0516c3ad2d8f6c774a3c6ac5e72458eb6196dfc02ed71f7eeb5f753f1afa44fd", size = 205826, upload-time = "2026-11-28T19:28:53.676Z" }, + { url = "https://files.pythonhosted.org/packages/36/a6/7c0a1efff67399b7ac6ca6d3f55b645132acd2510e769bb944c5ac95285e/msgspec-0.23.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:6f1bc450334fe4571c710d555e6b3654285f23b66d074633973d5a42596d63fb", size = 212630, upload-time = "2026-11-28T19:28:54.941Z" }, + { url = "https://files.pythonhosted.org/packages/72/ba/2435104bc78822fd6e75748c6876f46cde0a71f1c8fe159ad1f11f718609/msgspec-0.23.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d33ec9e27926254558e84251790798c03fd6220c27ee0f7633315439b4b3a5be", size = 205199, upload-time = "2026-11-28T19:28:56.28Z" }, + { url = "https://files.pythonhosted.org/packages/9d/20/0bd08638eff23b25f96470f59c9765546a11ab367a1dd1328e9241d9ec32/msgspec-0.23.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dfeef9ad65224f06430e7413fda72802b917a56e42a4e982b23301f018e1a245", size = 238340, upload-time = "2026-11-28T19:28:57.716Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ee/8087965ea8fd4fe1d356f48dc61f9a6ef79665275a270ca0df991a50406a/msgspec-0.23.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c00ac40e1fa738c8b91cbd327331f4a8acf44d74a0c7217016a4e0746c486d82", size = 242541, upload-time = "2026-11-28T19:28:58.952Z" }, + { url = "https://files.pythonhosted.org/packages/4f/95/9d353ae41398265b5367282838c4d5ad2923548c55ac47c53d5f7ef1f762/msgspec-0.23.0-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9188481152e4f7a1b77c9e3023c086b5ad46253e0ca7b1b067914997e1f89d34", size = 253297, upload-time = "2026-11-28T19:29:00.259Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a4/ebb158a3a4d87a099e2c24381cc4164519bf2d758ed3e3d43571538a3f36/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:fea7eeada89851826e240bba0cd29e7f406d83653a614dddf8c32232aca0425f", size = 241029, upload-time = "2026-11-28T19:29:01.538Z" }, + { url = "https://files.pythonhosted.org/packages/d1/ac/d79d5d3933a778946e807bfd87f15dd6e54fe2e35ff994d439b26152386b/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:a7cd9381789b2dc8f6fef5d7ae8a65a8a8511bbd8e04f3a48946a98b03a24bff", size = 254370, upload-time = "2026-11-28T19:29:03.043Z" }, + { url = "https://files.pythonhosted.org/packages/69/7f/6819edf18bd4999aaa1cbbd8d3484187f3770f291b5a4464fe56123a67c5/msgspec-0.23.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b0c55588edf6e403d76570ea9493574703f328f7adffc111de70f2adaf1834e4", size = 244917, upload-time = "2026-11-28T19:29:04.291Z" }, + { url = "https://files.pythonhosted.org/packages/2e/2f/a37cfbb946de4c8b12518dee0ae8d9ed73f9340ca0f605dfd62cb38a6a67/msgspec-0.23.0-cp315-cp315t-win_amd64.whl", hash = "sha256:5f6993f0d0382cb6a6afb2f48531ca3f6e47526c79aed028702813b6f4a0ed6b", size = 217521, upload-time = "2026-11-28T19:29:05.554Z" }, + { url = "https://files.pythonhosted.org/packages/81/d2/87bb8406c3d172af5ecd21fdce3eed558be3f6cce6692fc7d938e90c396a/msgspec-0.23.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8cb516c68f9b91fbe5c08de75394ec4629fbc78ba2e7da84ed3130f876234ddd", size = 210112, upload-time = "2026-11-28T19:29:06.882Z" }, +] + +[[package]] +name = "mypy-extensions" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/6f/43edf3be2748d0e40974a5ee046a8bb4c9961a4bdd3e7d5c6dcbf32d1af6/mypy_extensions-1.2.0.tar.gz", hash = "sha256:c6e275a07f1c2fc096b62940452d0eaa3f3af7de45d704787866240a7c6d5a51", size = 6566, upload-time = "2026-11-03T16:26:33.692Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/99/7b1adac7e97ce7bbda34792dc6e9b2f5cc5cffd1875883f78a818b2a2687/mypy_extensions-1.2.0-py3-none-any.whl", hash = "sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768", size = 5114, upload-time = "2026-11-03T16:26:32.731Z" }, +] + +[[package]] +name = "networkx" +version = "3.4.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/fd/1d/06475e1cd5264c0b870ea2cc6fdb3e37177c1e565c43f56ff17a10e3937f/networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1", size = 2151368, upload-time = "2024-10-21T12:39:38.695Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/54/dd730b32ea14ea797530a4479b2ed46a6fb250f682a9cfb997e968bf0261/networkx-3.4.2-py3-none-any.whl", hash = "sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", size = 1723263, upload-time = "2024-10-21T12:39:36.247Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "networkx" +version = "3.7" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.13.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/56/8895a76abe4ec94ebd01eeb6d74f587bc4cddd46569670e1402852a5da13/numcodecs-0.13.1.tar.gz", hash = "sha256:a3cf37881df0898f3a9c0d4477df88133fe85185bffe57ba31bcc2fa207709bc", size = 5955215, upload-time = "2024-10-09T16:28:00.188Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/c0/6d72cde772bcec196b7188731d41282993b2958440f77fdf0db216f722da/numcodecs-0.13.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:96add4f783c5ce57cc7e650b6cac79dd101daf887c479a00a29bc1487ced180b", size = 1580012, upload-time = "2024-10-09T16:27:19.069Z" }, + { url = "https://files.pythonhosted.org/packages/94/1d/f81fc1fa9210bbea97258242393a1f9feab4f6d8fb201f81f76003005e4b/numcodecs-0.13.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:237b7171609e868a20fd313748494444458ccd696062f67e198f7f8f52000c15", size = 1176919, upload-time = "2024-10-09T16:27:21.634Z" }, + { url = "https://files.pythonhosted.org/packages/16/e4/b9ec2f4dfc34ecf724bc1beb96a9f6fa9b91801645688ffadacd485089da/numcodecs-0.13.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:96e42f73c31b8c24259c5fac6adba0c3ebf95536e37749dc6c62ade2989dca28", size = 8625842, upload-time = "2024-10-09T16:27:24.168Z" }, + { url = "https://files.pythonhosted.org/packages/fe/90/299952e1477954ec4f92813fa03e743945e3ff711bb4f6c9aace431cb3da/numcodecs-0.13.1-cp310-cp310-win_amd64.whl", hash = "sha256:eda7d7823c9282e65234731fd6bd3986b1f9e035755f7fed248d7d366bb291ab", size = 828638, upload-time = "2024-10-09T16:27:27.063Z" }, + { url = "https://files.pythonhosted.org/packages/f0/78/34b8e869ef143e88d62e8231f4dbfcad85e5c41302a11fc5bd2228a13df5/numcodecs-0.13.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2eda97dd2f90add98df6d295f2c6ae846043396e3d51a739ca5db6c03b5eb666", size = 1580199, upload-time = "2024-10-09T16:27:29.336Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cf/f70797d86bb585d258d1e6993dced30396f2044725b96ce8bcf87a02be9c/numcodecs-0.13.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2a86f5367af9168e30f99727ff03b27d849c31ad4522060dde0bce2923b3a8bc", size = 1177203, upload-time = "2024-10-09T16:27:31.011Z" }, + { url = "https://files.pythonhosted.org/packages/a8/b5/d14ad69b63fde041153dfd05d7181a49c0d4864de31a7a1093c8370da957/numcodecs-0.13.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:233bc7f26abce24d57e44ea8ebeb5cd17084690b4e7409dd470fdb75528d615f", size = 8868743, upload-time = "2024-10-09T16:27:32.833Z" }, + { url = "https://files.pythonhosted.org/packages/13/d4/27a7b5af0b33f6d61e198faf177fbbf3cb83ff10d9d1a6857b7efc525ad5/numcodecs-0.13.1-cp311-cp311-win_amd64.whl", hash = "sha256:796b3e6740107e4fa624cc636248a1580138b3f1c579160f260f76ff13a4261b", size = 829603, upload-time = "2024-10-09T16:27:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/37/3a/bc09808425e7d3df41e5fc73fc7a802c429ba8c6b05e55f133654ade019d/numcodecs-0.13.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5195bea384a6428f8afcece793860b1ab0ae28143c853f0b2b20d55a8947c917", size = 1575806, upload-time = "2024-10-09T16:27:37.804Z" }, + { url = "https://files.pythonhosted.org/packages/3a/cc/dc74d0bfdf9ec192332a089d199f1e543e747c556b5659118db7a437dcca/numcodecs-0.13.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3501a848adaddce98a71a262fee15cd3618312692aa419da77acd18af4a6a3f6", size = 1178233, upload-time = "2024-10-09T16:27:40.169Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/434e8e3970b8e92ae9ab6d9db16cb9bc7aa1cd02e17c11de6848224100a1/numcodecs-0.13.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:da2230484e6102e5fa3cc1a5dd37ca1f92dfbd183d91662074d6f7574e3e8f53", size = 8857827, upload-time = "2024-10-09T16:27:42.743Z" }, + { url = "https://files.pythonhosted.org/packages/83/e7/1d8b1b266a92f9013c755b1c146c5ad71a2bff147ecbc67f86546a2e4d6a/numcodecs-0.13.1-cp312-cp312-win_amd64.whl", hash = "sha256:e5db4824ebd5389ea30e54bc8aeccb82d514d28b6b68da6c536b8fa4596f4bca", size = 826539, upload-time = "2024-10-09T16:27:44.808Z" }, + { url = "https://files.pythonhosted.org/packages/83/8b/06771dead2cc4a8ae1ea9907737cf1c8d37a323392fa28f938a586373468/numcodecs-0.13.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a60d75179fd6692e301ddfb3b266d51eb598606dcae7b9fc57f986e8d65cb43", size = 1571660, upload-time = "2024-10-09T16:27:47.125Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ea/d925bf85f92dfe4635356018da9fe4bfecb07b1c72f62b01c1bc47f936b1/numcodecs-0.13.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3f593c7506b0ab248961a3b13cb148cc6e8355662ff124ac591822310bc55ecf", size = 1169925, upload-time = "2024-10-09T16:27:49.512Z" }, + { url = "https://files.pythonhosted.org/packages/0f/d6/643a3839d571d8e439a2c77dc4b0b8cab18d96ac808e4a81dbe88e959ab6/numcodecs-0.13.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80d3071465f03522e776a31045ddf2cfee7f52df468b977ed3afdd7fe5869701", size = 8814257, upload-time = "2024-10-09T16:27:52.059Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c5/f3e56bc9b4e438a287fff738993d6d11abef368c0328a612ac2842ba9fca/numcodecs-0.13.1-cp313-cp313-win_amd64.whl", hash = "sha256:90d3065ae74c9342048ae0046006f99dcb1388b7288da5a19b3bddf9c30c3176", size = 821887, upload-time = "2024-10-09T16:27:55.039Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.16.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f9/03/c82563fffd81245a5b0239be8ff7743b30fe35d044080261458ae3c6aee5/numcodecs-0.16.6.tar.gz", hash = "sha256:5e446928af7c40b4dc8f51e960b4c9fb14f617846577d2fcf35ae2f92738f00f", size = 6288989, upload-time = "2026-10-20T19:42:43.925Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/14/a962963a85357410969621a1a56ed026c70dfc3836949eec415bae7f7ecf/numcodecs-0.16.6-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:0916f0852500dd68fe2698682d490edaf08fc673b9bc992183a4e81aad25e322", size = 1634935, upload-time = "2026-10-20T19:42:11.706Z" }, + { url = "https://files.pythonhosted.org/packages/dc/ba/e5bd5a0812d320e370d153243775476378d12eface499e9b4a2bde9bc207/numcodecs-0.16.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:73df0384f20ecd662fea6da2a08933ea8885d74e3c4e5916819292c5c38c0dca", size = 1179199, upload-time = "2026-10-20T19:42:13.251Z" }, + { url = "https://files.pythonhosted.org/packages/06/87/3e2bf32adab8aa9337cfd450b789b0f8de4b24d0cba76748e109a628effe/numcodecs-0.16.6-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30f1533255c32aea337ef2c0b8cf14772f1d490cfb023ce4cdb80deedea4bd2", size = 8743497, upload-time = "2026-10-20T19:42:14.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/31/ff9f1bac85fa145710d1744423222d67a8d23c2bad332c4f04664732c291/numcodecs-0.16.6-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b271f5d7ebe079b0c2914cad256153d92b3a271de534c3d4220692e82daf870d", size = 9349451, upload-time = "2026-10-20T19:42:16.684Z" }, + { url = "https://files.pythonhosted.org/packages/81/ed/b1b224c3aabc24121fe247e341bab6f65c75e225936d37fbe9fb56edaec6/numcodecs-0.16.6-cp311-cp311-win_amd64.whl", hash = "sha256:e3e18c7dfe96c8c28411dc45a723c872c85ea4a6fcd9c214ed55e9bc9eec6ba6", size = 844468, upload-time = "2026-10-20T19:42:18.96Z" }, + { url = "https://files.pythonhosted.org/packages/53/02/26a65f7639089b378b79713340d59aa7f691f21ff9e1e44918da8dc36833/numcodecs-0.16.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3ff7c380b40e855ae8caf6c19c368f1c43bf75dcac876445286320bd9fce7753", size = 1666738, upload-time = "2026-10-20T19:42:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/10/c9/1ca1e577f54851126dd1652ec8352ffddef30b9b5eb4ffbade149b12eb6e/numcodecs-0.16.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:524278af1f81cdf4d47b4300650458096822bbdf073c8b3417fa10147e1f73d9", size = 1174596, upload-time = "2026-10-20T19:42:21.968Z" }, + { url = "https://files.pythonhosted.org/packages/a0/31/96be58c5acc480ba389b8c37f66d688e86e9e694aad8a275a455c9a1b296/numcodecs-0.16.6-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:58a02c60f9e4497f7a2c9653f58e8884fd2b7bf5b86ea205f965e363d495ecfd", size = 8710129, upload-time = "2026-10-20T19:42:23.403Z" }, + { url = "https://files.pythonhosted.org/packages/e0/13/01081ae906ae7574289818b08f076ab6663d220f0283b46837962a50ce0f/numcodecs-0.16.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:609fd6f5ab1dd27fcde21d3e2bbf7e05846d5d5fdd23cf34e02375278a44252f", size = 9346139, upload-time = "2026-10-20T19:42:25.563Z" }, + { url = "https://files.pythonhosted.org/packages/de/d1/5639161aa9524b609d9ce9088bd691ec228a027b141ffc5a88faebc686d2/numcodecs-0.16.6-cp312-cp312-win_amd64.whl", hash = "sha256:c9492c7d79674aac222cb11aba7d48de8b95a2dabadeab501ffe61c124aee664", size = 841956, upload-time = "2026-10-20T19:42:27.243Z" }, + { url = "https://files.pythonhosted.org/packages/c4/2a/829aada6ab1df933a7ebe2693ce6c243a4c4bbbe3040dca175e39005ee31/numcodecs-0.16.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e3b113eecf5509b116982ab7f30a8c861b158045f0702234322bad7bfdeab728", size = 1665051, upload-time = "2026-10-20T19:42:28.451Z" }, + { url = "https://files.pythonhosted.org/packages/8e/87/48fa19e087df8a1a1bd6157c345bef0cdc1133c0fe927219fd43b21cc8f2/numcodecs-0.16.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e7e41920099df1aec14d6112e3e1ab028b2451b9ed92e33163510667bfa2e384", size = 1172068, upload-time = "2026-10-20T19:42:29.77Z" }, + { url = "https://files.pythonhosted.org/packages/af/16/670283fc6aeccace1ed426fe223e73e4dba42ae714efad70e75f004942ad/numcodecs-0.16.6-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ea78370626cdf1436a9d1fa0984a4f7a227a0dc643abbbc2d1558e6d4afafeb", size = 8659446, upload-time = "2026-10-20T19:42:31.073Z" }, + { url = "https://files.pythonhosted.org/packages/fe/4e/0088e3a9a8e1c466a8c8500aa90f613f9aa418b79d303008f6b2e8a641ba/numcodecs-0.16.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a063fbac0403e8609a649c5fd716d05c8ac3f2fed0aa19d03c0d0ab2194a9527", size = 9301961, upload-time = "2026-10-20T19:42:32.904Z" }, + { url = "https://files.pythonhosted.org/packages/9e/73/875f008f7e4d8ac5e65a90222e27c14ea4e062192d5452a15e7d266beeb5/numcodecs-0.16.6-cp313-cp313-win_amd64.whl", hash = "sha256:40ed58a808c8a629391be8918ea251a884715deaf077d1618327429adf06c2f4", size = 838867, upload-time = "2026-10-20T19:42:34.603Z" }, + { url = "https://files.pythonhosted.org/packages/fc/a5/338e2fe244a285c9edb5d8764def8d726ccdb5cca83cca914780b27333f7/numcodecs-0.16.6-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ba4b67038a0542158c5a99004f571c5e11a27d4b7c62290e745dd98e86f15d67", size = 1664019, upload-time = "2026-10-20T19:42:35.814Z" }, + { url = "https://files.pythonhosted.org/packages/53/fd/b8a52c063f59f4e56747e9b116e7b1ced32420fcdd661a673035a82ea259/numcodecs-0.16.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c69ef06c1ba0c308e62cc8724627291248a4933ee2897ad61bf272258f1a2f12", size = 1174119, upload-time = "2026-10-20T19:42:36.987Z" }, + { url = "https://files.pythonhosted.org/packages/0e/bc/3b96459c6dd906a7a67d387541aadac207c5330c84d246bfa0dcecb93824/numcodecs-0.16.6-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5bee914099138110137ad1be750a8ac7be395b8a63873c9c2408551bec6f3d81", size = 8654534, upload-time = "2026-10-20T19:42:38.312Z" }, + { url = "https://files.pythonhosted.org/packages/14/71/b29cab99bd25b09de92749e4e98473877e7fcbf2a6ac492d4631f55946c1/numcodecs-0.16.6-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9de40cfbc9764313d9badabbe103def759d0676d64292805f80d08b9dee8c39d", size = 9276387, upload-time = "2026-10-20T19:42:40.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/10/1594ab5a44a7104efdd440d28857425cc524d139b38212d5b52e58304d02/numcodecs-0.16.6-cp314-cp314-win_amd64.whl", hash = "sha256:37f665249aa848ea1600f7513789767753c324d33ca6d7ea887150c2f3ff34e5", size = 858556, upload-time = "2026-10-20T19:42:42.352Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/f7/7fd3a5066fd07a1541b7937f3f9db73552f48b28a819470c5c00a0c3e472/numcodecs-0.17.1.tar.gz", hash = "sha256:5069dc01b0087c6135cbb3b043707aaf927c992fcd325248d15d907c51dd3747", size = 6290108, upload-time = "2026-10-20T19:37:58.903Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/42/3e48ae17b5810f4972140344d86d951c6620ff618901e4e84cb007c5e5e6/numcodecs-0.17.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7cc861d98827e92f93d3ff5b796ec6ee6785efadd44d721496b49e2609365457", size = 1172442, upload-time = "2026-10-20T19:37:28.792Z" }, + { url = "https://files.pythonhosted.org/packages/95/e0/338a68d002397fa896581ff3c8af6ca8c6cba259cda4da2496084b1b1785/numcodecs-0.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d639064acc8f38184e763a5bfe6b5376361c3a79583c67a86a57424629a247c8", size = 979779, upload-time = "2026-10-20T19:37:30.651Z" }, + { url = "https://files.pythonhosted.org/packages/73/72/ca2c75596fe84eba628510595d0b32395205ebf450870f07311adb9cd3e9/numcodecs-0.17.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bfa4d91bacec65232d02402efb82ad08e8c49298e5358d03fe205691ffcca397", size = 1385001, upload-time = "2026-10-20T19:37:32.092Z" }, + { url = "https://files.pythonhosted.org/packages/76/c7/e6b131d0240345bc523873b9f16b22aaca8319abdf0acef4247ccffb3cea/numcodecs-0.17.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e3c08f6f4074eb92b3312efbf293afbbae5697d6b9d009435671a3a18e22ba5", size = 1437783, upload-time = "2026-10-20T19:37:33.861Z" }, + { url = "https://files.pythonhosted.org/packages/8c/80/1fa323d38f42002bc3beb18ec3c5d1eecc8c3c703f497a9f0ea6ddf8e512/numcodecs-0.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:f65d08e20e16430dfb2a21e6a1298b09f98a0ca08a2a9e7aec25a81e4b98b7e5", size = 1497112, upload-time = "2026-10-20T19:37:35.912Z" }, + { url = "https://files.pythonhosted.org/packages/80/01/325b1b78c4602f808e4733e9f88ae4b3f15813c98c9a44d46d799e543bb9/numcodecs-0.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6ca56ab612dbdfffa69c24ad510eaf3cdd794b40dd47144f96f7e0c890fd712c", size = 1171680, upload-time = "2026-10-20T19:37:37.23Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3c/b5350ec12911abfcc69f87113e00ee01beecda4d8550fa081e6a840a73be/numcodecs-0.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0eca3c1c135890911971f6f31e66c9dbfdb28af780c8a53aeadb160478553cd8", size = 976932, upload-time = "2026-10-20T19:37:38.588Z" }, + { url = "https://files.pythonhosted.org/packages/61/3e/59c7ba952edf8e822d76b6b7933c93e7eb5edb11e273162a338c4bcf6985/numcodecs-0.17.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fed686b607d9c1afde8cd0b17d808e29d9a7c8d4ff2c12478456198f57b21e91", size = 1380146, upload-time = "2026-10-20T19:37:39.895Z" }, + { url = "https://files.pythonhosted.org/packages/fb/66/d7ed1f3cf2acdd7066c79e5fbb4a71df275860df4e1951d4209c8a4bf446/numcodecs-0.17.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3a67976c03dd62e1b6a5e938c61f643673a6a9a37e17800eca99d1a7ea3c89e2", size = 1431354, upload-time = "2026-10-20T19:37:41.298Z" }, + { url = "https://files.pythonhosted.org/packages/26/80/ab38a26d5633da6c9217bfb04cc38025371d1e785fd6484aed56dd9a6f37/numcodecs-0.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:a5cc666eba758ae20798c6bb1ce406d68db60e3fe0d65aa67e00d130aa1d00f0", size = 1493578, upload-time = "2026-10-20T19:37:42.997Z" }, + { url = "https://files.pythonhosted.org/packages/0a/cf/2a7406e1c0a8b28f885b7ff6b4f1059b1b157e1b221399ab021f3a97e720/numcodecs-0.17.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9edc7ab4a890cf24aaedb5e557c1d3fbdb697afd0135974d81b5b304ea75552d", size = 1173008, upload-time = "2026-10-20T19:37:44.286Z" }, + { url = "https://files.pythonhosted.org/packages/f3/36/47934b70b187a23560fa404ff4835356e3b438cd46f28bd0a4e17abce2af/numcodecs-0.17.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0dac6eaded2c6baeb292ec76df327ea7eb222915ba50b83babf48234b09746cf", size = 978823, upload-time = "2026-10-20T19:37:45.595Z" }, + { url = "https://files.pythonhosted.org/packages/fe/4b/f87f8a1b8c967a06792c052b9df0dd6db6714a42e0d8db3efa6404a72d15/numcodecs-0.17.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71a1d46317956b8402ce06697911c41fe6b1dd5f24ee7a793830784d202b2548", size = 1388057, upload-time = "2026-10-20T19:37:46.961Z" }, + { url = "https://files.pythonhosted.org/packages/c8/de/14562bb9c6d2b078570383859264b07ecf0d205139e13d37c4d56cb926d5/numcodecs-0.17.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6c0bdf72039d55538c774ac2f695146ab6e36392660664904bfcce1731f0a862", size = 1433317, upload-time = "2026-10-20T19:37:48.253Z" }, + { url = "https://files.pythonhosted.org/packages/d6/30/3b706e1784e3631b1d614447b3b06811a644879c9acca5dec00ab27bf2d4/numcodecs-0.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:fed097ba6c199be3c7dd5a79147d2a7ec23680967c99339a722b4d19069f527b", size = 1535610, upload-time = "2026-10-20T19:37:49.996Z" }, + { url = "https://files.pythonhosted.org/packages/1d/35/69e5a27dd41f8bd916dbff5cbccaf2e4c756884f183015c10b83a63bbee5/numcodecs-0.17.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2e78cec0a8d88a93cced1e8ad1385415ddbe7f01aa5ad7f7da35b68f4f79414b", size = 1197076, upload-time = "2026-10-20T19:37:51.39Z" }, + { url = "https://files.pythonhosted.org/packages/04/10/8c39a542d7572ab2398874df2b4465001e700e9d3c3ff959a42342a704e6/numcodecs-0.17.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e2b6d32c0e29a050a8f4b891c0f84a808a292b0dff0fb5602eeb5bcd6f7bd2ff", size = 1022856, upload-time = "2026-10-20T19:37:52.905Z" }, + { url = "https://files.pythonhosted.org/packages/00/6b/4549e705a32d8f74a55397f29b69904ec9c04590ec4c59881786c640c0fa/numcodecs-0.17.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a853f4fde6721b35bd33d3cf6f621c4b335d07072346d24cc6af956f6f1b4db", size = 1381637, upload-time = "2026-10-20T19:37:54.493Z" }, + { url = "https://files.pythonhosted.org/packages/1f/ab/5c5e298aade3ba59cff7f1e0a2afe81d180762f9467150976f0dfbb6561b/numcodecs-0.17.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b5930b538468779335640a294728da6737ed6e218316bf36a49d939ac6958e28", size = 1425742, upload-time = "2026-10-20T19:37:55.815Z" }, + { url = "https://files.pythonhosted.org/packages/2c/ce/420b5e439e96d7a619c3122ef58e8847701c9d79a2b8f94702704106ff34/numcodecs-0.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:39d477687e9b3ceccde69358a62bbdbddb0972638ed90e61eff65537821f03a7", size = 1524207, upload-time = "2026-10-20T19:37:57.3Z" }, +] + +[[package]] +name = "numpy" +version = "2.2.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245, upload-time = "2025-05-17T21:27:58.555Z" }, + { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048, upload-time = "2025-05-17T21:28:21.406Z" }, + { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542, upload-time = "2025-05-17T21:28:30.931Z" }, + { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301, upload-time = "2025-05-17T21:28:41.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320, upload-time = "2025-05-17T21:29:02.78Z" }, + { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050, upload-time = "2025-05-17T21:29:27.675Z" }, + { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034, upload-time = "2025-05-17T21:29:51.102Z" }, + { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185, upload-time = "2025-05-17T21:30:18.703Z" }, + { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149, upload-time = "2025-05-17T21:30:29.788Z" }, + { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620, upload-time = "2025-05-17T21:30:48.994Z" }, + { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963, upload-time = "2025-05-17T21:31:19.36Z" }, + { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743, upload-time = "2025-05-17T21:31:41.087Z" }, + { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616, upload-time = "2025-05-17T21:31:50.072Z" }, + { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579, upload-time = "2025-05-17T21:32:01.712Z" }, + { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005, upload-time = "2025-05-17T21:32:23.332Z" }, + { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570, upload-time = "2025-05-17T21:32:47.991Z" }, + { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548, upload-time = "2025-05-17T21:33:11.728Z" }, + { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521, upload-time = "2025-05-17T21:33:39.139Z" }, + { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866, upload-time = "2025-05-17T21:33:50.273Z" }, + { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455, upload-time = "2025-05-17T21:34:09.135Z" }, + { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348, upload-time = "2025-05-17T21:34:39.648Z" }, + { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362, upload-time = "2025-05-17T21:35:01.241Z" }, + { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103, upload-time = "2025-05-17T21:35:10.622Z" }, + { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382, upload-time = "2025-05-17T21:35:21.414Z" }, + { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462, upload-time = "2025-05-17T21:35:42.174Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618, upload-time = "2025-05-17T21:36:06.711Z" }, + { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511, upload-time = "2025-05-17T21:36:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783, upload-time = "2025-05-17T21:36:56.883Z" }, + { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506, upload-time = "2025-05-17T21:37:07.368Z" }, + { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190, upload-time = "2025-05-17T21:37:26.213Z" }, + { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828, upload-time = "2025-05-17T21:37:56.699Z" }, + { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006, upload-time = "2025-05-17T21:38:18.291Z" }, + { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765, upload-time = "2025-05-17T21:38:27.319Z" }, + { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736, upload-time = "2025-05-17T21:38:38.141Z" }, + { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719, upload-time = "2025-05-17T21:38:58.433Z" }, + { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072, upload-time = "2025-05-17T21:39:22.638Z" }, + { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213, upload-time = "2025-05-17T21:39:45.865Z" }, + { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632, upload-time = "2025-05-17T21:40:13.331Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532, upload-time = "2025-05-17T21:43:46.099Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885, upload-time = "2025-05-17T21:44:05.145Z" }, + { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467, upload-time = "2025-05-17T21:40:44Z" }, + { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144, upload-time = "2025-05-17T21:41:05.695Z" }, + { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217, upload-time = "2025-05-17T21:41:15.903Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014, upload-time = "2025-05-17T21:41:27.321Z" }, + { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935, upload-time = "2025-05-17T21:41:49.738Z" }, + { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122, upload-time = "2025-05-17T21:42:14.046Z" }, + { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143, upload-time = "2025-05-17T21:42:37.464Z" }, + { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260, upload-time = "2025-05-17T21:43:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225, upload-time = "2025-05-17T21:43:16.254Z" }, + { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374, upload-time = "2025-05-17T21:43:35.479Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391, upload-time = "2025-05-17T21:44:35.948Z" }, + { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754, upload-time = "2025-05-17T21:44:47.446Z" }, + { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476, upload-time = "2025-05-17T21:45:11.871Z" }, + { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666, upload-time = "2025-05-17T21:45:31.426Z" }, +] + +[[package]] +name = "numpy" +version = "2.4.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/49/ec46835a70be8fa6446c495126ac84fdb28cb2558e1620ffb87a10c8b64c/numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4", size = 16969194, upload-time = "2026-05-18T23:33:13.503Z" }, + { url = "https://files.pythonhosted.org/packages/0e/0d/f5957185c0ee2f3e12f78715aa9e3b353fd83633316c8532b38faa37e3f6/numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d", size = 14964111, upload-time = "2026-05-18T23:33:17.795Z" }, + { url = "https://files.pythonhosted.org/packages/ad/40/40a40ee0ddf7ceb782c49af278894b686e586d65d8c1889c8b5da01a3d7d/numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8", size = 5469159, upload-time = "2026-05-18T23:33:20.654Z" }, + { url = "https://files.pythonhosted.org/packages/63/13/f9a8046535cb21deae82f8d03de9617e08882d274fad2539630761888228/numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538", size = 6798936, upload-time = "2026-05-18T23:33:22.987Z" }, + { url = "https://files.pythonhosted.org/packages/33/a8/6fa8c1a345a8c85dbb21932c447bee07c30a2c2a3f31e369c0a84b300147/numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47", size = 15966692, upload-time = "2026-05-18T23:33:26.62Z" }, + { url = "https://files.pythonhosted.org/packages/02/03/74fe2a4cb3817d94d86402f2506554130a2f01414e299b5a843e5a8a957f/numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93", size = 16918164, upload-time = "2026-05-18T23:33:29.955Z" }, + { url = "https://files.pythonhosted.org/packages/c5/80/3615be3313f7e7696609bc194b9f0101da809df79e859bdb84e0cd043f46/numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8", size = 17322877, upload-time = "2026-05-18T23:33:34.724Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ac/a691e0fe2675e370d0e08ff905adc49a1c8830e8cae03efe4477e92cd55d/numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6", size = 18651487, upload-time = "2026-05-18T23:33:38.217Z" }, + { url = "https://files.pythonhosted.org/packages/15/a7/9bc1cd626d7bf6869bfedf27b91b6ab5dd607758bf8e959d6fa80c6a59cb/numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8", size = 6233945, upload-time = "2026-05-18T23:33:41.331Z" }, + { url = "https://files.pythonhosted.org/packages/c5/31/7fc6239c12bce7e931463251cca4426c465e1876ba3cc785402ef4dd8f4e/numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147", size = 12608406, upload-time = "2026-05-18T23:33:44.131Z" }, + { url = "https://files.pythonhosted.org/packages/27/83/140f85a466595a16382996a1bf06b2b54bcd597488921b0c9daaeeda72af/numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577", size = 10479528, upload-time = "2026-05-18T23:33:50.725Z" }, + { url = "https://files.pythonhosted.org/packages/95/2a/3d7b5ac8aac24feaf9ad7ed58f45b0bbc06d37e4338ae84c9f2298b570f9/numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1", size = 16689119, upload-time = "2026-05-18T23:33:54.065Z" }, + { url = "https://files.pythonhosted.org/packages/ea/12/92c4c131527599e8288d6918e888d88726f84d805d784b771f32408aeaef/numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb", size = 14699246, upload-time = "2026-05-18T23:33:57.621Z" }, + { url = "https://files.pythonhosted.org/packages/ad/fe/c0a6b7b2ca128a8fb228575147073b660656734b8ebe4d76c8fd748dcc79/numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41", size = 5204410, upload-time = "2026-05-18T23:34:00.302Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d4/9770d14ba719432bb90a421bfd443872ed0f70f7264b64bec12ea363d5fd/numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698", size = 6551240, upload-time = "2026-05-18T23:34:02.852Z" }, + { url = "https://files.pythonhosted.org/packages/c9/c6/50a46a6205feba2343f1d6d17438107c5dc491ed1c736e6ea68689fd906b/numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f", size = 15671012, upload-time = "2026-05-18T23:34:05.485Z" }, + { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538, upload-time = "2026-05-18T23:34:09.265Z" }, + { url = "https://files.pythonhosted.org/packages/ae/c5/693cbe59e57db94d2231fa519ca3978dc9e19da5a8f088588f5c6e947ff2/numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a", size = 17020706, upload-time = "2026-05-18T23:34:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541, upload-time = "2026-05-18T23:34:17.024Z" }, + { url = "https://files.pythonhosted.org/packages/f6/81/e1b27545deedce7f4a0b348618c6b62d74e36a4dc9ccd42f3eb2f85eee32/numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45", size = 5962825, upload-time = "2026-05-18T23:34:20.3Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ca/feab00bd44aa5fe1ad2c18f08b4d3bb92e26484b0b1d1443897809ed528c/numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751", size = 12321687, upload-time = "2026-05-18T23:34:23.095Z" }, + { url = "https://files.pythonhosted.org/packages/63/cf/5a6d34850a39d1093558564f77ee8e8e0bee5061151b8f05a55711001ec7/numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8", size = 10221482, upload-time = "2026-05-18T23:34:25.876Z" }, + { url = "https://files.pythonhosted.org/packages/fb/82/bdab26d7438c6791ca31b7c024ca37c1eab8b726ba236129005cd4a06e45/numpy-2.4.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:511dbaf848decaaaf4b4ca48032619fb3138710c4bf7da7617765edad1ef96b0", size = 16684648, upload-time = "2026-05-18T23:34:29.41Z" }, + { url = "https://files.pythonhosted.org/packages/1b/30/a80189bcc7f5e4258b3fbc3968d909d1756f54d023299ecc39ad6fdb9ef8/numpy-2.4.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bf162abab1c1a736333192707cef898e735a5ca00f38f27eeedf44b39d9e85eb", size = 14693902, upload-time = "2026-05-18T23:34:33.013Z" }, + { url = "https://files.pythonhosted.org/packages/97/12/70b5d0d7c15e1ebb8a6a84a8caa1d19e181d84fb58bb6d70aca29099dec1/numpy-2.4.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:043191bfa8eab18c776647b62723ac9dddece59743b13f49b2016094129c2b3f", size = 5198992, upload-time = "2026-05-18T23:34:36.132Z" }, + { url = "https://files.pythonhosted.org/packages/ba/8c/ebd2a8f8a83541f8d38cc5667e8c2b69cecfd30da6e45693e8158857d44b/numpy-2.4.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:6180d8b35af935aed8ece3a85e0a43f87393ae0ac87c8d2c8bd2c993f7270ef3", size = 6546944, upload-time = "2026-05-18T23:34:38.484Z" }, + { url = "https://files.pythonhosted.org/packages/bb/c5/7b863a97a91671a0338f4253bd3b5a3d3852f0692dae91711c9f4a10e787/numpy-2.4.6-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72fbe16c6fac95aedf5937fa873445cec2110be35d8a4e9433d7501fd98dae6b", size = 15669392, upload-time = "2026-05-18T23:34:41.257Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9d/3584b9984ca4c047aea75214ce1a4c4c73d849bd71b604264b7f5653f8a8/numpy-2.4.6-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7830bab239b79cda9c08c2da014761cafb48da6150e1da17ac06283f43b6089", size = 16633220, upload-time = "2026-05-18T23:34:45.075Z" }, + { url = "https://files.pythonhosted.org/packages/05/ae/7c67fba23bd98caec7c99261f3a16072ade14813486b0282cb29846de832/numpy-2.4.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ef4aea96ce4d3b074422cb4f2f64e216bf9e213004bb58ecfdf50ea02ea8eb9a", size = 17020800, upload-time = "2026-05-18T23:34:49.065Z" }, + { url = "https://files.pythonhosted.org/packages/d9/5d/3b6725cb31d983c5e66916f5d36f6d7e5521129e4c4404d64f918292a5b6/numpy-2.4.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dfa20cc6ca228e6b155b11da03825975ce66aea520985dbbddf0f2a5a495c605", size = 18357600, upload-time = "2026-05-18T23:34:52.709Z" }, + { url = "https://files.pythonhosted.org/packages/f7/da/2ccc6c2fe8898dee01d90c75c5f5f914a23daf99e3e0f59516a08760c8b5/numpy-2.4.6-cp313-cp313-win32.whl", hash = "sha256:56b39e5e0622a09a25bf5baf62f4bcf0cb8a41ae6e2819cf49bbc5a74c083f91", size = 5961134, upload-time = "2026-05-18T23:34:55.618Z" }, + { url = "https://files.pythonhosted.org/packages/b5/cd/9cc4dc876fb065d5c220aae4d5e14826b2715331bb7618ce1fb07a679d99/numpy-2.4.6-cp313-cp313-win_amd64.whl", hash = "sha256:c4fc99836233ea196540b17ab0983aff60ed07941751930f5f4d05bc3b3b7359", size = 12318598, upload-time = "2026-05-18T23:34:58.928Z" }, + { url = "https://files.pythonhosted.org/packages/39/1e/c0bcba1f8694116485fe28fd1be698c278fcda4141c5b0e53a2aed8b12a8/numpy-2.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:a7c711e21628b52034bb5ab8d1bce291f752fcc5e92accc615778acee1ff4778", size = 10222272, upload-time = "2026-05-18T23:35:02.167Z" }, + { url = "https://files.pythonhosted.org/packages/63/6d/cc5619247c8f4204e507f5883528372e4ac4bb189e579fb859a12e480b1f/numpy-2.4.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:112b06a867b235ef466ed3508ddf0238050df9c727cafb5301ac385b899189a1", size = 14821197, upload-time = "2026-05-18T23:35:05.468Z" }, + { url = "https://files.pythonhosted.org/packages/00/58/f1c39161c87d9e9bed660f1ed4bafc0e403d5ec9650b6dd77aead07d489b/numpy-2.4.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:eaf7fa2de5c0be8ae6ff8e9bea2ccd725e980541244521d8d4b5f3354a27babe", size = 5326287, upload-time = "2026-05-18T23:35:08.693Z" }, + { url = "https://files.pythonhosted.org/packages/af/57/3917ab0fd97f271a8694513581b8a36c655f111c446852c302f04ccdb6fc/numpy-2.4.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:7265a2f3d436e54ef9f2b52b5c937e6be778781bd97a590319d7348f1c1ca997", size = 6646763, upload-time = "2026-05-18T23:35:11.459Z" }, + { url = "https://files.pythonhosted.org/packages/eb/0f/037e64c494b67581ae18193d770adef354c41f3f2c8ebf865602d949bf8f/numpy-2.4.6-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f74a575920ab21fe304421a3fc28793d82e299cae9eccb37084e9fc7f3617c20", size = 15728070, upload-time = "2026-05-18T23:35:14.79Z" }, + { url = "https://files.pythonhosted.org/packages/21/a6/5d2bae9c9542eb4df16dc9c46dc79c186e9bad53805dfa5399a6023c6db0/numpy-2.4.6-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ede83e07a75dd06bc501566c1eca2afc0d61677c1472ac9ad93fdee6e638a48d", size = 16681752, upload-time = "2026-05-18T23:35:18.836Z" }, + { url = "https://files.pythonhosted.org/packages/92/14/23d1dfb410ae362cd59ce53e936b1513d545eb40db3949ced632e19a459e/numpy-2.4.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:68bb27509ac1b9a3443094260f6326150663b06abe40b73a2f81160623da5b67", size = 17086024, upload-time = "2026-05-18T23:35:22.52Z" }, + { url = "https://files.pythonhosted.org/packages/4b/6e/23595a2c642cdf3bc567877064bdd7f91c8b0038a4453cf2daf7248eafe9/numpy-2.4.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a0df0043bdb289bde1f62da130d20df23d58b45429f752bc7a8fc5325a225ecd", size = 18403398, upload-time = "2026-05-18T23:35:26.398Z" }, + { url = "https://files.pythonhosted.org/packages/8a/90/0ac3bc947217e66dec77e7cbc6a1979d1af70b6461b82f620d3bccd5e4c8/numpy-2.4.6-cp313-cp313t-win32.whl", hash = "sha256:29a287e0cf63ff528da061de6b9f64a4618da591ca1046aafc54062e40ca7eab", size = 6084971, upload-time = "2026-05-18T23:35:29.387Z" }, + { url = "https://files.pythonhosted.org/packages/77/71/5673e351671a1d2bd6063b91b44f70c0affea7d1516fa7a6572941ba4aa1/numpy-2.4.6-cp313-cp313t-win_amd64.whl", hash = "sha256:25c692919ac5a01f170a3bfcd62d745b24fd095c353d50812637d6fcab442e75", size = 12458532, upload-time = "2026-05-18T23:35:32.175Z" }, + { url = "https://files.pythonhosted.org/packages/3f/88/19d3503c5046e688f049274b27a3ef3d771152fa80d3ba3d01a3dff61abe/numpy-2.4.6-cp313-cp313t-win_arm64.whl", hash = "sha256:1e978ec1e8bd0e0e4de6bb75de9d30cbb74db6b6a2bb727618613703ca0167dd", size = 10291881, upload-time = "2026-05-18T23:35:35.465Z" }, + { url = "https://files.pythonhosted.org/packages/f8/91/3ab2044d05fd16d343c5ac2e69b127f1b2854040dd20b193257c78028bd3/numpy-2.4.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:06ca2f61ec4385a07a6977c55ba998a4466c123642b4a32694d3128fce18c079", size = 16683458, upload-time = "2026-05-18T23:35:38.353Z" }, + { url = "https://files.pythonhosted.org/packages/8e/62/764ce66fa4147ae6d73071a3abf804ffe606f174618697c571acdf26a7c9/numpy-2.4.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:38efbc8de75c7a0fc1ac190162d892787f3f47b57cc291231aafee36b80982b7", size = 14704559, upload-time = "2026-05-18T23:35:42.14Z" }, + { url = "https://files.pythonhosted.org/packages/60/61/23f27c172f022e04025b7dc2367f4d63c1a398120607ec896228649a6f48/numpy-2.4.6-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:d581b735e177fdcdce6fed8e7e8880a3fb6ee4e3653a3ac6af01c6f4c03effc5", size = 5209716, upload-time = "2026-05-18T23:35:45.377Z" }, + { url = "https://files.pythonhosted.org/packages/03/71/21cf70dc6ea3e3acb95fc53a265b2fc248b981f0194ceb5b475271b8809d/numpy-2.4.6-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:0a041d3d761dc3c35cc56ce0351506a02bcbc25f7b169f652435141a17db9096", size = 6543947, upload-time = "2026-05-18T23:35:47.926Z" }, + { url = "https://files.pythonhosted.org/packages/d5/91/64288395ee1799bd2e0b04a305dce9666da90c961e1f3fe982a05ee1c036/numpy-2.4.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40fdc1ae7125e518ea98e53e69a4ebc27e1fd50510c47b7ea130cf21e5e1d42b", size = 15685197, upload-time = "2026-05-18T23:35:50.863Z" }, + { url = "https://files.pythonhosted.org/packages/f3/eb/ebffaa97dc55502df69584a8f0dcf07f69a3e0b3e2323670a2722db9aa39/numpy-2.4.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a2c306dea656c12c68f51f4cea133cbe78ca7435eb28c735eac1d3ebe73be6e8", size = 16638245, upload-time = "2026-05-18T23:35:54.752Z" }, + { url = "https://files.pythonhosted.org/packages/b8/0b/54f9da33128d7e350fab89c7455902eeae70349ee52bddb448dc4a576f45/numpy-2.4.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:33111801a01c12a8a1e3721f0a9232f8cfc8ae2c6b7098167e6f623c6073f402", size = 17036587, upload-time = "2026-05-18T23:35:58.355Z" }, + { url = "https://files.pythonhosted.org/packages/b6/f0/fdebc1052db1cc37c64beb22072d67cd6d1c71adca1299f53dec2b5e20d3/numpy-2.4.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ae506e6902902557576a26ff33eda8695e7ecb3cb36c3b573a0765dee114ebdb", size = 18363226, upload-time = "2026-05-18T23:36:02.845Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b4/298628d98c72b57e57f7165ae6a481a1deaf6f3c28262a6e4c739c275930/numpy-2.4.6-cp314-cp314-win32.whl", hash = "sha256:aaf159caa35993cb1f56fb9b8e4610d35758e7ca005412eb1daa856a78c9c4b1", size = 6010196, upload-time = "2026-05-18T23:36:05.92Z" }, + { url = "https://files.pythonhosted.org/packages/df/ac/46de6dda46478f7942f839e094970be2d4a861e005c4b3bf07c92e291a09/numpy-2.4.6-cp314-cp314-win_amd64.whl", hash = "sha256:b507f5c4c1d508876d1819b6bf9a49d365b96320b5d4993426b33a23ca4b8261", size = 12450334, upload-time = "2026-05-18T23:36:09.107Z" }, + { url = "https://files.pythonhosted.org/packages/78/92/b8b798ac784102c0da830d2257d59358e3d3d90d1e2b3f2575dad976c5cf/numpy-2.4.6-cp314-cp314-win_arm64.whl", hash = "sha256:6f41ae150c4e32db4f3310cdaf64b1593a03dbabe29eec77fc9b50fe64061df6", size = 10495678, upload-time = "2026-05-18T23:36:12.766Z" }, + { url = "https://files.pythonhosted.org/packages/30/34/ec28d1aa8115971537c01469ab2011ee96827930f0a124de1000cc2a7ed7/numpy-2.4.6-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ece3d2cfe132e7d51f44a832b303895e6f2d499c5e74dfbdb06ee246147a304a", size = 14823672, upload-time = "2026-05-18T23:36:16.473Z" }, + { url = "https://files.pythonhosted.org/packages/16/bd/f6d1fede4e54e8042a7ff97bb495510f3c220f94bcd9e8b228e87c92cc0d/numpy-2.4.6-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:e3e5193ef5a3dc73bceee50f7fdc2c90dbb76c42df8d8fae3d1067a583df579e", size = 5328731, upload-time = "2026-05-18T23:36:19.767Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f0/e105b9e2fd728a9910103884decd6951d9dd73896b914a98d9a231de02ee/numpy-2.4.6-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:17f9ade344e7d9b464a084d69bcf18fc691cb1db67c62ed80820bf4926d78f0e", size = 6649805, upload-time = "2026-05-18T23:36:22.266Z" }, + { url = "https://files.pythonhosted.org/packages/82/dd/1206a7ca6ab15e3f02069707ca96222e202af681bb73756da7527f3cb837/numpy-2.4.6-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cd5ffd25db4e7ba6a375693b3fc0fc1791ec636c17db3720da19bde7180ec43", size = 15730496, upload-time = "2026-05-18T23:36:25.713Z" }, + { url = "https://files.pythonhosted.org/packages/51/e7/38d3ea825dcab85a591734decb2f6c67caa7c8367d374df1a1c3842f9b07/numpy-2.4.6-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7d92c3819208a60205a12a245c91ad70cb0a85336659b19b834205573ac8456e", size = 16679616, upload-time = "2026-05-18T23:36:29.652Z" }, + { url = "https://files.pythonhosted.org/packages/93/b7/caabfdf53edf663e0b4eb74d7d405d83baef09eb5e83bcd32d601d72b93e/numpy-2.4.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e85b752a1e912b70eaad4fafbd4d1238007ab221de2009b9a2f5ae7461239895", size = 17085145, upload-time = "2026-05-18T23:36:33.449Z" }, + { url = "https://files.pythonhosted.org/packages/f9/45/68d7c33a6bcf3e5aa3bdbd57a367e6f615286dfd6482f97e8ffeb734306e/numpy-2.4.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:29cb7f67d10b479ff07c17d33e39f78c07f71c40ef30d63c153d340e96cd3fb4", size = 18403813, upload-time = "2026-05-18T23:36:37.369Z" }, + { url = "https://files.pythonhosted.org/packages/9c/50/0753655aa844c99cd9e018aacf76f130f1bd81d881bb74bc0aef5d73a8ba/numpy-2.4.6-cp314-cp314t-win32.whl", hash = "sha256:260a5d70215b61ab4fadf5c7baacd64821842975eea312125ed3c39a6391b063", size = 6156982, upload-time = "2026-05-18T23:36:40.817Z" }, + { url = "https://files.pythonhosted.org/packages/b2/d4/7c67becf668f973cb490cec3e98dfd799d866f9c989a54d355672cfa0db6/numpy-2.4.6-cp314-cp314t-win_amd64.whl", hash = "sha256:81a1cca95ed5bb92aa8b10dd2cdc9a0d3853a50fad926c28b5d7e8ea54389627", size = 12638908, upload-time = "2026-05-18T23:36:43.996Z" }, + { url = "https://files.pythonhosted.org/packages/43/bb/e1c71a4295b1b1d1393d50dbb4f2a36283c6859d9d3892e84f00ec5a91d5/numpy-2.4.6-cp314-cp314t-win_arm64.whl", hash = "sha256:0c9136e14ed34a9e343a31c533d78a9813a69a3148332bce5e9821cb2f996e66", size = 10565867, upload-time = "2026-05-18T23:36:47.114Z" }, + { url = "https://files.pythonhosted.org/packages/de/12/b422cc84439adc0d00de605bf4a308890ae5c26f2c71fbd73e5d08fbb0dd/numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662", size = 16847511, upload-time = "2026-05-18T23:36:50.673Z" }, + { url = "https://files.pythonhosted.org/packages/44/53/f481bef68011740f8849418d82db07230e825013f31f4eef5ba5b805316a/numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7", size = 14889064, upload-time = "2026-05-18T23:36:53.879Z" }, + { url = "https://files.pythonhosted.org/packages/7f/57/42ed575c10ced8af951d426bc4e1f8aff16fd851db33f067036215a7f860/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f", size = 5394157, upload-time = "2026-05-18T23:36:57.194Z" }, + { url = "https://files.pythonhosted.org/packages/6a/ef/f66cc724fcc36c1e364c67f51ae9146090b8b584f27d58b97fdae3edd737/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c", size = 6708728, upload-time = "2026-05-18T23:36:59.575Z" }, + { url = "https://files.pythonhosted.org/packages/1a/9c/c531f2293b91265d8b48e9b329f54fdd7ffae73cb4134ea10cca4237e9cc/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0", size = 15798374, upload-time = "2026-05-18T23:37:02.674Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b0/413077f6b1153ed3cba361401c6783bbad6114804a000cc22eb71c13e190/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02", size = 16747286, upload-time = "2026-05-18T23:37:06.327Z" }, + { url = "https://files.pythonhosted.org/packages/15/ce/e5ec180bc41812edcd8daeb8639d205622c0e8c02259d8ab25a0201b3c2a/numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73", size = 12504263, upload-time = "2026-05-18T23:37:09.715Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.5" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/4e/3a/8770c288c47f0b5c2a786d3c20e79f66fd245f2d42cd232d7cd5e00e83e5/numpy-2.5.5.tar.gz", hash = "sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf", size = 20873892, upload-time = "2026-11-15T21:32:28.607Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/74/5b99f425938870958d43dc9f7b17c684e793ce47ec46b7885cdc7acea285/numpy-2.5.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7da9a248f149cfbb220c6da964a59c8d051d516704f7758acfb81eb382a05d97", size = 14750374, upload-time = "2026-11-15T21:30:10.113Z" }, + { url = "https://files.pythonhosted.org/packages/5c/f4/06db317e93dd6d618786004c1761214b113832bb77294c8513776956702a/numpy-2.5.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b96e9ee49ccbdb5676359f852a4497f7a9c5df6c377d8877f5330d6fd3ff42e4", size = 10749920, upload-time = "2026-11-15T21:30:13.092Z" }, + { url = "https://files.pythonhosted.org/packages/8a/92/6de34324a266b73c04ba977db5864b9016500076b26f09078a565f527d34/numpy-2.5.5-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a3856a97e48ed8371c680fb04120b99fbcc29f2076ebe6dc3deb34f77947c5ca", size = 5513680, upload-time = "2026-11-15T21:30:15.201Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a1/6563b74cd67e3873f9897afebb3244529b1494d4c0df30f3201329a7e316/numpy-2.5.5-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:f5e8603f0892d1b848e12124863b5b29af72383ee9b25ddc6fe4967d4c1ee6ef", size = 6797540, upload-time = "2026-11-15T21:30:17.172Z" }, + { url = "https://files.pythonhosted.org/packages/c2/22/82184e9a5b50a4a298e9f8fe0bd8cfc483672dbfea8a3b57c78e2376b139/numpy-2.5.5-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a0750f2156d53446caca85663d0b65d67214e1664b9050454a731ea1418d176a", size = 15284117, upload-time = "2026-11-15T21:30:19.167Z" }, + { url = "https://files.pythonhosted.org/packages/99/61/522b973ba38987b22a4a71beaed2ea6ac9fd4f687baaa2bc9a45100625e0/numpy-2.5.5-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:704d819265e5d1064d932968e9ee85fff2103ccc78c05b878c06943ba27b8507", size = 15720599, upload-time = "2026-11-15T21:30:21.273Z" }, + { url = "https://files.pythonhosted.org/packages/25/cd/182cf60bd9c34e617c516f138f2f68988760062fa65fca8fcc97875cf7cf/numpy-2.5.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:86868185bf4b6c4e5a8628ac42cfa165cd9530266c731f7dd1d11b4ad7e7cd1c", size = 16503566, upload-time = "2026-11-15T21:30:24.023Z" }, + { url = "https://files.pythonhosted.org/packages/f3/57/4fa4723e80be805f68af552731ed483974b2a11e511284a9ef6aafbcb3cf/numpy-2.5.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7fb87c4bcc73850ef433a0c42f096b010d3d3d284e9d00028bb030b43df3d078", size = 17082560, upload-time = "2026-11-15T21:30:26.224Z" }, + { url = "https://files.pythonhosted.org/packages/d5/0b/73d2bd5be85d3178a862e8354e2d6441b4040fadf1e7d999e01b0bdfa5c6/numpy-2.5.5-cp312-cp312-win32.whl", hash = "sha256:263b2aa236d752b18f90c5107137d24b2e3856d7db37725609f0ab5bcdb58881", size = 6146378, upload-time = "2026-11-15T21:30:28.328Z" }, + { url = "https://files.pythonhosted.org/packages/d1/71/b1ce51834c21020d189332979d38ba7350eb6cd7ca8c8ec424a663b0ca6f/numpy-2.5.5-cp312-cp312-win_amd64.whl", hash = "sha256:919eb420662b0b4ba34889df503f3d5329775b0c1d5f7e5f5af4fba8315b1e30", size = 12580189, upload-time = "2026-11-15T21:30:30.025Z" }, + { url = "https://files.pythonhosted.org/packages/c2/5e/09ae9d0d02fbfe6b160043349bbe73e6bbbbfb2565bb46146dd943687271/numpy-2.5.5-cp312-cp312-win_arm64.whl", hash = "sha256:f6622e32cb46c60bee3b2c7dd7f5c22bdc86fcb8630336b4822ec81c3986111a", size = 10535386, upload-time = "2026-11-15T21:30:32.112Z" }, + { url = "https://files.pythonhosted.org/packages/0f/fa/4ae71d860267f2f9eaf7640516f693acf61c9575d48157cdea459c0215aa/numpy-2.5.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:228e3d90e967495d61ddc79dd64e95267aae3bcf1b1c516a6186429106a0b444", size = 14747053, upload-time = "2026-11-15T21:30:34.251Z" }, + { url = "https://files.pythonhosted.org/packages/d4/9a/01a332ebb0899ddb14d782f86ed66d080463e5387a8778029462d1902019/numpy-2.5.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7e71ac4284c700afa654e2d15b1b174166710dca932f24045e5dc92001b5bda0", size = 10744599, upload-time = "2026-11-15T21:30:36.23Z" }, + { url = "https://files.pythonhosted.org/packages/03/bd/a1a721ab8da5632c811caf56b7735646a440eddbbf6e57817ae1a900c9c9/numpy-2.5.5-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:e0cf407a83118faf0463ade48a4533982f1737c7c58aac29e08855f7d9ad2977", size = 5508218, upload-time = "2026-11-15T21:30:38.357Z" }, + { url = "https://files.pythonhosted.org/packages/9c/63/eb5311935b313926d9127ec59632cc74bdf1fa815089fba4dbee9c6dd90c/numpy-2.5.5-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:ac910558645a4b006f70596b450712b8564730c1b2ac10291fcedd656d321ec0", size = 6794377, upload-time = "2026-11-15T21:30:40.026Z" }, + { url = "https://files.pythonhosted.org/packages/57/06/de83b859944409bb9058bc6110581a3d7fc1f54d6df1222744911d7f6b19/numpy-2.5.5-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae2b8285d0b4eed24739c3ca9ec0fa424a0247489c01e1d5fe2815a599e11d33", size = 15278148, upload-time = "2026-11-15T21:30:41.819Z" }, + { url = "https://files.pythonhosted.org/packages/40/d6/68dd5a83914bbcaf32b3165993f7955979916708cb0156d1e28231e18803/numpy-2.5.5-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:824025655df929268bfe6b47ed91a00d14209a6f760847cf150be446829e1ce4", size = 15713899, upload-time = "2026-11-15T21:30:44.066Z" }, + { url = "https://files.pythonhosted.org/packages/1f/6e/a78932a1a838ce0d7d759cee2aca225054da8aa4151688edb5867b4af491/numpy-2.5.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4302902ebf82d37f446664757be59db53587822c8b35f16368ca69fe66ec4315", size = 16501259, upload-time = "2026-11-15T21:30:46.469Z" }, + { url = "https://files.pythonhosted.org/packages/bc/08/f4da0ebfa6b684c18f1c300b279bd706f68f3828a2c9aaa1bca54c93a16f/numpy-2.5.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3cedc2980b45794a6a2cfee9c8c3a80f04517082cc1d387e4cc895506c481696", size = 17077101, upload-time = "2026-11-15T21:30:48.916Z" }, + { url = "https://files.pythonhosted.org/packages/1b/81/0ccf314229450ec76363f3f6ec13d0ef54a24c53188787fc13136d6e52e6/numpy-2.5.5-cp313-cp313-win32.whl", hash = "sha256:10396f7c5ebc37d8f3cbdec44e3313912ccc2dc5841cc905de5de54ebbe8e2d3", size = 6141929, upload-time = "2026-11-15T21:30:51.528Z" }, + { url = "https://files.pythonhosted.org/packages/45/74/bb9161943fb65caf24e4bb04c788f5c7815e6cb78ac595e7f46781033c82/numpy-2.5.5-cp313-cp313-win_amd64.whl", hash = "sha256:e0608d1585557b68dcb6a70a41654f7536567960afad79d91752d2863b242b68", size = 12573354, upload-time = "2026-11-15T21:30:53.308Z" }, + { url = "https://files.pythonhosted.org/packages/ac/b0/792631d03588912e948c1249c03a78ca9af0c548670f8fd63ea014cbc14a/numpy-2.5.5-cp313-cp313-win_arm64.whl", hash = "sha256:e0b87886bb45621d9279dad4ab9f2d154b5db0b019d378c107b8f71527b06a4a", size = 10528296, upload-time = "2026-11-15T21:30:55.681Z" }, + { url = "https://files.pythonhosted.org/packages/6a/9a/f1493d897f51947644c45516ba63a67e66a7b06692f930fe37c58346cfbd/numpy-2.5.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ab3ff087826c49d07953d0219eb00663ce5b1a0ef0a6b757e1ac041b09387428", size = 14754557, upload-time = "2026-11-15T21:30:58.008Z" }, + { url = "https://files.pythonhosted.org/packages/18/46/5d1c70b54257a56b3137d6fcc90c6db306f6177c02951eac7ebb42e7e1c7/numpy-2.5.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7ca51125c76817de53473dae31ddc17213776472761bea9cca68a1a0037a4827", size = 10754769, upload-time = "2026-11-15T21:31:00.146Z" }, + { url = "https://files.pythonhosted.org/packages/4c/e1/016c3d9c9c6e5a457d615cfbcf6bcd01a4cabde82c639776be23365186c1/numpy-2.5.5-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:229743571f901a082f031f511dc4f926b4b4a714075d98b1ff2af62d836365ac", size = 5518338, upload-time = "2026-11-15T21:31:02.38Z" }, + { url = "https://files.pythonhosted.org/packages/12/7f/f2369b42edb1a32a7f048c2126e6ab5b8bc527308ce9eb6e680ad9c3d2e7/numpy-2.5.5-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:1c24be6a82f5f257afc4dbefde4c3b56dee02146dfed2be2811940e79576b237", size = 6800110, upload-time = "2026-11-15T21:31:04.211Z" }, + { url = "https://files.pythonhosted.org/packages/26/5b/5cd4b88a64bb57ca6d3bd6a9e057db445544a2179a2ebf985660e0454648/numpy-2.5.5-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cc6eb7502facce90349b4097a26821af224aaa0ab36e78304711cdb544352882", size = 15300777, upload-time = "2026-11-15T21:31:05.967Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1f/fcdce1061fba2bfb2e9bfda01fbd8132d5f7522a4f7c8e2b2f629d54ee38/numpy-2.5.5-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c48960d420e90cf305cb1fde0d4e6082cc90512cda87a9acf0b6e04e91cf4abe", size = 15718051, upload-time = "2026-11-15T21:31:08.12Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/9b7de1d0b747e3d1d24874b1cba374c8b0eab6c2034b785387677ecc4dba/numpy-2.5.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:5e202d5facc9c0681834018062466d0b3eabd48c540c3570f72905c97f641a90", size = 16518123, upload-time = "2026-11-15T21:31:10.714Z" }, + { url = "https://files.pythonhosted.org/packages/66/14/60c3fc30e63876e44212392eacd4ea1bd201c29835c99f42daa04c2501e4/numpy-2.5.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e10e81d1db6c8fa507f61bebfd1ea383971dbc40c2005ed4db88fac5538b1ef6", size = 17079719, upload-time = "2026-11-15T21:31:13.245Z" }, + { url = "https://files.pythonhosted.org/packages/ac/b9/c0d3a63804a58823155ae221ce48afa4530e0cab8a33fcfb76a7b46b11ef/numpy-2.5.5-cp314-cp314-win32.whl", hash = "sha256:ef2a874cc70e2132c1c499268bdc34e211a715e481bc33c97b8a0190f2559295", size = 6193548, upload-time = "2026-11-15T21:31:15.602Z" }, + { url = "https://files.pythonhosted.org/packages/74/e2/494516771374b43060c1b778b371cba53d576abd3aee1275eecd73896e3b/numpy-2.5.5-cp314-cp314-win_amd64.whl", hash = "sha256:20145b11776d2f7570cd61351b156a51d3a341822282095baa819d87272bc710", size = 12710543, upload-time = "2026-11-15T21:31:17.461Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e7/abe56b23f4dddf8277429d0efa442abac4c1940ec776c1b707c1e58435e8/numpy-2.5.5-cp314-cp314-win_arm64.whl", hash = "sha256:2abd39cfbb3d2af11e9bc8cc92b08cd089b0975fe9b1a30c8b7c740c67d397ce", size = 10812026, upload-time = "2026-11-15T21:31:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/06/76/2974340b984ecd43bb4ee91c06a3fd59968330752c316d36fb8a23310ac1/numpy-2.5.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f82a7567c590ff266f8c18fd527a0662edde074de11be256541a656e274f2b05", size = 10857031, upload-time = "2026-11-15T21:31:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/38/d2/cc6d1f0f4c848f18e30d0f464a70598369336591920952f6aee440da4a2f/numpy-2.5.5-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:31e5be6cd4b896004cb9e416741612ade530fc9a04bceca5219cf66a675113b4", size = 5620763, upload-time = "2026-11-15T21:31:24.1Z" }, + { url = "https://files.pythonhosted.org/packages/c7/d0/2d014e5b68965530ebe46c0d2b07b1242210a029acba5800f53fcb4d4973/numpy-2.5.5-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:b3d328eebe0056c634878c251131d73d74e0c4af317a3aea718816d6fa0bb963", size = 6897520, upload-time = "2026-11-15T21:31:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/b1/ee/a0fb000c6a57602a7a2958f72a5d07837dd88cb9a158f1edb0a279126428/numpy-2.5.5-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e99bf8a3d54693f2063fa6c7d13955d460a9f543d9dbc80e69a92da288259b28", size = 15342131, upload-time = "2026-11-15T21:31:27.707Z" }, + { url = "https://files.pythonhosted.org/packages/93/43/85cfae380e4e2fe1d246c39a12c88c7a224e751604b6fa13236df3b86600/numpy-2.5.5-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:479e43c183049ec1a820eeb36549e493924f56b3e893a1d5865d0fff12abad47", size = 15751077, upload-time = "2026-11-15T21:31:29.851Z" }, + { url = "https://files.pythonhosted.org/packages/cd/41/5938f05404d2f4531409b658cfd578b0b653a87f22915759afa7f414b4f3/numpy-2.5.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9f44875964889bd9088cf838d191b58c04088d10b4dc9b140e9da2431ecfbb60", size = 16569544, upload-time = "2026-11-15T21:31:32.017Z" }, + { url = "https://files.pythonhosted.org/packages/a0/b1/75f51d9e2fb970228bd7599d46f34eb0829070b4df8b293c43fdf1c81c44/numpy-2.5.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2a9c502cdb9a3050ac1686774624cc278658b11f72e11b971a3a8542d6ded357", size = 17122494, upload-time = "2026-11-15T21:31:34.267Z" }, + { url = "https://files.pythonhosted.org/packages/71/1b/68f54066eb445a98e7c677863d1ece9667151f8d8565eea5860d8445fb72/numpy-2.5.5-cp314-cp314t-win32.whl", hash = "sha256:dec156cda7322bcb1479ca992794705fe226a911b0ffebe13bff97fa1f3be63c", size = 6350011, upload-time = "2026-11-15T21:31:36.491Z" }, + { url = "https://files.pythonhosted.org/packages/58/29/c57eca063b680b23c0ca8d07789b3011a9e962fd4994a656b11f7a21226e/numpy-2.5.5-cp314-cp314t-win_amd64.whl", hash = "sha256:84dfb1611993a3525b250c955b1e2ebab6ce0ed36e4ab4dd5746432dd362fb5d", size = 12909875, upload-time = "2026-11-15T21:31:38.311Z" }, + { url = "https://files.pythonhosted.org/packages/72/06/70b2717589eb8ba57bce789c0f1e477fc5869c720fa0ad444e31fb9aef55/numpy-2.5.5-cp314-cp314t-win_arm64.whl", hash = "sha256:567994389edd2963b643d63d826138402a63401176f1daf84dbb3204eb838b39", size = 10899621, upload-time = "2026-11-15T21:31:40.518Z" }, + { url = "https://files.pythonhosted.org/packages/9c/61/8578c9fdbfb59ba2c4ee633102666937ce4e66f8c3de8bc700573c856af5/numpy-2.5.5-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:ad0c8b963f9281f2eb118e283eb61964c716c8e344ed8e8c309b49c586d41ed1", size = 14752489, upload-time = "2026-11-15T21:31:42.902Z" }, + { url = "https://files.pythonhosted.org/packages/a7/ef/d0f38ea7ca697c03af3d687cb70d8ddc8414dcf430f8f7194ab7359d80f6/numpy-2.5.5-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:d7d9be35d50366fe5ac28188364154c9e1e22ad1b977a06c9465c0680c8eeefe", size = 10753050, upload-time = "2026-11-15T21:31:45.123Z" }, + { url = "https://files.pythonhosted.org/packages/84/b7/de9e6d1ffbc33cc7bcf452c7924a7953daaf06bde559b73ebef93b7f85c6/numpy-2.5.5-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:d0c7c0dfabdcb7cde080b7c9ef301c7533e90110198b39965141a903c7dddcf8", size = 5516639, upload-time = "2026-11-15T21:31:47.537Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ac/a95824882c5818a7e31893ebdab2944f5e65b4108bc8bed9e240e3c624be/numpy-2.5.5-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:b7dd0287b6cdd35a27d5678a56b1bc508ff206c2b78b30b4821dd5c3197b393a", size = 6797936, upload-time = "2026-11-15T21:31:49.2Z" }, + { url = "https://files.pythonhosted.org/packages/08/64/c39a7b41df0d433ff37fd4fdd6e32b3fa3b51a82110bbcd386d0e37f5da6/numpy-2.5.5-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a207eb88a18e30add597c366c1db7e79f48fc94084b8e7dbd0eefb95a645db12", size = 15294336, upload-time = "2026-11-15T21:31:50.908Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ce/ef0ca1a7dbf657a68ec52ce150cc477a7cdd8d09c7ef77662cdecbca39e4/numpy-2.5.5-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c3e1ac3cd5d3329f4d38709ff4c21f0621bbe8779c094d6de8ec8347246fcdc", size = 15713633, upload-time = "2026-11-15T21:31:53.261Z" }, + { url = "https://files.pythonhosted.org/packages/dd/08/023029d269a7adec40749ef98439af4260ee92bc203d8a7749cc4eee8183/numpy-2.5.5-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:095113ee2ceab6a9501b184eff5ea806973d3a63d74a8cbc15e4911e754da9c1", size = 16510376, upload-time = "2026-11-15T21:31:55.401Z" }, + { url = "https://files.pythonhosted.org/packages/9f/0b/38e65a5ff61b174df3a930898a3b31e94b24caaf4155c719d18417ad63b1/numpy-2.5.5-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:bea7de36bb304a850710c1dfbb35e7cdb9a005928106a3adfc6dc3a753469dec", size = 17078342, upload-time = "2026-11-15T21:31:57.714Z" }, + { url = "https://files.pythonhosted.org/packages/4d/3e/09a62f920e5869888387ba988eeba560057c1f718404cc737e5dbc07e81e/numpy-2.5.5-cp315-cp315-win32.whl", hash = "sha256:fd47c92e0d1e53f9498b1a30305072434fbae6b5a305cbcab514f959e9ce0fab", size = 6192918, upload-time = "2026-11-15T21:31:59.798Z" }, + { url = "https://files.pythonhosted.org/packages/5a/7e/a4c5b4b30dbab285b380130dbf780bccece06de020221491058ea2c66310/numpy-2.5.5-cp315-cp315-win_amd64.whl", hash = "sha256:ae9cfe4e985139c5f2db69d4310de7348bd0abc02cfdc06991c4419065f6fdca", size = 12710024, upload-time = "2026-11-15T21:32:01.352Z" }, + { url = "https://files.pythonhosted.org/packages/7d/57/bdec7de41e7442b9ea0ac938b7597f754d4d625d853551466e8a208e3e64/numpy-2.5.5-cp315-cp315-win_arm64.whl", hash = "sha256:08f1b9abf1707fa89c125aaa17e78389c063fb20ce37a141b47821e996f4a1db", size = 10814707, upload-time = "2026-11-15T21:32:03.326Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e9/7f20d2144d4fbe2876d567a1ae1266cb62a67498af7d3006e2a0ba93deed/numpy-2.5.5-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3d59ab8f6bfc4ffd29b0f558450e17922c1bc88459882e37726fbcd5834afbfd", size = 14845589, upload-time = "2026-11-15T21:32:05.476Z" }, + { url = "https://files.pythonhosted.org/packages/66/02/ded297ac4c917f7cf90254a50f888f992c028e2ed9a3efd82349c12d4904/numpy-2.5.5-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bf6fa5a4d73b3a9699a57b8824d4863acde7241808a5305882222843537f02a2", size = 10851494, upload-time = "2026-11-15T21:32:07.944Z" }, + { url = "https://files.pythonhosted.org/packages/c6/ac/1ae013866575827dcec6239ca413b76c05652fa5ac405afd8d904940197c/numpy-2.5.5-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:d64daa409e9b1ac818b0c59e47b005f802e130c8281e40c6a2f7e70c43f75e0f", size = 5615246, upload-time = "2026-11-15T21:32:09.876Z" }, + { url = "https://files.pythonhosted.org/packages/f5/e2/2d89896606a325e584157fe669578ac1b22558e4b3e45e0cb554970e5a19/numpy-2.5.5-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:ff5c1ab54a637c0adcdbb69ad10e5c4f1c4dedba69c0d1de383249b70c36908f", size = 6890873, upload-time = "2026-11-15T21:32:11.545Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a0/de0484dbe0665ae69cbf9c2bb777c2fa4f402e03a102384c54fe54048d44/numpy-2.5.5-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:178cb1eaed819b2cb4e398c554b0776d1499f307e30cb58b9bae1921de35dae6", size = 15340077, upload-time = "2026-11-15T21:32:13.223Z" }, + { url = "https://files.pythonhosted.org/packages/39/d8/60a70cb61b8063e4dfc5b8b55f93c247cb7f1a36515d810e70ca94446396/numpy-2.5.5-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6e30929e3443f46aa7be2749fb003fefbbad6b6a1e2168bf8850a55b657914a", size = 15752447, upload-time = "2026-11-15T21:32:15.629Z" }, + { url = "https://files.pythonhosted.org/packages/09/14/db7e8f5560a329a118bcea53da883f077bac5f00124799c5ac7e9eb1823e/numpy-2.5.5-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:2efb2ae4e0414b6bd636dde7235c158cd65dd52891ff64a320a4847a8ce7400f", size = 16566475, upload-time = "2026-11-15T21:32:17.974Z" }, + { url = "https://files.pythonhosted.org/packages/ec/33/060b8c68e2ed79fe50a20139f7f89fa2d9862f2d3e127fc353d8e6b2589c/numpy-2.5.5-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:32dce94d74bb4d5bb058d65b0d9dad7fa61d07ff9375fd7695d8aa7ea82ee73d", size = 17120613, upload-time = "2026-11-15T21:32:20.094Z" }, + { url = "https://files.pythonhosted.org/packages/99/3a/ab02c902cb380d0b950eccda4f0b67ac4f66ba490c98756d38adc4b3ccb5/numpy-2.5.5-cp315-cp315t-win32.whl", hash = "sha256:b5d08742de581c9eb61102768ccca125a2982913de399611b56981a07278de74", size = 6344124, upload-time = "2026-11-15T21:32:22.058Z" }, + { url = "https://files.pythonhosted.org/packages/fd/49/b04b1f12231e6fbcf26fd5e7949f629530e11c46a6fcd91923f61b017243/numpy-2.5.5-cp315-cp315t-win_amd64.whl", hash = "sha256:410eab02c6718cb42d06ccbb8604659f3522d2ce06ae70cacd5042092659f5af", size = 12898288, upload-time = "2026-11-15T21:32:23.871Z" }, + { url = "https://files.pythonhosted.org/packages/36/7b/935a5896b0bd441c6dd6da81f39bc5ebf8d5da891b7dcff768e1e1c088b5/numpy-2.5.5-cp315-cp315t-win_arm64.whl", hash = "sha256:b6ecbc1ff292c6799067d8064a4dd35cd25ba9d1a24aa41dd635d701691a49b5", size = 10891314, upload-time = "2026-11-15T21:32:26.357Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "nvidia-cuda-nvrtc", version = "13.0.88", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.4.1.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-cuda-nvrtc", version = "13.2.86", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/d0/a0/5cd9d4b08a8320f7ca150ee0d66c97e98092922e338336cb4b62da7500c3/nvidia_cublas-13.4.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:4eb1472bf92b741e7cf24da7978dde251b58ddec2092d9f6a04f3623eb4e9a15", size = 513048232, upload-time = "2026-07-16T09:45:07.751Z" }, + { url = "https://files.pythonhosted.org/packages/e1/97/d483a41da34df5c88727c57319576967f6d7befba5028d70928d2999635e/nvidia_cublas-13.4.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:a5917cb642cfb07f4a0231ee16aec7e2e0357d8cb8b1b78a0c9c68dba3e6afc7", size = 404870805, upload-time = "2026-07-16T09:46:05.62Z" }, +] + +[[package]] +name = "nvidia-cuda-cccl" +version = "13.3.5.0.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/dc/9a056ef9bd05c55ddaed3afce160702e4ce8303b9ec1b38066044c18dcd2/nvidia_cuda_cccl-13.3.5.0.6-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6f30b8076b3e69951c459c94ae190bde51924b320076ebaec376d36848b4c76e", size = 4113650, upload-time = "2026-11-04T23:21:46.803Z" }, + { url = "https://files.pythonhosted.org/packages/a7/7e/4aa67cca14e0558b5a151a692f5ffe609930cdfc20d16c7a584de68424d4/nvidia_cuda_cccl-13.3.5.0.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d5230098fa2df5021e1a00c0c4eee41797671a91119d31e892463e5ccf3ee326", size = 4113651, upload-time = "2026-11-04T23:21:54.262Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.2.86" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/ab/52414925ea803a5f86b994ae97d951e5943ed27a6f1da4a5c4ac09e308af/nvidia_cuda_cupti-13.2.86-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:d9a5c133f73fcb9013f3ada0da6fb54d4117618d81f3f5a0419417ea6ee829d4", size = 11760263, upload-time = "2026-07-16T09:35:34.643Z" }, + { url = "https://files.pythonhosted.org/packages/b4/76/a10d9fb5d9a0e46d5f95e5520bd1b2d8ad22a9c0a09d2f8c20c5ee842a96/nvidia_cuda_cupti-13.2.86-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:8fa29f15dd8336181f961764d9d95236fc6b931dd0c8fcf8cd70aab0c310b586", size = 11988600, upload-time = "2026-07-16T09:36:06.061Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.2.86" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/39/c58835ec8392a91b8d7bad83760eafc3085f64788b722ec2b44a27b3ca3e/nvidia_cuda_nvrtc-13.2.86-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:8111c5130e967b78222ea2124145f8efe9ce201b752b2579a2513100a53be1c5", size = 47018468, upload-time = "2026-07-16T09:40:35.085Z" }, + { url = "https://files.pythonhosted.org/packages/13/95/029e91026e1d378cba9fb2cdb62394bb15d06de7586bab73d76397df6b7f/nvidia_cuda_nvrtc-13.2.86-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1e5d7b411a2eb83f5c71c98d58133a763fc9fa86a4241ee320c5c4782d9ad1fd", size = 44755454, upload-time = "2026-07-16T09:39:59.909Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.2.86" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/d4/fa981071e3d9f29158ca16c69ee617831cd6df4dd47024149c16eec717f8/nvidia_cuda_runtime-13.2.86-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:37844957894bfdecf90243568d21a2cb251b66106915b71459a23c8e6ef2da69", size = 2341433, upload-time = "2026-07-16T09:33:00.116Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/8f8c5e893d183082ea78f973aebc7ebc845ee219d68bddac73b0f62490fe/nvidia_cuda_runtime-13.2.86-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3498247680dfddce31bad102af7e3e26fc795342a3cac64722bb0fa95e7f60f0", size = 2323576, upload-time = "2026-07-16T09:33:28.652Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.24.0.43" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "nvidia-cublas", version = "13.1.1.3", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/30/7c257e3d5cb4fecb147b93895c66e29c93f8e76d74b45bb418ff0587c4ec/nvidia_cudnn_cu13-9.24.0.43-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:a6812a554a1ff0413e9c52b84c26c050380649ab9615f9c16bded368ce9f421f", size = 650976863, upload-time = "2026-07-02T16:23:39.248Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ba/791cffd048fe5b044e620df55267e3e95c0e6e07d50b41e377c03dfc910f/nvidia_cudnn_cu13-9.24.0.43-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:71f181cd810e90f9b6023b01186fe82d13d65f0ec098581ee201d39fad769e4b", size = 553099438, upload-time = "2026-07-02T16:27:42.58Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.26.0.51" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-cublas", version = "13.4.1.3", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/1c/01e1dd3dec6ffe0baaff7e722b8946d867353d05a01301f128f1730fde0b/nvidia_cudnn_cu13-9.26.0.51-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:8e5b4f5eccff721416f70ecf4353172fc4d5cdd8ca869fe6f983a4a5b0147b20", size = 595329497, upload-time = "2026-09-10T16:45:39.945Z" }, + { url = "https://files.pythonhosted.org/packages/ac/1b/ea72dd62f26ce3e0a7870b85148b75a5987507629b712deebeb87f7cce9a/nvidia_cudnn_cu13-9.26.0.51-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:9c976d539786698c71d6bcdbe2053b7485fae062ff7e1215d2f2ff67b1a2149a", size = 519150073, upload-time = "2026-09-10T16:47:58.332Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.2.0.57" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/8d/f650e6d527f9d22b5ded906c000eaebb037721c06d4ecd906df62f300979/nvidia_cufft-12.2.0.57-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1ed438568ae1088ba2c25789d10205d4104b8b140b7bd942e39a787947a0fb74", size = 218244742, upload-time = "2026-07-16T09:47:08.76Z" }, + { url = "https://files.pythonhosted.org/packages/41/28/868ed0c6ade5e6a75b25166b3cf191f4a2ff58ad618c1e40befb776c97c5/nvidia_cufft-12.2.0.57-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34da27fadf3979b0b042c43823f0530be8408b86df31ee0108e1ca0b621d4ef6", size = 218258101, upload-time = "2026-07-16T09:47:50.978Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.17.1.22" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/fd/4b4157512a131a51e1514d40d0199b1c5b7b10c6856db274ff22e5fe15be/nvidia_cufile-1.17.1.22-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bec33d7f1f12691dce330275246587569c2ed90b1ce43b0f94b3e1ce9268744b", size = 1226736, upload-time = "2026-04-13T09:52:40.142Z" }, + { url = "https://files.pythonhosted.org/packages/23/c5/661a73a9042fc5f81cdd5fe6e89f4170b3b33f7962e709987e2b5e5f1381/nvidia_cufile-1.17.1.22-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:87feaf8c3ad20d3d03a01933181801ff6892bace5c8f0b1e4b48f319d3e62d36", size = 1387670, upload-time = "2026-04-13T09:52:57.783Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "nvidia-cublas", version = "13.1.1.3", source = { registry = "https://pypi.org/simple" } }, + { name = "nvidia-cusparse", version = "12.6.3.3", source = { registry = "https://pypi.org/simple" } }, + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.2.0.11" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-cublas", version = "13.4.1.3", source = { registry = "https://pypi.org/simple" } }, + { name = "nvidia-cusparse", version = "12.7.10.12", source = { registry = "https://pypi.org/simple" } }, + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/df/9e6b603f1d64040ce3e076e9bce1b78e2d588d0aabc9783f351cecd861ab/nvidia_cusolver-12.2.0.11-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:8be097fca28de6be0990ab216ee9b804dd51077e1d1d83acf6c9850650bdc64d", size = 250383075, upload-time = "2026-07-16T09:50:16.355Z" }, + { url = "https://files.pythonhosted.org/packages/e4/a4/90f7ade9992190788658c3c285f196fdb9bcc3a5bb93a325c245121d22fd/nvidia_cusolver-12.2.0.11-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:fab5778f6769947389a1a6abc07e635576825a08c0ffc68c3ae7f1392c794b42", size = 227913465, upload-time = "2026-07-16T09:50:56.976Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.7.10.12" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/35/abbd278fb6d039fcfb5175efa10a21007a11878bec59920d84854b47d766/nvidia_cusparse-12.7.10.12-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:597eff2cd83e3ab1d1e3a0dce9c9c879d77cf64ec2659bfdb5af6a5d02e7aaa9", size = 169043093, upload-time = "2026-07-16T09:51:37.058Z" }, + { url = "https://files.pythonhosted.org/packages/bc/46/3a9700cc13f30c9279af9a862363535c814fa27597199b21fd93cad66237/nvidia_cusparse-12.7.10.12-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:25907c75e4db1581685f06f61cc6cdecc04611765516a52373e0a18ebd69fa00", size = 150999307, upload-time = "2026-07-16T09:52:17.727Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.30.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/21/a73174c6157101bdf1ffc22b517f76ff0082613989dd9bc8f43e8034caac/nvidia_nccl_cu13-2.30.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:ca786ffa5a647c75d4d1f5cc72a6c4f537947e2ba8823d7c8aaf768e7a7b9f77", size = 215983881, upload-time = "2026-06-09T03:23:15.633Z" }, + { url = "https://files.pythonhosted.org/packages/3f/34/c500f90c7ae641b8e0f98965b36b8a7ac79cc8b296e8d251fe3eb592ee54/nvidia_nccl_cu13-2.30.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:cefa7fdb9710efd0f39c5f1be1d61ff6fc9a996c451265bd7fbdcf9455ed4b50", size = 215965170, upload-time = "2026-06-09T03:23:39.73Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.7.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "nvidia-cuda-cccl" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/11/1767ef120299972822a43aceffbc81ac813aad2089d817e36e4e12aa4c9c/nvidia_nvshmem_cu13-3.7.2-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0e748308b9e0a8a8d81859353f3e6c98fbe85a85f652a915a2ba60149a0bd124", size = 135174619, upload-time = "2026-07-17T19:24:15.404Z" }, + { url = "https://files.pythonhosted.org/packages/4f/4a/037dfbbafc96ad1828ef62326f27970cae2c0eb271cf5b8e6922f32a7427/nvidia_nvshmem_cu13-3.7.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b9a4f843c62b5dded8ad33fd6d220e007dcd39f06cee549292f5ba14ce4c235c", size = 135397797, upload-time = "2026-07-17T19:25:26.4Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.2.86" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/ee/16bde09927e7ffacd50b117cd7d1dc764d145f03249fc41fdf6dfba3301f/nvidia_nvtx-13.2.86-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:968ce72baee2a01791c7d3254000eac81f24677b0b91c62d21b449a1f309c245", size = 153463, upload-time = "2026-07-16T09:41:23.242Z" }, + { url = "https://files.pythonhosted.org/packages/52/5f/74e2d29240de30a971d59ca20f4a3c4f2720cd49752809eeb4177d385c2c/nvidia_nvtx-13.2.86-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1c6ae1be92fba569dd271f7b9b3056f99f5642726dc6c53d1b93ae4110c398fb", size = 154292, upload-time = "2026-07-16T09:40:53.791Z" }, +] + +[[package]] +name = "opencv-python" +version = "5.1.0.95" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/24/a2/97d6867da049747d3cd39ddddbe31d421eec42a2f4edadd2e20d5a84b1da/opencv_python-5.1.0.95.tar.gz", hash = "sha256:3d4a901a458e9503c92610f237850cfc970c66b3f1cc94f45f2942715280ebab", size = 83412736, upload-time = "2026-11-17T18:18:58.78Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/9e/cf62919a706d3288f1a5d9158d5614f1c44e0c3ee978cc769f942a22a232/opencv_python-5.1.0.95-cp37-abi3-macosx_15_0_arm64.whl", hash = "sha256:0b62fb3c71086ea96369e0f47e3b11949345b2f301b88dff97c92c5118176d7b", size = 25824349, upload-time = "2026-11-17T17:40:16.287Z" }, + { url = "https://files.pythonhosted.org/packages/f3/25/018c8ad2f404bd235d03d822b033a1e59464054bd57d164575fb0939608a/opencv_python-5.1.0.95-cp37-abi3-macosx_15_0_x86_64.whl", hash = "sha256:6438ef9bfbd15b9ff6474115d836932d24fba80f693f6b1b53b8e0a7a4b387a6", size = 47012381, upload-time = "2026-11-17T17:40:20.193Z" }, + { url = "https://files.pythonhosted.org/packages/7a/35/1b920c87c56c6aa181b0d249ae767e6834e70dfb6d5caaa4e238a44d95e1/opencv_python-5.1.0.95-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a36fc15cb1ccf31dc2883ff9f13b214340267ff1ff4c51f198ea3d6a4a6cbdbb", size = 49914363, upload-time = "2026-11-17T18:16:25.401Z" }, + { url = "https://files.pythonhosted.org/packages/69/b5/d55ad2e38fafe028c21639fa750ddcfdee29eaa047c3638e2e71741a6cda/opencv_python-5.1.0.95-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:63ad2b9e34c8ee4acde30fd93a162bc91f53480273f595667fedb5bb65ce6069", size = 72331896, upload-time = "2026-11-17T18:16:37.174Z" }, + { url = "https://files.pythonhosted.org/packages/58/1a/97d26c43318bdfbc2dcef3de833c00a95c5c31c5c153c7255faa2b409c3c/opencv_python-5.1.0.95-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4764e8da33b82ccacaf1e6601224d3d1570e97fbdb8343834415260bd5afcbd4", size = 55014603, upload-time = "2026-11-17T18:16:49.183Z" }, + { url = "https://files.pythonhosted.org/packages/f8/a1/c7f78207d0fcc2d655b9a15598d64da14edf0808db2a86df24459d31cc56/opencv_python-5.1.0.95-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:54e3be8acbda657c51227379a657a706a4e88032ce4a070728a8d6531e7c9ffc", size = 79247133, upload-time = "2026-11-17T18:17:03.743Z" }, + { url = "https://files.pythonhosted.org/packages/ae/f0/12cf2079221a98b7849645d2401197d35b66de6c3b4da57c9c9f2efe77fb/opencv_python-5.1.0.95-cp37-abi3-win32.whl", hash = "sha256:c752bbfd6f5e343e039dcedcdbc3832b4f75f0c4f7d1c084e446b911ad97f44a", size = 37231052, upload-time = "2026-11-17T14:37:09.52Z" }, + { url = "https://files.pythonhosted.org/packages/b2/40/e8c3938d34f22e629a7c599482360b1cadebc22b3c5b25bbbdccded52624/opencv_python-5.1.0.95-cp37-abi3-win_amd64.whl", hash = "sha256:ab505983b1c1e21e89b5c43bf59cccc805b8aa7981f4385a17812efa63ceccb9", size = 47965460, upload-time = "2026-11-17T14:37:05.247Z" }, + { url = "https://files.pythonhosted.org/packages/fc/a2/4f404c12cdd3d3486f65dd69572a5336bea8bab96d6e1e475b40d5374bef/opencv_python-5.1.0.95-cp37-abi3-win_arm64.whl", hash = "sha256:1c6714e81ddae43726cfd438eb8ae025585f35852e71e9e474620c2eafed71be", size = 15819422, upload-time = "2026-11-17T14:37:01.093Z" }, +] + +[[package]] +name = "packaging" +version = "26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", hash = "sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a", size = 355877, upload-time = "2026-11-23T21:44:11.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.whl", hash = "sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2", size = 140049, upload-time = "2026-11-23T21:44:09.531Z" }, +] + +[[package]] +name = "pandas" +version = "2.3.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil", version = "3.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pytz" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3d/f7/f425a00df4fcc22b292c6895c6831c0c8ae1d9fac1e024d16f98a9ce8749/pandas-2.3.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:376c6446ae31770764215a6c937f72d917f214b43560603cd60da6408f183b6c", size = 11555763, upload-time = "2025-09-29T23:16:53.287Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/66d99628ff8ce7857aca52fed8f0066ce209f96be2fede6cef9f84e8d04f/pandas-2.3.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e19d192383eab2f4ceb30b412b22ea30690c9e618f78870357ae1d682912015a", size = 10801217, upload-time = "2025-09-29T23:17:04.522Z" }, + { url = "https://files.pythonhosted.org/packages/1d/03/3fc4a529a7710f890a239cc496fc6d50ad4a0995657dccc1d64695adb9f4/pandas-2.3.3-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5caf26f64126b6c7aec964f74266f435afef1c1b13da3b0636c7518a1fa3e2b1", size = 12148791, upload-time = "2025-09-29T23:17:18.444Z" }, + { url = "https://files.pythonhosted.org/packages/40/a8/4dac1f8f8235e5d25b9955d02ff6f29396191d4e665d71122c3722ca83c5/pandas-2.3.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd7478f1463441ae4ca7308a70e90b33470fa593429f9d4c578dd00d1fa78838", size = 12769373, upload-time = "2025-09-29T23:17:35.846Z" }, + { url = "https://files.pythonhosted.org/packages/df/91/82cc5169b6b25440a7fc0ef3a694582418d875c8e3ebf796a6d6470aa578/pandas-2.3.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4793891684806ae50d1288c9bae9330293ab4e083ccd1c5e383c34549c6e4250", size = 13200444, upload-time = "2025-09-29T23:17:49.341Z" }, + { url = "https://files.pythonhosted.org/packages/10/ae/89b3283800ab58f7af2952704078555fa60c807fff764395bb57ea0b0dbd/pandas-2.3.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:28083c648d9a99a5dd035ec125d42439c6c1c525098c58af0fc38dd1a7a1b3d4", size = 13858459, upload-time = "2025-09-29T23:18:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/72/530900610650f54a35a19476eca5104f38555afccda1aa11a92ee14cb21d/pandas-2.3.3-cp310-cp310-win_amd64.whl", hash = "sha256:503cf027cf9940d2ceaa1a93cfb5f8c8c7e6e90720a2850378f0b3f3b1e06826", size = 11346086, upload-time = "2025-09-29T23:18:18.505Z" }, + { url = "https://files.pythonhosted.org/packages/c1/fa/7ac648108144a095b4fb6aa3de1954689f7af60a14cf25583f4960ecb878/pandas-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:602b8615ebcc4a0c1751e71840428ddebeb142ec02c786e8ad6b1ce3c8dec523", size = 11578790, upload-time = "2025-09-29T23:18:30.065Z" }, + { url = "https://files.pythonhosted.org/packages/9b/35/74442388c6cf008882d4d4bdfc4109be87e9b8b7ccd097ad1e7f006e2e95/pandas-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8fe25fc7b623b0ef6b5009149627e34d2a4657e880948ec3c840e9402e5c1b45", size = 10833831, upload-time = "2025-09-29T23:38:56.071Z" }, + { url = "https://files.pythonhosted.org/packages/fe/e4/de154cbfeee13383ad58d23017da99390b91d73f8c11856f2095e813201b/pandas-2.3.3-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b468d3dad6ff947df92dcb32ede5b7bd41a9b3cceef0a30ed925f6d01fb8fa66", size = 12199267, upload-time = "2025-09-29T23:18:41.627Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c9/63f8d545568d9ab91476b1818b4741f521646cbdd151c6efebf40d6de6f7/pandas-2.3.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b98560e98cb334799c0b07ca7967ac361a47326e9b4e5a7dfb5ab2b1c9d35a1b", size = 12789281, upload-time = "2025-09-29T23:18:56.834Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/a5ac8c7a0e67fd1a6059e40aa08fa1c52cc00709077d2300e210c3ce0322/pandas-2.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37b5848ba49824e5c30bedb9c830ab9b7751fd049bc7914533e01c65f79791", size = 13240453, upload-time = "2025-09-29T23:19:09.247Z" }, + { url = "https://files.pythonhosted.org/packages/27/4d/5c23a5bc7bd209231618dd9e606ce076272c9bc4f12023a70e03a86b4067/pandas-2.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:db4301b2d1f926ae677a751eb2bd0e8c5f5319c9cb3f88b0becbbb0b07b34151", size = 13890361, upload-time = "2025-09-29T23:19:25.342Z" }, + { url = "https://files.pythonhosted.org/packages/8e/59/712db1d7040520de7a4965df15b774348980e6df45c129b8c64d0dbe74ef/pandas-2.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:f086f6fe114e19d92014a1966f43a3e62285109afe874f067f5abbdcbb10e59c", size = 11348702, upload-time = "2025-09-29T23:19:38.296Z" }, + { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" }, + { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" }, + { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" }, + { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" }, + { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" }, + { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" }, + { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" }, + { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" }, + { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" }, + { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" }, + { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" }, + { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" }, + { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" }, + { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" }, + { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" }, + { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" }, + { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" }, + { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" }, + { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" }, + { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" }, + { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" }, + { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" }, + { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" }, + { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" }, + { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" }, + { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" }, + { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" }, + { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" }, +] + +[[package]] +name = "pandas" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "python-dateutil", version = "4.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/1c/c72c50f6da0283a55096f004c67ecf8f4523eae4dc97fe2b124332ba58f6/pandas-3.1.2.tar.gz", hash = "sha256:66c6613dbc2b5e47c1e716d8b74e78849e19ec8ef61b60d4752e725bf61e758b", size = 5939817, upload-time = "2026-11-30T17:15:19.293Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/61/ca/d4b9a632144a8162e13f3bb5839519412eeb9503a3ff9c500bbcf7655d05/pandas-3.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:85cbe4d138db8270bc8dfbe25876aa5a5e2651e61f333e18f87ce1b582cc887b", size = 11604824, upload-time = "2026-11-30T17:12:33.275Z" }, + { url = "https://files.pythonhosted.org/packages/17/35/b6c67fb514093975a3a03b01b43ba678bca8b49e076cf34f6dca912f4544/pandas-3.1.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2f3e8dfbf4d71b4a149fbe0a3a1b9ce36f37b516da96fb48fe10ed519ab64e9d", size = 11168536, upload-time = "2026-11-30T17:12:37.055Z" }, + { url = "https://files.pythonhosted.org/packages/d2/7c/c0f07ef497e774a4a61c19923cea97881b9c99a43c11db981b67a23711fc/pandas-3.1.2-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f54e6b3903ee68121387aad456d7a4949f31271e5ea42c23358078e6d4a7fb", size = 11759947, upload-time = "2026-11-30T17:12:39.753Z" }, + { url = "https://files.pythonhosted.org/packages/de/69/7062050d295addc084c5fe1890b74ae24ff2d84a3ac4b94a86766d54b673/pandas-3.1.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:430246ff24c68d22e83a00976928095bee4bf82885ce5123ef71baa0f303dbbd", size = 12364446, upload-time = "2026-11-30T17:12:42.284Z" }, + { url = "https://files.pythonhosted.org/packages/14/e4/377801041797d26498e6e983b276d8a9c6d9edb27a81d5e695f3dc949b1f/pandas-3.1.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ac3c31358d531d7a25057e88f5eaf1fbe98262e7195da7a521ac5a7b22d67725", size = 12781582, upload-time = "2026-11-30T17:12:44.982Z" }, + { url = "https://files.pythonhosted.org/packages/d1/e4/edb5d6babe33c9351083391ab7579b5340a4c870c20a26d781d7564b4f1a/pandas-3.1.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c1b25481af2eb2697c1cabaffd81f369110f617ead19583d7fd6fa354f3e2ec0", size = 13434835, upload-time = "2026-11-30T17:12:47.797Z" }, + { url = "https://files.pythonhosted.org/packages/a6/57/c2f8f37a0ef8a32ac057a45a0fae3437725677acb7ac433d20bfb56c708d/pandas-3.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:8d05bf79cd3527d60b2d43f64f3463ed959697e5eada0e26dcfb742d49058441", size = 10900220, upload-time = "2026-11-30T17:12:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/d3/17/adf5d0625a7504f2b9b1f3af4de74956be2cf7f982d438b5bd33842f7b92/pandas-3.1.2-cp311-cp311-win_arm64.whl", hash = "sha256:bf7141faf7e7eb45c63eee54e159d145a655b8cf2996fb08fa0cd6189e713141", size = 10294020, upload-time = "2026-11-30T17:12:53.097Z" }, + { url = "https://files.pythonhosted.org/packages/87/36/68075a97bc4513e73914b4189999c85aa6dec9af4872068e2e5d15db6f66/pandas-3.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:591afc1752e934df6ed12b87df3f5901dff47933df90be4b605617e031f6eff4", size = 11594295, upload-time = "2026-11-30T17:12:55.936Z" }, + { url = "https://files.pythonhosted.org/packages/3c/09/de1a750767d6884efb0aabaed17931d547cecb121f09b0a00b2e3250b377/pandas-3.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:88f565b046befa51b6729a4c1e919302209cf4026ef0414264f01514842b0984", size = 11177348, upload-time = "2026-11-30T17:12:58.631Z" }, + { url = "https://files.pythonhosted.org/packages/99/45/4eb0cdd84c095890624587d3583a18cefc93b4e1703babc2015699dfd739/pandas-3.1.2-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ac731e4a1a9b03a8d155ea65171aa37124345ef16ec8370d751386b1f1e2dd62", size = 11487273, upload-time = "2026-11-30T17:13:02.103Z" }, + { url = "https://files.pythonhosted.org/packages/b3/23/bbcf4ce35c6d19c4b124a988bb7826ce524725468c714e2c25509809cecc/pandas-3.1.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fd9db4e343bdea7949c1daa8c532839ebf3ab00176b435b51cd8528af1e3d045", size = 12029019, upload-time = "2026-11-30T17:13:04.804Z" }, + { url = "https://files.pythonhosted.org/packages/04/29/7ab020953b001546af726b263752c66179c774d669a03a238d53e8c1161b/pandas-3.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b0adace90b89d169d3780425ddd028e6e951d4e684b61178537e59b5d17998e9", size = 12512700, upload-time = "2026-11-30T17:13:07.863Z" }, + { url = "https://files.pythonhosted.org/packages/f4/6c/6ea8f3987f86373b59e4a2e1e5096084e7990b3acae1e9d4b1f05d54ad6f/pandas-3.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f61403e4430861e9a70f09062721c080076a6d6a8004d2f4a063c07e3edadf6d", size = 13107314, upload-time = "2026-11-30T17:13:10.999Z" }, + { url = "https://files.pythonhosted.org/packages/82/66/4833124c4b62a49127a59c58ac545469b5ed677e2c42872d00f15aba1927/pandas-3.1.2-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:e4c2eac02e69b812e0194fd14896bbc3db6504559c035887fb3444c5169fc8d3", size = 8097111, upload-time = "2026-11-30T17:13:13.51Z" }, + { url = "https://files.pythonhosted.org/packages/c4/2f/df6247a8ae7aec2c14fe5adf0e423c0e66f72f9375e93bf96dde7f643699/pandas-3.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:32a1b598e148b8c1ea028f3dc1324dd0d8f4d2850e968151638edf6efd31c276", size = 10679544, upload-time = "2026-11-30T17:13:15.719Z" }, + { url = "https://files.pythonhosted.org/packages/90/4e/334f3b8031f75ec56dea863d156619744326e1a2b3e2a9248a3ad6d63a48/pandas-3.1.2-cp312-cp312-win_arm64.whl", hash = "sha256:948d13a9a54861004797f0137ef2018df7a0283440e24b5f5ca8429a8b27b811", size = 10128274, upload-time = "2026-11-30T17:13:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a1/21c8015572410662079c4dad29ea3398e7b8d92a196229ab5770328bd344/pandas-3.1.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4ffd517536ead91a84586d13e402b2b69407a6f33461e29a52d7b8a95d29fa9c", size = 11617739, upload-time = "2026-11-30T17:13:21.026Z" }, + { url = "https://files.pythonhosted.org/packages/f9/cc/1fa91d968ecf5a4f44b38dbbd1d1387138c60a0f1eee8b409c7d58999278/pandas-3.1.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7993f966066ad8d33e0011bc13937205e1a679fde3dae97a2f46c712dffce375", size = 11193677, upload-time = "2026-11-30T17:13:23.851Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b2/d39ef624f5f7391b907febfd2a929406f01b6db9c9c5ed2e637325a5fd44/pandas-3.1.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e15d65b03cd50a3fbb8a5853f1464ab46a601c0268f3ea62bc50ef1a8e57b5b4", size = 11437841, upload-time = "2026-11-30T17:13:26.844Z" }, + { url = "https://files.pythonhosted.org/packages/74/7e/2bfa9e23353796bd3a2bae1056916de6bcf03eeef7f1dde9d01964d36f22/pandas-3.1.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8b019b0f4875226840cd5ccaed037214f3498f11a28429b62e0d484686ca194f", size = 11989029, upload-time = "2026-11-30T17:13:29.499Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/4fe4fb323cc4b02dbfc26142055a21751508d7fcd9ec93a87f4e555c7526/pandas-3.1.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:64e8998ae1392527c1967c51955241c90544581073a7bc148a859102686d0084", size = 12462687, upload-time = "2026-11-30T17:13:32.546Z" }, + { url = "https://files.pythonhosted.org/packages/14/79/20e232e6ee2c5428f64c983ed746da53bb9d842c39a39567b8427113a446/pandas-3.1.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b7aa66ed45f0fcccd0db8db51ac266a198fbfc3f22013c6b19df6137b20608ae", size = 13048896, upload-time = "2026-11-30T17:13:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/70/87/f27f8e3bc9d53e69f1cd8b9eba0914659b86af556f012f182e4ff4e7971a/pandas-3.1.2-cp313-cp313-win_amd64.whl", hash = "sha256:e76df95f47c5ea3b95267c0b7c155f0ee2837cdeb61d6404a593230ec3a20f3f", size = 10667825, upload-time = "2026-11-30T17:13:39.378Z" }, + { url = "https://files.pythonhosted.org/packages/87/f6/33144cd14719c2660daca86abb081549c9992a15e1e8fc966804f0294704/pandas-3.1.2-cp313-cp313-win_arm64.whl", hash = "sha256:a3c26bee2650d283ac3ddca61a8f19c6c810bcff596b27af5bceac91b8faa555", size = 10112949, upload-time = "2026-11-30T17:13:41.816Z" }, + { url = "https://files.pythonhosted.org/packages/ad/e2/d06a9877d6eb32736302696ecf1376764c7ed0329c7bf0036a0a5c6ba588/pandas-3.1.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:597e86099550c1b667ef9fe5b8f5819ae1cd3bad83d03c47415e0e73b81b10ef", size = 11679670, upload-time = "2026-11-30T17:13:44.607Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/5da2e9fb93503f113cf9cf9bb9475144b671c1e356701d5daba1a41ed102/pandas-3.1.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:042e8696c5c5b2595c2b3ff830923076d73c1bbaeed95a628b24a63072b97bd0", size = 11267777, upload-time = "2026-11-30T17:13:47.823Z" }, + { url = "https://files.pythonhosted.org/packages/bd/44/e5aeb01e0203aa6596576d6dfc7e1073fc5ce83370c31b5d130de885761e/pandas-3.1.2-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e2ef8bcd84308f83a1e3e4f7076b1c8201fa25a17481c3725b030164afe4f7ca", size = 11555000, upload-time = "2026-11-30T17:13:50.577Z" }, + { url = "https://files.pythonhosted.org/packages/43/a2/2b19983a63aa647966b50dcd16a963ab1721a53f79f40f3324130b8bfeaa/pandas-3.1.2-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e197a15ffe7a712afedbbf28cd3d4149bbf1f08a2bfad48c86141fcf22ec5d01", size = 12043034, upload-time = "2026-11-30T17:13:53.491Z" }, + { url = "https://files.pythonhosted.org/packages/70/be/c0796e15d7e60fa8f88d4be5ceb424cb6823052dfb4b0837556e3566c9e4/pandas-3.1.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:19015ad74f490227853ed4419ee710fba0eb0643bf7558d4a73e161403e1788b", size = 12584324, upload-time = "2026-11-30T17:13:56.689Z" }, + { url = "https://files.pythonhosted.org/packages/c3/ac/6b91d5a9d6e4676336c317447038e9e68e0a3a95161535d9e7b2246b2ca8/pandas-3.1.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2c363c468a65a7f55c45f72a424faec89984b7bc67fbb4d234560fa1e8608697", size = 13113160, upload-time = "2026-11-30T17:13:59.783Z" }, + { url = "https://files.pythonhosted.org/packages/73/b5/b576756829e1d28782e23486c42c1609add406a716daa4caff4b453efff6/pandas-3.1.2-cp314-cp314-win_amd64.whl", hash = "sha256:0849f0025cac1a7f08f0a30c1896893b20fdd2254941b1b62c34a95de0ac65a6", size = 10813635, upload-time = "2026-11-30T17:14:02.562Z" }, + { url = "https://files.pythonhosted.org/packages/72/ed/078d824e3a9b2679e8be4a88b1dc107379d1fe0d9dcf2f38c84df491195f/pandas-3.1.2-cp314-cp314-win_arm64.whl", hash = "sha256:0a8f34d9f1222561c4d51845aafd4cc427bf25a1ddf88ef5e36548725b67da79", size = 10276388, upload-time = "2026-11-30T17:14:05.364Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e9/b7d76f1adb827ffe6f87e96ade9306e792031e6b51b17dd614eb03bde458/pandas-3.1.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:5b1e0b2b2beb19b6176900b75c59e10c6024f05028abff75b7ea345e1f4ccbb9", size = 12142507, upload-time = "2026-11-30T17:14:08.937Z" }, + { url = "https://files.pythonhosted.org/packages/4d/8e/cd56d206dffbff81dc285fc61c7db7e6667dbc6c3dd362143b057bc6cf01/pandas-3.1.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:345e1e501d9e7cab1e63b9082a7969b4b23910ca21e59d601f1d9c715a0ae196", size = 11740734, upload-time = "2026-11-30T17:14:11.912Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c0/546ed78f9e505a9ff323f17a480bb82be7224daf79bd9e45fc3c5707a821/pandas-3.1.2-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f209ee41e7388335a9314d592104a51c1681345320886b13ebb20b8020544add", size = 11418409, upload-time = "2026-11-30T17:14:14.534Z" }, + { url = "https://files.pythonhosted.org/packages/eb/9a/0625b6c82411a3351ecc30b19d88412b9d57cea3c463725dee1a82da7791/pandas-3.1.2-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93b34e5bc571fec9eafda55947ac68450e23e98b68592f414e927d589e38f45f", size = 11878642, upload-time = "2026-11-30T17:14:17.804Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ee/d724401ad1360ba4db0c2d88d5c5920269d260eb5b63f2a9c0e28b0ab3f6/pandas-3.1.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:06f6e4e9c336555fe91371d65a54c81e920dc87e09f64cb0b3c2eab6e63f965a", size = 12437302, upload-time = "2026-11-30T17:14:20.514Z" }, + { url = "https://files.pythonhosted.org/packages/98/53/6c2f437969a6c5ebb9599ecb27662e3c6915b7c29ee534402860325196d8/pandas-3.1.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3d131200ae3412c01f9928b6ab4f6a1eb624975757b9d9f3a7ec2dea89ed9d7e", size = 12962426, upload-time = "2026-11-30T17:14:23.44Z" }, + { url = "https://files.pythonhosted.org/packages/6b/93/29101c12088c5a6142ae81a525625ecd1e39e347a3581c1fcced22e5e434/pandas-3.1.2-cp314-cp314t-win_amd64.whl", hash = "sha256:4be8da0150f082a08da54478d3fbffc32669b4b4a5d93cddda5acfac8bc8533b", size = 11240546, upload-time = "2026-11-30T17:14:26.093Z" }, + { url = "https://files.pythonhosted.org/packages/02/03/9d3d29170c65661c35a79dd6876b829410dc2bac9049ba2d2c085dd15693/pandas-3.1.2-cp314-cp314t-win_arm64.whl", hash = "sha256:221bd05d7b4af065b93fd8d7c9fdac2cf7c71cb87acd32adf5870d7d9fa6e8b3", size = 10647280, upload-time = "2026-11-30T17:14:28.74Z" }, + { url = "https://files.pythonhosted.org/packages/96/3e/423517681e0269847fb29d26f692637f237beb7ed83105df1f6678abbfbf/pandas-3.1.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:31c641c31e67b9071f5b8d7f2d41c440900a7fa5819dcaea50ecf0d5618ae6ad", size = 11671922, upload-time = "2026-11-30T17:14:31.649Z" }, + { url = "https://files.pythonhosted.org/packages/04/1e/7de6829c9e4af9fb227e74fffdbd8349fe3a65d761a34747143b63e408c8/pandas-3.1.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9f6c7b6f2fcdc2515a4f23747ace67d95154ec5f6895f89942edbac8a04f9af0", size = 11259669, upload-time = "2026-11-30T17:14:34.4Z" }, + { url = "https://files.pythonhosted.org/packages/3a/8e/ff606b982a24f802188aa8538885e2b2871e193431004e4b3a5783891493/pandas-3.1.2-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0e23036989a24b1a9f166e0ec4a105e3e3126d41dc7e39120b0dec8c8f574f1b", size = 11550773, upload-time = "2026-11-30T17:14:37.257Z" }, + { url = "https://files.pythonhosted.org/packages/33/c9/0b82e09e19f6cf16cabd16214484c2690b21a23a0e3c4c676e834d99543b/pandas-3.1.2-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:595ecce4c64f8515fdeaa703b7bd2f4dc020037adbc888b043a32bbf1d5185de", size = 12033489, upload-time = "2026-11-30T17:14:40.101Z" }, + { url = "https://files.pythonhosted.org/packages/17/df/b7b40de055a6c1541425bb4ef3c960854a6b82094471636467da7148451b/pandas-3.1.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:00c808db534954484d487793bad8205dab2f8dc4370d6347183e9d6169859c26", size = 12573416, upload-time = "2026-11-30T17:14:43.09Z" }, + { url = "https://files.pythonhosted.org/packages/37/4a/e38f19c502b94e602a5ec81abef7dc37234610473f46b01e4376bd89f15d/pandas-3.1.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:144397476d770102fa30757a60161d2f1bbce297931716a75886eed118499964", size = 13103147, upload-time = "2026-11-30T17:14:46.107Z" }, + { url = "https://files.pythonhosted.org/packages/1e/9d/9d188a08ff86dc26a9c37b998d1d2257f2b25710f0e0e116e920a19d9b84/pandas-3.1.2-cp315-cp315-win_amd64.whl", hash = "sha256:74e4f775656f37b61a6823471de7be6b6691aeb6b3bea59e506fad9ca04f876b", size = 10806263, upload-time = "2026-11-30T17:14:49.012Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9a/21db85fea95544fcc26ccdc217857eb84b5044c1fcc0466672e85c6eea1a/pandas-3.1.2-cp315-cp315-win_arm64.whl", hash = "sha256:89f13714c2a653246091eab89c794eb5ec8047164320c23f10b16fb235f71da4", size = 10270084, upload-time = "2026-11-30T17:14:52.028Z" }, + { url = "https://files.pythonhosted.org/packages/84/24/b415795914bc93876fa19564b1fbffb42ff80e55e1c02ed239295861db95/pandas-3.1.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3060f84be10a593526a9e94af773089b945332f0cda1ef8bf5678094a3fbea9e", size = 12116492, upload-time = "2026-11-30T17:14:55.172Z" }, + { url = "https://files.pythonhosted.org/packages/ea/a6/51232118d73a64d3ec783993368496e9680adf6501688b3fcbefabb55b6d/pandas-3.1.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c25de63e060008d6e3aa677d0b445901470fe65aa12626b34db867bbff613884", size = 11716123, upload-time = "2026-11-30T17:14:58.092Z" }, + { url = "https://files.pythonhosted.org/packages/94/9a/3b28e4059da3083cfe4b872a78840a205c73668f85a94af1736537173710/pandas-3.1.2-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fdfc776463ab8c597cc918e4a194489a9b1572228c7d6ef0c7e3f2d7c63e966d", size = 11391064, upload-time = "2026-11-30T17:15:01.008Z" }, + { url = "https://files.pythonhosted.org/packages/cd/87/bfd45919453cf7545b069d4f3f5306bc65aed498099783c1647f445c3866/pandas-3.1.2-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f53b5dcaa76f07b1871bd0994f86f5e3a2398af931929cd3d4e90efc275b900", size = 11859933, upload-time = "2026-11-30T17:15:04.043Z" }, + { url = "https://files.pythonhosted.org/packages/1f/6c/85fce00c73ad4dd025fd6e722b0f8fcf2a4407b1914238e89707a1c97121/pandas-3.1.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:a2bc884fdfdd7ee6cd479249e4eb6de11d68156b5a1c470471879c21bd7cc0cc", size = 12401105, upload-time = "2026-11-30T17:15:07.161Z" }, + { url = "https://files.pythonhosted.org/packages/ff/38/c848754ec307eec5164c5fbfa74ab98e4f2801f5c24614cdfcf0a975d3f2/pandas-3.1.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:568c78d6f970e7f7cc95815b8439097f96c36a83e6ac010fa77a090598787b35", size = 12923174, upload-time = "2026-11-30T17:15:10.285Z" }, + { url = "https://files.pythonhosted.org/packages/6e/db/f9f0a97c099f07f7bc9a88deb188670f2d1bfb68ca8b4cd93fa90d2ccda6/pandas-3.1.2-cp315-cp315t-win_amd64.whl", hash = "sha256:18cf3e93b3a992800cffe3000628ca6fdf636aed577f7e972871b7a5750c918a", size = 11211869, upload-time = "2026-11-30T17:15:13.321Z" }, + { url = "https://files.pythonhosted.org/packages/53/d0/fb6a3def92ab15333b7755e1a5e637a9b9aa8683ed7a29b59fd14d490b38/pandas-3.1.2-cp315-cp315t-win_arm64.whl", hash = "sha256:677cb21de2defd3a4f14096e6a04280a8687bcef91a1b18338508178a78ca338", size = 10616613, upload-time = "2026-11-30T17:15:16.113Z" }, +] + +[[package]] +name = "parso" +version = "0.8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, +] + +[[package]] +name = "partd" +version = "1.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "locket" }, + { name = "toolz" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b2/3a/3f06f34820a31257ddcabdfafc2672c5816be79c7e353b02c1f318daa7d4/partd-1.4.2.tar.gz", hash = "sha256:d022c33afbdc8405c226621b015e8067888173d85f7f5ecebb3cafed9a20f02c", size = 21029, upload-time = "2024-05-06T19:51:41.945Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/e7/40fb618334dcdf7c5a316c0e7343c5cd82d3d866edc100d98e29bc945ecd/partd-1.4.2-py3-none-any.whl", hash = "sha256:978e4ac767ec4ba5b86c6eaa52e5a2a3bc748a2ca839e8cc798f1cc6ce6efb0f", size = 18905, upload-time = "2024-05-06T19:51:39.271Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "pexpect" +version = "4.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ptyprocess" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, +] + +[[package]] +name = "pillow" +version = "12.3.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ba/3762f376a2948e3036488d773a146e0ae6ecc2ca03ac20e2615bd0b2ba02/pillow-12.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7", size = 4785287, upload-time = "2026-07-01T11:53:29.761Z" }, + { url = "https://files.pythonhosted.org/packages/07/50/b5d688cc9c52d4482f3d5bcab6ce20bc2a74a85d2343841c907444a3be2c/pillow-12.3.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f", size = 6253754, upload-time = "2026-07-01T11:53:32.298Z" }, + { url = "https://files.pythonhosted.org/packages/4e/89/36f4cd76cf4baf05c50ababb976249153f18c959171c7f6ba09a6f217260/pillow-12.3.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec", size = 6925605, upload-time = "2026-07-01T11:53:34.487Z" }, + { url = "https://files.pythonhosted.org/packages/eb/c0/4de58cf6633b9e3a6061ef4be6fb91fc3c90b812ece886f531e3c523d777/pillow-12.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468", size = 6327788, upload-time = "2026-07-01T11:53:36.433Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/14d53682a19550dbbaf3b598f807d5457646c510805a44c7d7891cd1cd1a/pillow-12.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed", size = 7036288, upload-time = "2026-07-01T11:53:38.712Z" }, + { url = "https://files.pythonhosted.org/packages/38/1d/36279e3c77efe034e4cc2b0393ee74ffdb5a62391dacbf9b916154f5f0b8/pillow-12.3.0-cp310-cp310-win32.whl", hash = "sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1", size = 6472396, upload-time = "2026-07-01T11:53:40.781Z" }, + { url = "https://files.pythonhosted.org/packages/48/7c/8fa0039574c476d7c6fa57dd7c32a130436877c6ec1e5ce1cc8ec44878c1/pillow-12.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb", size = 7226887, upload-time = "2026-07-01T11:53:42.764Z" }, + { url = "https://files.pythonhosted.org/packages/fa/17/e324be141d173c1c919428066c3259f21c1b8982e564e01a4a81e96dbdcf/pillow-12.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f", size = 2568039, upload-time = "2026-07-01T11:53:45.372Z" }, + { url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" }, + { url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" }, + { url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" }, + { url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" }, + { url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" }, + { url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" }, + { url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" }, + { url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" }, + { url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" }, + { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" }, + { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" }, + { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" }, + { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" }, + { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" }, + { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" }, + { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" }, + { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" }, + { url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" }, + { url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" }, + { url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" }, + { url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" }, + { url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" }, + { url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" }, + { url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" }, + { url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" }, + { url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" }, + { url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" }, + { url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" }, + { url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" }, + { url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" }, + { url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" }, + { url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" }, + { url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" }, + { url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" }, + { url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" }, + { url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" }, + { url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" }, + { url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" }, + { url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" }, + { url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" }, + { url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" }, + { url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" }, + { url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" }, + { url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" }, + { url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" }, + { url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" }, + { url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" }, + { url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" }, + { url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" }, + { url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" }, + { url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" }, + { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" }, + { url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" }, + { url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" }, + { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" }, + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, + { url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" }, + { url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" }, + { url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" }, + { url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" }, + { url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" }, + { url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" }, + { url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" }, + { url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" }, + { url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" }, + { url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" }, + { url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" }, + { url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" }, + { url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" }, + { url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" }, + { url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" }, + { url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" }, + { url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" }, + { url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" }, + { url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" }, + { url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, + { url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" }, + { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" }, + { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.12.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/90/a1/d5f9002a70298c64a789779077d8dd90c10aa1f47fe40c86802df874f2a6/platformdirs-4.12.4.tar.gz", hash = "sha256:63743c02414e755de4e31b8f68125c1407495b86c5a006e203c01ff8b9924250", size = 60010, upload-time = "2026-10-07T23:30:32.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/ba/223e00b885e960edd5d4b4d178c88acce019bd5b83786093681b8c393492/platformdirs-4.12.4-py3-none-any.whl", hash = "sha256:78bfb9db2a8471ed7eebe3c3c932da413911042994e699b384fbb4493fa872d7", size = 32596, upload-time = "2026-10-07T23:30:30.825Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.9" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/96/549558270586699a271a18b1111482dc3fc39baa0ef61d183e230d2c961d/platformdirs-4.14.9.tar.gz", hash = "sha256:c6b188e03ffd4dfe1bf8c4bcb47cd94711af244a9852dbff60297bd753684d5d", size = 87729, upload-time = "2026-11-27T20:53:44.721Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/e7/fc53dfd2f9469cce9be9c58385bdcdb5087e790c135c9dadd4cc8401bb3d/platformdirs-4.14.9-py3-none-any.whl", hash = "sha256:d0d3a23e7ff282cfa94b77f5a22b81030dcb68ba0430f90c74f4bd8d090782ea", size = 94272, upload-time = "2026-11-27T20:53:43.511Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "prompt-toolkit" +version = "3.0.53" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, +] + +[[package]] +name = "psutil" +version = "7.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, + { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, + { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, + { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, +] + +[[package]] +name = "ptyprocess" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, +] + +[[package]] +name = "pure-eval" +version = "0.2.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/9f/abfd2959e9261dd5217ca8551d4de211ca6ab26fe9b72cf44731ff6c4442/pure_eval-0.2.4.tar.gz", hash = "sha256:260c2774686e651b79f8b8e7fc9d80b3599ea6a66334b47d5f4abb69fc2c0ea1", size = 20563, upload-time = "2026-09-10T21:41:22.836Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/18/83376915176eb058cb86470eb7396388a13350b09a8f233a79303bbcbc5b/pure_eval-0.2.4-py3-none-any.whl", hash = "sha256:96cae060a313cfaad51bb761278bfb0e62dc0248d9315a81173752dc546cd37a", size = 11893, upload-time = "2026-09-10T21:41:21.532Z" }, +] + +[[package]] +name = "py" +version = "1.11.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/98/ff/fec109ceb715d2a6b4c4a85a61af3b40c723a961e8828319fbcb15b868dc/py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719", size = 207796, upload-time = "2021-11-04T17:17:01.377Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f6/f0/10642828a8dfb741e5f3fbaac830550a518a775c7fff6f04a007259b0548/py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378", size = 98708, upload-time = "2021-11-04T17:17:00.152Z" }, +] + +[[package]] +name = "pycodestyle" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/86/df/178e41c9ed0ff33c23b3f3757e4e658c889f9abc5ad76ece6cd607b12e9c/pycodestyle-2.15.0.tar.gz", hash = "sha256:318f5db083869b4c4dad922d0b11124fb27ab181b6730b93371da671e31bd50e", size = 39765, upload-time = "2026-09-22T22:15:34.926Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/e2/480bcdb153feecde4d736b18c908c7eee4846f11d7547d2e0c71499af630/pycodestyle-2.15.0-py2.py3-none-any.whl", hash = "sha256:12fd2f73c7b8ee8845a0431111df8faf4c1a07d6e64e2ee7f0c74014dab14181", size = 31583, upload-time = "2026-09-22T22:15:34.007Z" }, +] + +[[package]] +name = "pyflakes" +version = "4.0.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/2c/1b/3ba8bd62723cfe1b651c4e4b89b33767fce7a08bb800491cf1d3dd3a7716/pyflakes-4.0.3.tar.gz", hash = "sha256:94762a3a5a343a79b28754f96c554bce057a592a4896907d73f0369fe824e053", size = 67126, upload-time = "2026-10-07T18:57:25.327Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/44/b0/554d720d71083ccd24ba2f376c048544c073570e7bb18b34d769cef77f66/pyflakes-4.0.3-py2.py3-none-any.whl", hash = "sha256:330ba92b8c1db2eb0b8f4068f6c58674e2649a99e334769aa50e3e9c5b11c23a", size = 66250, upload-time = "2026-10-07T18:57:24.403Z" }, +] + +[[package]] +name = "pyflakes" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/9b/43/f4566b992ab97abd18426aeba516a83c7a833230614a2c3f4d3e9d8ff0f0/pyflakes-4.1.0.tar.gz", hash = "sha256:592beb57058eb82eb190fb7514f2081c555c51000b029ff71286a681e6cf2f83", size = 67243, upload-time = "2026-10-28T20:10:02.469Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/52/98c9a0e4718abe887121279457bc7140115df22d714b7183880eb61e359f/pyflakes-4.1.0-py2.py3-none-any.whl", hash = "sha256:b2e05e6bac8e49b67be2a6ffa63422c60f7193fc72e8180255907b41ec997dc1", size = 66258, upload-time = "2026-10-28T20:10:01.109Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pyneurotrace" +version = "0.9.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ipython", version = "8.39.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "ipython", version = "9.19.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "ipywidgets" }, + { name = "matplotlib", version = "3.10.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "matplotlib", version = "3.11.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "matplotlib-scalebar" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "pyqt5" }, + { name = "pytest" }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ee/64/a7a5dc8b605a7bd1c042743333a874dcde7dc984d1f7665f8d94d753cac0/pyneurotrace-0.9.8.tar.gz", hash = "sha256:c2a565c900e5e8158cb4f0f88f1acd80c6885ce29cedf0bd2d28074eb7d3d2f9", size = 34165, upload-time = "2024-06-13T21:06:15.068Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ab/93/41727b888e3b5644a7ae50c1a36776f4b37f406c3a1763339b2370f32f15/pyNeuroTrace-0.9.8-py3-none-any.whl", hash = "sha256:6ccf1a5202903d52946b14ac191e8ff1ca713ff84d2577a76a36545608e4ae27", size = 34552, upload-time = "2024-06-13T21:06:13.142Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "pyqt5" +version = "5.15.11" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyqt5-qt5" }, + { name = "pyqt5-sip" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/07/c9ed0bd428df6f87183fca565a79fee19fa7c88c7f00a7f011ab4379e77a/PyQt5-5.15.11.tar.gz", hash = "sha256:fda45743ebb4a27b4b1a51c6d8ef455c4c1b5d610c90d2934c7802b5c1557c52", size = 3216775, upload-time = "2024-07-19T08:39:57.756Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/64/42ec1b0bd72d87f87bde6ceb6869f444d91a2d601f2e67cd05febc0346a1/PyQt5-5.15.11-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:c8b03dd9380bb13c804f0bdb0f4956067f281785b5e12303d529f0462f9afdc2", size = 6579776, upload-time = "2024-07-19T08:39:19.775Z" }, + { url = "https://files.pythonhosted.org/packages/49/f5/3fb696f4683ea45d68b7e77302eff173493ac81e43d63adb60fa760b9f91/PyQt5-5.15.11-cp38-abi3-macosx_11_0_x86_64.whl", hash = "sha256:6cd75628f6e732b1ffcfe709ab833a0716c0445d7aec8046a48d5843352becb6", size = 7016415, upload-time = "2024-07-19T08:39:32.977Z" }, + { url = "https://files.pythonhosted.org/packages/b4/8c/4065950f9d013c4b2e588fe33cf04e564c2322842d84dbcbce5ba1dc28b0/PyQt5-5.15.11-cp38-abi3-manylinux_2_17_x86_64.whl", hash = "sha256:cd672a6738d1ae33ef7d9efa8e6cb0a1525ecf53ec86da80a9e1b6ec38c8d0f1", size = 8188103, upload-time = "2024-07-19T08:39:40.561Z" }, + { url = "https://files.pythonhosted.org/packages/f3/f0/ae5a5b4f9b826b29ea4be841b2f2d951bcf5ae1d802f3732b145b57c5355/PyQt5-5.15.11-cp38-abi3-win32.whl", hash = "sha256:76be0322ceda5deecd1708a8d628e698089a1cea80d1a49d242a6d579a40babd", size = 5433308, upload-time = "2024-07-19T08:39:46.932Z" }, + { url = "https://files.pythonhosted.org/packages/56/d5/68eb9f3d19ce65df01b6c7b7a577ad3bbc9ab3a5dd3491a4756e71838ec9/PyQt5-5.15.11-cp38-abi3-win_amd64.whl", hash = "sha256:bdde598a3bb95022131a5c9ea62e0a96bd6fb28932cc1619fd7ba211531b7517", size = 6865864, upload-time = "2024-07-19T08:39:53.572Z" }, +] + +[[package]] +name = "pyqt5-qt5" +version = "5.15.19" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/af/c0e00d353cad261ee9ccd5f6039b7ef4e09a1cb9a22c6a4b233854f6fa30/pyqt5_qt5-5.15.19-py3-none-macosx_10_13_x86_64.whl", hash = "sha256:cac6b78e4805848c25979a0622660251070781b6b4f810688a960cb44d1ae5a2", size = 39777655, upload-time = "2026-05-21T09:12:43.94Z" }, + { url = "https://files.pythonhosted.org/packages/1c/d0/fd4876b90bbadaa92444ff452ab78d9ba839014a6d303e77d29c0c591631/pyqt5_qt5-5.15.19-py3-none-macosx_11_0_arm64.whl", hash = "sha256:66fa299dcdea1f430edbd6f6ca3dcb20430f19c508d13e3aa851d19034b7be7e", size = 36838788, upload-time = "2026-05-21T09:12:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/de/a0/dd9889ed9bf100d6d8b9d608b2689dc2a7f871f9489a0c563a8cf78c329f/pyqt5_qt5-5.15.19-py3-none-manylinux2014_x86_64.whl", hash = "sha256:31421d9c31fb29a8faee4b8b3c32658fb51a9e8c4c708075121162fa44faf80e", size = 60933242, upload-time = "2026-05-21T09:13:16.308Z" }, +] + +[[package]] +name = "pyqt5-sip" +version = "12.20.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/5d/778b6bb5d65c32e40ab8bd2b40e218108a31e323c5e8c026895da7833444/pyqt5_sip-12.20.1.tar.gz", hash = "sha256:b94f0c7cf8f6335adb90aab1981756c94e1250854dbcc209271ba8c058c4ddbb", size = 107025, upload-time = "2026-11-11T12:32:21.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3c/5d/0c8b9209e51a77a23ba1d95fcd329f4cf7f456a38718fe484e6894a493d9/pyqt5_sip-12.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c02e4a62433e6a3d98e669b2f373a9809f69e6648c639b09647d36b5fc0c1961", size = 124342, upload-time = "2026-11-11T12:31:50.263Z" }, + { url = "https://files.pythonhosted.org/packages/2a/31/667e0b7aa1df7bf2c7f40247070d19f69d5ecbdcdcb711274f018b038dc3/pyqt5_sip-12.20.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9e32a1970bb5040ae81053a5b1b2cf6b97cb49924b3031b933fde1bdb4959de2", size = 273419, upload-time = "2026-11-11T12:31:51.567Z" }, + { url = "https://files.pythonhosted.org/packages/52/e7/7324654308c78dc242cd85541f4748f25df4907690652f3794e6897cc767/pyqt5_sip-12.20.1-cp310-cp310-win32.whl", hash = "sha256:91a7aa4e98f7ac318869be9b7d0e87df7fd0ab3bab561f173c2948a991e90de1", size = 49234, upload-time = "2026-11-11T12:31:53.678Z" }, + { url = "https://files.pythonhosted.org/packages/d8/e7/2838666dbff15d71c6217731c1451d955deaa8b9d52d8f7d0bd85b475250/pyqt5_sip-12.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:948088ac5f05e09ce313b7a5b8f3e585ee6e6bca27961445302d230be62c2db4", size = 59171, upload-time = "2026-11-11T12:31:52.657Z" }, + { url = "https://files.pythonhosted.org/packages/62/b4/1c9730583ee899996fcff1ae35eb5f1653dcb333a9bcc321921d1338927c/pyqt5_sip-12.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7be2c759917fc9be925f001c1ad0d0532f8ea4131016ef3f31087e86113489fa", size = 124348, upload-time = "2026-11-11T12:31:54.622Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e0/e4778da58166e77f2cbb86d756a72a28dbd399b86e33725986826d2b9261/pyqt5_sip-12.20.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:36212154c64f91c4d1584ea1792e5e71a7502f53a10a3b52659f660243e461eb", size = 277583, upload-time = "2026-11-11T12:31:56.108Z" }, + { url = "https://files.pythonhosted.org/packages/be/35/2415f61e7020874fc0f501a7d2ad9ea243e5258c2f19e2fe433d0c15f237/pyqt5_sip-12.20.1-cp311-cp311-win32.whl", hash = "sha256:9851d4417a348d573318853acb0a7deec36a42f8f992dbd71dba50c40657a806", size = 49240, upload-time = "2026-11-11T12:31:58.928Z" }, + { url = "https://files.pythonhosted.org/packages/64/69/9b6dfb55483cafe49fc2ae16493a84bc71623ba53525cfe1cbfeab176693/pyqt5_sip-12.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:7723028416fdf4f06539ef7bd85652fdf0896bb808529d0c78c87d3d926c5bc4", size = 59179, upload-time = "2026-11-11T12:31:57.752Z" }, + { url = "https://files.pythonhosted.org/packages/98/94/3b3c8476d173fc1fbdd836d4fa73c7c3a072512d44b9bf137a64c9580401/pyqt5_sip-12.20.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:9f5c9571c09ad76818797f5a478e2822f4cbff856d784e43932d066ecfaa010e", size = 125601, upload-time = "2026-11-11T12:32:00.072Z" }, + { url = "https://files.pythonhosted.org/packages/00/57/1e3d1c73662fb67ac50c02aa42d27600ce9adcd13a036e4283a705db8f6d/pyqt5_sip-12.20.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:b3df856ad5cb8399c52997ec67074e0295d7bcd2b35199fa0e6387f7c609e08a", size = 282881, upload-time = "2026-11-11T12:32:01.483Z" }, + { url = "https://files.pythonhosted.org/packages/7f/e8/6d937bfecb183b0c46dd9132052955a6b500646006f13c0e384fdaed5000/pyqt5_sip-12.20.1-cp312-cp312-win32.whl", hash = "sha256:62e3e2ce307c7879c8b02867ecb84d3501a022e915ed3c97374069fa303d6982", size = 49707, upload-time = "2026-11-11T12:32:03.744Z" }, + { url = "https://files.pythonhosted.org/packages/03/e8/3a9e98a9bde1d4d18a3f9c13e136d78145ad0b2b88b6378806fd24474ffa/pyqt5_sip-12.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:c3f05d231d3a57d3fda6ed7edd83c376d0d42ec5d5f1f1558be26a86e1343440", size = 58368, upload-time = "2026-11-11T12:32:02.838Z" }, + { url = "https://files.pythonhosted.org/packages/21/2e/63a3632ba8ede2e1c627c518cbad248e52267ce3b37b1c1c0aa4c3981e79/pyqt5_sip-12.20.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:49f6b284220aa9cad3901f24b964a7e722ec62dd3d9df9ede97dc436c7edd5f2", size = 125558, upload-time = "2026-11-11T12:32:04.799Z" }, + { url = "https://files.pythonhosted.org/packages/02/d4/5b7d5ce8577faf7811209494cbae43ed0844a69cc9b8ff7562c24cab15d0/pyqt5_sip-12.20.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:f0a9f1eeae6ffe25f29b4e58bbd0cd77dfadbcc08de0fdab74f2f089c51a05b1", size = 282846, upload-time = "2026-11-11T12:32:06.064Z" }, + { url = "https://files.pythonhosted.org/packages/e8/e5/ba6065d16cb9e7702389445b0e032df1b90694d6c78cd315b7b6cc2894a2/pyqt5_sip-12.20.1-cp313-cp313-win32.whl", hash = "sha256:056c141ffc479697f2dfd67198bc461c5a107c9fed4d0c283e0387c83ece5b26", size = 49673, upload-time = "2026-11-11T12:32:08.891Z" }, + { url = "https://files.pythonhosted.org/packages/b6/e9/3fba752019e4068be2cb4c4d7614f95c5a4c11148b1f8800c259b5cf39c2/pyqt5_sip-12.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:fe8129359f904934bc1be1ef0be29bae96bb35bfc57fa6bb28b71f0cb918e47f", size = 58408, upload-time = "2026-11-11T12:32:07.613Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e4/6a3606c7fcacdf7c5457b42fd946d38e38582402d1317bce1ebcc9fb188c/pyqt5_sip-12.20.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:b822f36f3665f59c7856f1fbf88a3ce7a4046c20e3eb03cd13b4203117e7a1ce", size = 125813, upload-time = "2026-11-11T12:32:11.588Z" }, + { url = "https://files.pythonhosted.org/packages/87/6e/caea55c1039d5189c43d03799a3fd781f9959d8e540363bdada64c1f82db/pyqt5_sip-12.20.1-cp314-cp314-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:d815b444fba57024a5f051905286c048792ded4edc89ea5de40a8c5f2f8fcd21", size = 283524, upload-time = "2026-11-11T12:32:12.729Z" }, + { url = "https://files.pythonhosted.org/packages/47/b2/b6a12595adfa5010b8ff057a897ee8dda21bf824601e3d7d6420135b539e/pyqt5_sip-12.20.1-cp314-cp314-win32.whl", hash = "sha256:d6f3aefdc344d91a6c4a50c3a0d85cc6b28435180792decf968a5c947839cd0a", size = 50943, upload-time = "2026-11-11T12:32:14.946Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/b675f823fdc9b4922140c7f44304d985761cf4bb4e290064302a552eb874/pyqt5_sip-12.20.1-cp314-cp314-win_amd64.whl", hash = "sha256:6b086f44af4a01241f7941b846b05367385988a448608d28a97305aee8c43c36", size = 59929, upload-time = "2026-11-11T12:32:14.018Z" }, + { url = "https://files.pythonhosted.org/packages/a5/94/6914d7850ed49487890c3bd41e815fd8134aaad27cca7de26f175ca2f55d/pyqt5_sip-12.20.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:e510433fccd10adffb1e32752da8410b1a568fcdc9d5cc4a30ab5d3bb10640f7", size = 126140, upload-time = "2026-11-11T12:32:15.883Z" }, + { url = "https://files.pythonhosted.org/packages/80/21/44ddd086ce2b8aa6026440ec194116083d6fafc93f59ceb574905c7bbe6d/pyqt5_sip-12.20.1-cp315-cp315-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:462040f2d3450d3fc6ebd4e30cdaee7e30db8bb02544f367d9120437fb77d025", size = 286596, upload-time = "2026-11-11T12:32:17.176Z" }, + { url = "https://files.pythonhosted.org/packages/89/ed/d4717a379ffaf0ae0ee15e9587441989c75e6304f12d647da9b25323bedb/pyqt5_sip-12.20.1-cp315-cp315-win32.whl", hash = "sha256:08e5a1c77fd362d8fc8f5f5f0e92c0123a719da04ffe916c8eafef8d3aaa8a87", size = 51016, upload-time = "2026-11-11T12:32:19.998Z" }, + { url = "https://files.pythonhosted.org/packages/ea/83/8a7428cfef62c08a0c262e9e5a8b6ef2101661eef62c3f8c7d3c8bc28996/pyqt5_sip-12.20.1-cp315-cp315-win_amd64.whl", hash = "sha256:77ed5391e746d531d9a292e19ad5ce8540e56ebec33c74f6ca0a74be7f63fff6", size = 60056, upload-time = "2026-11-11T12:32:18.901Z" }, +] + +[[package]] +name = "pyqt6" +version = "6.12.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyqt6-qt6" }, + { name = "pyqt6-sip" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/5f/39d2cf3eabc36006a5c87df6e1ed34928025b4a1768d752859bf404ec341/pyqt6-6.12.1.tar.gz", hash = "sha256:17bb18b3ae953ab54b23026291ecea2579b028597b56c281a752c8ed66dd1a58", size = 1108330, upload-time = "2026-11-14T14:52:49.456Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/bd/3a0264000c18bcc7df045bdd9609c92062d7047f83692a7e4a4258ad4e48/pyqt6-6.12.1-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:f3c5588b42e786e25d94e070366762225a863de77c884a6aabc7553a9eeb98ad", size = 12690786, upload-time = "2026-11-14T14:52:38.18Z" }, + { url = "https://files.pythonhosted.org/packages/68/2a/869f7452ba0368b4e1ddbe9679f6fbf1ade5251861a87e1f58acd4215e1b/pyqt6-6.12.1-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:b432aa5ffbdaf90a0b909fd47cb1aa908808ae20928561beed0db9fe2ac6347e", size = 8505955, upload-time = "2026-11-14T14:52:41.233Z" }, + { url = "https://files.pythonhosted.org/packages/17/10/bd39e3799aefa74501e4f51f0ccaf05d954dca4d86009140fb54b4c42954/pyqt6-6.12.1-cp310-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:04d189a18acdd8d5d64f3e99152af42381f26761f1e84c049dec317efe5372a9", size = 8517695, upload-time = "2026-11-14T14:52:43.388Z" }, + { url = "https://files.pythonhosted.org/packages/22/a2/9b45fd134614f76ea9ba37dded8e57360a6a8d73407bff6a93bc214aed01/pyqt6-6.12.1-cp310-abi3-win_amd64.whl", hash = "sha256:91c3a6a520f3e35e022bb7e05a6bf7d47d5b25eb0f0d6ca9c734c18d12d470ff", size = 7092507, upload-time = "2026-11-14T14:52:45.497Z" }, + { url = "https://files.pythonhosted.org/packages/01/7a/c7580ca2d2c49753e1f48dab77d4360859e45e8b64e90b6a3c3c2509b241/pyqt6-6.12.1-cp310-abi3-win_arm64.whl", hash = "sha256:86f77dcb30882014fce9fe0912d9d7aed7f20f17b957b7c5fb0ee67410e89870", size = 6120775, upload-time = "2026-11-14T14:52:47.255Z" }, +] + +[[package]] +name = "pyqt6-qt6" +version = "6.12.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/81/6f1976a8c2bbfb5c8a7f282d25864ddbf9cd7aa4da8c8cf0b75796f3838a/pyqt6_qt6-6.12.1-py3-none-macosx_10_14_x86_64.whl", hash = "sha256:2281045392c42924108d954b66f7dbd2b4f4c87f16c2dac5ee54c7be285d1a99", size = 69600237, upload-time = "2026-11-24T21:17:31.578Z" }, + { url = "https://files.pythonhosted.org/packages/55/d1/0a06fbe3bd62fae4f20c1d8553f0586a239381d011e29354e3ab44fd1903/pyqt6_qt6-6.12.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:79ffa2afd4d196bd24ea91c798927b047f15a2cda24fdcab5b1b96df2c84d1ef", size = 63521363, upload-time = "2026-11-24T21:18:19.601Z" }, + { url = "https://files.pythonhosted.org/packages/f7/eb/4540b5d63a68629b62acb02c4163becdd8d41dca6784fa0fc7feffec6ca5/pyqt6_qt6-6.12.1-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:33208952342131e0477a461e31c654b679fa71b2b32af96422587ed0ea3e47ca", size = 88791593, upload-time = "2026-11-24T21:18:55.62Z" }, + { url = "https://files.pythonhosted.org/packages/4d/92/f38f9a1fe007458cce9d2936bfdae57851bc3c3f0c8412923a73c24d00b0/pyqt6_qt6-6.12.1-py3-none-manylinux_2_39_aarch64.whl", hash = "sha256:d33dbe32aa5bd9d49dba3ca65b1b96875bf9888447ec3b291253725cad5b7cb2", size = 89623542, upload-time = "2026-11-24T21:19:37.566Z" }, + { url = "https://files.pythonhosted.org/packages/28/c6/26fd9524059e71a2ae89c5c8bd7e8f2358e49641b0273471e3f9ad13f902/pyqt6_qt6-6.12.1-py3-none-win_amd64.whl", hash = "sha256:1ab5f90b863cbc074f8f097a9ddf8bfff7efa6a3048e4bb59bb94fc904a5ac91", size = 77883468, upload-time = "2026-11-24T21:20:54.195Z" }, + { url = "https://files.pythonhosted.org/packages/96/93/1b8932e71642fb37b018644c1af52af61e2b02ea980e03a658c48e3344fe/pyqt6_qt6-6.12.1-py3-none-win_arm64.whl", hash = "sha256:2a5fcffb71a07cb434485004fd7ad83e76766de08142cc30802f9fd386f00ecb", size = 63163844, upload-time = "2026-11-24T21:21:25.454Z" }, +] + +[[package]] +name = "pyqt6-sip" +version = "13.13.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/da/164fe6759acbd04c4523a9471c4d11f4b3c744182cb7bbd87faf249ce172/pyqt6_sip-13.13.1.tar.gz", hash = "sha256:83c3c9cb93b6c631af7048084fb0f234b610a01edbf9b2b44c4ee4bda4197efe", size = 95283, upload-time = "2026-11-11T12:33:32.625Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/28/13be7c938b38cf39fac751febd17cfae17a89128d895366249a2e35f3a66/pyqt6_sip-13.13.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:5fbfdfd31a2983cc32e629b531cc3c05e210cd30cb6f3a189894b2876655c37a", size = 113253, upload-time = "2026-11-11T12:32:46.747Z" }, + { url = "https://files.pythonhosted.org/packages/28/31/2844193428c6f9ac2970df90ba72cbc101e176fc7625002eff9f3db106de/pyqt6_sip-13.13.1-cp310-cp310-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a8a6758e3c49da9106887d6ce53231aa8434736985a3aa4db15927b713bc8f50", size = 284046, upload-time = "2026-11-11T12:32:51.653Z" }, + { url = "https://files.pythonhosted.org/packages/e1/28/4618c85731ace7bff6afc813e9a2f397d6acd9ec3c5d3510f7f86c09ae14/pyqt6_sip-13.13.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:944ba044d08efc227498f25810fc24fbdcd2852dc529feb0f966647fe35e57bc", size = 307008, upload-time = "2026-11-11T12:32:48.155Z" }, + { url = "https://files.pythonhosted.org/packages/50/fe/600f5f43c590ae9eaed2adc4805ccebfd87d23a8c2019179cebddc7a663b/pyqt6_sip-13.13.1-cp310-cp310-win_amd64.whl", hash = "sha256:2f4e822dc7f10f8170da56a961a09a974e3fcb0c4ae6c5347fe3d18b608f0d06", size = 54488, upload-time = "2026-11-11T12:32:53.267Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/d78ae0bdd5c585e8c3f96e1a75c48690fcf2c145a0142eb350e1b15311fb/pyqt6_sip-13.13.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:867f86e43666c6f8f98ca3a78a2ca8702e8feb9b776b671488461e8eda5ec899", size = 113257, upload-time = "2026-11-11T12:32:54.542Z" }, + { url = "https://files.pythonhosted.org/packages/66/92/b085cf4266f2879e1547fc85ff29af0a99a5c30d9eda50eef91186dd1761/pyqt6_sip-13.13.1-cp311-cp311-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:19262605e2a3bc62284f118efdc0cd2db891bfbdb4d5c98b497df4efd2eac80b", size = 293089, upload-time = "2026-11-11T12:32:57.183Z" }, + { url = "https://files.pythonhosted.org/packages/5c/41/83ab00281f4c97618c6d949b9bced3caea8c46c8185665ae69a54aa2aeb9/pyqt6_sip-13.13.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9ac602ce5b603994708c9c54ebab00af73ab66490e58da9b28c19a2f095c936b", size = 318638, upload-time = "2026-11-11T12:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/10/64/bed68c4c058f2a67899370260f9950d2723cbe36fdd32b60c2ea9d6052bc/pyqt6_sip-13.13.1-cp311-cp311-win_amd64.whl", hash = "sha256:e1f66f2b06e3de46e6b416ad5cade2c348a818059b5ff2c1431e843307ea9f4b", size = 54484, upload-time = "2026-11-11T12:32:58.381Z" }, + { url = "https://files.pythonhosted.org/packages/85/70/2facce7817d23e72f244aa75c7c609afc7f074832c868f904cfec99d94f7/pyqt6_sip-13.13.1-cp311-cp311-win_arm64.whl", hash = "sha256:c813c6fa69493763487873202ff3d62cf064025cd38925b42cbc071c2eaed39b", size = 48741, upload-time = "2026-11-11T12:33:01.392Z" }, + { url = "https://files.pythonhosted.org/packages/bb/b6/76f5d8aa751f0a2409a38220aadcc4ed7809045425991fbfcc41fc7fef66/pyqt6_sip-13.13.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:8c3ca59c49c39dc518193384ea3d2e842b168c0d5562a5834d22d177cee94369", size = 114065, upload-time = "2026-11-11T12:33:02.419Z" }, + { url = "https://files.pythonhosted.org/packages/70/01/6b4cd724cf503ec58418f40a7a9c110394032ad48e6b209cca0bf2d76769/pyqt6_sip-13.13.1-cp312-cp312-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5417e01a4b3079d60dc9401739c1a851ec7a2267b67b5cc57424a202b6f75044", size = 302313, upload-time = "2026-11-11T12:33:05.404Z" }, + { url = "https://files.pythonhosted.org/packages/cb/ab/7f6b190ebe3e96832a531db2490a09996844159f575c1d5fdcee9988968c/pyqt6_sip-13.13.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9ce18cb83284bc233366b9337cdf1dcefd4054aeaa87f9b76650aba240b6193d", size = 323491, upload-time = "2026-11-11T12:33:03.614Z" }, + { url = "https://files.pythonhosted.org/packages/b8/61/a172e0dd7800e4ea708c58c02099ace2d77094231144cbca4bb1f590c2cb/pyqt6_sip-13.13.1-cp312-cp312-win_amd64.whl", hash = "sha256:5413111b1d3bf4e6672b97bfb2cc47eaa781d8e215d96ea2c62733e1373dfe4f", size = 53756, upload-time = "2026-11-11T12:33:06.604Z" }, + { url = "https://files.pythonhosted.org/packages/d8/4f/2b66f1dd0b62c308c591b02af450b3519ba1ad763ff99b4aeeb09f8071be/pyqt6_sip-13.13.1-cp312-cp312-win_arm64.whl", hash = "sha256:de44a446767ee232f7d94f189124bb483c2bd63ae52166d29b5e7687691164aa", size = 49099, upload-time = "2026-11-11T12:33:07.739Z" }, + { url = "https://files.pythonhosted.org/packages/7e/cc/a778151be3c472a63c272f80edaed233b798a2d97aeaf5d910dfa6af4fbe/pyqt6_sip-13.13.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:748b2d4c238fc1b9c1d37fc702050c481fd83be81909112e079bb8f32b937e99", size = 114050, upload-time = "2026-11-11T12:33:08.668Z" }, + { url = "https://files.pythonhosted.org/packages/d5/fb/97ba2fa6370b93b9595f0dcd78e1a99451853c9a4dc3b545698d90c35694/pyqt6_sip-13.13.1-cp313-cp313-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:50b6d3a20076457ac1675a235721947b6fd9493017d36b6ef42397a8f38da0f6", size = 302710, upload-time = "2026-11-11T12:33:14.965Z" }, + { url = "https://files.pythonhosted.org/packages/48/31/5a7ce8393fa5db0f3e51a20063f83f5d03d3bb1e64002a8ef93edad2c828/pyqt6_sip-13.13.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:402926d57bd15ba41d21e269b6941ad949f60b5e0ce53146a5914771cd2be3b0", size = 323904, upload-time = "2026-11-11T12:33:11.318Z" }, + { url = "https://files.pythonhosted.org/packages/e8/c1/1b029a92a7da8b84fedf3a0d4949389dc247da9cfd97ed07ca2bb75b08b5/pyqt6_sip-13.13.1-cp313-cp313-win_amd64.whl", hash = "sha256:f3c7709d928b40aec5aad21edfed16996d180d4471e386dd2356dec76a4b1bd8", size = 53787, upload-time = "2026-11-11T12:33:16.056Z" }, + { url = "https://files.pythonhosted.org/packages/64/dc/f8e1a45c63d2e81f6070d1a02e532856ab0379edf8ccabd06104235a9ba0/pyqt6_sip-13.13.1-cp313-cp313-win_arm64.whl", hash = "sha256:85922d8a3b5f0836e0da1a094871b9ba0d6728b2505825b9e7e20273636ca2cc", size = 49098, upload-time = "2026-11-11T12:33:17.024Z" }, + { url = "https://files.pythonhosted.org/packages/a3/e0/0de87b831245dc88223a88f37ceb2eaf911d7212f6e471b118f571ffe3ec/pyqt6_sip-13.13.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8e60f616d766142f641ebe1d5b2953271a381d1541785d348d18ea9de92014c7", size = 114221, upload-time = "2026-11-11T12:33:17.899Z" }, + { url = "https://files.pythonhosted.org/packages/bd/cc/6bee3cf016e053fa41579518614b835723ec33746ef8022e78302a9d905a/pyqt6_sip-13.13.1-cp314-cp314-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c3bbc6d119c581d3f90a5c3cfc97025e6ae2ccc5bfc87a2fa68fe3d72ec2e631", size = 302681, upload-time = "2026-11-11T12:33:21.246Z" }, + { url = "https://files.pythonhosted.org/packages/5e/d1/95c6481ab4017cd4c3d50bc34401b6ae24aeade473426cc501692ff62180/pyqt6_sip-13.13.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4a751c542ffb7afcc945eb824fc3fa3c3dae002c91fe5c1da86a5a567c6271b9", size = 324504, upload-time = "2026-11-11T12:33:19.236Z" }, + { url = "https://files.pythonhosted.org/packages/29/5c/bd1a36a72c0d217ef67edc571c07ea83d9de6ad765d711530ebfca3ceec8/pyqt6_sip-13.13.1-cp314-cp314-win_amd64.whl", hash = "sha256:f2f18b1410676b6a7651862ce99d17ba56b7c113fdbae2c231b395d69f0224d3", size = 55454, upload-time = "2026-11-11T12:33:22.347Z" }, + { url = "https://files.pythonhosted.org/packages/7a/1f/8dc9b29d7e768a87ce0f1ee65d8706a57d39427005e5290f0a23d7b4f701/pyqt6_sip-13.13.1-cp314-cp314-win_arm64.whl", hash = "sha256:e52f87f5417b0a335e6f7f8921e3611632868f956267830150b0e467674867a6", size = 49897, upload-time = "2026-11-11T12:33:23.407Z" }, + { url = "https://files.pythonhosted.org/packages/41/dd/3b19955b81b8fe23b0a36fb98db27dee39d148f3571a21a5c9a7314992af/pyqt6_sip-13.13.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:52c10777e7eee608dca24d7ef0a8b19e675c9dca30cd4c2f962d6d17ed50ff75", size = 114562, upload-time = "2026-11-11T12:33:24.417Z" }, + { url = "https://files.pythonhosted.org/packages/27/2e/d141b7684ae99c3e46c274247a4d08d957772cebd450808473e7334819f0/pyqt6_sip-13.13.1-cp315-cp315-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6478e99eb2a096160987bf4e789fe81e70cf80eeb672a0fae7fedfafe33860f7", size = 305906, upload-time = "2026-11-11T12:33:27.068Z" }, + { url = "https://files.pythonhosted.org/packages/98/a7/017fa22df33f130d9b3c2b407f471a3673a3f567b6708bd2eafc14750af1/pyqt6_sip-13.13.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:439404e590625a20fc64377ce07d441ae44e40b75e09570f64cc4387e665b50a", size = 328287, upload-time = "2026-11-11T12:33:25.709Z" }, + { url = "https://files.pythonhosted.org/packages/13/3c/bce908f711be068c6cdc4b8b1d500276d2e859e4568f0107a65d14f16e29/pyqt6_sip-13.13.1-cp315-cp315-win_amd64.whl", hash = "sha256:70feff48f32a860ca41303ee9afd0a193ac0a970f5c508e052c91c6de2192583", size = 55571, upload-time = "2026-11-11T12:33:28.176Z" }, + { url = "https://files.pythonhosted.org/packages/8a/5a/2336cb72ad8bd035d22b9697985cd8b21a725b8335b03bc6b2ddb571ae1a/pyqt6_sip-13.13.1-cp315-cp315-win_arm64.whl", hash = "sha256:fa8342720a6239112ca6e57316d5e988d6b6342424fe863b392597d68a3848ef", size = 49967, upload-time = "2026-11-11T12:33:31.492Z" }, +] + +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + +[[package]] +name = "python-dateutil" +version = "3.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "six" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/df/f15f80383f152452d8985b36d95cb8751f901a3e0ff4cd27f7e118f168e2/python_dateutil-3.0.0.tar.gz", hash = "sha256:7ebcb3c29a92f3ceafe79a7a48a5c45677e9e004bbeec5742ac0bbb00560b7a2", size = 271066, upload-time = "2026-10-21T23:41:45.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/17/cebee01d1c0c1441174cf0456ddc91b280d79acb65340c05e41d77866ee8/python_dateutil-3.0.0-py2.py3-none-any.whl", hash = "sha256:3c79630202e4152c6add678446984236efe4f57e84d8e892aab0637bab82e9fd", size = 94659, upload-time = "2026-10-21T23:41:43.431Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pytokens" +version = "0.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b6/34/b4e015b99031667a7b960f888889c5bd34ef585c85e1cb56a594b92836ac/pytokens-0.4.1.tar.gz", hash = "sha256:292052fe80923aae2260c073f822ceba21f3872ced9a68bb7953b348e561179a", size = 23015, upload-time = "2026-01-30T01:03:45.924Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/42/24/f206113e05cb8ef51b3850e7ef88f20da6f4bf932190ceb48bd3da103e10/pytokens-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2a44ed93ea23415c54f3face3b65ef2b844d96aeb3455b8a69b3df6beab6acc5", size = 161522, upload-time = "2026-01-30T01:02:50.393Z" }, + { url = "https://files.pythonhosted.org/packages/d4/e9/06a6bf1b90c2ed81a9c7d2544232fe5d2891d1cd480e8a1809ca354a8eb2/pytokens-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:add8bf86b71a5d9fb5b89f023a80b791e04fba57960aa790cc6125f7f1d39dfe", size = 246945, upload-time = "2026-01-30T01:02:52.399Z" }, + { url = "https://files.pythonhosted.org/packages/69/66/f6fb1007a4c3d8b682d5d65b7c1fb33257587a5f782647091e3408abe0b8/pytokens-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:670d286910b531c7b7e3c0b453fd8156f250adb140146d234a82219459b9640c", size = 259525, upload-time = "2026-01-30T01:02:53.737Z" }, + { url = "https://files.pythonhosted.org/packages/04/92/086f89b4d622a18418bac74ab5db7f68cf0c21cf7cc92de6c7b919d76c88/pytokens-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:4e691d7f5186bd2842c14813f79f8884bb03f5995f0575272009982c5ac6c0f7", size = 262693, upload-time = "2026-01-30T01:02:54.871Z" }, + { url = "https://files.pythonhosted.org/packages/b4/7b/8b31c347cf94a3f900bdde750b2e9131575a61fdb620d3d3c75832262137/pytokens-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:27b83ad28825978742beef057bfe406ad6ed524b2d28c252c5de7b4a6dd48fa2", size = 103567, upload-time = "2026-01-30T01:02:56.414Z" }, + { url = "https://files.pythonhosted.org/packages/3d/92/790ebe03f07b57e53b10884c329b9a1a308648fc083a6d4a39a10a28c8fc/pytokens-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d70e77c55ae8380c91c0c18dea05951482e263982911fc7410b1ffd1dadd3440", size = 160864, upload-time = "2026-01-30T01:02:57.882Z" }, + { url = "https://files.pythonhosted.org/packages/13/25/a4f555281d975bfdd1eba731450e2fe3a95870274da73fb12c40aeae7625/pytokens-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a58d057208cb9075c144950d789511220b07636dd2e4708d5645d24de666bdc", size = 248565, upload-time = "2026-01-30T01:02:59.912Z" }, + { url = "https://files.pythonhosted.org/packages/17/50/bc0394b4ad5b1601be22fa43652173d47e4c9efbf0044c62e9a59b747c56/pytokens-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b49750419d300e2b5a3813cf229d4e5a4c728dae470bcc89867a9ad6f25a722d", size = 260824, upload-time = "2026-01-30T01:03:01.471Z" }, + { url = "https://files.pythonhosted.org/packages/4e/54/3e04f9d92a4be4fc6c80016bc396b923d2a6933ae94b5f557c939c460ee0/pytokens-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d9907d61f15bf7261d7e775bd5d7ee4d2930e04424bab1972591918497623a16", size = 264075, upload-time = "2026-01-30T01:03:04.143Z" }, + { url = "https://files.pythonhosted.org/packages/d1/1b/44b0326cb5470a4375f37988aea5d61b5cc52407143303015ebee94abfd6/pytokens-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:ee44d0f85b803321710f9239f335aafe16553b39106384cef8e6de40cb4ef2f6", size = 103323, upload-time = "2026-01-30T01:03:05.412Z" }, + { url = "https://files.pythonhosted.org/packages/41/5d/e44573011401fb82e9d51e97f1290ceb377800fb4eed650b96f4753b499c/pytokens-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:140709331e846b728475786df8aeb27d24f48cbcf7bcd449f8de75cae7a45083", size = 160663, upload-time = "2026-01-30T01:03:06.473Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/5bbc3019f8e6f21d09c41f8b8654536117e5e211a85d89212d59cbdab381/pytokens-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d6c4268598f762bc8e91f5dbf2ab2f61f7b95bdc07953b602db879b3c8c18e1", size = 255626, upload-time = "2026-01-30T01:03:08.177Z" }, + { url = "https://files.pythonhosted.org/packages/bf/3c/2d5297d82286f6f3d92770289fd439956b201c0a4fc7e72efb9b2293758e/pytokens-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:24afde1f53d95348b5a0eb19488661147285ca4dd7ed752bbc3e1c6242a304d1", size = 269779, upload-time = "2026-01-30T01:03:09.756Z" }, + { url = "https://files.pythonhosted.org/packages/20/01/7436e9ad693cebda0551203e0bf28f7669976c60ad07d6402098208476de/pytokens-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ad948d085ed6c16413eb5fec6b3e02fa00dc29a2534f088d3302c47eb59adf9", size = 268076, upload-time = "2026-01-30T01:03:10.957Z" }, + { url = "https://files.pythonhosted.org/packages/2e/df/533c82a3c752ba13ae7ef238b7f8cdd272cf1475f03c63ac6cf3fcfb00b6/pytokens-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:3f901fe783e06e48e8cbdc82d631fca8f118333798193e026a50ce1b3757ea68", size = 103552, upload-time = "2026-01-30T01:03:12.066Z" }, + { url = "https://files.pythonhosted.org/packages/cb/dc/08b1a080372afda3cceb4f3c0a7ba2bde9d6a5241f1edb02a22a019ee147/pytokens-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8bdb9d0ce90cbf99c525e75a2fa415144fd570a1ba987380190e8b786bc6ef9b", size = 160720, upload-time = "2026-01-30T01:03:13.843Z" }, + { url = "https://files.pythonhosted.org/packages/64/0c/41ea22205da480837a700e395507e6a24425151dfb7ead73343d6e2d7ffe/pytokens-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5502408cab1cb18e128570f8d598981c68a50d0cbd7c61312a90507cd3a1276f", size = 254204, upload-time = "2026-01-30T01:03:14.886Z" }, + { url = "https://files.pythonhosted.org/packages/e0/d2/afe5c7f8607018beb99971489dbb846508f1b8f351fcefc225fcf4b2adc0/pytokens-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29d1d8fb1030af4d231789959f21821ab6325e463f0503a61d204343c9b355d1", size = 268423, upload-time = "2026-01-30T01:03:15.936Z" }, + { url = "https://files.pythonhosted.org/packages/68/d4/00ffdbd370410c04e9591da9220a68dc1693ef7499173eb3e30d06e05ed1/pytokens-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:970b08dd6b86058b6dc07efe9e98414f5102974716232d10f32ff39701e841c4", size = 266859, upload-time = "2026-01-30T01:03:17.458Z" }, + { url = "https://files.pythonhosted.org/packages/a7/c9/c3161313b4ca0c601eeefabd3d3b576edaa9afdefd32da97210700e47652/pytokens-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:9bd7d7f544d362576be74f9d5901a22f317efc20046efe2034dced238cbbfe78", size = 103520, upload-time = "2026-01-30T01:03:18.652Z" }, + { url = "https://files.pythonhosted.org/packages/8f/a7/b470f672e6fc5fee0a01d9e75005a0e617e162381974213a945fcd274843/pytokens-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4a14d5f5fc78ce85e426aa159489e2d5961acf0e47575e08f35584009178e321", size = 160821, upload-time = "2026-01-30T01:03:19.684Z" }, + { url = "https://files.pythonhosted.org/packages/80/98/e83a36fe8d170c911f864bfded690d2542bfcfacb9c649d11a9e6eb9dc41/pytokens-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97f50fd18543be72da51dd505e2ed20d2228c74e0464e4262e4899797803d7fa", size = 254263, upload-time = "2026-01-30T01:03:20.834Z" }, + { url = "https://files.pythonhosted.org/packages/0f/95/70d7041273890f9f97a24234c00b746e8da86df462620194cef1d411ddeb/pytokens-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc74c035f9bfca0255c1af77ddd2d6ae8419012805453e4b0e7513e17904545d", size = 268071, upload-time = "2026-01-30T01:03:21.888Z" }, + { url = "https://files.pythonhosted.org/packages/da/79/76e6d09ae19c99404656d7db9c35dfd20f2086f3eb6ecb496b5b31163bad/pytokens-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f66a6bbe741bd431f6d741e617e0f39ec7257ca1f89089593479347cc4d13324", size = 271716, upload-time = "2026-01-30T01:03:23.633Z" }, + { url = "https://files.pythonhosted.org/packages/79/37/482e55fa1602e0a7ff012661d8c946bafdc05e480ea5a32f4f7e336d4aa9/pytokens-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:b35d7e5ad269804f6697727702da3c517bb8a5228afa450ab0fa787732055fc9", size = 104539, upload-time = "2026-01-30T01:03:24.788Z" }, + { url = "https://files.pythonhosted.org/packages/30/e8/20e7db907c23f3d63b0be3b8a4fd1927f6da2395f5bcc7f72242bb963dfe/pytokens-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8fcb9ba3709ff77e77f1c7022ff11d13553f3c30299a9fe246a166903e9091eb", size = 168474, upload-time = "2026-01-30T01:03:26.428Z" }, + { url = "https://files.pythonhosted.org/packages/d6/81/88a95ee9fafdd8f5f3452107748fd04c24930d500b9aba9738f3ade642cc/pytokens-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79fc6b8699564e1f9b521582c35435f1bd32dd06822322ec44afdeba666d8cb3", size = 290473, upload-time = "2026-01-30T01:03:27.415Z" }, + { url = "https://files.pythonhosted.org/packages/cf/35/3aa899645e29b6375b4aed9f8d21df219e7c958c4c186b465e42ee0a06bf/pytokens-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d31b97b3de0f61571a124a00ffe9a81fb9939146c122c11060725bd5aea79975", size = 303485, upload-time = "2026-01-30T01:03:28.558Z" }, + { url = "https://files.pythonhosted.org/packages/52/a0/07907b6ff512674d9b201859f7d212298c44933633c946703a20c25e9d81/pytokens-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:967cf6e3fd4adf7de8fc73cd3043754ae79c36475c1c11d514fc72cf5490094a", size = 306698, upload-time = "2026-01-30T01:03:29.653Z" }, + { url = "https://files.pythonhosted.org/packages/39/2a/cbbf9250020a4a8dd53ba83a46c097b69e5eb49dd14e708f496f548c6612/pytokens-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:584c80c24b078eec1e227079d56dc22ff755e0ba8654d8383b2c549107528918", size = 116287, upload-time = "2026-01-30T01:03:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/c6/78/397db326746f0a342855b81216ae1f0a32965deccfd7c830a2dbc66d2483/pytokens-0.4.1-py3-none-any.whl", hash = "sha256:26cef14744a8385f35d0e095dc8b3a7583f6c953c2e3d269c7f82484bf5ad2de", size = 13729, upload-time = "2026-01-30T01:03:45.029Z" }, +] + +[[package]] +name = "pytz" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/b0/168030b0bfcc334cf09fa3313afdb888d892c8a0027324683d1de0ec277e/pytz-2026.6.tar.gz", hash = "sha256:3b0fc2727707663d6e517936f444fd8a8b240f1fc32f4bf7ee03274245945284", size = 318520, upload-time = "2026-10-29T09:05:47.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/25/564f3fc5b70c1398d706c51f2b1470d0ea0b1b2f96fee67877b6f5bdf3b6/pytz-2026.6-py2.py3-none-any.whl", hash = "sha256:7fed3fee8fd6bd4a2b7b75a8d56021d0624127bf69bd5691f115db929ac570b3", size = 506321, upload-time = "2026-10-29T09:05:45.14Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b8/c0b780928e2fb1c87e9e375818c6f121da2398b071012d1747be300b83f4/pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a", size = 136336, upload-time = "2026-11-20T23:37:05.977Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/d6/10c1227ed099bde0d79f826e919495100a6f6052a1f38090181cbf83f863/pyyaml-6.0.4-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489", size = 191158, upload-time = "2026-11-20T23:34:39.807Z" }, + { url = "https://files.pythonhosted.org/packages/87/dd/56bd01e126bec3c669ab1203d3b62337de98419bd776fcea6118a19c0321/pyyaml-6.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c", size = 181299, upload-time = "2026-11-20T23:34:41.003Z" }, + { url = "https://files.pythonhosted.org/packages/c9/10/05ad3d0fce05c0c4838c0f7770e92ce44762684b9b40274d34d08d70385b/pyyaml-6.0.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:54c23934cf166bb2090d73d82b1388aadb1cead5e73885223dcfa4a459a22d43", size = 782161, upload-time = "2026-11-20T23:34:42.3Z" }, + { url = "https://files.pythonhosted.org/packages/3f/4f/b908ce0fbb258a168245c1f45fc5f049a2d900daed8ca685466d125d83cb/pyyaml-6.0.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d58fe9fa2056fed24f055b74d5dc808fa1f5d084c22e4118f0a08253fe677ffd", size = 881030, upload-time = "2026-11-20T23:34:43.419Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d8/4e4b17fa9eafeaf6402e8f2ec46e76fd64930cf02be909a67310b222f217/pyyaml-6.0.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88a089e6424a8a256321270620d5a4328ad5227fb2061b07d33f596894336914", size = 798866, upload-time = "2026-11-20T23:34:44.454Z" }, + { url = "https://files.pythonhosted.org/packages/f5/73/fbb7833d3f0219ee437a347710e5fae2116fb5addaabb4c7e01dd528f4bd/pyyaml-6.0.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:52460c6dd874b22d49fda228fac59da74d7a7b06175ffcc80bfa3ba5389d7f73", size = 771033, upload-time = "2026-11-20T23:34:45.858Z" }, + { url = "https://files.pythonhosted.org/packages/cb/5e/f37cf6924d5cf5d9804edb438f12876c5aceae0c51f7786afea2bfce0559/pyyaml-6.0.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c24097c0462f66358c99dc83d3e1850e005f6293cfa1df1edb243428da1668bf", size = 806497, upload-time = "2026-11-20T23:34:46.966Z" }, + { url = "https://files.pythonhosted.org/packages/3d/99/bb13a9895b5392149f784901221f96b0a0b0527b46afe09fb88e64722233/pyyaml-6.0.4-cp310-cp310-win32.whl", hash = "sha256:34edca7ab64b705ee7c80bf3f9ac609240677db11e83d9317191f483a4b5a433", size = 146258, upload-time = "2026-11-20T23:34:48.053Z" }, + { url = "https://files.pythonhosted.org/packages/57/73/825597bf3616276767117c6fdc13572231e0b5123d91a493080330362f80/pyyaml-6.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:5246a0feaaac497b09c9462aa926280ae02fc8791b0099c0a925ebd7c7f249a6", size = 161774, upload-time = "2026-11-20T23:34:49.357Z" }, + { url = "https://files.pythonhosted.org/packages/e1/ba/fb2aad330bc4f31041f989630ceae5f32e307d3ba9819573d35b71e078fa/pyyaml-6.0.4-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055", size = 190856, upload-time = "2026-11-20T23:34:50.753Z" }, + { url = "https://files.pythonhosted.org/packages/16/da/1b8397614250ec63bb7ef1cbb0aa5878367ff729ef35a4abf2accbf48a18/pyyaml-6.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed", size = 180950, upload-time = "2026-11-20T23:34:51.629Z" }, + { url = "https://files.pythonhosted.org/packages/fa/88/d99fc8f2cfb33ab7786fb3f6da90eddc1ed9709196bffcb4a487d7f53844/pyyaml-6.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028", size = 810905, upload-time = "2026-11-20T23:34:52.77Z" }, + { url = "https://files.pythonhosted.org/packages/d7/7f/500e5ec119990d1784c72b64197cee8a4f2982f6bc76c572af7f8df02385/pyyaml-6.0.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843", size = 914779, upload-time = "2026-11-20T23:34:54.086Z" }, + { url = "https://files.pythonhosted.org/packages/9d/3e/c1c307b6c03e4ea7d86f166f14920ead07aecc35e88d873814d12aa2da66/pyyaml-6.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee", size = 828016, upload-time = "2026-11-20T23:34:55.213Z" }, + { url = "https://files.pythonhosted.org/packages/03/49/dc931722d7de757596c1c3b944287e4f7d3f419655cd8f5fae382c6179e6/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67", size = 799807, upload-time = "2026-11-20T23:34:56.589Z" }, + { url = "https://files.pythonhosted.org/packages/bf/8b/2b7ad9af1c6c5b147c3c860a31586737034a83693d7ae86f854036c6aeb4/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e", size = 836213, upload-time = "2026-11-20T23:34:57.655Z" }, + { url = "https://files.pythonhosted.org/packages/8c/d8/ebdc04bbf7c00a3c78ea577322239534556418a958d2242af8c0c6ef9093/pyyaml-6.0.4-cp311-cp311-win32.whl", hash = "sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd", size = 146012, upload-time = "2026-11-20T23:34:58.75Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c6/ffe94f3159f3543b1ea1702519e1e0a74a67f3a255c286c1f00d51780b82/pyyaml-6.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318", size = 161819, upload-time = "2026-11-20T23:34:59.853Z" }, + { url = "https://files.pythonhosted.org/packages/86/df/5aec8a8c65e4c11fab31b55d53029d8013e5ccfcf409c20f8175e3e267c7/pyyaml-6.0.4-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788", size = 187835, upload-time = "2026-11-20T23:35:00.829Z" }, + { url = "https://files.pythonhosted.org/packages/c7/30/efaabf2d135d11f32cbd4752f3b7df0d592894ee3ca252bbba013a7d5891/pyyaml-6.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019", size = 179510, upload-time = "2026-11-20T23:35:01.826Z" }, + { url = "https://files.pythonhosted.org/packages/af/fb/d5ff6957db5c843151ff13196277bb8e20b2d5db2e2db3e8d051038d888b/pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e", size = 814700, upload-time = "2026-11-20T23:35:02.923Z" }, + { url = "https://files.pythonhosted.org/packages/c4/de/569b907a281bbc49b934bcdad881486b7a476b011cf733f936ca85a8b37d/pyyaml-6.0.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3", size = 879806, upload-time = "2026-11-20T23:35:04.34Z" }, + { url = "https://files.pythonhosted.org/packages/94/80/1d27f7084b983b7cfd1fb35e65a38276d9eddfdcdabc0922bb26cf9521bc/pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0", size = 849249, upload-time = "2026-11-20T23:35:05.457Z" }, + { url = "https://files.pythonhosted.org/packages/53/37/9b49dff68570bedf27a05ff447e9a281d75bbdfa4d08dc1ee100a844c612/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70", size = 799796, upload-time = "2026-11-20T23:35:06.566Z" }, + { url = "https://files.pythonhosted.org/packages/05/bb/f7df529541b98113bea84129a78f93c3889acb08385ca25f9786823dce67/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db", size = 825424, upload-time = "2026-11-20T23:35:07.783Z" }, + { url = "https://files.pythonhosted.org/packages/44/00/fc5d40087cc55bf3d7bb5ef55cc3e6513e6946afe33a188680fe1d846eb0/pyyaml-6.0.4-cp312-cp312-win32.whl", hash = "sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1", size = 140667, upload-time = "2026-11-20T23:35:08.846Z" }, + { url = "https://files.pythonhosted.org/packages/a3/95/307a6ceafbad9a08300743d19329c31726224e583e05c4fe5358522ba283/pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531", size = 154452, upload-time = "2026-11-20T23:35:09.792Z" }, + { url = "https://files.pythonhosted.org/packages/62/81/15c300b14cca818cb9ee27d8cb61cc124229d04f4f7f7bc4e3fca8e2e8d8/pyyaml-6.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768", size = 147167, upload-time = "2026-11-20T23:35:10.763Z" }, + { url = "https://files.pythonhosted.org/packages/95/22/b445c43210fe7f466fcf5a38bcbe850fd3db31b85594db22b5a43e63c482/pyyaml-6.0.4-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e", size = 188392, upload-time = "2026-11-20T23:35:11.776Z" }, + { url = "https://files.pythonhosted.org/packages/1f/c3/1536ad41fd962d3915f3f8252ecc7f91192ab15c3120ba72ff45e76b7077/pyyaml-6.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace", size = 179961, upload-time = "2026-11-20T23:35:12.722Z" }, + { url = "https://files.pythonhosted.org/packages/40/fd/c5297cc6370e4ab63d0c44d2e63510cc53354f5e8e74bcff047e2a384698/pyyaml-6.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3", size = 804464, upload-time = "2026-11-20T23:35:14.066Z" }, + { url = "https://files.pythonhosted.org/packages/0c/2e/20385f63727a6c08df1adad34a88bde90e2bcc1146d1c8588a83190d53b8/pyyaml-6.0.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45", size = 875357, upload-time = "2026-11-20T23:35:15.537Z" }, + { url = "https://files.pythonhosted.org/packages/70/f2/f280d52f22f6d9853517d02495c02fbf4c80214fae8ca498efa8605013da/pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794", size = 838459, upload-time = "2026-11-20T23:35:16.681Z" }, + { url = "https://files.pythonhosted.org/packages/2a/ee/5f7142110583686e94ab4492e3724ed0869cd9fe26ba8293ec25a47ee223/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa", size = 789384, upload-time = "2026-11-20T23:35:17.734Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ab/1fd22df5305561cbefb85363182a0af5e81d219e8b8b8dfd73f20eb70859/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175", size = 814502, upload-time = "2026-11-20T23:35:19.171Z" }, + { url = "https://files.pythonhosted.org/packages/c1/5a/6b53e1711a78fcc14619a341618c36b862ad8c634e7bc43ae18e6a7376b2/pyyaml-6.0.4-cp313-cp313-win32.whl", hash = "sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe", size = 140447, upload-time = "2026-11-20T23:35:20.134Z" }, + { url = "https://files.pythonhosted.org/packages/bd/09/e785d2a9d64de2449cc3aecaa03f1c34670d7a688dc00da7246a858b7e8f/pyyaml-6.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f", size = 154298, upload-time = "2026-11-20T23:36:22.105Z" }, + { url = "https://files.pythonhosted.org/packages/94/44/0ed649c2c1cc37b342042c3a4609247b74201c23a6f7f01f5dd222eae2bd/pyyaml-6.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7", size = 146938, upload-time = "2026-11-20T23:36:23.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/90/a2d37db959cb771389bb6171eff83905776e5aead12a985a5118a587d6eb/pyyaml-6.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56", size = 189727, upload-time = "2026-11-20T23:36:24.518Z" }, + { url = "https://files.pythonhosted.org/packages/71/40/de4380acb2bcc733f502a7c8562b08f741890741dcaa8a7f018c87acc060/pyyaml-6.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851", size = 181969, upload-time = "2026-11-20T23:36:25.675Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a1/88baf9d84981ea723fc1dd5cb534548caebff3071939f899509ab7c62d2f/pyyaml-6.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b", size = 804091, upload-time = "2026-11-20T23:36:26.979Z" }, + { url = "https://files.pythonhosted.org/packages/b8/d4/ce94fe5b0e3cc04834d4a30237c1b5388a13ff5a383b919e857898834857/pyyaml-6.0.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92", size = 869794, upload-time = "2026-11-20T23:36:28.069Z" }, + { url = "https://files.pythonhosted.org/packages/ef/1b/54ce11b40c8fa1883f14eef46525c3c329509dcc268164074fbe60add8ed/pyyaml-6.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7", size = 819491, upload-time = "2026-11-20T23:36:29.189Z" }, + { url = "https://files.pythonhosted.org/packages/8a/d2/6202ffb5d61667c993211a9231836b5d9be5e34165efd1714ac68ea76029/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f", size = 790345, upload-time = "2026-11-20T23:36:30.597Z" }, + { url = "https://files.pythonhosted.org/packages/d4/39/d62587fae4a9a32197ea43182c38f221f3f173a09c6f4380254533bdd89e/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43", size = 824626, upload-time = "2026-11-20T23:36:31.9Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b5/e5cf6ca786f8a5b9bd91e01fe8f2113300bc5628fcfdd3ca02d271970824/pyyaml-6.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e", size = 157525, upload-time = "2026-11-20T23:36:44.254Z" }, + { url = "https://files.pythonhosted.org/packages/75/9c/d78ce9adda3f7db933f73bb2b17ede76f5786fff747a2b73f6e8a6b7bab5/pyyaml-6.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd", size = 151175, upload-time = "2026-11-20T23:36:45.191Z" }, + { url = "https://files.pythonhosted.org/packages/83/f0/e48b8e9736380a039a17506200c4c3080ef181ee86b0e8e2cd6c345ae78a/pyyaml-6.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1", size = 193903, upload-time = "2026-11-20T23:36:33.086Z" }, + { url = "https://files.pythonhosted.org/packages/98/ba/682030d1e08f2e4bbd57f164b9085d37560386cf54f6299825e754b32d1a/pyyaml-6.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03", size = 188971, upload-time = "2026-11-20T23:36:34.034Z" }, + { url = "https://files.pythonhosted.org/packages/e9/2b/4b29107aae981b4d4575945a73d6c73ebd407d27934dcf35a7daa8fbeb43/pyyaml-6.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6", size = 851356, upload-time = "2026-11-20T23:36:35.21Z" }, + { url = "https://files.pythonhosted.org/packages/12/d4/2b05dddc8f59c3762e67c8d5ac01c1759767ee6ea4aba183a01950644668/pyyaml-6.0.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1", size = 887294, upload-time = "2026-11-20T23:36:36.484Z" }, + { url = "https://files.pythonhosted.org/packages/3e/2a/ce3e0ff674c67b9e1706912aae61063581b3dba22142e60ccdaa64b25c75/pyyaml-6.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91", size = 850982, upload-time = "2026-11-20T23:36:38.247Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ad/701d83221865b2512067a9ab2b8e062145af2d362cc2451e72c146ef34cf/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b", size = 822547, upload-time = "2026-11-20T23:36:39.852Z" }, + { url = "https://files.pythonhosted.org/packages/61/d1/d88b389313be382ddabd1bca86dbf5da31ac02ecbf29c893588aafb6e11f/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865", size = 845538, upload-time = "2026-11-20T23:36:41.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/a6/c25ff1b5ebc8bfb11a783a5fde40435f0459629af6f56f9487479bca9766/pyyaml-6.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399", size = 164060, upload-time = "2026-11-20T23:36:42.238Z" }, + { url = "https://files.pythonhosted.org/packages/08/ad/25d2ac566f0e2f4eb822c9c5e8d9a053406cbfff142273a072b194856823/pyyaml-6.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a", size = 157379, upload-time = "2026-11-20T23:36:43.181Z" }, + { url = "https://files.pythonhosted.org/packages/e5/29/fb680bd299c2c6e004c1cc1914f8bad276c6014fe8debd5d6d61ea4c4ff4/pyyaml-6.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8", size = 189560, upload-time = "2026-11-20T23:36:46.145Z" }, + { url = "https://files.pythonhosted.org/packages/af/6c/2ffdab56d7afeb039d957479a305516ddbaa08d0162d1e9165fb928e3aeb/pyyaml-6.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a", size = 181949, upload-time = "2026-11-20T23:36:47.065Z" }, + { url = "https://files.pythonhosted.org/packages/b3/07/3a20ed31a60084206ac20449583b0d1a42116b3c530d6857918e4ddbe4b6/pyyaml-6.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd", size = 803806, upload-time = "2026-11-20T23:36:48.145Z" }, + { url = "https://files.pythonhosted.org/packages/26/5b/3dd56027457b96e7e5ea2f4f5976e530d699884b4fd4e360e99e57fa6cca/pyyaml-6.0.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7", size = 876808, upload-time = "2026-11-20T23:36:49.294Z" }, + { url = "https://files.pythonhosted.org/packages/b0/51/096a5495b33ff2da32f0c84f5bf8e042cf76f72641cba06ee9618ad01f4d/pyyaml-6.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963", size = 833052, upload-time = "2026-11-20T23:36:50.505Z" }, + { url = "https://files.pythonhosted.org/packages/da/75/b4e86b5a27fcb9a9cf88e3b81d1b0c12cae2734311e508af18b93ff56286/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca", size = 788983, upload-time = "2026-11-20T23:36:51.821Z" }, + { url = "https://files.pythonhosted.org/packages/2c/00/2a2cdad68237bcd416bd01688ecfb0e3fa1e68a841b74193db97ffd1c716/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36", size = 828806, upload-time = "2026-11-20T23:36:52.959Z" }, + { url = "https://files.pythonhosted.org/packages/a8/15/39efefc88dd6fbc3be23cef08a819f5e8bf9a6c0bcf003fc09d38dd0010e/pyyaml-6.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6", size = 157467, upload-time = "2026-11-20T23:37:04.171Z" }, + { url = "https://files.pythonhosted.org/packages/40/1d/fddc53420d9c12e7d27c36a59fabf186ba1f6117314da4927dc40b2da19b/pyyaml-6.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25", size = 151203, upload-time = "2026-11-20T23:37:05.079Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ea/48e62a25084fc4b317f8bcc5c9823ddaaa73a0c7769ca451dda6919ff491/pyyaml-6.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb", size = 193500, upload-time = "2026-11-20T23:36:54.416Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/8c4df6becc936125261607073fbcd55e1d902a8d53ae4e4893d53b9df0ef/pyyaml-6.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7", size = 188474, upload-time = "2026-11-20T23:36:55.651Z" }, + { url = "https://files.pythonhosted.org/packages/d0/63/b60236ef09cbab7c5ce174aff59d49a3425b9a8e9bbe4690bd3b9b7d4fba/pyyaml-6.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39", size = 848311, upload-time = "2026-11-20T23:36:56.961Z" }, + { url = "https://files.pythonhosted.org/packages/f6/3b/4b14f064ae5d6f69638a86bb7bf1a46d02bb4de083798e693a4a83b1418a/pyyaml-6.0.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a", size = 891181, upload-time = "2026-11-20T23:36:58.077Z" }, + { url = "https://files.pythonhosted.org/packages/01/36/4e0b01e380bf3695d34a4bf6b9272c529f4c8d3195c733687d64fb9f8f06/pyyaml-6.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b", size = 855715, upload-time = "2026-11-20T23:36:59.165Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a8/2784a29e687fa7a5882d47c925a98d1dbdd60ead521be14a9342c6a74ff9/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70", size = 818754, upload-time = "2026-11-20T23:37:00.248Z" }, + { url = "https://files.pythonhosted.org/packages/bb/85/62d54e223b4bc89ff85f087a5ce2648e5d929d3214d64613dbae17d5e045/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520", size = 845763, upload-time = "2026-11-20T23:37:01.331Z" }, + { url = "https://files.pythonhosted.org/packages/eb/40/6bd9090368664be984a83fd7fe64f8e044b067a52449679c309706e3199d/pyyaml-6.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33", size = 163170, upload-time = "2026-11-20T23:37:02.3Z" }, + { url = "https://files.pythonhosted.org/packages/0d/22/468d36762a0c650cf2295052998eb1d419053335ea9ff48a043f5ae4d578/pyyaml-6.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886", size = 156942, upload-time = "2026-11-20T23:37:03.209Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "roman-numerals" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/f9/41dc953bbeb056c17d5f7a519f50fdf010bd0553be2d630bc69d1e022703/roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2", size = 9077, upload-time = "2025-12-17T18:25:34.381Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/54/6f679c435d28e0a568d8e8a7c0a93a09010818634c3c3907fc98d8983770/roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7", size = 7676, upload-time = "2025-12-17T18:25:33.098Z" }, +] + +[[package]] +name = "scikit-image" +version = "0.25.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "imageio", version = "2.38.0", source = { registry = "https://pypi.org/simple" } }, + { name = "lazy-loader" }, + { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" } }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" } }, + { name = "tifffile", version = "2025.5.10", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c7/a8/3c0f256012b93dd2cb6fda9245e9f4bff7dc0486880b248005f15ea2255e/scikit_image-0.25.2.tar.gz", hash = "sha256:e5a37e6cd4d0c018a7a55b9d601357e3382826d3888c10d0213fc63bff977dde", size = 22693594, upload-time = "2025-02-18T18:05:24.538Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/cb/016c63f16065c2d333c8ed0337e18a5cdf9bc32d402e4f26b0db362eb0e2/scikit_image-0.25.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d3278f586793176599df6a4cf48cb6beadae35c31e58dc01a98023af3dc31c78", size = 13988922, upload-time = "2025-02-18T18:04:11.069Z" }, + { url = "https://files.pythonhosted.org/packages/30/ca/ff4731289cbed63c94a0c9a5b672976603118de78ed21910d9060c82e859/scikit_image-0.25.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:5c311069899ce757d7dbf1d03e32acb38bb06153236ae77fcd820fd62044c063", size = 13192698, upload-time = "2025-02-18T18:04:15.362Z" }, + { url = "https://files.pythonhosted.org/packages/39/6d/a2aadb1be6d8e149199bb9b540ccde9e9622826e1ab42fe01de4c35ab918/scikit_image-0.25.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be455aa7039a6afa54e84f9e38293733a2622b8c2fb3362b822d459cc5605e99", size = 14153634, upload-time = "2025-02-18T18:04:18.496Z" }, + { url = "https://files.pythonhosted.org/packages/96/08/916e7d9ee4721031b2f625db54b11d8379bd51707afaa3e5a29aecf10bc4/scikit_image-0.25.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4c464b90e978d137330be433df4e76d92ad3c5f46a22f159520ce0fdbea8a09", size = 14767545, upload-time = "2025-02-18T18:04:22.556Z" }, + { url = "https://files.pythonhosted.org/packages/5f/ee/c53a009e3997dda9d285402f19226fbd17b5b3cb215da391c4ed084a1424/scikit_image-0.25.2-cp310-cp310-win_amd64.whl", hash = "sha256:60516257c5a2d2f74387c502aa2f15a0ef3498fbeaa749f730ab18f0a40fd054", size = 12812908, upload-time = "2025-02-18T18:04:26.364Z" }, + { url = "https://files.pythonhosted.org/packages/c4/97/3051c68b782ee3f1fb7f8f5bb7d535cf8cb92e8aae18fa9c1cdf7e15150d/scikit_image-0.25.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f4bac9196fb80d37567316581c6060763b0f4893d3aca34a9ede3825bc035b17", size = 14003057, upload-time = "2025-02-18T18:04:30.395Z" }, + { url = "https://files.pythonhosted.org/packages/19/23/257fc696c562639826065514d551b7b9b969520bd902c3a8e2fcff5b9e17/scikit_image-0.25.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:d989d64ff92e0c6c0f2018c7495a5b20e2451839299a018e0e5108b2680f71e0", size = 13180335, upload-time = "2025-02-18T18:04:33.449Z" }, + { url = "https://files.pythonhosted.org/packages/ef/14/0c4a02cb27ca8b1e836886b9ec7c9149de03053650e9e2ed0625f248dd92/scikit_image-0.25.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2cfc96b27afe9a05bc92f8c6235321d3a66499995675b27415e0d0c76625173", size = 14144783, upload-time = "2025-02-18T18:04:36.594Z" }, + { url = "https://files.pythonhosted.org/packages/dd/9b/9fb556463a34d9842491d72a421942c8baff4281025859c84fcdb5e7e602/scikit_image-0.25.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:24cc986e1f4187a12aa319f777b36008764e856e5013666a4a83f8df083c2641", size = 14785376, upload-time = "2025-02-18T18:04:39.856Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/b57c500ee85885df5f2188f8bb70398481393a69de44a00d6f1d055f103c/scikit_image-0.25.2-cp311-cp311-win_amd64.whl", hash = "sha256:b4f6b61fc2db6340696afe3db6b26e0356911529f5f6aee8c322aa5157490c9b", size = 12791698, upload-time = "2025-02-18T18:04:42.868Z" }, + { url = "https://files.pythonhosted.org/packages/35/8c/5df82881284459f6eec796a5ac2a0a304bb3384eec2e73f35cfdfcfbf20c/scikit_image-0.25.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8db8dd03663112783221bf01ccfc9512d1cc50ac9b5b0fe8f4023967564719fb", size = 13986000, upload-time = "2025-02-18T18:04:47.156Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e6/93bebe1abcdce9513ffec01d8af02528b4c41fb3c1e46336d70b9ed4ef0d/scikit_image-0.25.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:483bd8cc10c3d8a7a37fae36dfa5b21e239bd4ee121d91cad1f81bba10cfb0ed", size = 13235893, upload-time = "2025-02-18T18:04:51.049Z" }, + { url = "https://files.pythonhosted.org/packages/53/4b/eda616e33f67129e5979a9eb33c710013caa3aa8a921991e6cc0b22cea33/scikit_image-0.25.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9d1e80107bcf2bf1291acfc0bf0425dceb8890abe9f38d8e94e23497cbf7ee0d", size = 14178389, upload-time = "2025-02-18T18:04:54.245Z" }, + { url = "https://files.pythonhosted.org/packages/6b/b5/b75527c0f9532dd8a93e8e7cd8e62e547b9f207d4c11e24f0006e8646b36/scikit_image-0.25.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a17e17eb8562660cc0d31bb55643a4da996a81944b82c54805c91b3fe66f4824", size = 15003435, upload-time = "2025-02-18T18:04:57.586Z" }, + { url = "https://files.pythonhosted.org/packages/34/e3/49beb08ebccda3c21e871b607c1cb2f258c3fa0d2f609fed0a5ba741b92d/scikit_image-0.25.2-cp312-cp312-win_amd64.whl", hash = "sha256:bdd2b8c1de0849964dbc54037f36b4e9420157e67e45a8709a80d727f52c7da2", size = 12899474, upload-time = "2025-02-18T18:05:01.166Z" }, + { url = "https://files.pythonhosted.org/packages/e6/7c/9814dd1c637f7a0e44342985a76f95a55dd04be60154247679fd96c7169f/scikit_image-0.25.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7efa888130f6c548ec0439b1a7ed7295bc10105458a421e9bf739b457730b6da", size = 13921841, upload-time = "2025-02-18T18:05:03.963Z" }, + { url = "https://files.pythonhosted.org/packages/84/06/66a2e7661d6f526740c309e9717d3bd07b473661d5cdddef4dd978edab25/scikit_image-0.25.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:dd8011efe69c3641920614d550f5505f83658fe33581e49bed86feab43a180fc", size = 13196862, upload-time = "2025-02-18T18:05:06.986Z" }, + { url = "https://files.pythonhosted.org/packages/4e/63/3368902ed79305f74c2ca8c297dfeb4307269cbe6402412668e322837143/scikit_image-0.25.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:28182a9d3e2ce3c2e251383bdda68f8d88d9fff1a3ebe1eb61206595c9773341", size = 14117785, upload-time = "2025-02-18T18:05:10.69Z" }, + { url = "https://files.pythonhosted.org/packages/cd/9b/c3da56a145f52cd61a68b8465d6a29d9503bc45bc993bb45e84371c97d94/scikit_image-0.25.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8abd3c805ce6944b941cfed0406d88faeb19bab3ed3d4b50187af55cf24d147", size = 14977119, upload-time = "2025-02-18T18:05:13.871Z" }, + { url = "https://files.pythonhosted.org/packages/8a/97/5fcf332e1753831abb99a2525180d3fb0d70918d461ebda9873f66dcc12f/scikit_image-0.25.2-cp313-cp313-win_amd64.whl", hash = "sha256:64785a8acefee460ec49a354706db0b09d1f325674107d7fa3eadb663fb56d6f", size = 12885116, upload-time = "2025-02-18T18:05:17.844Z" }, + { url = "https://files.pythonhosted.org/packages/10/cc/75e9f17e3670b5ed93c32456fda823333c6279b144cd93e2c03aa06aa472/scikit_image-0.25.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:330d061bd107d12f8d68f1d611ae27b3b813b8cdb0300a71d07b1379178dd4cd", size = 13862801, upload-time = "2025-02-18T18:05:20.783Z" }, +] + +[[package]] +name = "scikit-image" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "imageio", version = "2.38.2", source = { registry = "https://pypi.org/simple" } }, + { name = "lazy-loader" }, + { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "networkx", version = "3.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "tifffile", version = "2026.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "tifffile", version = "2026.11.26", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/16/8a407688b607f86f81f8c649bf0d68a2a6d67375f18c2d660aba20f5b648/scikit_image-0.26.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b1ede33a0fb3731457eaf53af6361e73dd510f449dac437ab54573b26788baf0", size = 12355510, upload-time = "2025-12-20T17:10:31.628Z" }, + { url = "https://files.pythonhosted.org/packages/6b/f9/7efc088ececb6f6868fd4475e16cfafc11f242ce9ab5fc3557d78b5da0d4/scikit_image-0.26.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7af7aa331c6846bd03fa28b164c18d0c3fd419dbb888fb05e958ac4257a78fdd", size = 12056334, upload-time = "2025-12-20T17:10:34.559Z" }, + { url = "https://files.pythonhosted.org/packages/9f/1e/bc7fb91fb5ff65ef42346c8b7ee8b09b04eabf89235ab7dbfdfd96cbd1ea/scikit_image-0.26.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9ea6207d9e9d21c3f464efe733121c0504e494dbdc7728649ff3e23c3c5a4953", size = 13297768, upload-time = "2025-12-20T17:10:37.733Z" }, + { url = "https://files.pythonhosted.org/packages/a5/2a/e71c1a7d90e70da67b88ccc609bd6ae54798d5847369b15d3a8052232f9d/scikit_image-0.26.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74aa5518ccea28121f57a95374581d3b979839adc25bb03f289b1bc9b99c58af", size = 13711217, upload-time = "2025-12-20T17:10:40.935Z" }, + { url = "https://files.pythonhosted.org/packages/d4/59/9637ee12c23726266b91296791465218973ce1ad3e4c56fc81e4d8e7d6e1/scikit_image-0.26.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d5c244656de905e195a904e36dbc18585e06ecf67d90f0482cbde63d7f9ad59d", size = 14337782, upload-time = "2025-12-20T17:10:43.452Z" }, + { url = "https://files.pythonhosted.org/packages/e7/5c/a3e1e0860f9294663f540c117e4bf83d55e5b47c281d475cc06227e88411/scikit_image-0.26.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:21a818ee6ca2f2131b9e04d8eb7637b5c18773ebe7b399ad23dcc5afaa226d2d", size = 14805997, upload-time = "2025-12-20T17:10:45.93Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c6/2eeacf173da041a9e388975f54e5c49df750757fcfc3ee293cdbbae1ea0a/scikit_image-0.26.0-cp311-cp311-win_amd64.whl", hash = "sha256:9490360c8d3f9a7e85c8de87daf7c0c66507960cf4947bb9610d1751928721c7", size = 11878486, upload-time = "2025-12-20T17:10:48.246Z" }, + { url = "https://files.pythonhosted.org/packages/c3/a4/a852c4949b9058d585e762a66bf7e9a2cd3be4795cd940413dfbfbb0ce79/scikit_image-0.26.0-cp311-cp311-win_arm64.whl", hash = "sha256:0baa0108d2d027f34d748e84e592b78acc23e965a5de0e4bb03cf371de5c0581", size = 11346518, upload-time = "2025-12-20T17:10:50.575Z" }, + { url = "https://files.pythonhosted.org/packages/99/e8/e13757982264b33a1621628f86b587e9a73a13f5256dad49b19ba7dc9083/scikit_image-0.26.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d454b93a6fa770ac5ae2d33570f8e7a321bb80d29511ce4b6b78058ebe176e8c", size = 12376452, upload-time = "2025-12-20T17:10:52.796Z" }, + { url = "https://files.pythonhosted.org/packages/e3/be/f8dd17d0510f9911f9f17ba301f7455328bf13dae416560126d428de9568/scikit_image-0.26.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3409e89d66eff5734cd2b672d1c48d2759360057e714e1d92a11df82c87cba37", size = 12061567, upload-time = "2025-12-20T17:10:55.207Z" }, + { url = "https://files.pythonhosted.org/packages/b3/2b/c70120a6880579fb42b91567ad79feb4772f7be72e8d52fec403a3dde0c6/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c717490cec9e276afb0438dd165b7c3072d6c416709cc0f9f5a4c1070d23a44", size = 13084214, upload-time = "2025-12-20T17:10:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/f4/a2/70401a107d6d7466d64b466927e6b96fcefa99d57494b972608e2f8be50f/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7df650e79031634ac90b11e64a9eedaf5a5e06fcd09bcd03a34be01745744466", size = 13561683, upload-time = "2025-12-20T17:10:59.49Z" }, + { url = "https://files.pythonhosted.org/packages/13/a5/48bdfd92794c5002d664e0910a349d0a1504671ef5ad358150f21643c79a/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cefd85033e66d4ea35b525bb0937d7f42d4cdcfed2d1888e1570d5ce450d3932", size = 14112147, upload-time = "2025-12-20T17:11:02.083Z" }, + { url = "https://files.pythonhosted.org/packages/ee/b5/ac71694da92f5def5953ca99f18a10fe98eac2dd0a34079389b70b4d0394/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3f5bf622d7c0435884e1e141ebbe4b2804e16b2dd23ae4c6183e2ea99233be70", size = 14661625, upload-time = "2025-12-20T17:11:04.528Z" }, + { url = "https://files.pythonhosted.org/packages/23/4d/a3cc1e96f080e253dad2251bfae7587cf2b7912bcd76fd43fd366ff35a87/scikit_image-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:abed017474593cd3056ae0fe948d07d0747b27a085e92df5474f4955dd65aec0", size = 11911059, upload-time = "2025-12-20T17:11:06.61Z" }, + { url = "https://files.pythonhosted.org/packages/35/8a/d1b8055f584acc937478abf4550d122936f420352422a1a625eef2c605d8/scikit_image-0.26.0-cp312-cp312-win_arm64.whl", hash = "sha256:4d57e39ef67a95d26860c8caf9b14b8fb130f83b34c6656a77f191fa6d1d04d8", size = 11348740, upload-time = "2025-12-20T17:11:09.118Z" }, + { url = "https://files.pythonhosted.org/packages/4f/48/02357ffb2cca35640f33f2cfe054a4d6d5d7a229b88880a64f1e45c11f4e/scikit_image-0.26.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a2e852eccf41d2d322b8e60144e124802873a92b8d43a6f96331aa42888491c7", size = 12346329, upload-time = "2025-12-20T17:11:11.599Z" }, + { url = "https://files.pythonhosted.org/packages/67/b9/b792c577cea2c1e94cda83b135a656924fc57c428e8a6d302cd69aac1b60/scikit_image-0.26.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:98329aab3bc87db352b9887f64ce8cdb8e75f7c2daa19927f2e121b797b678d5", size = 12031726, upload-time = "2025-12-20T17:11:13.871Z" }, + { url = "https://files.pythonhosted.org/packages/07/a9/9564250dfd65cb20404a611016db52afc6268b2b371cd19c7538ea47580f/scikit_image-0.26.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:915bb3ba66455cf8adac00dc8fdf18a4cd29656aec7ddd38cb4dda90289a6f21", size = 13094910, upload-time = "2025-12-20T17:11:16.2Z" }, + { url = "https://files.pythonhosted.org/packages/a3/b8/0d8eeb5a9fd7d34ba84f8a55753a0a3e2b5b51b2a5a0ade648a8db4a62f7/scikit_image-0.26.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b36ab5e778bf50af5ff386c3ac508027dc3aaeccf2161bdf96bde6848f44d21b", size = 13660939, upload-time = "2025-12-20T17:11:18.464Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d6/91d8973584d4793d4c1a847d388e34ef1218d835eeddecfc9108d735b467/scikit_image-0.26.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:09bad6a5d5949c7896c8347424c4cca899f1d11668030e5548813ab9c2865dcb", size = 14138938, upload-time = "2025-12-20T17:11:20.919Z" }, + { url = "https://files.pythonhosted.org/packages/39/9a/7e15d8dc10d6bbf212195fb39bdeb7f226c46dd53f9c63c312e111e2e175/scikit_image-0.26.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:aeb14db1ed09ad4bee4ceb9e635547a8d5f3549be67fc6c768c7f923e027e6cd", size = 14752243, upload-time = "2025-12-20T17:11:23.347Z" }, + { url = "https://files.pythonhosted.org/packages/8f/58/2b11b933097bc427e42b4a8b15f7de8f24f2bac1fd2779d2aea1431b2c31/scikit_image-0.26.0-cp313-cp313-win_amd64.whl", hash = "sha256:ac529eb9dbd5954f9aaa2e3fe9a3fd9661bfe24e134c688587d811a0233127f1", size = 11906770, upload-time = "2025-12-20T17:11:25.297Z" }, + { url = "https://files.pythonhosted.org/packages/ad/ec/96941474a18a04b69b6f6562a5bd79bd68049fa3728d3b350976eccb8b93/scikit_image-0.26.0-cp313-cp313-win_arm64.whl", hash = "sha256:a2d211bc355f59725efdcae699b93b30348a19416cc9e017f7b2fb599faf7219", size = 11342506, upload-time = "2025-12-20T17:11:27.399Z" }, + { url = "https://files.pythonhosted.org/packages/03/e5/c1a9962b0cf1952f42d32b4a2e48eed520320dbc4d2ff0b981c6fa508b6b/scikit_image-0.26.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9eefb4adad066da408a7601c4c24b07af3b472d90e08c3e7483d4e9e829d8c49", size = 12663278, upload-time = "2025-12-20T17:11:29.358Z" }, + { url = "https://files.pythonhosted.org/packages/ae/97/c1a276a59ce8e4e24482d65c1a3940d69c6b3873279193b7ebd04e5ee56b/scikit_image-0.26.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:6caec76e16c970c528d15d1c757363334d5cb3069f9cea93d2bead31820511f3", size = 12405142, upload-time = "2025-12-20T17:11:31.282Z" }, + { url = "https://files.pythonhosted.org/packages/d4/4a/f1cbd1357caef6c7993f7efd514d6e53d8fd6f7fe01c4714d51614c53289/scikit_image-0.26.0-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a07200fe09b9d99fcdab959859fe0f7db8df6333d6204344425d476850ce3604", size = 12942086, upload-time = "2025-12-20T17:11:33.683Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6f/74d9fb87c5655bd64cf00b0c44dc3d6206d9002e5f6ba1c9aeb13236f6bf/scikit_image-0.26.0-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:92242351bccf391fc5df2d1529d15470019496d2498d615beb68da85fe7fdf37", size = 13265667, upload-time = "2025-12-20T17:11:36.11Z" }, + { url = "https://files.pythonhosted.org/packages/a7/73/faddc2413ae98d863f6fa2e3e14da4467dd38e788e1c23346cf1a2b06b97/scikit_image-0.26.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:52c496f75a7e45844d951557f13c08c81487c6a1da2e3c9c8a39fcde958e02cc", size = 14001966, upload-time = "2025-12-20T17:11:38.55Z" }, + { url = "https://files.pythonhosted.org/packages/02/94/9f46966fa042b5d57c8cd641045372b4e0df0047dd400e77ea9952674110/scikit_image-0.26.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:20ef4a155e2e78b8ab973998e04d8a361d49d719e65412405f4dadd9155a61d9", size = 14359526, upload-time = "2025-12-20T17:11:41.087Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b4/2840fe38f10057f40b1c9f8fb98a187a370936bf144a4ac23452c5ef1baf/scikit_image-0.26.0-cp313-cp313t-win_amd64.whl", hash = "sha256:c9087cf7d0e7f33ab5c46d2068d86d785e70b05400a891f73a13400f1e1faf6a", size = 12287629, upload-time = "2025-12-20T17:11:43.11Z" }, + { url = "https://files.pythonhosted.org/packages/22/ba/73b6ca70796e71f83ab222690e35a79612f0117e5aaf167151b7d46f5f2c/scikit_image-0.26.0-cp313-cp313t-win_arm64.whl", hash = "sha256:27d58bc8b2acd351f972c6508c1b557cfed80299826080a4d803dd29c51b707e", size = 11647755, upload-time = "2025-12-20T17:11:45.279Z" }, + { url = "https://files.pythonhosted.org/packages/51/44/6b744f92b37ae2833fd423cce8f806d2368859ec325a699dc30389e090b9/scikit_image-0.26.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:63af3d3a26125f796f01052052f86806da5b5e54c6abef152edb752683075a9c", size = 12365810, upload-time = "2025-12-20T17:11:47.357Z" }, + { url = "https://files.pythonhosted.org/packages/40/f5/83590d9355191f86ac663420fec741b82cc547a4afe7c4c1d986bf46e4db/scikit_image-0.26.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ce00600cd70d4562ed59f80523e18cdcc1fae0e10676498a01f73c255774aefd", size = 12075717, upload-time = "2025-12-20T17:11:49.483Z" }, + { url = "https://files.pythonhosted.org/packages/72/48/253e7cf5aee6190459fe136c614e2cbccc562deceb4af96e0863f1b8ee29/scikit_image-0.26.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6381edf972b32e4f54085449afde64365a57316637496c1325a736987083e2ab", size = 13161520, upload-time = "2025-12-20T17:11:51.58Z" }, + { url = "https://files.pythonhosted.org/packages/73/c3/cec6a3cbaadfdcc02bd6ff02f3abfe09eaa7f4d4e0a525a1e3a3f4bce49c/scikit_image-0.26.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6624a76c6085218248154cc7e1500e6b488edcd9499004dd0d35040607d7505", size = 13684340, upload-time = "2025-12-20T17:11:53.708Z" }, + { url = "https://files.pythonhosted.org/packages/d4/0d/39a776f675d24164b3a267aa0db9f677a4cb20127660d8bf4fd7fef66817/scikit_image-0.26.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f775f0e420faac9c2aa6757135f4eb468fb7b70e0b67fa77a5e79be3c30ee331", size = 14203839, upload-time = "2025-12-20T17:11:55.89Z" }, + { url = "https://files.pythonhosted.org/packages/ee/25/2514df226bbcedfe9b2caafa1ba7bc87231a0c339066981b182b08340e06/scikit_image-0.26.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede4d6d255cc5da9faeb2f9ba7fedbc990abbc652db429f40a16b22e770bb578", size = 14770021, upload-time = "2025-12-20T17:11:58.014Z" }, + { url = "https://files.pythonhosted.org/packages/8d/5b/0671dc91c0c79340c3fe202f0549c7d3681eb7640fe34ab68a5f090a7c7f/scikit_image-0.26.0-cp314-cp314-win_amd64.whl", hash = "sha256:0660b83968c15293fd9135e8d860053ee19500d52bf55ca4fb09de595a1af650", size = 12023490, upload-time = "2025-12-20T17:12:00.013Z" }, + { url = "https://files.pythonhosted.org/packages/65/08/7c4cb59f91721f3de07719085212a0b3962e3e3f2d1818cbac4eeb1ea53e/scikit_image-0.26.0-cp314-cp314-win_arm64.whl", hash = "sha256:b8d14d3181c21c11170477a42542c1addc7072a90b986675a71266ad17abc37f", size = 11473782, upload-time = "2025-12-20T17:12:01.983Z" }, + { url = "https://files.pythonhosted.org/packages/49/41/65c4258137acef3d73cb561ac55512eacd7b30bb4f4a11474cad526bc5db/scikit_image-0.26.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:cde0bbd57e6795eba83cb10f71a677f7239271121dc950bc060482834a668ad1", size = 12686060, upload-time = "2025-12-20T17:12:03.886Z" }, + { url = "https://files.pythonhosted.org/packages/e7/32/76971f8727b87f1420a962406388a50e26667c31756126444baf6668f559/scikit_image-0.26.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:163e9afb5b879562b9aeda0dd45208a35316f26cc7a3aed54fd601604e5cf46f", size = 12422628, upload-time = "2025-12-20T17:12:05.921Z" }, + { url = "https://files.pythonhosted.org/packages/37/0d/996febd39f757c40ee7b01cdb861867327e5c8e5f595a634e8201462d958/scikit_image-0.26.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:724f79fd9b6cb6f4a37864fe09f81f9f5d5b9646b6868109e1b100d1a7019e59", size = 12962369, upload-time = "2025-12-20T17:12:07.912Z" }, + { url = "https://files.pythonhosted.org/packages/48/b4/612d354f946c9600e7dea012723c11d47e8d455384e530f6daaaeb9bf62c/scikit_image-0.26.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3268f13310e6857508bd87202620df996199a016a1d281b309441d227c822394", size = 13272431, upload-time = "2025-12-20T17:12:10.255Z" }, + { url = "https://files.pythonhosted.org/packages/0a/6e/26c00b466e06055a086de2c6e2145fe189ccdc9a1d11ccc7de020f2591ad/scikit_image-0.26.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fac96a1f9b06cd771cbbb3cd96c5332f36d4efd839b1d8b053f79e5887acde62", size = 14016362, upload-time = "2025-12-20T17:12:12.793Z" }, + { url = "https://files.pythonhosted.org/packages/47/88/00a90402e1775634043c2a0af8a3c76ad450866d9fa444efcc43b553ba2d/scikit_image-0.26.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2c1e7bd342f43e7a97e571b3f03ba4c1293ea1a35c3f13f41efdc8a81c1dc8f2", size = 14364151, upload-time = "2025-12-20T17:12:14.909Z" }, + { url = "https://files.pythonhosted.org/packages/da/ca/918d8d306bd43beacff3b835c6d96fac0ae64c0857092f068b88db531a7c/scikit_image-0.26.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b702c3bb115e1dcf4abf5297429b5c90f2189655888cbed14921f3d26f81d3a4", size = 12413484, upload-time = "2025-12-20T17:12:17.046Z" }, + { url = "https://files.pythonhosted.org/packages/dc/cd/4da01329b5a8d47ff7ec3c99a2b02465a8017b186027590dc7425cee0b56/scikit_image-0.26.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0608aa4a9ec39e0843de10d60edb2785a30c1c47819b67866dd223ebd149acaf", size = 11769501, upload-time = "2025-12-20T17:12:19.339Z" }, +] + +[[package]] +name = "scipy" +version = "1.15.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770, upload-time = "2025-05-08T16:04:20.849Z" }, + { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511, upload-time = "2025-05-08T16:04:27.103Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151, upload-time = "2025-05-08T16:04:31.731Z" }, + { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732, upload-time = "2025-05-08T16:04:36.596Z" }, + { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617, upload-time = "2025-05-08T16:04:43.546Z" }, + { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964, upload-time = "2025-05-08T16:04:49.431Z" }, + { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749, upload-time = "2025-05-08T16:04:55.215Z" }, + { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383, upload-time = "2025-05-08T16:05:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201, upload-time = "2025-05-08T16:05:08.166Z" }, + { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255, upload-time = "2025-05-08T16:05:14.596Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035, upload-time = "2025-05-08T16:05:20.152Z" }, + { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499, upload-time = "2025-05-08T16:05:24.494Z" }, + { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602, upload-time = "2025-05-08T16:05:29.313Z" }, + { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415, upload-time = "2025-05-08T16:05:34.699Z" }, + { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622, upload-time = "2025-05-08T16:05:40.762Z" }, + { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796, upload-time = "2025-05-08T16:05:48.119Z" }, + { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684, upload-time = "2025-05-08T16:05:54.22Z" }, + { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504, upload-time = "2025-05-08T16:06:00.437Z" }, + { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735, upload-time = "2025-05-08T16:06:06.471Z" }, + { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284, upload-time = "2025-05-08T16:06:11.686Z" }, + { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958, upload-time = "2025-05-08T16:06:15.97Z" }, + { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454, upload-time = "2025-05-08T16:06:20.394Z" }, + { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199, upload-time = "2025-05-08T16:06:26.159Z" }, + { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455, upload-time = "2025-05-08T16:06:32.778Z" }, + { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140, upload-time = "2025-05-08T16:06:39.249Z" }, + { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549, upload-time = "2025-05-08T16:06:45.729Z" }, + { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184, upload-time = "2025-05-08T16:06:52.623Z" }, + { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256, upload-time = "2025-05-08T16:06:58.696Z" }, + { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540, upload-time = "2025-05-08T16:07:04.209Z" }, + { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115, upload-time = "2025-05-08T16:07:08.998Z" }, + { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884, upload-time = "2025-05-08T16:07:14.091Z" }, + { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018, upload-time = "2025-05-08T16:07:19.427Z" }, + { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716, upload-time = "2025-05-08T16:07:25.712Z" }, + { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342, upload-time = "2025-05-08T16:07:31.468Z" }, + { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869, upload-time = "2025-05-08T16:07:38.002Z" }, + { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851, upload-time = "2025-05-08T16:08:33.671Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011, upload-time = "2025-05-08T16:07:44.039Z" }, + { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407, upload-time = "2025-05-08T16:07:49.891Z" }, + { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030, upload-time = "2025-05-08T16:07:54.121Z" }, + { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709, upload-time = "2025-05-08T16:07:58.506Z" }, + { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045, upload-time = "2025-05-08T16:08:03.929Z" }, + { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062, upload-time = "2025-05-08T16:08:09.558Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132, upload-time = "2025-05-08T16:08:15.34Z" }, + { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503, upload-time = "2025-05-08T16:08:21.513Z" }, + { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097, upload-time = "2025-05-08T16:08:27.627Z" }, +] + +[[package]] +name = "scipy" +version = "1.17.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, + { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, + { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, + { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, + { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, + { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, + { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, + { url = "https://files.pythonhosted.org/packages/35/48/b992b488d6f299dbe3f11a20b24d3dda3d46f1a635ede1c46b5b17a7b163/scipy-1.17.1-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:35c3a56d2ef83efc372eaec584314bd0ef2e2f0d2adb21c55e6ad5b344c0dcb8", size = 31610954, upload-time = "2026-02-23T00:17:49.855Z" }, + { url = "https://files.pythonhosted.org/packages/b2/02/cf107b01494c19dc100f1d0b7ac3cc08666e96ba2d64db7626066cee895e/scipy-1.17.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:fcb310ddb270a06114bb64bbe53c94926b943f5b7f0842194d585c65eb4edd76", size = 28172662, upload-time = "2026-02-23T00:18:01.64Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a9/599c28631bad314d219cf9ffd40e985b24d603fc8a2f4ccc5ae8419a535b/scipy-1.17.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:cc90d2e9c7e5c7f1a482c9875007c095c3194b1cfedca3c2f3291cdc2bc7c086", size = 20344366, upload-time = "2026-02-23T00:18:12.015Z" }, + { url = "https://files.pythonhosted.org/packages/35/f5/906eda513271c8deb5af284e5ef0206d17a96239af79f9fa0aebfe0e36b4/scipy-1.17.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:c80be5ede8f3f8eded4eff73cc99a25c388ce98e555b17d31da05287015ffa5b", size = 22704017, upload-time = "2026-02-23T00:18:21.502Z" }, + { url = "https://files.pythonhosted.org/packages/da/34/16f10e3042d2f1d6b66e0428308ab52224b6a23049cb2f5c1756f713815f/scipy-1.17.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e19ebea31758fac5893a2ac360fedd00116cbb7628e650842a6691ba7ca28a21", size = 32927842, upload-time = "2026-02-23T00:18:35.367Z" }, + { url = "https://files.pythonhosted.org/packages/01/8e/1e35281b8ab6d5d72ebe9911edcdffa3f36b04ed9d51dec6dd140396e220/scipy-1.17.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02ae3b274fde71c5e92ac4d54bc06c42d80e399fec704383dcd99b301df37458", size = 35235890, upload-time = "2026-02-23T00:18:49.188Z" }, + { url = "https://files.pythonhosted.org/packages/c5/5c/9d7f4c88bea6e0d5a4f1bc0506a53a00e9fcb198de372bfe4d3652cef482/scipy-1.17.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8a604bae87c6195d8b1045eddece0514d041604b14f2727bbc2b3020172045eb", size = 35003557, upload-time = "2026-02-23T00:18:54.74Z" }, + { url = "https://files.pythonhosted.org/packages/65/94/7698add8f276dbab7a9de9fb6b0e02fc13ee61d51c7c3f85ac28b65e1239/scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea", size = 37625856, upload-time = "2026-02-23T00:19:00.307Z" }, + { url = "https://files.pythonhosted.org/packages/a2/84/dc08d77fbf3d87d3ee27f6a0c6dcce1de5829a64f2eae85a0ecc1f0daa73/scipy-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:41b71f4a3a4cab9d366cd9065b288efc4d4f3c0b37a91a8e0947fb5bd7f31d87", size = 36549682, upload-time = "2026-02-23T00:19:07.67Z" }, + { url = "https://files.pythonhosted.org/packages/bc/98/fe9ae9ffb3b54b62559f52dedaebe204b408db8109a8c66fdd04869e6424/scipy-1.17.1-cp312-cp312-win_arm64.whl", hash = "sha256:f4115102802df98b2b0db3cce5cb9b92572633a1197c77b7553e5203f284a5b3", size = 24547340, upload-time = "2026-02-23T00:19:12.024Z" }, + { url = "https://files.pythonhosted.org/packages/76/27/07ee1b57b65e92645f219b37148a7e7928b82e2b5dbeccecb4dff7c64f0b/scipy-1.17.1-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:5e3c5c011904115f88a39308379c17f91546f77c1667cea98739fe0fccea804c", size = 31590199, upload-time = "2026-02-23T00:19:17.192Z" }, + { url = "https://files.pythonhosted.org/packages/ec/ae/db19f8ab842e9b724bf5dbb7db29302a91f1e55bc4d04b1025d6d605a2c5/scipy-1.17.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:6fac755ca3d2c3edcb22f479fceaa241704111414831ddd3bc6056e18516892f", size = 28154001, upload-time = "2026-02-23T00:19:22.241Z" }, + { url = "https://files.pythonhosted.org/packages/5b/58/3ce96251560107b381cbd6e8413c483bbb1228a6b919fa8652b0d4090e7f/scipy-1.17.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:7ff200bf9d24f2e4d5dc6ee8c3ac64d739d3a89e2326ba68aaf6c4a2b838fd7d", size = 20325719, upload-time = "2026-02-23T00:19:26.329Z" }, + { url = "https://files.pythonhosted.org/packages/b2/83/15087d945e0e4d48ce2377498abf5ad171ae013232ae31d06f336e64c999/scipy-1.17.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4b400bdc6f79fa02a4d86640310dde87a21fba0c979efff5248908c6f15fad1b", size = 22683595, upload-time = "2026-02-23T00:19:30.304Z" }, + { url = "https://files.pythonhosted.org/packages/b4/e0/e58fbde4a1a594c8be8114eb4aac1a55bcd6587047efc18a61eb1f5c0d30/scipy-1.17.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2b64ca7d4aee0102a97f3ba22124052b4bd2152522355073580bf4845e2550b6", size = 32896429, upload-time = "2026-02-23T00:19:35.536Z" }, + { url = "https://files.pythonhosted.org/packages/f5/5f/f17563f28ff03c7b6799c50d01d5d856a1d55f2676f537ca8d28c7f627cd/scipy-1.17.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:581b2264fc0aa555f3f435a5944da7504ea3a065d7029ad60e7c3d1ae09c5464", size = 35203952, upload-time = "2026-02-23T00:19:42.259Z" }, + { url = "https://files.pythonhosted.org/packages/8d/a5/9afd17de24f657fdfe4df9a3f1ea049b39aef7c06000c13db1530d81ccca/scipy-1.17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:beeda3d4ae615106d7094f7e7cef6218392e4465cc95d25f900bebabfded0950", size = 34979063, upload-time = "2026-02-23T00:19:47.547Z" }, + { url = "https://files.pythonhosted.org/packages/8b/13/88b1d2384b424bf7c924f2038c1c409f8d88bb2a8d49d097861dd64a57b2/scipy-1.17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6609bc224e9568f65064cfa72edc0f24ee6655b47575954ec6339534b2798369", size = 37598449, upload-time = "2026-02-23T00:19:53.238Z" }, + { url = "https://files.pythonhosted.org/packages/35/e5/d6d0e51fc888f692a35134336866341c08655d92614f492c6860dc45bb2c/scipy-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:37425bc9175607b0268f493d79a292c39f9d001a357bebb6b88fdfaff13f6448", size = 36510943, upload-time = "2026-02-23T00:20:50.89Z" }, + { url = "https://files.pythonhosted.org/packages/2a/fd/3be73c564e2a01e690e19cc618811540ba5354c67c8680dce3281123fb79/scipy-1.17.1-cp313-cp313-win_arm64.whl", hash = "sha256:5cf36e801231b6a2059bf354720274b7558746f3b1a4efb43fcf557ccd484a87", size = 24545621, upload-time = "2026-02-23T00:20:55.871Z" }, + { url = "https://files.pythonhosted.org/packages/6f/6b/17787db8b8114933a66f9dcc479a8272e4b4da75fe03b0c282f7b0ade8cd/scipy-1.17.1-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:d59c30000a16d8edc7e64152e30220bfbd724c9bbb08368c054e24c651314f0a", size = 31936708, upload-time = "2026-02-23T00:19:58.694Z" }, + { url = "https://files.pythonhosted.org/packages/38/2e/524405c2b6392765ab1e2b722a41d5da33dc5c7b7278184a8ad29b6cb206/scipy-1.17.1-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:010f4333c96c9bb1a4516269e33cb5917b08ef2166d5556ca2fd9f082a9e6ea0", size = 28570135, upload-time = "2026-02-23T00:20:03.934Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c3/5bd7199f4ea8556c0c8e39f04ccb014ac37d1468e6cfa6a95c6b3562b76e/scipy-1.17.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:2ceb2d3e01c5f1d83c4189737a42d9cb2fc38a6eeed225e7515eef71ad301dce", size = 20741977, upload-time = "2026-02-23T00:20:07.935Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b8/8ccd9b766ad14c78386599708eb745f6b44f08400a5fd0ade7cf89b6fc93/scipy-1.17.1-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:844e165636711ef41f80b4103ed234181646b98a53c8f05da12ca5ca289134f6", size = 23029601, upload-time = "2026-02-23T00:20:12.161Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a0/3cb6f4d2fb3e17428ad2880333cac878909ad1a89f678527b5328b93c1d4/scipy-1.17.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:158dd96d2207e21c966063e1635b1063cd7787b627b6f07305315dd73d9c679e", size = 33019667, upload-time = "2026-02-23T00:20:17.208Z" }, + { url = "https://files.pythonhosted.org/packages/f3/c3/2d834a5ac7bf3a0c806ad1508efc02dda3c8c61472a56132d7894c312dea/scipy-1.17.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74cbb80d93260fe2ffa334efa24cb8f2f0f622a9b9febf8b483c0b865bfb3475", size = 35264159, upload-time = "2026-02-23T00:20:23.087Z" }, + { url = "https://files.pythonhosted.org/packages/4d/77/d3ed4becfdbd217c52062fafe35a72388d1bd82c2d0ba5ca19d6fcc93e11/scipy-1.17.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:dbc12c9f3d185f5c737d801da555fb74b3dcfa1a50b66a1a93e09190f41fab50", size = 35102771, upload-time = "2026-02-23T00:20:28.636Z" }, + { url = "https://files.pythonhosted.org/packages/bd/12/d19da97efde68ca1ee5538bb261d5d2c062f0c055575128f11a2730e3ac1/scipy-1.17.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:94055a11dfebe37c656e70317e1996dc197e1a15bbcc351bcdd4610e128fe1ca", size = 37665910, upload-time = "2026-02-23T00:20:34.743Z" }, + { url = "https://files.pythonhosted.org/packages/06/1c/1172a88d507a4baaf72c5a09bb6c018fe2ae0ab622e5830b703a46cc9e44/scipy-1.17.1-cp313-cp313t-win_amd64.whl", hash = "sha256:e30bdeaa5deed6bc27b4cc490823cd0347d7dae09119b8803ae576ea0ce52e4c", size = 36562980, upload-time = "2026-02-23T00:20:40.575Z" }, + { url = "https://files.pythonhosted.org/packages/70/b0/eb757336e5a76dfa7911f63252e3b7d1de00935d7705cf772db5b45ec238/scipy-1.17.1-cp313-cp313t-win_arm64.whl", hash = "sha256:a720477885a9d2411f94a93d16f9d89bad0f28ca23c3f8daa521e2dcc3f44d49", size = 24856543, upload-time = "2026-02-23T00:20:45.313Z" }, + { url = "https://files.pythonhosted.org/packages/cf/83/333afb452af6f0fd70414dc04f898647ee1423979ce02efa75c3b0f2c28e/scipy-1.17.1-cp314-cp314-macosx_10_14_x86_64.whl", hash = "sha256:a48a72c77a310327f6a3a920092fa2b8fd03d7deaa60f093038f22d98e096717", size = 31584510, upload-time = "2026-02-23T00:21:01.015Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a6/d05a85fd51daeb2e4ea71d102f15b34fedca8e931af02594193ae4fd25f7/scipy-1.17.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:45abad819184f07240d8a696117a7aacd39787af9e0b719d00285549ed19a1e9", size = 28170131, upload-time = "2026-02-23T00:21:05.888Z" }, + { url = "https://files.pythonhosted.org/packages/db/7b/8624a203326675d7746a254083a187398090a179335b2e4a20e2ddc46e83/scipy-1.17.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:3fd1fcdab3ea951b610dc4cef356d416d5802991e7e32b5254828d342f7b7e0b", size = 20342032, upload-time = "2026-02-23T00:21:09.904Z" }, + { url = "https://files.pythonhosted.org/packages/c9/35/2c342897c00775d688d8ff3987aced3426858fd89d5a0e26e020b660b301/scipy-1.17.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:7bdf2da170b67fdf10bca777614b1c7d96ae3ca5794fd9587dce41eb2966e866", size = 22678766, upload-time = "2026-02-23T00:21:14.313Z" }, + { url = "https://files.pythonhosted.org/packages/ef/f2/7cdb8eb308a1a6ae1e19f945913c82c23c0c442a462a46480ce487fdc0ac/scipy-1.17.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:adb2642e060a6549c343603a3851ba76ef0b74cc8c079a9a58121c7ec9fe2350", size = 32957007, upload-time = "2026-02-23T00:21:19.663Z" }, + { url = "https://files.pythonhosted.org/packages/0b/2e/7eea398450457ecb54e18e9d10110993fa65561c4f3add5e8eccd2b9cd41/scipy-1.17.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eee2cfda04c00a857206a4330f0c5e3e56535494e30ca445eb19ec624ae75118", size = 35221333, upload-time = "2026-02-23T00:21:25.278Z" }, + { url = "https://files.pythonhosted.org/packages/d9/77/5b8509d03b77f093a0d52e606d3c4f79e8b06d1d38c441dacb1e26cacf46/scipy-1.17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d2650c1fb97e184d12d8ba010493ee7b322864f7d3d00d3f9bb97d9c21de4068", size = 35042066, upload-time = "2026-02-23T00:21:31.358Z" }, + { url = "https://files.pythonhosted.org/packages/f9/df/18f80fb99df40b4070328d5ae5c596f2f00fffb50167e31439e932f29e7d/scipy-1.17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:08b900519463543aa604a06bec02461558a6e1cef8fdbb8098f77a48a83c8118", size = 37612763, upload-time = "2026-02-23T00:21:37.247Z" }, + { url = "https://files.pythonhosted.org/packages/4b/39/f0e8ea762a764a9dc52aa7dabcfad51a354819de1f0d4652b6a1122424d6/scipy-1.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:3877ac408e14da24a6196de0ddcace62092bfc12a83823e92e49e40747e52c19", size = 37290984, upload-time = "2026-02-23T00:22:35.023Z" }, + { url = "https://files.pythonhosted.org/packages/7c/56/fe201e3b0f93d1a8bcf75d3379affd228a63d7e2d80ab45467a74b494947/scipy-1.17.1-cp314-cp314-win_arm64.whl", hash = "sha256:f8885db0bc2bffa59d5c1b72fad7a6a92d3e80e7257f967dd81abb553a90d293", size = 25192877, upload-time = "2026-02-23T00:22:39.798Z" }, + { url = "https://files.pythonhosted.org/packages/96/ad/f8c414e121f82e02d76f310f16db9899c4fcde36710329502a6b2a3c0392/scipy-1.17.1-cp314-cp314t-macosx_10_14_x86_64.whl", hash = "sha256:1cc682cea2ae55524432f3cdff9e9a3be743d52a7443d0cba9017c23c87ae2f6", size = 31949750, upload-time = "2026-02-23T00:21:42.289Z" }, + { url = "https://files.pythonhosted.org/packages/7c/b0/c741e8865d61b67c81e255f4f0a832846c064e426636cd7de84e74d209be/scipy-1.17.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:2040ad4d1795a0ae89bfc7e8429677f365d45aa9fd5e4587cf1ea737f927b4a1", size = 28585858, upload-time = "2026-02-23T00:21:47.706Z" }, + { url = "https://files.pythonhosted.org/packages/ed/1b/3985219c6177866628fa7c2595bfd23f193ceebbe472c98a08824b9466ff/scipy-1.17.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:131f5aaea57602008f9822e2115029b55d4b5f7c070287699fe45c661d051e39", size = 20757723, upload-time = "2026-02-23T00:21:52.039Z" }, + { url = "https://files.pythonhosted.org/packages/c0/19/2a04aa25050d656d6f7b9e7b685cc83d6957fb101665bfd9369ca6534563/scipy-1.17.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:9cdc1a2fcfd5c52cfb3045feb399f7b3ce822abdde3a193a6b9a60b3cb5854ca", size = 23043098, upload-time = "2026-02-23T00:21:56.185Z" }, + { url = "https://files.pythonhosted.org/packages/86/f1/3383beb9b5d0dbddd030335bf8a8b32d4317185efe495374f134d8be6cce/scipy-1.17.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e3dcd57ab780c741fde8dc68619de988b966db759a3c3152e8e9142c26295ad", size = 33030397, upload-time = "2026-02-23T00:22:01.404Z" }, + { url = "https://files.pythonhosted.org/packages/41/68/8f21e8a65a5a03f25a79165ec9d2b28c00e66dc80546cf5eb803aeeff35b/scipy-1.17.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9956e4d4f4a301ebf6cde39850333a6b6110799d470dbbb1e25326ac447f52a", size = 35281163, upload-time = "2026-02-23T00:22:07.024Z" }, + { url = "https://files.pythonhosted.org/packages/84/8d/c8a5e19479554007a5632ed7529e665c315ae7492b4f946b0deb39870e39/scipy-1.17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:a4328d245944d09fd639771de275701ccadf5f781ba0ff092ad141e017eccda4", size = 35116291, upload-time = "2026-02-23T00:22:12.585Z" }, + { url = "https://files.pythonhosted.org/packages/52/52/e57eceff0e342a1f50e274264ed47497b59e6a4e3118808ee58ddda7b74a/scipy-1.17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a77cbd07b940d326d39a1d1b37817e2ee4d79cb30e7338f3d0cddffae70fcaa2", size = 37682317, upload-time = "2026-02-23T00:22:18.513Z" }, + { url = "https://files.pythonhosted.org/packages/11/2f/b29eafe4a3fbc3d6de9662b36e028d5f039e72d345e05c250e121a230dd4/scipy-1.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:eb092099205ef62cd1782b006658db09e2fed75bffcae7cc0d44052d8aa0f484", size = 37345327, upload-time = "2026-02-23T00:22:24.442Z" }, + { url = "https://files.pythonhosted.org/packages/07/39/338d9219c4e87f3e708f18857ecd24d22a0c3094752393319553096b98af/scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21", size = 25489165, upload-time = "2026-02-23T00:22:29.563Z" }, +] + +[[package]] +name = "scipy" +version = "1.18.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7e/74/66de6258867beb2ef08f35f9f2ac017a52cacd5081714d239ff1a442d458/scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307", size = 30781235, upload-time = "2026-08-21T23:28:50.599Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/f7/240c110c08693826b4513a52f5717d62ec7c7af72f2920821247c03b17b3/scipy-1.18.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:457fd7a2a8edeb044ab6ffbc0aa03ff6cd18491356e5e0c834d76ce621b916d1", size = 31111061, upload-time = "2026-08-21T23:23:44.522Z" }, + { url = "https://files.pythonhosted.org/packages/05/4a/78c6285577c375e7cf27277ea8ee6961224327f1e1a0c44af5f17f23635c/scipy-1.18.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:e708533e8b2ae2497d65346538a7dcc92814410b25b81432eac66de0f2af8265", size = 28733332, upload-time = "2026-08-21T23:23:50.015Z" }, + { url = "https://files.pythonhosted.org/packages/a5/f6/a5b82f8abbe14d134691b8b903696f701d25a081353a29dc655c364d9e62/scipy-1.18.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7bbf207c4453ce1ad2e00b17313852b33310b83090c2311bdaf97f93c0380d12", size = 20475078, upload-time = "2026-08-21T23:23:54.138Z" }, + { url = "https://files.pythonhosted.org/packages/23/22/0858a0bbd6b3e825ceb8cd9baf9eaf3b2f2b1d77727eb6be40500bcdc92f/scipy-1.18.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:78c0665edead396b1abb4897c41a5c1d9bf090c8a637a4c20a61678e0a264e66", size = 23108904, upload-time = "2026-08-21T23:23:57.824Z" }, + { url = "https://files.pythonhosted.org/packages/75/9a/2e71719f31eaefe0e3a1706c4a1ded94e664bfd95ffca2b219a671faee01/scipy-1.18.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c085faa2cfa879c5141df483f836f4d691045a078224a670fa570fa01612d89", size = 34025113, upload-time = "2026-08-21T23:24:02.209Z" }, + { url = "https://files.pythonhosted.org/packages/df/64/ff35eb9e54894cf471ff4716abd3c81eb0a0626869217ce3e6ba4ccf17d7/scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f55fa87b6c612ecd6b058f167c53231b1d14e412efe361d3d6e38b3631c73218", size = 35344199, upload-time = "2026-08-21T23:24:07.844Z" }, + { url = "https://files.pythonhosted.org/packages/d3/af/c5538be1792f7034c12c7db6ee67cace58253c7b87b122d68253eaf5de89/scipy-1.18.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c35d74ce0e193ff740c2f2be2ac913ddc232fe6c1ff40b26cfecb9c670c63314", size = 35639587, upload-time = "2026-08-21T23:24:13.05Z" }, + { url = "https://files.pythonhosted.org/packages/91/4c/075e4f66471bac101141ac739e9e135549be1bae584571bd03a530c056e1/scipy-1.18.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d2924a03db38dc2e848bca2fe9f077dafb891480b91a00a0963a8cf86dfc31c1", size = 37480330, upload-time = "2026-08-21T23:24:19.608Z" }, + { url = "https://files.pythonhosted.org/packages/39/e7/979fd14e75008623df31ba70d6bb144700f68feadcea042021c06a05bf82/scipy-1.18.1-cp312-cp312-win_amd64.whl", hash = "sha256:5e4d44984abc0020154ea81b247adeddcc3ac5527b975ff798bd1ba0adc513c2", size = 36658278, upload-time = "2026-08-21T23:24:25.463Z" }, + { url = "https://files.pythonhosted.org/packages/c7/0b/e1525354ff9d7d5feb6d1b31af6d14072e5c91e9607b421fa1ec889660b3/scipy-1.18.1-cp312-cp312-win_arm64.whl", hash = "sha256:d65d448389b8436493abcf629cc94ad0cf32aecaf06e1acca1de53cc795f2f12", size = 24400588, upload-time = "2026-08-21T23:24:30.579Z" }, + { url = "https://files.pythonhosted.org/packages/b6/55/4540ee0f9c42a9ad7109d0d1a8cc70de54c3572b01c6693a2b1c70e90ceb/scipy-1.18.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:3ab3523da44749156e1f68b464dc56af11ae4cbc5c739a49d05f32b982eca9f3", size = 31089958, upload-time = "2026-08-21T23:24:35.8Z" }, + { url = "https://files.pythonhosted.org/packages/2a/f5/769f36d14922b8071a43e95d24d18b6bdafad10d7f5cf647867e1ac052bc/scipy-1.18.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e6fb6a55cc0ba97b59a1f288fb86dc6fce8bdfc0fffcbfd015e3a954bf2a2d93", size = 28715106, upload-time = "2026-08-21T23:24:40.775Z" }, + { url = "https://files.pythonhosted.org/packages/9a/d7/21d890274f75ea37a8209d5519e72da3da90302e3b9fb8397a0918386a62/scipy-1.18.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:ea324d9dd34c38bfb9bec8ca4d1b407db97dbb74029f566b8e322b1b6fe56fe6", size = 20456846, upload-time = "2026-08-21T23:24:45.066Z" }, + { url = "https://files.pythonhosted.org/packages/ec/01/798430ecea2e78ec7c02663d5f71c007bb6abeca931080debd40d7fa55ea/scipy-1.18.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b00eb8fb802090aa903f4ea1c7f5a584779f967361e68b7e98e531cc2d7174", size = 23087986, upload-time = "2026-08-21T23:24:49.539Z" }, + { url = "https://files.pythonhosted.org/packages/e6/5f/4634e9d35c68496e4e34cb6946eafab044458e6cedab42b40b6588e475b6/scipy-1.18.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d416b16cccfd70fbf62400e84d0bb2f4e6af519a45557f1692c749b37f14b315", size = 33998146, upload-time = "2026-08-21T23:24:54.714Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/6450ed9243315322bbc19ac57b9b70d66a20bf1d38d124c96bc4bf6af9ea/scipy-1.18.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fdaf5ea890a6183d0565f51a61799d67081bd5b1cf03c5f4b3fd3732108625c9", size = 35312578, upload-time = "2026-08-21T23:25:00.44Z" }, + { url = "https://files.pythonhosted.org/packages/00/bd/bf5a4be6a3525676499f6dff307991739ff6fdcad1481b1aeb6745339f58/scipy-1.18.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c825cef2f49e46753726a7181a8e199804a912b29519ada542c6ebc654951899", size = 35612621, upload-time = "2026-08-21T23:25:06.144Z" }, + { url = "https://files.pythonhosted.org/packages/bd/4e/3c45c33e00a77996c4b1cb707929f833ba7b1d522ee29f882512c330676d/scipy-1.18.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3b417bf8c2c7c16e8f58ad91db17783ec911ac16e7b50eb6eab6e809b4f5b07", size = 37457323, upload-time = "2026-08-21T23:25:12.483Z" }, + { url = "https://files.pythonhosted.org/packages/93/0e/e0348fbc0dbab65c114cf78957e7dfeb49f8e8b556b4d930cc12ff195e18/scipy-1.18.1-cp313-cp313-win_amd64.whl", hash = "sha256:559ed65f60c1af5a03f3912605a1b5114f522c7c32fb23c3376ae8f03219fe28", size = 36622841, upload-time = "2026-08-21T23:25:18.722Z" }, + { url = "https://files.pythonhosted.org/packages/50/a8/6a77f5f267c555108f0a864b6db714363dab567a8266422a79a385f9232b/scipy-1.18.1-cp313-cp313-win_arm64.whl", hash = "sha256:cd479fc04dd9401e3b4f49e76518768ef99c4f517a98c284eb091fd725719adf", size = 24399315, upload-time = "2026-08-21T23:25:23.458Z" }, + { url = "https://files.pythonhosted.org/packages/06/d5/d8eb4e280ddb56a4ab2c6f02ee49b56b23f6e977cf0802fd6d68dbef14f5/scipy-1.18.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:83de5453a7799afc9048b4616bd085cef126e36412f0ea2f6370c36a2a3a51e7", size = 31090936, upload-time = "2026-08-21T23:25:28.686Z" }, + { url = "https://files.pythonhosted.org/packages/2a/49/59ea385dc3a62ff498ddf3cfff7c2b41b0f9f9d3c4122b3f1dcb6d6327fe/scipy-1.18.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:9554bcc6d715ee87a633a3cc8e7703c6628b100dd29cb8a2efc4c0533c7ff729", size = 28725221, upload-time = "2026-08-21T23:25:33.244Z" }, + { url = "https://files.pythonhosted.org/packages/70/e8/6b0c288c50942d78193696c9f15f9a0874f5178aa0ddf40f83d9924b3e8d/scipy-1.18.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:011413b7426b75012840e35649e00fe0a2c3bae89fed433876e3a99251572efc", size = 20466839, upload-time = "2026-08-21T23:25:37.516Z" }, + { url = "https://files.pythonhosted.org/packages/4b/e0/54fd3793c729e3b936782f181b59cbb1205bf250ab605a16cb1ba61cdd5e/scipy-1.18.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:88f0e784020649f88ea48c9f5ddfa403bf9205820667c0914740b392035afb82", size = 23089121, upload-time = "2026-08-21T23:25:42.019Z" }, + { url = "https://files.pythonhosted.org/packages/0b/56/030af62bea3cf878e0028515dff78c123b01633606a879b63f42d2db99cc/scipy-1.18.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2d3ab0e8c69a17dd3559eab8cbb88f258e285c94d572c2719033f90f83290c89", size = 34053851, upload-time = "2026-08-21T23:25:47.998Z" }, + { url = "https://files.pythonhosted.org/packages/6b/89/2a844506d49651e9aa1af6ef95b6bd8031cb1d5a4375edec6155037e04cf/scipy-1.18.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ac0333bdf38309aa3dcbe7e3fa7ea29e7a2c37c6ea306a757b700ded8e4596ad", size = 35329183, upload-time = "2026-08-21T23:25:53.522Z" }, + { url = "https://files.pythonhosted.org/packages/eb/56/c7370c3640e92ac9613cbf26cb3f729f9b12ddf1727b55b94b53b24d6f48/scipy-1.18.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:911de823097db8b63f034299d12662db93344e6ffa0b881cbb57748974b70168", size = 35672551, upload-time = "2026-08-21T23:25:59.387Z" }, + { url = "https://files.pythonhosted.org/packages/24/16/ec8536f351421f8bf60a1120930638f83790f4710b8230446aca3d6159d4/scipy-1.18.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:95298364e251be3e60249facbeeca03631d3bb7584f85879516ec55ac717b81f", size = 37469416, upload-time = "2026-08-21T23:26:05.432Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/d73da0d28f16c45bb9b0a5691b91610b0275c5ef0eb5e43c87cf2dc1bf31/scipy-1.18.1-cp314-cp314-win_amd64.whl", hash = "sha256:78a0d7c918e74a232394117160e7e3db503377572a45bcef8826e4ab8a35feba", size = 37362755, upload-time = "2026-08-21T23:26:11.366Z" }, + { url = "https://files.pythonhosted.org/packages/89/25/e996e4dc74e10e227b1e14db5eaf6608bb6dd33884a64851c38f18dd4249/scipy-1.18.1-cp314-cp314-win_arm64.whl", hash = "sha256:cbf38d043c1aa4ab306e1ada6ab6eddacc3322a20b7af1b30bc93254b366fe09", size = 25036090, upload-time = "2026-08-21T23:26:15.887Z" }, + { url = "https://files.pythonhosted.org/packages/fa/c9/c00213f92309d753b48903e6a451b87eb52ff5b7a16e789d1568bbf221c4/scipy-1.18.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0fcb3c93519f27bb4f0c4b0f7802cdcaca7fcf93267b75edda2e9f4e8a55cbd7", size = 31485550, upload-time = "2026-08-21T23:26:20.776Z" }, + { url = "https://files.pythonhosted.org/packages/74/b2/e3067c487982d4eeab2938928529410370c06fea84a4d3f4925e7d96647d/scipy-1.18.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ddef79fb382df40104a19bb7151b3b23e57c1778fcf857c71ceecd9bd264513f", size = 29174642, upload-time = "2026-08-21T23:26:25.395Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ab/374c9fe2d1ec014e576c781a4b5d8e1ba340e8f6b4638c16f711d2b194f0/scipy-1.18.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:0e82073ecc7acc6436fac4b31674109c7e1d3e596789767eda01258a8c9e8123", size = 20916357, upload-time = "2026-08-21T23:26:30.112Z" }, + { url = "https://files.pythonhosted.org/packages/90/38/223915c88a17317cafbf8ca2a42b11c265a9fb1e804aa665544132b5fe8a/scipy-1.18.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:8bcf3c1ba5d6456e2effd30fcbd3459b044d683fcdac79a2e6830f0bdf7de487", size = 23482611, upload-time = "2026-08-21T23:26:34.846Z" }, + { url = "https://files.pythonhosted.org/packages/c4/d1/db0948da8ca57a80b36520ef0a768b967d99f3af65f4b6f1bf6362ad4dd4/scipy-1.18.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cfbf154f2ba187f2ed6cce2639efff7d105f1140573642c0161615b6d91d6a87", size = 34143202, upload-time = "2026-08-21T23:26:40.4Z" }, + { url = "https://files.pythonhosted.org/packages/87/53/39d046cc7574ed6acacb6bd5723e220107ece80bff12faaf3efc4ddeede4/scipy-1.18.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1d33a7836f7ddc1993427966a0823468ec41bcbdb1a9f9942d1d7e57f803ba3", size = 35380876, upload-time = "2026-08-21T23:26:46.1Z" }, + { url = "https://files.pythonhosted.org/packages/f9/da/32e0e799d875a85ca57d9bde6c78148afcc0e38276df683d95854eadc8c3/scipy-1.18.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7f4b8bc363b6d65ee2152bec57568e3c52639bb34c46057b09857a307ed5e21d", size = 35770885, upload-time = "2026-08-21T23:26:51.533Z" }, + { url = "https://files.pythonhosted.org/packages/88/2e/f97a666d362fee68b18f41c9c30ed502ca5c98b549749bfcb52a8b74d1eb/scipy-1.18.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:11c423f1049c5755ad4409af52a9ada1cff96fe9b50795d4af3619f292901239", size = 37525424, upload-time = "2026-08-21T23:26:56.751Z" }, + { url = "https://files.pythonhosted.org/packages/ca/d5/a9e765a84654ebba8479a1fd1b059ced1af72b168a3b2a3a46540ea38d20/scipy-1.18.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c24acac1e18912761c4700239bbc1fd32f615af690f1584d49b35859be51324d", size = 37416961, upload-time = "2026-08-21T23:27:01.546Z" }, + { url = "https://files.pythonhosted.org/packages/ee/16/e79e0d1c63ef698879d85439d37e9fb434e3b804e506a6991038d086ebd9/scipy-1.18.1-cp314-cp314t-win_arm64.whl", hash = "sha256:9f2897bf7737392ad0d5213ea7b6add72a4edf5679b3153106aeb88b6507b3b9", size = 25331848, upload-time = "2026-08-21T23:27:05.884Z" }, + { url = "https://files.pythonhosted.org/packages/be/4f/1bd37c883b67163e2ca1f60977a399500e6879c15defecac62831c8d078d/scipy-1.18.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:eb0dfcf4e28a99c12c999744a2ff67c9b06200e20401c7c88186e33552a46331", size = 31091484, upload-time = "2026-08-21T23:27:11.051Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c5/ba929d7feb9b2332f96827c12e0e924b61973b59b4dea383b603372c65ce/scipy-1.18.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:30f464bee641fa8e282577c7dce027308403213c6ca8270bba73285c91024bc5", size = 28725057, upload-time = "2026-08-21T23:27:15.9Z" }, + { url = "https://files.pythonhosted.org/packages/a4/19/68f1c50f609d955d230e66d25d02bd3e1e167ec540232135354fb9a4b9e3/scipy-1.18.1-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:1bca3b943fc2567ea49cd02c99abde49da4d5178ec46f624bd8255cda8755beb", size = 20466734, upload-time = "2026-08-21T23:27:20.044Z" }, + { url = "https://files.pythonhosted.org/packages/ef/6d/319fa29b73d1802fa80b32a6eaf3f5be456ef81526da2716a9493bcb5501/scipy-1.18.1-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:c9d18a33309122074ea483dd92dd444189166b8b2ec429fe9ed5ac73c7a0aa23", size = 23089664, upload-time = "2026-08-21T23:27:24.345Z" }, + { url = "https://files.pythonhosted.org/packages/b7/db/30992f9b51a63de671daf3888ffd18378b6cb9ec9f2c972264238ffa7fd6/scipy-1.18.1-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82f201b4c878551d48558337aab270d3c6cca5507b8737c8d8a608d234cccde0", size = 34054035, upload-time = "2026-08-21T23:27:29.409Z" }, + { url = "https://files.pythonhosted.org/packages/91/d4/bf3e735dc0b9d5a8ff45079d2540e17d3aff7a2f0048dd8f552ffd031d2b/scipy-1.18.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ac49ea97594532dd44b7136094d35f5440fa06e6d9c6384a74c01764df388c5", size = 35333883, upload-time = "2026-08-21T23:27:34.293Z" }, + { url = "https://files.pythonhosted.org/packages/19/93/12d78ce9f871fe945fca588d32644e6e63f553c2a35c564d73f3b22a3313/scipy-1.18.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:ceb30a00ce7c92d459819443d29ca486d882b83fb6738bdcbb2a1cce94ac5daa", size = 35673124, upload-time = "2026-08-21T23:27:39.059Z" }, + { url = "https://files.pythonhosted.org/packages/70/cd/886219313a1012a48e6ae0ec4f302c837151beb92e1ff0d709ef8fdfc488/scipy-1.18.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f29633129f9fa7e88a3f0fca835de2d030bfc9643f7799e1a0c46cee24d38fc7", size = 37470753, upload-time = "2026-08-21T23:27:44.435Z" }, + { url = "https://files.pythonhosted.org/packages/17/6c/a776888ce618bee54fbde26172f0f46ac1da70d27b63861797fe78e1904b/scipy-1.18.1-cp315-cp315-win_amd64.whl", hash = "sha256:92c14f5bdbfb6216315ce33e78080474082de8b3830122ba97809bfbe65f75c0", size = 37361483, upload-time = "2026-08-21T23:27:49.334Z" }, + { url = "https://files.pythonhosted.org/packages/ab/09/97b651691322ebee97999b017ffc18a15a0b815103844c97e8da9d469731/scipy-1.18.1-cp315-cp315-win_arm64.whl", hash = "sha256:e402cf31eb68f453dbb2d36fc6d722b33f24a55d68b2ae1d92fa6305ca71c298", size = 25035883, upload-time = "2026-08-21T23:27:53.596Z" }, + { url = "https://files.pythonhosted.org/packages/ed/0f/9ec20467bbabd0d44e2a77d0fd3d124f884b4d67df92af82c91d2d6a486f/scipy-1.18.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2a0b02f9fc46f8520330c23d45e6560db7e3a0d927232139427637f98943e11d", size = 31474926, upload-time = "2026-08-21T23:27:57.993Z" }, + { url = "https://files.pythonhosted.org/packages/8a/58/dcb79161e56efbedc50079fcd2f5fe427a0ebb53022eb476aa73c015ad8f/scipy-1.18.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:1d73131e358976663dd969e1fb4ed1404b815cd977eaaedc3b3a133ba2d81c35", size = 29164940, upload-time = "2026-08-21T23:28:03.062Z" }, + { url = "https://files.pythonhosted.org/packages/71/d3/1eeea80c817fcb8ef7bd4a05a58824977a0e57a375cfc3d7ea7c911c01ad/scipy-1.18.1-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:bff0b729edd992766136b34e39cc76bc2fad905aa58897ee72a9cd000a6d8443", size = 20906742, upload-time = "2026-08-21T23:28:07.642Z" }, + { url = "https://files.pythonhosted.org/packages/54/46/e59350428b6099301a20128108c995e2eb175a43f383af9a346e38824f9b/scipy-1.18.1-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:10ac20c69d880f77f375db44c22e3e6a644f9fefa291d4cd2fb9790a89fc99fd", size = 23472183, upload-time = "2026-08-21T23:28:12.109Z" }, + { url = "https://files.pythonhosted.org/packages/89/31/cc91623fa98f0621766a0f0aaaadb2c66de74a7ea7e3837164f6e4354260/scipy-1.18.1-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:33a834464fdabc0f26a45508df31b3cc5d028e04dbf6c5ed398541418e0a12fe", size = 34130796, upload-time = "2026-08-21T23:28:17.906Z" }, + { url = "https://files.pythonhosted.org/packages/fc/3e/8572ef536957ddb8aa81bb4090d9e25f257e3b4e05d97deb54319deb8a3a/scipy-1.18.1-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:49023963c193dacee096301452f223ee24d86ec5807f8df93c0f7221d119e305", size = 35374253, upload-time = "2026-08-21T23:28:23.732Z" }, + { url = "https://files.pythonhosted.org/packages/b5/c6/59fdeffb4f1435299f93d9dc8140b43ad2916e6cfc944be6c3041fcec86d/scipy-1.18.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:d84a09d0dad90ba6525d8ac1c2334b33e64bf3ccfe9e841f02feb867a22681e4", size = 35758543, upload-time = "2026-08-21T23:28:29.431Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d9/135be205d9de8783193aff9cc3bf483a03a38e4b29432c954e8cb66ac14e/scipy-1.18.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:179ce34a8d0fe273d8883ba59e17e052247d08973dfcb743ca52bb1cce2d60b0", size = 37521946, upload-time = "2026-08-21T23:28:35.245Z" }, + { url = "https://files.pythonhosted.org/packages/5c/a2/5b7d5270621ab7cfa3f7766067bf95dc360b5efb6394694e8143b4156e2b/scipy-1.18.1-cp315-cp315t-win_amd64.whl", hash = "sha256:5632e3ae3d09197c446310cd5187de63e28448ce22f0f67b2b93d97503c0c230", size = 37408295, upload-time = "2026-08-21T23:28:40.724Z" }, + { url = "https://files.pythonhosted.org/packages/63/ad/741c19fcb66755ff953daf9243af8480e4bf3d7fbe57583c178c7d2b6b51/scipy-1.18.1-cp315-cp315t-win_arm64.whl", hash = "sha256:eda632a7981f69730d6281f451db9c1c370993a2c0d7ddb43e2a809a2862b83a", size = 25319710, upload-time = "2026-08-21T23:28:45.713Z" }, +] + +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "slap2-utils" +version = "0.6.1" +source = { git = "https://github.com/m-xie/SLAP2_Utils.git?rev=multidatafiles#265316401e496afc7f6f078781f215abb89ae7b9" } +dependencies = [ + { name = "dask" }, + { name = "h5py" }, + { name = "matplotlib", version = "3.10.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "matplotlib", version = "3.11.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "pyneurotrace" }, + { name = "pyqt6" }, + { name = "scikit-image", version = "0.25.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scikit-image", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "vispy" }, + { name = "zarr", version = "2.18.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "zarr", version = "3.1.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "zarr", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] + +[[package]] +name = "snowballstemmer" +version = "3.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/f5/04e7d0d3e5a8c4cb340e79379b84660ef9e68d080d786e56bbfe8a4a9eac/snowballstemmer-3.2.1.tar.gz", hash = "sha256:9fb598dd17dafe7b3679605b40aa54452dc5fad2fb67c860fffef05f67867fe7", size = 138165, upload-time = "2026-12-02T04:32:16.283Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/1b/9a7e232c5b4b9bfb260c9967c6439417cc7ce34e1b2fd5220ae54d4f63c1/snowballstemmer-3.2.1-py3-none-any.whl", hash = "sha256:694eb9753e14fb8ad77297fe440605711166191bdffe332027a36c58b5085d78", size = 115895, upload-time = "2026-12-02T04:32:14.627Z" }, +] + +[[package]] +name = "soupsieve" +version = "2.10" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/71/c3/1b817965ac12dc002d7c9cd7dfffdd7d4fbf9b45763ef2ffe7b86ee94670/soupsieve-2.10.tar.gz", hash = "sha256:49e9380d7d2905463583bafe285e818c7366a9ed7b3aee221c1ac79c905d8bc0", size = 124337, upload-time = "2026-09-24T02:36:35.048Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/66/87/5ed59e1d0290564e2027ed066c52b059892c4637741337fc0967183c8d4d/soupsieve-2.10-py3-none-any.whl", hash = "sha256:8596eb8967d744174820280fa62b4542a2e955bfaccca73ed8a13c6eb8e9b502", size = 38019, upload-time = "2026-09-24T02:36:33.709Z" }, +] + +[[package]] +name = "soupsieve" +version = "4.1.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/0c/68/ea74670eae744f7da505778c4e555dbd7b59bf4458342f56fded9fac09f0/soupsieve-4.1.4.tar.gz", hash = "sha256:9f12cb9fabef3bbde8eea07539412512960fe2320d67834b3c5be71d9aea522f", size = 189763, upload-time = "2026-12-01T16:02:51.365Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/50/3ff53ec2d16bac3a7b21def7c2773a32a5aebe45d01c6adf96b685cb6504/soupsieve-4.1.4-py3-none-any.whl", hash = "sha256:03bbb16915c1e13a4746fdc84a97e5999888aae3208516604d7bfc786aba0aef", size = 62119, upload-time = "2026-12-01T16:02:49.801Z" }, +] + +[[package]] +name = "sphinx" +version = "8.1.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils", version = "0.21.2", source = { registry = "https://pypi.org/simple" } }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, + { name = "tomli" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/be0b61178fe2cdcb67e2a92fc9ebb488e3c51c4f74a36a7824c0adf23425/sphinx-8.1.3.tar.gz", hash = "sha256:43c1911eecb0d3e161ad78611bc905d1ad0e523e4ddc202a58a821773dc4c927", size = 8184611, upload-time = "2024-10-13T20:27:13.93Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/26/60/1ddff83a56d33aaf6f10ec8ce84b4c007d9368b21008876fceda7e7381ef/sphinx-8.1.3-py3-none-any.whl", hash = "sha256:09719015511837b76bf6e03e42eb7595ac8c2e41eeb9c29c5b755c6b677992a2", size = 3487125, upload-time = "2024-10-13T20:27:10.448Z" }, +] + +[[package]] +name = "sphinx" +version = "9.0.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" } }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "roman-numerals" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/50/a8c6ccc36d5eacdfd7913ddccd15a9cee03ecafc5ee2bc40e1f168d85022/sphinx-9.0.4.tar.gz", hash = "sha256:594ef59d042972abbc581d8baa577404abe4e6c3b04ef61bd7fc2acbd51f3fa3", size = 8710502, upload-time = "2025-12-04T07:45:27.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/3f/4bbd76424c393caead2e1eb89777f575dee5c8653e2d4b6afd7a564f5974/sphinx-9.0.4-py3-none-any.whl", hash = "sha256:5bebc595a5e943ea248b99c13814c1c5e10b3ece718976824ffa7959ff95fffb", size = 3917713, upload-time = "2025-12-04T07:45:24.944Z" }, +] + +[[package]] +name = "sphinx" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" } }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "roman-numerals" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fc/73/567727fc8c8d85bc3adc88a246e12937cfda8d565cf1d80e85bceaa61fe5/sphinx-9.1.1.tar.gz", hash = "sha256:48b627f02908f22c601b3ba9c7b17265b4f315dd05c8bc64cd4da41183f44fbc", size = 8725638, upload-time = "2026-10-20T00:41:13.96Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/18/3c66ea76da7de47e716b181c35bdbfafbd5e9af0bb247b14578e9de348e9/sphinx-9.1.1-py3-none-any.whl", hash = "sha256:f8b60013ce25017be41a509e5c2d265bc1918410061315c36b809c7f335646c0", size = 3923559, upload-time = "2026-10-20T00:41:11.288Z" }, +] + +[[package]] +name = "sphinx" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils", version = "0.23.1", source = { registry = "https://pypi.org/simple" } }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "roman-numerals" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/64/d4/413466f0be8b1cb0e3e43893a148b96d7462d0923d82b4166b21afc5f30c/sphinx-9.2.0.tar.gz", hash = "sha256:90470459f3cab15d9dfed146c71cf77694b0445df17b2e0e69059cb9f7fc9ee4", size = 8782438, upload-time = "2026-10-21T00:05:15.019Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c4/28/a0c50761cd215b7042f4bc617a6bc5c0cd7be62f75bc908e169e28a4d21e/sphinx-9.2.0-py3-none-any.whl", hash = "sha256:4c3ec13b612712c0d3ce4cbdd9e3eb91e68577e07a8e31f32f21cf178453578c", size = 3925388, upload-time = "2026-10-21T00:05:12.241Z" }, +] + +[[package]] +name = "sphinx-basic-ng" +version = "1.0.0b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/0b/a866924ded68efec7a1759587a4e478aec7559d8165fac8b2ad1c0e774d6/sphinx_basic_ng-1.0.0b2.tar.gz", hash = "sha256:9ec55a47c90c8c002b5960c57492ec3021f5193cb26cebc2dc4ea226848651c9", size = 20736, upload-time = "2023-07-08T18:40:54.166Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3c/dd/018ce05c532a22007ac58d4f45232514cd9d6dd0ee1dc374e309db830983/sphinx_basic_ng-1.0.0b2-py3-none-any.whl", hash = "sha256:eb09aedbabfb650607e9b4b68c9d240b90b1e1be221d6ad71d61c52e29f7932b", size = 22496, upload-time = "2023-07-08T18:40:52.659Z" }, +] + +[[package]] +name = "sphinxcontrib-applehelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/6e/b837e84a1a704953c62ef8776d45c3e8d759876b4a84fe14eba2859106fe/sphinxcontrib_applehelp-2.0.0.tar.gz", hash = "sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1", size = 20053, upload-time = "2024-07-29T01:09:00.465Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/85/9ebeae2f76e9e77b952f4b274c27238156eae7979c5421fba91a28f4970d/sphinxcontrib_applehelp-2.0.0-py3-none-any.whl", hash = "sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5", size = 119300, upload-time = "2024-07-29T01:08:58.99Z" }, +] + +[[package]] +name = "sphinxcontrib-devhelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/d2/5beee64d3e4e747f316bae86b55943f51e82bb86ecd325883ef65741e7da/sphinxcontrib_devhelp-2.0.0.tar.gz", hash = "sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad", size = 12967, upload-time = "2024-07-29T01:09:23.417Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/7a/987e583882f985fe4d7323774889ec58049171828b58c2217e7f79cdf44e/sphinxcontrib_devhelp-2.0.0-py3-none-any.whl", hash = "sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2", size = 82530, upload-time = "2024-07-29T01:09:21.945Z" }, +] + +[[package]] +name = "sphinxcontrib-htmlhelp" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/93/983afd9aa001e5201eab16b5a444ed5b9b0a7a010541e0ddfbbfd0b2470c/sphinxcontrib_htmlhelp-2.1.0.tar.gz", hash = "sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9", size = 22617, upload-time = "2024-07-29T01:09:37.889Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/7b/18a8c0bcec9182c05a0b3ec2a776bba4ead82750a55ff798e8d406dae604/sphinxcontrib_htmlhelp-2.1.0-py3-none-any.whl", hash = "sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8", size = 98705, upload-time = "2024-07-29T01:09:36.407Z" }, +] + +[[package]] +name = "sphinxcontrib-jsmath" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/59/02/4f334c7fc3e54c51d2364575a41cd2fae6847e7f53001949f0be5f32e18b/sphinxcontrib_jsmath-2.0.0.tar.gz", hash = "sha256:551f780cf9687f9c3c74f0cf9f18aca06e0d6958853453f3803fe4d357c5b924", size = 14511, upload-time = "2026-10-20T18:22:05.514Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/c2/2965c35b39587d4b7a397f65a9c7d4b942b031061e7ac1ce91782f394a0d/sphinxcontrib_jsmath-2.0.0-py3-none-any.whl", hash = "sha256:15ca92fe0eec82f0baf91a7efcc51ffacdb605924be6327683a52ebdacb6744c", size = 78095, upload-time = "2026-10-20T18:22:04.42Z" }, +] + +[[package]] +name = "sphinxcontrib-qthelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/68/bc/9104308fc285eb3e0b31b67688235db556cd5b0ef31d96f30e45f2e51cae/sphinxcontrib_qthelp-2.0.0.tar.gz", hash = "sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab", size = 17165, upload-time = "2024-07-29T01:09:56.435Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/83/859ecdd180cacc13b1f7e857abf8582a64552ea7a061057a6c716e790fce/sphinxcontrib_qthelp-2.0.0-py3-none-any.whl", hash = "sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb", size = 88743, upload-time = "2024-07-29T01:09:54.885Z" }, +] + +[[package]] +name = "sphinxcontrib-serializinghtml" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3b/44/6716b257b0aa6bfd51a1b31665d1c205fb12cb5ad56de752dfa15657de2f/sphinxcontrib_serializinghtml-2.0.0.tar.gz", hash = "sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d", size = 16080, upload-time = "2024-07-29T01:10:09.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/a7/d2782e4e3f77c8450f727ba74a8f12756d5ba823d81b941f1b04da9d033a/sphinxcontrib_serializinghtml-2.0.0-py3-none-any.whl", hash = "sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331", size = 92072, upload-time = "2024-07-29T01:10:08.203Z" }, +] + +[[package]] +name = "stack-data" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asttokens" }, + { name = "executing" }, + { name = "pure-eval" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "tabulate" +version = "0.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/46/58/8c37dea7bbf769b20d58e7ace7e5edfe65b849442b00ffcdd56be88697c6/tabulate-0.10.0.tar.gz", hash = "sha256:e2cfde8f79420f6deeffdeda9aaec3b6bc5abce947655d17ac662b126e48a60d", size = 91754, upload-time = "2026-03-04T18:55:34.402Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/55/db07de81b5c630da5cbf5c7df646580ca26dfaefa593667fc6f2fe016d2e/tabulate-0.10.0-py3-none-any.whl", hash = "sha256:f0b0622e567335c8fabaaa659f1b33bcb6ddfe2e496071b743aa113f8774f2d3", size = 39814, upload-time = "2026-03-04T18:55:31.284Z" }, +] + +[[package]] +name = "tifffile" +version = "2025.5.10" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/d0/18fed0fc0916578a4463f775b0fbd9c5fed2392152d039df2fb533bfdd5d/tifffile-2025.5.10.tar.gz", hash = "sha256:018335d34283aa3fd8c263bae5c3c2b661ebc45548fde31504016fcae7bf1103", size = 365290, upload-time = "2025-05-10T19:22:34.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/06/bd0a6097da704a7a7c34a94cfd771c3ea3c2f405dd214e790d22c93f6be1/tifffile-2025.5.10-py3-none-any.whl", hash = "sha256:e37147123c0542d67bc37ba5cdd67e12ea6fbe6e86c52bee037a9eb6a064e5ad", size = 226533, upload-time = "2025-05-10T19:22:27.279Z" }, +] + +[[package]] +name = "tifffile" +version = "2026.3.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c5/cb/2f6d79c7576e22c116352a801f4c3c8ace5957e9aced862012430b62e14f/tifffile-2026.3.3.tar.gz", hash = "sha256:d9a1266bed6f2ee1dd0abde2018a38b4f8b2935cb843df381d70ac4eac5458b7", size = 388745, upload-time = "2026-03-03T19:14:38.134Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/e4/e804505f87627cd8cdae9c010c47c4485fd8c1ce31a7dd0ab7fcc4707377/tifffile-2026.3.3-py3-none-any.whl", hash = "sha256:e8be15c94273113d31ecb7aa3a39822189dd11c4967e3cc88c178f1ad2fd1170", size = 243960, upload-time = "2026-03-03T19:14:35.808Z" }, +] + +[[package]] +name = "tifffile" +version = "2026.11.26" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d1/d7/d1f14418e759dca772b49c3fbc9319d686cb1bdb26b2326896600ecd4a7d/tifffile-2026.11.26.tar.gz", hash = "sha256:1ae33db235b269809a1e18e123fbaf19aca8adfbc624b92ab10e83d15b0f12a0", size = 462559, upload-time = "2026-11-27T02:01:19.779Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/56/f8e1db6bc942ab6457a13c7ea8975d183b683fb9939dcc5cc59e39ad2c48/tifffile-2026.11.26-py3-none-any.whl", hash = "sha256:5a8abf8e792a94f43e5c318931fbc2fd61fb9469ca095cdc94a396f45d51cca5", size = 281496, upload-time = "2026-11-27T02:01:18.427Z" }, +] + +[[package]] +name = "tomli" +version = "2.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/78/9ad63712633ed3ab5cc1a648d863d7e7da371e9425e209555a0fe711b695/tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6", size = 17662, upload-time = "2026-10-07T12:23:37.892Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/ab99b60ee52acd949684febabc3005d0045d0f66bebd9cdebd67372d26dd/tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545", size = 163901, upload-time = "2026-10-07T12:22:15.601Z" }, + { url = "https://files.pythonhosted.org/packages/bc/00/ee01b7ed4579180fff07142d290257f25ba786f23f3ec6005f620933c2f5/tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef", size = 163756, upload-time = "2026-10-07T12:22:16.957Z" }, + { url = "https://files.pythonhosted.org/packages/72/c2/4efebf65372f6583185f79799312109dddb61102d47e5c33dcfd1a297aca/tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b", size = 268038, upload-time = "2026-10-07T12:22:18.135Z" }, + { url = "https://files.pythonhosted.org/packages/53/07/5850468e925d898abb36038666f9c333a94d2a223e802a8ba5b6d319d23f/tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56", size = 276422, upload-time = "2026-10-07T12:22:19.567Z" }, + { url = "https://files.pythonhosted.org/packages/b4/87/f293984cdcf83c054196d4fd3dad44fc68ae55b4b8c44bc76cef360c3150/tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1", size = 272616, upload-time = "2026-10-07T12:22:20.794Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ce/db582886b3c1219d3fec93ebd669332482e5aee7a91e0f7838d84f2d1759/tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885", size = 276593, upload-time = "2026-10-07T12:22:22.12Z" }, + { url = "https://files.pythonhosted.org/packages/bf/72/7619b87dea4261fc27dd7b54c4461c129c1f7d9bb7ba3aec89c797a431b8/tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e", size = 101830, upload-time = "2026-10-07T12:22:23.651Z" }, + { url = "https://files.pythonhosted.org/packages/1e/74/220106da34502304b6751a2a9b8a9fbca6c3fd47e737a2e2e3da7c61c9db/tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8", size = 112742, upload-time = "2026-10-07T12:22:24.972Z" }, + { url = "https://files.pythonhosted.org/packages/27/99/7d9c8b41837a7773613e169504147375c157a290167aa59ad74a085f521f/tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980", size = 109332, upload-time = "2026-10-07T12:22:26.117Z" }, + { url = "https://files.pythonhosted.org/packages/52/ed/7baa86f87493646a594de388c7c1c40a39dd0461f7e9c0359cbeefc91fe8/tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df", size = 164854, upload-time = "2026-10-07T12:22:27.444Z" }, + { url = "https://files.pythonhosted.org/packages/a5/b1/44c0341f2224397855723c7a8a39f718ea6fcbcc3dacc66e5aeca0f334e3/tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b", size = 164074, upload-time = "2026-10-07T12:22:28.679Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e2d5b7d3fba47adedb23de616c16d428ea076c79a3d8e1d95d649ffe197e/tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0", size = 274274, upload-time = "2026-10-07T12:22:29.804Z" }, + { url = "https://files.pythonhosted.org/packages/43/90/6090e706ff27a6f89f4a40578e3324b95c3cd8c4150868aabf33a8f414c3/tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6", size = 286435, upload-time = "2026-10-07T12:22:31.297Z" }, + { url = "https://files.pythonhosted.org/packages/0a/9e/a2c40768df16c408f22430afb0a73e9d7e5f79c950884954649d1146b74d/tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc", size = 278119, upload-time = "2026-10-07T12:22:32.601Z" }, + { url = "https://files.pythonhosted.org/packages/12/25/3c0cb485b98e9cfac495629b1c93c87ccf0b72fbe9d2689fd8fe62c6d5a3/tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7", size = 286177, upload-time = "2026-10-07T12:22:33.745Z" }, + { url = "https://files.pythonhosted.org/packages/77/8b/0144c65f0e37e51c18d04ae15c21b19431c165002d0131fe9aa8b0b8b1e8/tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2", size = 102760, upload-time = "2026-10-07T12:22:34.887Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/5d6d8f42fc9a05fce69354e00ff256484192f5f2fc9a2165718fa0de61ec/tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7", size = 112722, upload-time = "2026-10-07T12:22:36.162Z" }, + { url = "https://files.pythonhosted.org/packages/30/65/df18032218db0fb9b769fb23c8039a051f15c811993995ea04c350273a32/tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea", size = 109534, upload-time = "2026-10-07T12:22:37.296Z" }, + { url = "https://files.pythonhosted.org/packages/42/e5/51736d70da209350969e15aca5c5ab6e2ce1ea87a0a892a6c13aec172a86/tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea", size = 163328, upload-time = "2026-10-07T12:22:38.373Z" }, + { url = "https://files.pythonhosted.org/packages/ec/55/086f80dab4ab497602644274e6dea7ec5dd0b4e262e443a8ad3bb7edee2d/tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043", size = 162246, upload-time = "2026-10-07T12:22:39.673Z" }, + { url = "https://files.pythonhosted.org/packages/aa/eb/3ecc94459f3635c92321f4e7bde571323fdb2267c50e19e3188a281eae3b/tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0", size = 272655, upload-time = "2026-10-07T12:22:41.08Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d7/494fd1f0c37a621f1ad9975c2efadb523e8101f144ed6edb2e7fe64738f2/tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b", size = 283595, upload-time = "2026-10-07T12:22:42.222Z" }, + { url = "https://files.pythonhosted.org/packages/70/51/bb8d62b1317e6640866f6949b2d5855e5300f2c99d46de1cd245570bba65/tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066", size = 276253, upload-time = "2026-10-07T12:22:43.625Z" }, + { url = "https://files.pythonhosted.org/packages/66/f4/f46bd7f0763cd47de2db697dca9257c6a4adfd1a93b018cc75c8190ed5a8/tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b", size = 283582, upload-time = "2026-10-07T12:22:44.983Z" }, + { url = "https://files.pythonhosted.org/packages/ac/03/70f2bcb2923a6db37818d917e124270a7f4cfd38ea576f5aa753a91c0ef5/tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68", size = 102628, upload-time = "2026-10-07T12:22:46.508Z" }, + { url = "https://files.pythonhosted.org/packages/dc/98/d52024bb5b0ff68b4f0d276d867f634c84a67319a7e9f6b7708a37742333/tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc", size = 113301, upload-time = "2026-10-07T12:22:47.647Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f2/540db3a70572a8c23a28aba3e9c358ce0ffffbafc990905c1343aa265b31/tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84", size = 109744, upload-time = "2026-10-07T12:22:48.925Z" }, + { url = "https://files.pythonhosted.org/packages/e4/49/caf6b307766eb9567664a8707e9d6be5fcc0e8903f18781c6677a60d80c7/tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105", size = 162899, upload-time = "2026-10-07T12:22:50.088Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/68cfce773a2733a49c74f99d627fb461bd990756860099eac25617889585/tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646", size = 162080, upload-time = "2026-10-07T12:22:51.558Z" }, + { url = "https://files.pythonhosted.org/packages/7e/b2/e5bb8651fdad593f670501a7d718b1a7f73f064d44dea15e04c04dfef45d/tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b", size = 273380, upload-time = "2026-10-07T12:22:52.918Z" }, + { url = "https://files.pythonhosted.org/packages/8d/d2/9e2d7f8b1dfe0e2b34c245986ebd55c4c553ea4ce6c47c443b332673253f/tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75", size = 283228, upload-time = "2026-10-07T12:22:54.173Z" }, + { url = "https://files.pythonhosted.org/packages/ba/df/ec7b876b7b1a2718bd74a3743c076fff565b04029ba33e8f61fac262739f/tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb", size = 277189, upload-time = "2026-10-07T12:22:55.342Z" }, + { url = "https://files.pythonhosted.org/packages/7d/7b/e192d9eed0b9cb80da799f4d77052297fb9a2c3cc9b19f571f56ea88add6/tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3", size = 283632, upload-time = "2026-10-07T12:22:56.735Z" }, + { url = "https://files.pythonhosted.org/packages/84/50/ff94454e75461d75623e47401ed323d65c10aab8fe9033242c20cd2fdf32/tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b", size = 103535, upload-time = "2026-10-07T12:22:58.084Z" }, + { url = "https://files.pythonhosted.org/packages/54/0b/bdacf05f963bd6026ebf6eeb0beda847d1d60e03e440725c64a4e08a0afd/tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a", size = 114621, upload-time = "2026-10-07T12:22:59.2Z" }, + { url = "https://files.pythonhosted.org/packages/61/99/53f438fa6ae4f9d4ed0ddde3e7242b3bdc34b48c8f9948b72b9e9b127676/tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3", size = 111572, upload-time = "2026-10-07T12:23:00.479Z" }, + { url = "https://files.pythonhosted.org/packages/b9/20/1f88f19427d380a40e90a770e087489eaafe4aeee070ae88ed2bbec00acd/tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4", size = 171814, upload-time = "2026-10-07T12:23:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d0/56/cbe5079c9f9a54b9b3e27fc82f08f3cb36edee75561679f53d2380c801d6/tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d", size = 171324, upload-time = "2026-10-07T12:23:03.18Z" }, + { url = "https://files.pythonhosted.org/packages/2b/30/1d53fd3b0f1cb3ba542e345ec32c26aefdddc4e829e4f3429af8a4f27782/tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9", size = 297441, upload-time = "2026-10-07T12:23:04.345Z" }, + { url = "https://files.pythonhosted.org/packages/66/d9/0800acb6a111686f764c1b91ef15cc42a20a66a46013bb42220f1d2c61c1/tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f", size = 307476, upload-time = "2026-10-07T12:23:05.671Z" }, + { url = "https://files.pythonhosted.org/packages/e8/63/30a8f3cd51b5bec37f04744bad0b0dc6160df84aad4f27b0e9283d66f221/tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374", size = 296113, upload-time = "2026-10-07T12:23:07.202Z" }, + { url = "https://files.pythonhosted.org/packages/ab/18/0b9ffc597e69c5a1e20a7823cb60d54b39a9f54e91edcb8574f022186758/tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442", size = 307725, upload-time = "2026-10-07T12:23:08.508Z" }, + { url = "https://files.pythonhosted.org/packages/ab/c7/18f8baae0b5607a60e8e19b4a7fedee43a8ff6458e3896dcbbadeeac9c22/tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03", size = 108546, upload-time = "2026-10-07T12:23:09.956Z" }, + { url = "https://files.pythonhosted.org/packages/72/34/4cca9739254130627bde87500b3f2b512154fe2f278efa7e2a5e10ad4bcb/tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1", size = 117814, upload-time = "2026-10-07T12:23:11.486Z" }, + { url = "https://files.pythonhosted.org/packages/7d/fb/afa530d47dd80a78fce43beac6bc6e00f84558eafcffbc6f37b21e80d056/tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0", size = 115188, upload-time = "2026-10-07T12:23:12.728Z" }, + { url = "https://files.pythonhosted.org/packages/66/98/316fdc00f8c0939e6fe50461dd343c162d3ad51d1286eb25b7db54361d50/tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc", size = 162775, upload-time = "2026-10-07T12:23:13.941Z" }, + { url = "https://files.pythonhosted.org/packages/c5/22/7b10fa5bb01c9539f53f69b619361b19350acc73657772ea7ac70ba309a8/tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276", size = 161406, upload-time = "2026-10-07T12:23:15.215Z" }, + { url = "https://files.pythonhosted.org/packages/9c/e7/1a069d86dfd20f1f84f71c63faed9f83c1d890bc06c27d82dc7d888fb573/tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52", size = 273855, upload-time = "2026-10-07T12:23:16.471Z" }, + { url = "https://files.pythonhosted.org/packages/ae/83/d1ef43d1687d092ab9c235455c76e6e709483b346b056f086095c7c263a5/tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7", size = 284910, upload-time = "2026-10-07T12:23:18.166Z" }, + { url = "https://files.pythonhosted.org/packages/cc/05/f4d9cf7de61822ece0c3873f30d291e324911c71a378b8bfe5ced13fd9f5/tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391", size = 277723, upload-time = "2026-10-07T12:23:19.355Z" }, + { url = "https://files.pythonhosted.org/packages/42/28/78262493141fa543151cf005760c3cb01d09fc28a11f993c05109902cb8c/tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859", size = 285115, upload-time = "2026-10-07T12:23:20.698Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b9/e1dab9a30bcb677b5cc5cee810609cfd64f24306a3055767dd3fda00b1e0/tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb", size = 103475, upload-time = "2026-10-07T12:23:21.941Z" }, + { url = "https://files.pythonhosted.org/packages/4c/bd/31a3790c11d6ea95fcf5e6022ac0f8d0543c9b61120b730fc481bd43d3b4/tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5", size = 114589, upload-time = "2026-10-07T12:23:23.098Z" }, + { url = "https://files.pythonhosted.org/packages/47/a2/4f6310fa699364f0e3af7ee3af88dddd9af066d33e716a0265bbe2b3ea84/tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd", size = 111493, upload-time = "2026-10-07T12:23:24.233Z" }, + { url = "https://files.pythonhosted.org/packages/68/14/00853f0b396d8971107ae1921bb5b322fdee1650d2f16bf06c20adb532e5/tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57", size = 171380, upload-time = "2026-10-07T12:23:25.512Z" }, + { url = "https://files.pythonhosted.org/packages/89/ad/fa6949321dadee46b27363974fb197b94c911c3b0f7a5fd26d7dc18fc2a0/tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd", size = 170553, upload-time = "2026-10-07T12:23:26.855Z" }, + { url = "https://files.pythonhosted.org/packages/53/aa/3056c919eb3e084df3752b2cf5f865dcc04af0b27dba2f66d7b28af4633a/tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01", size = 294428, upload-time = "2026-10-07T12:23:28.132Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/faeeb5d8769ea3832021d73e892c8391eae7b4b4f8b55a789127bd8b18a9/tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f", size = 304909, upload-time = "2026-10-07T12:23:29.381Z" }, + { url = "https://files.pythonhosted.org/packages/f6/52/f094c09e73fb654b621716d019acb5d29bdfd1be01df80c281d552bda48d/tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a", size = 293220, upload-time = "2026-10-07T12:23:30.608Z" }, + { url = "https://files.pythonhosted.org/packages/86/f5/0c30541078ca4b505ce3bd76ed931facbfec524dd018535d691d1af0a6d2/tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142", size = 305705, upload-time = "2026-10-07T12:23:32.181Z" }, + { url = "https://files.pythonhosted.org/packages/05/74/590e7d19d6a118fc5cc5704ff358e21d95b8573f6b9443b1519f29ca8825/tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5", size = 108432, upload-time = "2026-10-07T12:23:33.496Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b8/63a75cfb27a17c38550e44025d3a6e7be64516fd8608a3b75703bf37d81b/tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571", size = 117281, upload-time = "2026-10-07T12:23:34.648Z" }, + { url = "https://files.pythonhosted.org/packages/72/01/e8c1debb2173973372934c68fc8e46170ab60ef23ed4592dff4dec6e8993/tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7", size = 115069, upload-time = "2026-10-07T12:23:35.77Z" }, + { url = "https://files.pythonhosted.org/packages/60/3f/3e3f8fd0919249b0200c80fbc4f9a1e70be19f9883da71dfb7f8b9ab8aca/tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b", size = 14765, upload-time = "2026-10-07T12:23:36.875Z" }, +] + +[[package]] +name = "toolz" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/31/6f/ae20c212a07aa2d156c787383d8088a5e045ee39628661edb190c97e1659/toolz-1.2.0.tar.gz", hash = "sha256:9667a038e9d6ecba37995e26cb2f59ec6420b6ad8dd9677de59db9b956b08490", size = 55442, upload-time = "2026-10-07T04:16:25.639Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/db/17/4c8beb6c8c4176c6bf143bfd7e1e4dd6719b00ced90738c7ac471b71c1df/toolz-1.2.0-py3-none-any.whl", hash = "sha256:890f820b1cb8152785aaf9386d8707770110809035800985ca65cb24ce1120ef", size = 60789, upload-time = "2026-10-07T04:16:24.173Z" }, +] + +[[package]] +name = "torch" +version = "2.14.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "cuda-bindings", version = "13.4.4", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "cuda-toolkit", version = "13.0.3.0", source = { registry = "https://pypi.org/simple" }, extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" }, + { name = "filelock", version = "4.1.0", source = { registry = "https://pypi.org/simple" } }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" } }, + { name = "nvidia-cudnn-cu13", version = "9.24.0.43", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvshmem-cu13", version = "3.4.5", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", version = "3.8.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/45/b0c389051ed02d77227202caf2c2abb1706ca4362781eb79bd6707359970/torch-2.14.1-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:e24b9815001d18e73e76eae1ea25f8ef908c6103e857378ad20f8f6cf5c954f5", size = 127249640, upload-time = "2026-09-30T17:43:48.426Z" }, + { url = "https://files.pythonhosted.org/packages/95/b3/fcbd9ff6ef8a0c318275e613b085d0c49b4fd549fa25bf62496b10a540e8/torch-2.14.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:957df236525bcd940ccd9ca59074e9821182171253417c0d98e7b82647254799", size = 453974659, upload-time = "2026-09-30T17:44:21.385Z" }, + { url = "https://files.pythonhosted.org/packages/54/91/365b45c4c8a16c7c398354b341273d15cdbd01c9feeadac16a02ce070b27/torch-2.14.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:1fee6b20869a90ccec05e35559a706338ac8aab40a9c4fb58f16667e93af36ae", size = 554550266, upload-time = "2026-09-30T17:44:37.477Z" }, + { url = "https://files.pythonhosted.org/packages/48/88/28360126b07082ce4ab96a1bf8547595d06d6fea5eaffdfc7d2b56459e79/torch-2.14.1-cp310-cp310-win_amd64.whl", hash = "sha256:9ee7d50ec80ae5b4258cafc0ea108711988d961f21d0a68cf685650da2812e5f", size = 124096027, upload-time = "2026-09-30T17:43:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/5d/9b/fd1cd143a7bda5abc1fc352ed7b431f6f52aa3c454293211a33656db2cb5/torch-2.14.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:b6074b130fd26bc50f5d171f07dfed70db22dd0c354ab34767729249f9e0f042", size = 127281154, upload-time = "2026-09-30T17:43:58.328Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0e/21281ff4015779255229f487f4481c5bfba53b8c83e01eaa4a8a8f1180c9/torch-2.14.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:ef1276fd07adb8d463ac402a24ea7482e45c9a42df8ebdac211aa757779200ba", size = 453982557, upload-time = "2026-09-30T17:44:52.656Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4f/7af6fbada912b3023cc79b6ab30f89234b258a9a373880ea52ed914a2ae9/torch-2.14.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:305a61f61f35f128579f299c5bd33d475f6a01c6307336139632e30856c4854d", size = 554581699, upload-time = "2026-09-30T17:49:10.777Z" }, + { url = "https://files.pythonhosted.org/packages/fe/54/4e0a71376b2fb15aaf65ed9e6a4c8043d36f554338c6daabc63059a5e157/torch-2.14.1-cp311-cp311-win_amd64.whl", hash = "sha256:0bd2fb0c4098856bc5af59fe5988bf38bdbcdb6550b44273c12ae425cb8ec17e", size = 124096268, upload-time = "2026-09-30T17:44:04.362Z" }, + { url = "https://files.pythonhosted.org/packages/4b/3c/379349820e9a6e713826de3d0b88f07728541bdcabe2a3afd128871cdc4b/torch-2.14.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:420dbf314c180ee4b86e9bc00aee5746a7d6e5bacdd7df925af671ed393f0b2e", size = 127307099, upload-time = "2026-09-30T17:44:10.421Z" }, + { url = "https://files.pythonhosted.org/packages/a4/3e/474930ab971e306957ec763b7df695d659179e15ccab9e7073d47ae14ce8/torch-2.14.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:0b13acde294b401509830d85a8906cbf2fc97425a12a66cce1d9fa13c5106a2a", size = 453998918, upload-time = "2026-09-30T17:52:45.134Z" }, + { url = "https://files.pythonhosted.org/packages/ba/fd/c470857d0dfc5d4c94430658b3eed60fd5292b0bf596a8aae7b9fd66d674/torch-2.14.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:23011fe29a99b591eabb3a31a25080c62e2c2f0690a3c798744e5489dae50451", size = 554618695, upload-time = "2026-09-30T17:53:06.8Z" }, + { url = "https://files.pythonhosted.org/packages/ad/1a/b9648b0d228e513f69f8453ec3f90a8d436d78ff6d85a2773e539f0c07cf/torch-2.14.1-cp312-cp312-win_amd64.whl", hash = "sha256:38bee9f2a2ccfc6898172a5075e4ba52522fbe143eeb099674fc67ab390e858d", size = 124113906, upload-time = "2026-09-30T17:52:21.377Z" }, + { url = "https://files.pythonhosted.org/packages/7d/11/faaca4f8541c45127b7e0d6bb141221fe944c8466d89986b8466c6c195f9/torch-2.14.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:dbe359d705f4d67236743794c296c6dee93a922fd8117eff8c3e880d7d0fb2b9", size = 127315286, upload-time = "2026-09-30T17:52:27.43Z" }, + { url = "https://files.pythonhosted.org/packages/60/1f/0330275c705b846882531c64e80d32b13fb572eeb9b995e87e84154b0712/torch-2.14.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:6d530bd11479fb574567af3a1f384af9a77bf5bb9550cde8080b356ca7220d5a", size = 453999200, upload-time = "2026-09-30T17:53:21.716Z" }, + { url = "https://files.pythonhosted.org/packages/7c/cc/bb579ac0c80e077c58204e43b37a254b74dea5873635100bea25789a55d4/torch-2.14.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:c8f71aabc67bcbfc9373dc131537a5968d04edce73e88add21354a7cd0a76985", size = 554618164, upload-time = "2026-09-30T17:53:42.73Z" }, + { url = "https://files.pythonhosted.org/packages/7b/4b/32c00cacbe682a4c08d9c6c3e7a7116c912184cc7155f06c64f545db97d1/torch-2.14.1-cp313-cp313-win_amd64.whl", hash = "sha256:711713391d26a1ce5e9fbc6c996d954a8c12e8825374cc77b809a6af29539b8c", size = 124113754, upload-time = "2026-09-30T17:52:33.474Z" }, + { url = "https://files.pythonhosted.org/packages/43/19/23a1aed488423a5055727256b25406e4b93bd2bcf1352bef582b9951c10c/torch-2.14.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:cee091caf2a6229e248daf41d18ceebf590ba02d9179205610062c64ee5fef03", size = 127325330, upload-time = "2026-09-30T17:52:54.752Z" }, + { url = "https://files.pythonhosted.org/packages/93/f4/94219ada13edd62fda1f976163292b7b8595f1fd2f4ef74af24b3baad375/torch-2.14.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:f68f5476e2bc0e8f60b74f7ca21acda885c4477af6392f8977e4f0d1ea1aa162", size = 454016297, upload-time = "2026-09-30T17:54:03.078Z" }, + { url = "https://files.pythonhosted.org/packages/fd/df/23c69e9b9fd19fe6563422f1bc59f89601bda47234a89a1cf432cfde3aee/torch-2.14.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:1d4df07be7338bbcc4d54085adee21363c91314702b9bd4d78ef72ffac9465ba", size = 554621744, upload-time = "2026-09-30T17:54:22.951Z" }, + { url = "https://files.pythonhosted.org/packages/d9/dc/a36a4431ab5e3ad168a75f341e24677a4bbbf0c5dda59c97a7079262bb94/torch-2.14.1-cp314-cp314-win_amd64.whl", hash = "sha256:d02a4c48a2ca5fb7654e36e71f710f74494d83f1f10aaff8e059dd554adca956", size = 124110781, upload-time = "2026-09-30T17:53:31.141Z" }, + { url = "https://files.pythonhosted.org/packages/2d/bc/1afbd1a22f6023eafcdb9295ac1d97137a7816f54091d693701072da2218/torch-2.14.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:06c3ec25f3b497f9a73dc0c36f293f295cfe8d5584fd446238d9a501b30a66d5", size = 127657364, upload-time = "2026-09-30T17:53:53.837Z" }, + { url = "https://files.pythonhosted.org/packages/e4/94/b97e863c9ceef2bc6e082e967cbfb9065b5e232f2a60c5af0f5115a1bc31/torch-2.14.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:9113f94f70429f9f302bf55b090b5411269083e8a72a5d015ffcc5a7f83f2c69", size = 453998592, upload-time = "2026-09-30T17:54:38.268Z" }, + { url = "https://files.pythonhosted.org/packages/03/d8/8272157c438cc26a199a8fa0caf87985477b8a1ed8a09084eb2ae40609d8/torch-2.14.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:e65d5fe136e533b23c2d134377f7f126721c7c78dd75b3dbb735af082a8aeb85", size = 554578730, upload-time = "2026-09-30T17:54:54.838Z" }, + { url = "https://files.pythonhosted.org/packages/45/05/451a69a4287033d8f106f5c65f92c2c0c37229d81ea101d4b047caf758cc/torch-2.14.1-cp314-cp314t-win_amd64.whl", hash = "sha256:e07306caa1de2a4ac1467e11ecfc92fc44f523dd6a521145039aef46d913963c", size = 124400129, upload-time = "2026-09-30T17:54:12.306Z" }, +] + +[[package]] +name = "torch" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "cuda-bindings", version = "13.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15' and sys_platform == 'linux'" }, + { name = "cuda-toolkit", version = "13.2.2", source = { registry = "https://pypi.org/simple" }, extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" }, + { name = "filelock", version = "4.3.2", source = { registry = "https://pypi.org/simple" } }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "networkx", version = "3.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "nvidia-cudnn-cu13", version = "9.26.0.51", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvshmem-cu13", version = "3.7.2", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", version = "3.9.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.16' and sys_platform == 'linux'" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/2d/a5/fa947e2bbb072933f8c0ad5e02bd11126bcfc2b624fe234ac29a7b63600c/torch-2.15.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e808b63d616a43b326e1a5677d45a2e5babe7a8ce27edb03ddb48e7dd9b6d663", size = 138527954, upload-time = "2026-10-28T15:16:30.29Z" }, + { url = "https://files.pythonhosted.org/packages/8c/06/439e6434bef959507463fa3fd21c580304f3798ea06ab3e932ef908cff1d/torch-2.15.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:58ce2ebfb3430941353109a85be63ee8e941da22f13daa2c43344eeb51c81e06", size = 483605887, upload-time = "2026-10-28T15:16:55.208Z" }, + { url = "https://files.pythonhosted.org/packages/06/7d/57b7f46934e1148b436889e385693bfcb94ae047b3fe0b6015922e3b66f7/torch-2.15.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:48c2d861134c0b5697c7602cb5ffa68f62a2989fdcd1717e593356f67996ca1e", size = 539136850, upload-time = "2026-10-28T15:17:10.346Z" }, + { url = "https://files.pythonhosted.org/packages/d1/7e/7f1252812e8048bc24f203fc0757a251f26af797b4ff986e19046e2b5f73/torch-2.15.0-cp311-cp311-win_amd64.whl", hash = "sha256:d2c5938f593a47cf6d151a16d130a3cc3f0c105df1b905a571efc00b01e38c1f", size = 126720349, upload-time = "2026-10-28T15:16:25.498Z" }, + { url = "https://files.pythonhosted.org/packages/17/24/7b9b755e8c4dd2395c6a94bab6a4ed8aded1735ff2538bc63cbba8abeddd/torch-2.15.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:593e5fd0c204284890d1c3dff643be34e549e1d24523e13402510f960d4da438", size = 138558517, upload-time = "2026-10-28T15:16:35.918Z" }, + { url = "https://files.pythonhosted.org/packages/56/c9/ac253c63f13212393483bfa6c180b684c8e5437960c06ec9292797e09357/torch-2.15.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:9e51cf9460c5441dcd2a4f31ece207e35ea7c3d2535be0f929cca4944e2eeb18", size = 483664949, upload-time = "2026-10-28T15:17:27.418Z" }, + { url = "https://files.pythonhosted.org/packages/42/43/612036bf387d34afff1ec77d3aabe0d16776f1727b00b8bc4540fe5472b1/torch-2.15.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6d8c86f4e33a9f12a58149bd9b0d64351632b8eb44479be8ff85e5389932dd79", size = 539172785, upload-time = "2026-10-28T15:17:47.95Z" }, + { url = "https://files.pythonhosted.org/packages/74/0b/a57c0b58a64b7a197dc40fc464bb96c0de867f95a2b1cbb3ec9e54414fde/torch-2.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:f2bd0a3709a7493a6ef2ac5a654111242a854439f7558f910b6b653b56f7504d", size = 126738207, upload-time = "2026-10-28T15:16:40.586Z" }, + { url = "https://files.pythonhosted.org/packages/87/fa/efeb85d3ba1d8ef497664db5358ac72a7d1d0f1d8a8ad487cba89753f279/torch-2.15.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:fbefd73b521d3c75c5a1d7c77056b2c6339b81468d14d4e33c55f525418a5855", size = 138556890, upload-time = "2026-10-28T15:16:45.195Z" }, + { url = "https://files.pythonhosted.org/packages/16/e7/4d67a9c8aef527423510e21ecf6f6a6ce45946b0891c54b04bc5edc5a9e2/torch-2.15.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a46cf67c6b574311ecdc24364a5c3a694c60dd3619043f594cfebb8f0b283ea4", size = 483665057, upload-time = "2026-10-28T15:18:13.892Z" }, + { url = "https://files.pythonhosted.org/packages/5a/23/70a1ae507f5ff94505c2c85bf20111020f7a19ecc6f5b36f6275c51b97d8/torch-2.15.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:241fea2bac4ed8351307cd13eca5020fbe231f990891be299cf683897caebfbc", size = 539167086, upload-time = "2026-10-28T15:18:30.056Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6c/f26ed528d197859cf8a634bbfafc3bc136f5590b6620df179d1858a34fdc/torch-2.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:e079089d36401261ebe145504309d0114fb9a00529eac4b33048221d2376a15c", size = 126736947, upload-time = "2026-10-28T15:17:36.768Z" }, + { url = "https://files.pythonhosted.org/packages/8a/04/ff26bb464e61f83e0176deca01e72fffa779190bbb476011e89c45791589/torch-2.15.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:0d2b2d9674fa0b9b3f50e83231aa6545a0b19e437a52f0af939a224faaa45515", size = 138575002, upload-time = "2026-10-28T15:17:58.526Z" }, + { url = "https://files.pythonhosted.org/packages/2b/ce/81dd3a77ea2ff436b3401b8237ff6b960f0a7bec4075cfb09948b3a41880/torch-2.15.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:59c3a521000ab76a11785276b3d56752e03ca2751658798a94c8f1032f93cf41", size = 483678906, upload-time = "2026-10-28T15:18:51.273Z" }, + { url = "https://files.pythonhosted.org/packages/59/9b/e8e2f15272cf45fe00dd8a077a74ded59606a424f8ce754906b3fce04126/torch-2.15.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:1412c79b0338ea61fa31e74a59d74e412c56307e226d3c6e61ccd6d4613ffc3f", size = 539172352, upload-time = "2026-10-28T15:19:10.949Z" }, + { url = "https://files.pythonhosted.org/packages/40/4e/e31abad54b00c940b33f8c6de724c7b1240fa6ba86acee3cbbf65a17a0f8/torch-2.15.0-cp314-cp314-win_amd64.whl", hash = "sha256:cf02d11e13819807389e172ecb8f400f6135969af860e2a9f677f67a011e6194", size = 126735321, upload-time = "2026-10-28T15:18:03.587Z" }, + { url = "https://files.pythonhosted.org/packages/66/98/cad8d73df09e1517beeebd6090f00a0d1bdf762285a8082cf0f22a432e62/torch-2.15.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:628f54cb55a2363a5f14471a80c1b6efb63724449d2611ad2772fb5d4c42d19d", size = 138900111, upload-time = "2026-10-28T15:18:40.575Z" }, + { url = "https://files.pythonhosted.org/packages/11/ff/6e4a6cb34ed2b112c7d3818a9249d99ca732e0de79ebff8a46d7ed762633/torch-2.15.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:2167ed5782ab62f41fb766b822ebea638c2ffcb72e8c3abdd3efc429bbe60a19", size = 483646483, upload-time = "2026-10-28T15:19:31.982Z" }, + { url = "https://files.pythonhosted.org/packages/6b/a7/9f76446e61b1306d2281d24aa5907b8ebdc3e1bfc8d9252f0ebe67aad2e6/torch-2.15.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:d0862b725d86a2795ff331f519fd332451ff75f2e7cff561673d61c44cef7155", size = 539145346, upload-time = "2026-10-28T15:19:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/4f/70/31911a8f46608a6c4fdc7744050a69168312984bed5ab7c8e18f4c9ad9d0/torch-2.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:4a906d0fa6dc9aa9a9b5f3b96437c8dfe661f855645b3f838c12fc5cf5cce562", size = 127025368, upload-time = "2026-10-28T15:19:00.808Z" }, + { url = "https://files.pythonhosted.org/packages/99/34/c7ff06165cb09238e945aa2ae63b9186583a47a9880aacd349d37e521f08/torch-2.15.0-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:06a686eb717cd3d1662363082820be45497318887c596d691af0af0c7649c8f0", size = 138573101, upload-time = "2026-10-28T15:19:21.942Z" }, + { url = "https://files.pythonhosted.org/packages/af/e1/0bf3da42a8491c2917287da4b086480662c3c9affc856a5a992b38366339/torch-2.15.0-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:eba5772cdce0f92a81d0f5c577ac571a4ee35e052ba7533c2d6dd860f0c5659f", size = 483684218, upload-time = "2026-10-28T15:20:13.353Z" }, + { url = "https://files.pythonhosted.org/packages/5a/19/2cf22cae319810b3b488313c917ba7dd8566a4e849e0b8ed64599b414658/torch-2.15.0-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:fbf74b432a5c1cac0824af3d482ecc64a0a8187a3d58cc6733efe349697daac4", size = 539172220, upload-time = "2026-10-28T15:20:33.793Z" }, + { url = "https://files.pythonhosted.org/packages/14/37/003c96b78f95a0dc25368c371452ed01ea9d9b63d59120b8e970c93381f6/torch-2.15.0-cp315-cp315-win_amd64.whl", hash = "sha256:04597a77bbcc7a1a01e7b9efce78d258b18a7f31bcb190f4ee00360bff75e7f6", size = 126735953, upload-time = "2026-10-28T15:19:41.917Z" }, + { url = "https://files.pythonhosted.org/packages/8b/e6/1df516e9d3c0a551e118d21a2a6cbc7c47cdb4a09b7cc363ad8e696c4744/torch-2.15.0-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:02ac0b22211c1984e5dc002d2e57fdbc13d32116537ea6ae1a0c9d07cafce0c9", size = 138897802, upload-time = "2026-10-28T15:19:46.702Z" }, + { url = "https://files.pythonhosted.org/packages/22/6a/6425a3e8e3c9b251c1a1994295eaa2fbbb7211255e2b55f26d3eebae31ae/torch-2.15.0-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:ed708117f2f0162dbbd958dbd2654c16c99ad4c8ac14ccc4617dc76f029b8a8d", size = 482878055, upload-time = "2026-10-28T15:20:49.213Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a8/dec4f9c0e4c1c9403294a62d5647fc5e46d23348bbd25f8ff143e57364cd/torch-2.15.0-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:9024cbf347dce95759bcde1411ef59b7cdb9ef0a846f4f24f356a17f8cf16f7d", size = 538397035, upload-time = "2026-10-28T15:21:05.11Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/1ad0107cec15706e4d972fcbfaa6b3da26734959109861a60902c922b50c/torch-2.15.0-cp315-cp315t-win_amd64.whl", hash = "sha256:c521a00891e92aba2f34717671c268acd0bde26444623efcceaeaf51c87b3b36", size = 127024483, upload-time = "2026-10-28T15:20:23.183Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "traitlets" +version = "5.16.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" }, +] + +[[package]] +name = "triton" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/ae/6b01bdd0dc082e190f5b04aa70fa955f968ac3fc70fd71dde71aeb835a8f/triton-3.8.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:398f4b009c7ab08ed9aeb1d1282dee822945b53f399a5e12a4fecb643cf2007d", size = 226352592, upload-time = "2026-08-28T16:07:49.055Z" }, + { url = "https://files.pythonhosted.org/packages/65/65/18d0871f353eb170b0b9c562cd65f6ab9619b6e7b8aaecea9709e9ad16a6/triton-3.8.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6d914c52f89dc942b1819db959e7c07a5999f678ec760f677625c706b7e0d743", size = 247838081, upload-time = "2026-08-28T15:55:34.877Z" }, + { url = "https://files.pythonhosted.org/packages/a3/cf/d21c9b1a4d1df9ba3aed218069f24f762a4b9565c5a362bef6f110c08e72/triton-3.8.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:372285307d4c44ee74cee32de0b4f04bd157e071427e38c6f4ee3e3beb2194f4", size = 226467015, upload-time = "2026-08-28T16:08:05.871Z" }, + { url = "https://files.pythonhosted.org/packages/6f/9a/2c3d3823726d5ad5359f7065b02b984925158b74611c1e3987f6a37461fb/triton-3.8.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:68988ac85d5e7086baeda0ddc175af9667db7529b3c5e11a5c0601b8bef2200a", size = 247945226, upload-time = "2026-08-28T15:55:43.795Z" }, + { url = "https://files.pythonhosted.org/packages/87/07/0f8cd8e8db0472334253efdaaab3d0819fea27aa99bf0e7f1aeea4ceb5ae/triton-3.8.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a9c404c69ed4a39e8ec632eaf6b9fe058a060bf98979c177f6ef666f06bb8d50", size = 226474486, upload-time = "2026-08-28T16:08:18.29Z" }, + { url = "https://files.pythonhosted.org/packages/c1/09/b7012e5bfae67640f268aa584caa80fe1674f6b0da949046b679972c33e3/triton-3.8.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91ffa46d095b252248297292dd22bcbacd53a125a0c2eefbbbf74925a320bc3", size = 247972921, upload-time = "2026-08-28T15:55:53.157Z" }, + { url = "https://files.pythonhosted.org/packages/87/4d/4c564374bcdadb166fccbf3e45aee0d4a473f88d341761bd2fefe3b8e8c1/triton-3.8.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b7004666652f500ed854a86988e4b3d69d247188b5d2092b5df1e44f4a954099", size = 226476793, upload-time = "2026-08-28T16:08:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b6/3394d5548404c1cabd1dadadd28d0b3f9478db1dff8180da53bb3f0a1e19/triton-3.8.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1f0497218e26b7d79773ad9c2a3fa3b539ee69f587a13fac2e552b1d322a8015", size = 247975122, upload-time = "2026-08-28T15:56:04.112Z" }, + { url = "https://files.pythonhosted.org/packages/b8/59/bf0e9493118bb353ab59a5d6a65db3618d9b314417cc1459f0121e0ec5c9/triton-3.8.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1f6b48d0591929a3867973acac3dccd4e058585f91bfb41022de496c9ffab304", size = 226488654, upload-time = "2026-08-28T16:08:47.141Z" }, + { url = "https://files.pythonhosted.org/packages/93/d9/08c75f3459f19ad00425b564058e40efa4bcd79b816064cf27499303ea42/triton-3.8.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:387dae4cb0089a7b6ba1a428ae0782b65c4c58f57d94617cb22ca8593d8ccbca", size = 247972313, upload-time = "2026-08-28T15:56:14.007Z" }, + { url = "https://files.pythonhosted.org/packages/7c/34/429c5592181cfb7361a0a8e0bff218e7224b726709d75da2472b3e819f70/triton-3.8.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b84e7d512490ba529111260fa6f7cad8b254a6bb5fbdf41d5ef9a5e57f52d0a", size = 226591133, upload-time = "2026-08-28T16:09:02.271Z" }, + { url = "https://files.pythonhosted.org/packages/fe/d1/aa8a3e935c37efee7945984fdb64d7e0851bf6d920afd97b2d21f9d23360/triton-3.8.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74217bb56ed8692759227758e4c4b3bd2d608a209c1a7a081bf361fb4c2c1bf9", size = 248077577, upload-time = "2026-08-28T15:56:24.94Z" }, +] + +[[package]] +name = "triton" +version = "3.9.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/0e/a2176f4ddc2a0c77796d7834cd9bb088cdba4d89e080716b36970dce4ad0/triton-3.9.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:feaaec13578ca84301d561d034cb08b3ae293d7f0b7ab6b8ddbb2d6796363716", size = 263373771, upload-time = "2026-10-27T18:38:49.077Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/51e1466f2941ed36dbe57d1f88f772ba6afe669e5ba1e24eaf148b7ec0e1/triton-3.9.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1622118a038b0c6e16fa4a0305da62c8b3c15904ee1cc4d4e65846a25969e41e", size = 285777556, upload-time = "2026-10-27T18:28:00.919Z" }, + { url = "https://files.pythonhosted.org/packages/c2/7f/79490a3e16cbda1817f00ad6d05694020f1decb1e063f96e83d1cfd2558d/triton-3.9.0-cp312-abi3-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5542f4328472fd827dbb1ec43873364c2894682cc3f5d1c74a643762900e243e", size = 263270508, upload-time = "2026-10-27T18:39:01.187Z" }, + { url = "https://files.pythonhosted.org/packages/3f/c9/af85b25e0d98bd921a7646ad1db1c8746250ee04b8f1595982d29b6283cf/triton-3.9.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e52ab4e2f1d64f0ac494c9aa723697b793f81a91c4cae4c36608ca0bc4267bf", size = 285674620, upload-time = "2026-10-27T18:28:11.992Z" }, + { url = "https://files.pythonhosted.org/packages/7c/56/21c542b570326950db7799145b706fef79a1c6da7e5975c278bb946d3854/triton-3.9.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d0b97b333d919e86d06a6b3c8656c27eecaf14f74c1eb64d210234603268ba2", size = 263460848, upload-time = "2026-10-27T18:39:15.547Z" }, + { url = "https://files.pythonhosted.org/packages/26/f5/cdcfdc92a47b3df01759a5172f1fa505aad2b23625ba689fa5883d3ac36e/triton-3.9.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eab30be40d412e947f3b74b20f50e4f8e07dd11439e7ddc6bd6184cabda2be79", size = 285881516, upload-time = "2026-10-27T18:28:23.251Z" }, + { url = "https://files.pythonhosted.org/packages/63/78/b0e44de35533e5b179ab75a70aad01b5ae012b15ec566064a29c818813e0/triton-3.9.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:990d43d967bbcc90f973fc17ad9cd7352e67940f41b31d94afd53b9867a3c1a1", size = 263467108, upload-time = "2026-10-27T18:39:28.236Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bb/931550491793a10fef98a305701a1459129edaaf9146820c529509cdcf74/triton-3.9.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bac2ed42a2b7aa232aeec57c2f7b0d88b61a74a29b3bf358f4cec6b20be356f6", size = 285878775, upload-time = "2026-10-27T18:28:33.737Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "vispy" +version = "0.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "freetype-py" }, + { name = "hsluv", version = "5.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "hsluv", version = "5.0.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "kiwisolver" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/3c/1b41b589ef759cc710b536aaefd9cafb9d5969ca9286a5987186d4bcac4b/vispy-0.17.0.tar.gz", hash = "sha256:20c2b51c3fc6f2700a648ede8560376dabdc5d258184cef8f6a34b3b4c80e46f", size = 5527987, upload-time = "2026-09-08T13:09:31.944Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/81/b0290c900bb2b3a1bd6a828902f57548313b286115e128b1da304fa5297c/vispy-0.17.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0c1ecd3910090561a8f9fce819bf129fca3ab17c279a1f95ecd8943c71645c3f", size = 1491363, upload-time = "2026-09-08T13:08:37.357Z" }, + { url = "https://files.pythonhosted.org/packages/e0/09/6cc78ad21aba5d223b45781baa1298697b821e93e7e885cb58b2c928c5ae/vispy-0.17.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cc883107267ce524caf1f5054b080d4785a23ff38ed92f3e0ed70957d4524024", size = 1491136, upload-time = "2026-09-08T13:08:38.977Z" }, + { url = "https://files.pythonhosted.org/packages/19/10/0f3a1cce06ac624b8224797fd06a3eb722540d233140dcc530a73eb722c8/vispy-0.17.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3bc07c22c4a1543994b213953f4bc534f33bb474ee2bb239773d585a643a27b4", size = 1808365, upload-time = "2026-09-08T13:08:40.281Z" }, + { url = "https://files.pythonhosted.org/packages/32/63/358c008a1bfe9e2ef8702edfe2b8d16817d4f55639e901d142cedf045330/vispy-0.17.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:45c5ba9cf9c77a77ffe4e1f513b8b537ae5bf7c187010560b7f20424146461a4", size = 1809705, upload-time = "2026-09-08T13:08:41.73Z" }, + { url = "https://files.pythonhosted.org/packages/65/e5/62617f43f3047434b3696e3827cf274ae70e1e9a22637802da1e51c1a114/vispy-0.17.0-cp310-cp310-win_amd64.whl", hash = "sha256:8319d2fa2fe77dcacffc754f65ecfa21ec99a897374c832082a1d364c2fea1e8", size = 1481535, upload-time = "2026-09-08T13:08:43.019Z" }, + { url = "https://files.pythonhosted.org/packages/df/65/b9ad460717cded77e99abbf0e84583ccddcb483b4fb51e2180a1d8afe7dd/vispy-0.17.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:dfb0a6f5f17898588681693425f982662b9529aec5d3815916584ebf8fe09df4", size = 1570601, upload-time = "2026-09-08T13:08:44.191Z" }, + { url = "https://files.pythonhosted.org/packages/cb/66/b81934f6987f6ec9fbc1fb45e587ca42fda1f4bcca640936e9881093df56/vispy-0.17.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:782e55f903b925ed59f006261ff1ff2b3df5234d7bb7114de530bf9062a0c5ef", size = 1570148, upload-time = "2026-09-08T13:08:45.596Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f7/9c34c3587cf9a39a9cba6c8a197a4c72ebaab8808b4cb76426cdefb7c99b/vispy-0.17.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:06de90f4723673c4a5a01543894ad298db02cca22b7dbec00eadccaf1ff216b0", size = 2225374, upload-time = "2026-09-08T13:08:46.758Z" }, + { url = "https://files.pythonhosted.org/packages/8c/a4/295459033e0cefc37a4c5c9e69e39969073ded37753c0d77a4e41c49861e/vispy-0.17.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b5c5d301e6d307b613a8ceb4dd193251d1690f8f170bd2953dd868d84641bd84", size = 2228089, upload-time = "2026-09-08T13:08:47.961Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f5/2f5d7bcf420e2b9ac08b790082e99fa0cfd0c0f00cdb02141e919a784a60/vispy-0.17.0-cp311-cp311-win_amd64.whl", hash = "sha256:9cd77c4adee1dbb9c12a8bb529378c7cbf10c3c55c078341695759be83f3d3f5", size = 1551058, upload-time = "2026-09-08T13:08:49.148Z" }, + { url = "https://files.pythonhosted.org/packages/11/7d/054c744754a431cf27d6597fa70d9607cf9d79d35c2630d4c844b4cc3029/vispy-0.17.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:18da89e75abed64ccd39c4019517730f9e416dbdc247d6a2e812739feb15e92c", size = 1650288, upload-time = "2026-09-08T13:08:50.455Z" }, + { url = "https://files.pythonhosted.org/packages/13/83/ff738316ebd2551705d699dad585dcca9dfcfb8c3bf156a220d6ba31eace/vispy-0.17.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c140716e323f30fe031e09cf906a39227a681ecc85fb1877e9c10542075cf20f", size = 1649375, upload-time = "2026-09-08T13:08:51.63Z" }, + { url = "https://files.pythonhosted.org/packages/7f/38/c98c53aec85e2d51fb8a763a4e481dda423551cbe02c8d24b59b44f60e47/vispy-0.17.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0b516b8f778f9442f1367ef1e7d3b8f11795dcf2d0eb9c9a7900b9e77f51b102", size = 2665077, upload-time = "2026-09-08T13:08:53.183Z" }, + { url = "https://files.pythonhosted.org/packages/c6/01/ed9b34430ca0efa50b25c1b2e08445f6cc39370b8aeb6629bfc49bd92126/vispy-0.17.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9e8d65572d164a8ab690815feee9f7b6848fe5a3ce761a9082ad0580c398ff3f", size = 2670947, upload-time = "2026-09-08T13:08:54.384Z" }, + { url = "https://files.pythonhosted.org/packages/73/e7/4e79b8c7da4eebea966be0d79e42b12fd0651252c4bb383a74f5b25c4534/vispy-0.17.0-cp312-cp312-win_amd64.whl", hash = "sha256:c4862155e735009b1af6aeda45ea94a72e1a375d6086c89273455d66238bb18e", size = 1621242, upload-time = "2026-09-08T13:08:55.558Z" }, + { url = "https://files.pythonhosted.org/packages/a0/28/71b493f2f531a3cc6bed9f0017d56fd08e14cb5158e51e2f5ae9e89bd460/vispy-0.17.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b1959bf7bb4c01243a5bd9b33d123c61eef4f1c38b8fde7b33610a2d63b7cd5f", size = 1730183, upload-time = "2026-09-08T13:08:57.146Z" }, + { url = "https://files.pythonhosted.org/packages/e4/2c/f069a682cbd5161fe185b83f85d5d87041e42a618b6a1cb3800a6808b51f/vispy-0.17.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3fa6cf44841857a903431761b0a5e08bcb0cac3ed1d1409529be9b551435b350", size = 1728868, upload-time = "2026-09-08T13:08:58.751Z" }, + { url = "https://files.pythonhosted.org/packages/61/c1/9fb8004190f10ba7d897696ac8741f0d71ba6eb8214beebd566b6a14e82c/vispy-0.17.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c677aac020a0939189c8ee143923cfaa1f7af7f36c6642d7a5afdf64568f4142", size = 3099390, upload-time = "2026-09-08T13:08:59.953Z" }, + { url = "https://files.pythonhosted.org/packages/f3/50/d1f5b5da39484aa250d31944195f25109bd5c36ae9d6be0f0f8db77558f9/vispy-0.17.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89d6ecd17c4ede82b617066efdee4645094101c14c95c4cdce74276804c0fc01", size = 3108373, upload-time = "2026-09-08T13:09:01.422Z" }, + { url = "https://files.pythonhosted.org/packages/c9/22/8cb51c2f3b7e8ecf771517a3c1a2605a298012c864a1317da9fb795a6e06/vispy-0.17.0-cp313-cp313-win_amd64.whl", hash = "sha256:c49f5d850dcfa27e94903a83fcae469a65bafe743cc6aa652dccc01181e7988f", size = 1691128, upload-time = "2026-09-08T13:09:02.706Z" }, + { url = "https://files.pythonhosted.org/packages/57/c1/57d54bd0ebca532edb89f8efb31bfe2abaa3d8d4cbca696229c80101a46f/vispy-0.17.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6ea94f406beb852757422de0f9b11fa508bb2aaaf32ecc4d86fddf9237b62904", size = 1810219, upload-time = "2026-09-08T13:09:03.881Z" }, + { url = "https://files.pythonhosted.org/packages/17/62/2aa46909228819fb7c260236d5c49a190bbc2914ae4f73465deda4ea8aa4/vispy-0.17.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8720f99baf22f8276b01c4723aa788c5c6aacd590ff4b3ea46684a97c46f8460", size = 1808547, upload-time = "2026-09-08T13:09:05.067Z" }, + { url = "https://files.pythonhosted.org/packages/ac/c5/59c585286cfb84b205e4b30877239d777d723be977baa21acfd28629f4b7/vispy-0.17.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3b0773c4117c90a76f13450baaf2e30841749f21399b516fd6afc886cafeb7b6", size = 3532310, upload-time = "2026-09-08T13:09:06.651Z" }, + { url = "https://files.pythonhosted.org/packages/64/d3/7830176f4f050f16ccb83918fbe1087814e1292094f3fdc5a4f58fc70cad/vispy-0.17.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a41928ba0bc04860bef45188fcbd419f148e40681bc58fc01571e3383957b589", size = 3541652, upload-time = "2026-09-08T13:09:07.982Z" }, + { url = "https://files.pythonhosted.org/packages/63/c5/186f410e95e230910e0b0f5896e52eb47ac6d60f0ec0c7456432dabf6055/vispy-0.17.0-cp314-cp314-win_amd64.whl", hash = "sha256:72acc85b2168bc56983b69605a96c5283f4def968663a30e6788159bbb7bb526", size = 1792636, upload-time = "2026-09-08T13:09:09.263Z" }, + { url = "https://files.pythonhosted.org/packages/17/07/fddd44fef75333ba41cc6bc15f40382d300e2b5bb0fac9a594e6a8de0c68/vispy-0.17.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:59652587e60643a258008f331a057504bf25b2687de9af12e23edafd81f59fee", size = 1893971, upload-time = "2026-09-08T13:09:10.465Z" }, + { url = "https://files.pythonhosted.org/packages/70/78/4801bfc9aa1bb0acc11c56ae1ea984801ea595b71d4f6014ee0cefeeff11/vispy-0.17.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:413cf1107364d334b75fc4e8812876fad1b45cc65e68b6141ede912bc6fe3930", size = 1892444, upload-time = "2026-09-08T13:09:11.859Z" }, + { url = "https://files.pythonhosted.org/packages/d4/cc/6d402cd2354dcb222ffb651c69dca17f914704133c7cf0f8c8b1ef15f41d/vispy-0.17.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:378211acb87d3e540e2385a65c50b7b1c99a9a4b6e262a93d29c332c55cc44b7", size = 4020265, upload-time = "2026-09-08T13:09:13.068Z" }, + { url = "https://files.pythonhosted.org/packages/1d/c6/e47af706105df2d17450d581ffe84523f39bf4908f9f6296645af10557fd/vispy-0.17.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d8669334b74b7728d665de156b34c9e12e04fd55f1b78545bc96b27dfbdf0190", size = 4020302, upload-time = "2026-09-08T13:09:14.414Z" }, + { url = "https://files.pythonhosted.org/packages/8d/cb/4c38da5ca20f848658fa6e5b8a28ab17f487d10ee7c9af128d5269cf34bf/vispy-0.17.0-cp314-cp314t-win_amd64.whl", hash = "sha256:81b9014de8c16867368c937210b0cd372d2b07a9a631603c98db457f5f52af77", size = 1869734, upload-time = "2026-09-08T13:09:15.714Z" }, + { url = "https://files.pythonhosted.org/packages/2d/5d/0aabda06424e1d025d9ee995bcf9c8fee891cfe6a1ecbfa9e44fca8f3b0e/vispy-0.17.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:053e626ebd4f53b68f8d62379ff2c383538218a2933256b52120dc13c089c936", size = 1974049, upload-time = "2026-09-08T13:09:17.01Z" }, + { url = "https://files.pythonhosted.org/packages/54/4e/8637b7df046c396fa072397051c7590d7e49cdb5dadad4cd17f3a6960e0a/vispy-0.17.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:d191d6f7690d5b7bd92e17d86f762912eda8fb0be7dde43bca7bd80324dd27d3", size = 1972254, upload-time = "2026-09-08T13:09:18.626Z" }, + { url = "https://files.pythonhosted.org/packages/11/90/98cc0556b3aa25f3107a3e1326f38f90020ed5ba14e31a9dbc0b35d48c22/vispy-0.17.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0a044c34f825303a8ea1f22012a8563cd000f1cec32e08bf4732c8b32a9dc67", size = 4454002, upload-time = "2026-09-08T13:09:19.851Z" }, + { url = "https://files.pythonhosted.org/packages/4b/ef/f8f54b54c990c4ade0c90548b95b3b29ff3a222cdfd97390d0512ca71258/vispy-0.17.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b702801bea1bfd946d542c34a19a9cf9b0617f6547bf38320922b044c7a08ba", size = 4458098, upload-time = "2026-09-08T13:09:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/9c/23/b3f9da7faf3ecd3970cfb67aa342608fe7c73c449a4c4ea2b35ad64862d8/vispy-0.17.0-cp315-cp315-win_amd64.whl", hash = "sha256:057540bab19fd24f5791830833df5f9ecf78d40ff179c1a6e7b0856e18ef57b4", size = 1941596, upload-time = "2026-09-08T13:09:23.687Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f9/a435198d92e23c96e4d2deba77660fd53fa966a7b5adad7ad3ea0aec0aa0/vispy-0.17.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:5f5175aac33dc01757858b6cad8d9ca3a93f59c90db822082aab343b9d40a73e", size = 2057314, upload-time = "2026-09-08T13:09:24.824Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ca/29f5442b945fb1fca1ef4b50123d20b12844c6153a7ef138ebd198f1b59b/vispy-0.17.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:27d5b833f5d7f3bbeb7de6194ee2326528364e6c9e342cc824b440d8bc183744", size = 2055762, upload-time = "2026-09-08T13:09:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b0/9be41b593a2210ff4319d32fe97bf147953fb7a9c26eaf9f339082a772c2/vispy-0.17.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:58d85b529879999941a5157f21ef9cba5c4485382a118742980f57e103599a4d", size = 4940475, upload-time = "2026-09-08T13:09:27.593Z" }, + { url = "https://files.pythonhosted.org/packages/92/34/f147f7c4c34955eea90f8d2c0d23b6d7365af8deda1f6abd113d556af88e/vispy-0.17.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ff4a53e25e27f206acffa8fccea195e8ff0184af7f466364bb92a2534b3de7f", size = 4936032, upload-time = "2026-09-08T13:09:28.906Z" }, + { url = "https://files.pythonhosted.org/packages/ec/b9/2a1d6cade8f68ae68f5ee79396a5fef402f3bee39ace3be1c8bee432f361/vispy-0.17.0-cp315-cp315t-win_amd64.whl", hash = "sha256:85f03b43b37079a119c75c0352aafdbc0188ee7a246d98c708524473ce419c18", size = 2018238, upload-time = "2026-09-08T13:09:30.696Z" }, +] + +[[package]] +name = "wcwidth" +version = "0.9.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/da/d59374b2c893ae70a41fdb064637ccef218f25df8c67e5431a96708235d9/wcwidth-0.9.5.tar.gz", hash = "sha256:713534e2ecb16e0fc39f19e0a5dda997da76d010953e9e8f803e7971f8accd80", size = 1020887, upload-time = "2026-11-21T21:40:03.823Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/37/3fd79ed60a52d3bef465abf826af97159b10ca0be16d5ad9f1dce3113fe2/wcwidth-0.9.5-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:020031ef4b8d11c8f3247103b9fb9ea5adea7474ed2bb0a3beeb1633c6ab00e6", size = 634579, upload-time = "2026-11-21T21:39:18.914Z" }, + { url = "https://files.pythonhosted.org/packages/34/65/12f5f1afd3bb6a2ac4b56ee71b43ac18d384f348daf2e20ede7b335a5a19/wcwidth-0.9.5-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:a7e0ccc62c7171a8f6b47f7127559e8d9fbfa36d36dfffefb409655dd669717d", size = 640980, upload-time = "2026-11-21T21:39:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/64/d5/783fd51c04352a13fdf41bf4697bca5dd13cd41d6bdd55d0240a360a0245/wcwidth-0.9.5-cp310-abi3-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:34964815cfb6e11bc1600d0c7e1ae483c8377b88717c2e7f86f243033e10e2ee", size = 814324, upload-time = "2026-11-21T21:39:22.052Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/6631bfa4d7666441d86053c58c208388e8f2c4bc28bbd96ba03f90a424b4/wcwidth-0.9.5-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a631629c8a131f7fa58c99bc0630f7011bcdc385146b1ebac9d74becba2b6a90", size = 826581, upload-time = "2026-11-21T21:39:23.694Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cb/55c50713af3697d7dc88b99763826e77ac1e5cec515670c9400a6dee980e/wcwidth-0.9.5-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:61ffb194ccf2224ff552b46912aa44f1bc841f8ef751b193335b317a286b7c03", size = 822732, upload-time = "2026-11-21T21:39:25.267Z" }, + { url = "https://files.pythonhosted.org/packages/da/b2/11139a4480a93b7e53f14ad56762fc2c2a118a417bf55f78d6213bb4cf75/wcwidth-0.9.5-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6ac35755bb1748b2e36f9ea758e90da251824d530b5fe46fb7a68b9d1ba2d985", size = 836137, upload-time = "2026-11-21T21:39:26.984Z" }, + { url = "https://files.pythonhosted.org/packages/8f/8d/c492d7b241367fa2afbd4efae756d4a08c12f0d5488b3c4e7b5c4a906eb0/wcwidth-0.9.5-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:ff7b3f3d69c38a45840349ad8d33e61d7ebaf0f2cd74b659f8baf5660d807f39", size = 830918, upload-time = "2026-11-21T21:39:28.513Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e2/19ae4d788ad8f92c4ef728fe6b83dffb30c8d1b3f1f209ed1e5c44563414/wcwidth-0.9.5-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:76523d4013b1373b74654b19f4c68ce2af2deb00bacdd7ef497403eeeaff2ec6", size = 835962, upload-time = "2026-11-21T21:39:30.032Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/312011b7e5eb898be73a303caef289a3313cfabfdc9c608e266695440065/wcwidth-0.9.5-cp310-abi3-win32.whl", hash = "sha256:f94b1c6d1252013826756c395279738d75386a7a06b3262900ac7c2719fafed4", size = 615657, upload-time = "2026-11-21T21:39:31.677Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f8/f192d5bb1ef6d373ab68e6797480bdc07f43650b8badecf61b96f046b598/wcwidth-0.9.5-cp310-abi3-win_amd64.whl", hash = "sha256:83392b339571c9f1161a360079229c65099c96801433fb71757ab183ce9742b0", size = 619979, upload-time = "2026-11-21T21:39:33.212Z" }, + { url = "https://files.pythonhosted.org/packages/32/ad/86a58e07dfa0aa7814702c144fd4ac2c5449e561c31a2161e2f3979f0fcd/wcwidth-0.9.5-cp310-abi3-win_arm64.whl", hash = "sha256:775076a8da66a9cea8e135331800ee2aa579d6898c23745ab7f19d1d637388e6", size = 619901, upload-time = "2026-11-21T21:39:34.869Z" }, + { url = "https://files.pythonhosted.org/packages/ff/65/d74ef733d53030e586de0330bbef792840cd1bef17343ed7ff9373664402/wcwidth-0.9.5-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:a83a10f25bda6cf6ecb471adc7026a69e2ef7aafc90e9fb3d05231800d5772f3", size = 635295, upload-time = "2026-11-21T21:39:36.493Z" }, + { url = "https://files.pythonhosted.org/packages/fd/68/023bb9583972d97d754da04806b72ce70dab6d4bb827e29491581cb5bd48/wcwidth-0.9.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e977155cd5d53d15aa7e70acaa72c28a00bd63a1bb5d25143961964908fafc8d", size = 641749, upload-time = "2026-11-21T21:39:38.071Z" }, + { url = "https://files.pythonhosted.org/packages/4a/de/37e1b72777b252e98d99dc94d5e399866ea1e2c449494ae4a03318aeea3d/wcwidth-0.9.5-cp314-cp314t-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:507aca0875120b669fdc4e901a7645e62fd7646a6eecfaa56f0c0ca9b899f100", size = 830611, upload-time = "2026-11-21T21:39:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/39/9c/031b2bdb292084f3ca15de7e08244026e0df2a0c529d0dc6d5e6db6102b5/wcwidth-0.9.5-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:210316fc465bda32d558206c0e72da5541aea9b648593176a03dfd6195db80df", size = 844080, upload-time = "2026-11-21T21:39:41.3Z" }, + { url = "https://files.pythonhosted.org/packages/10/42/ba312779b5eeddb51f861fe51d5d5fa3f059f5258cdd8930e4c6e1485625/wcwidth-0.9.5-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b452f39d40e9955f03701444d6c177529576ea6338922fcd88f438dc08b2bb31", size = 839745, upload-time = "2026-11-21T21:39:43.038Z" }, + { url = "https://files.pythonhosted.org/packages/5e/90/4cf55f5eb7727fc8c3868fcbeb72b5b45a7419d744cee21c731042c1dab9/wcwidth-0.9.5-cp314-cp314t-win32.whl", hash = "sha256:f026612a7932e6405b8c9d45c1c64bcbc2a5036ca8fc4983fda923e2863382b1", size = 619910, upload-time = "2026-11-21T21:39:44.612Z" }, + { url = "https://files.pythonhosted.org/packages/31/24/c0dd1d3fd25f4ef61ea28dbaca30997f1b82fd50e1a2e8ff34c1f5247eab/wcwidth-0.9.5-cp314-cp314t-win_amd64.whl", hash = "sha256:d265e7f5b53e1bb4e6ac70318e4efdc21000a7fd6e6f1598889e59fd7a1ecedd", size = 625111, upload-time = "2026-11-21T21:39:46.132Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e5/04e5bccf3a27994fdd52c1c3cc68fe218c80a406ebe0783707c498c95acf/wcwidth-0.9.5-cp314-cp314t-win_arm64.whl", hash = "sha256:be39e31075b4dbead45501db182472e0489a2d4173f7d7f81ca0a3849a4dfdcc", size = 623558, upload-time = "2026-11-21T21:39:47.666Z" }, + { url = "https://files.pythonhosted.org/packages/5e/c7/3da4822610089fdf1488adc1fe9e824485008bac611ea3baa1c7cb89b9cf/wcwidth-0.9.5-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c2aa6317c42bfacb15874284cdc83885627b4f1fadfdab8c24b95e28103ea638", size = 635329, upload-time = "2026-11-21T21:39:49.311Z" }, + { url = "https://files.pythonhosted.org/packages/7f/0d/83eb72637012ab8d5cc7e7a95b3469c207b036d9899f5e089ab700a9565c/wcwidth-0.9.5-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:89e3aa2e2b79fd13867db468f0c15a6ca135eb4b9e6b8268d0442235dbb6c04a", size = 642016, upload-time = "2026-11-21T21:39:50.946Z" }, + { url = "https://files.pythonhosted.org/packages/78/a5/677330c1933a9e4f52690a9b2aa270339616e7b43a7d3adcd6cfe3b663a4/wcwidth-0.9.5-cp315-cp315t-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:9e658e25eb69291bcb25a0b90b5ea1472e6d5e025fb4862a02a47233714f7bdf", size = 833104, upload-time = "2026-11-21T21:39:52.303Z" }, + { url = "https://files.pythonhosted.org/packages/68/16/cdca25179f65cfdb3725eb1f9998e962c12d8f16cb50616f4d6b39233a44/wcwidth-0.9.5-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:435694fb059a1335d883388f2321e315be465d3e0f1849e50ad5548465ff46fd", size = 843268, upload-time = "2026-11-21T21:39:53.923Z" }, + { url = "https://files.pythonhosted.org/packages/71/09/26473868d053fdf58dcc13f5fe0e1e6c33f31ceae7622cf2c84cb7b06ded/wcwidth-0.9.5-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e44a4315c60a3707e4cabce9e73bdd50184be5cf829d3c334a8f35bf66a79b44", size = 841214, upload-time = "2026-11-21T21:39:55.49Z" }, + { url = "https://files.pythonhosted.org/packages/39/02/bf889aa122fedba5df5334d310127bdb1b1a89d88a55604af1e52b164279/wcwidth-0.9.5-cp315-cp315t-win32.whl", hash = "sha256:0e83dbb5d10874d3ace494358b6aa3b21b552359b1a553f3a37fef25705876f3", size = 619912, upload-time = "2026-11-21T21:39:57.069Z" }, + { url = "https://files.pythonhosted.org/packages/f7/fd/d6d3cd1ce0ed31eeeb406276d1497e066ed4ef0d553236acc6b439a0ed5c/wcwidth-0.9.5-cp315-cp315t-win_amd64.whl", hash = "sha256:1c28f4a21e8cb13fd31e9961a78e78c34c24ea5fe62309f8976cf592bb51946f", size = 625089, upload-time = "2026-11-21T21:39:58.955Z" }, + { url = "https://files.pythonhosted.org/packages/ad/c4/e8acf094f8026ef818f94b04e1562e7da53f2417323494cb67a9b2694689/wcwidth-0.9.5-cp315-cp315t-win_arm64.whl", hash = "sha256:ff9601ca3d5c3de3748c029c0e1c9c66e72115d0b31922b6707b024be61bd947", size = 623747, upload-time = "2026-11-21T21:40:00.794Z" }, + { url = "https://files.pythonhosted.org/packages/ca/77/61587cff9534a911b3116009f42de1edb2fa12bbb7c45ca92c4a415993f1/wcwidth-0.9.5-py3-none-any.whl", hash = "sha256:ef205150ff317032d633de2d8ca26d03dc8d5ba6a00294f6acfd1d0cfe1365d6", size = 329353, upload-time = "2026-11-21T21:40:02.438Z" }, +] + +[[package]] +name = "widgetsnbextension" +version = "4.0.16" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/60/bc7a980fc78837d6ef8f5940cca4cadc433364503a4c4d42e2a7a0de3231/widgetsnbextension-4.0.16.tar.gz", hash = "sha256:adeea0ae78f0856ee4945f413299801b82a0a01416303301f39a704282a37b73", size = 1111094, upload-time = "2026-08-18T08:52:55.859Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/34/95/40e17e20046b7bc820d29d09ae84ec157ec8dd6e6f6cd722626292c31b2e/widgetsnbextension-4.0.16-py3-none-any.whl", hash = "sha256:a31a8774885b96fe825462f5d6496166f0c7cae111195b6465c801d230eb5a4e", size = 2225148, upload-time = "2026-08-18T08:52:53.736Z" }, +] + +[[package]] +name = "zarr" +version = "2.18.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "asciitree" }, + { name = "fasteners", marker = "sys_platform != 'emscripten'" }, + { name = "numcodecs", version = "0.13.1", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/23/c4/187a21ce7cf7c8f00c060dd0e04c2a81139bb7b1ab178bba83f2e1134ce2/zarr-2.18.3.tar.gz", hash = "sha256:2580d8cb6dd84621771a10d31c4d777dca8a27706a1a89b29f42d2d37e2df5ce", size = 3603224, upload-time = "2024-09-04T23:20:16.595Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/c9/142095e654c2b97133ff71df60979422717b29738b08bc8a1709a5d5e0d0/zarr-2.18.3-py3-none-any.whl", hash = "sha256:b1f7dfd2496f436745cdd4c7bcf8d3b4bc1dceef5fdd0d589c87130d842496dd", size = 210723, upload-time = "2024-09-04T23:20:14.491Z" }, +] + +[[package]] +name = "zarr" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "numcodecs", version = "0.16.6", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/31/5a/b8a0cf39a14c770c30bd1f2d120c54000c8cd9e84e8e79f38d9a7ce58071/zarr-3.1.6.tar.gz", hash = "sha256:d95e72cbea4b90e9a70679468b8266400331756232576ae2b43400ac5108d0eb", size = 386531, upload-time = "2026-03-23T17:25:18.748Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/7c/ba8ca8cbe9dbef8e83a95fc208fed8e6686c98b4719aaa0aa7f3d31fe390/zarr-3.1.6-py3-none-any.whl", hash = "sha256:b5a82c5079d1c3d4ee8f06746fa3b9a98a7d804300fa3f4be154362a33e1207e", size = 295655, upload-time = "2026-03-23T17:25:17.189Z" }, +] + +[[package]] +name = "zarr" +version = "3.4.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "msgspec" }, + { name = "numcodecs", version = "0.17.1", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.5.5", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/cc/6667f7b90476aea8ee201f4f2f3bfec7d0032389b77afe02f0ed3d2e3d33/zarr-3.4.2.tar.gz", hash = "sha256:645d64f292f457120fc0ca18dbe38f665b4c21aaea38a2a88b5eead8f06f3d28", size = 943610, upload-time = "2026-10-27T15:31:09.825Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/19/56f6907c420c54c7c81a648a266bd047882515fd5182ad432d5e6ca2d545/zarr-3.4.2-py3-none-any.whl", hash = "sha256:a21530a931ac3123b4a4aa17146d11eb9ace227733650d5efbebbbfe38053428", size = 410801, upload-time = "2026-10-27T15:31:08.148Z" }, +] + +[[package]] +name = "zipp" +version = "4.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/05/ba1458dee0ac485b2a01071c1b88f5199fe878a485df482e10e1ef2205cc/zipp-4.1.2.tar.gz", hash = "sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f", size = 27864, upload-time = "2026-10-21T18:57:04.743Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/44/7bd2007260da11cccca29ba2d4c345f1287aa663db38ee7cefeabf6386a5/zipp-4.1.2-py3-none-any.whl", hash = "sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d", size = 10581, upload-time = "2026-10-21T18:57:03.79Z" }, +] From 708fea1cdf27406e0aa844798c3e9e8c874d404e Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Wed, 2 Dec 2026 15:14:10 -0800 Subject: [PATCH 02/14] update pyproject.toml with dependencies for testing --- pyproject.toml | 99 ++++++++++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 43 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ac73128a..9b80b3c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,14 +1,14 @@ [build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" +requires = ["hatchling"] +build-backend = "hatchling.build" [project] name = "giant-python" 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" @@ -39,52 +39,65 @@ 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.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 = 100 -[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` and -# `giant spine view`. -giant_python = ["assets/psfs/*.tif", "viewer/page.html", "spine/view/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"] +ignore-init-methods = true +ignore-init-module = true +exclude = ["docs", "build", ".conda", ".venv", "env"] fail-under = 100 From 99c0e315c117501efcfb562c8a659f5955699b70 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Wed, 2 Dec 2026 15:17:55 -0800 Subject: [PATCH 03/14] configure hatch build --- pyproject.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 9b80b3c2..23337438 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,8 @@ docs = [ [tool.uv.dependency-groups] docs = { requires-python = ">=3.12" } - +[tool.hatch.build.targets.wheel] +packages = ["src/giant_python"] [tool.pytest.ini_options] addopts = [ From 421be83ce25a65514e2d2fb90de158220c397016 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Wed, 2 Dec 2026 15:29:16 -0800 Subject: [PATCH 04/14] add hatch versioning --- .github/workflows/tests_and_format_check.yml | 2 +- pyproject.toml | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests_and_format_check.yml b/.github/workflows/tests_and_format_check.yml index 4cdf9cb1..77864d54 100644 --- a/.github/workflows/tests_and_format_check.yml +++ b/.github/workflows/tests_and_format_check.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] + python-version: ["3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v6 diff --git a/pyproject.toml b/pyproject.toml index 23337438..a385328a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["hatchling"] +requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] @@ -51,6 +51,10 @@ docs = [ [tool.uv.dependency-groups] docs = { requires-python = ">=3.12" } +[tool.hatch.version] +source = "vcs" +fallback-version = "0.0.0" + [tool.hatch.build.targets.wheel] packages = ["src/giant_python"] From c5be8e3835d266f635363d74a4ee08751410b4f4 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Wed, 2 Dec 2026 15:36:01 -0800 Subject: [PATCH 05/14] allow direct references for the slap2_utils library --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index a385328a..51d74786 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,6 +55,9 @@ docs = { requires-python = ">=3.12" } source = "vcs" fallback-version = "0.0.0" +[tool.hatch.metadata] +allow-direct-references = true + [tool.hatch.build.targets.wheel] packages = ["src/giant_python"] From d9639a8bfd5d13189940301da5602ca5fbd5d87e Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 10:13:21 -0800 Subject: [PATCH 06/14] ruff fixes and docstring fixes --- pyproject.toml | 2 +- src/giant_python/cli_silo.py | 28 +- src/giant_python/export/f0_events.py | 30 +- src/giant_python/export/f0_injected.py | 78 +- src/giant_python/export/f0_layout.py | 57 +- src/giant_python/export/f0_mask.py | 26 +- src/giant_python/export/f0_qc.py | 108 +- src/giant_python/export/f0_training.py | 203 ++-- .../extraction/band/background.py | 2 +- src/giant_python/extraction/band/rois.py | 2 +- src/giant_python/extraction/band/traces.py | 2 +- src/giant_python/extraction/band/transient.py | 2 +- src/giant_python/extraction/band/workflow.py | 3 +- .../extraction/raster/__init__.py | 8 +- .../extraction/raster/alignment.py | 186 ++-- .../extraction/raster/annotations.py | 21 +- .../extraction/raster/baseline_map.py | 13 +- .../extraction/raster/container.py | 6 +- .../extraction/raster/kinetics.py | 9 +- .../extraction/raster/localization.py | 12 +- src/giant_python/extraction/raster/null.py | 37 +- src/giant_python/extraction/raster/peaks.py | 61 +- src/giant_python/extraction/raster/plan.py | 82 +- .../extraction/raster/refit_test.py | 36 +- src/giant_python/extraction/raster/results.py | 35 +- src/giant_python/extraction/raster/seeding.py | 25 +- src/giant_python/extraction/raster/solver.py | 20 +- .../extraction/raster/solver_baseline.py | 20 +- .../extraction/raster/solver_fits.py | 20 +- .../extraction/raster/solver_setup.py | 25 +- src/giant_python/extraction/raster/spots.py | 60 +- .../extraction/raster/stage_files.py | 17 +- src/giant_python/extraction/raster/summary.py | 90 +- src/giant_python/extraction/raster/trial.py | 12 +- .../extraction/raster/trial_data.py | 87 +- src/giant_python/gui/parameters_gui.py | 4 +- src/giant_python/gui/roi_editor.py | 2 +- src/giant_python/io/experiment_summary.py | 49 +- src/giant_python/io/hdf5.py | 2 +- src/giant_python/io/slap2.py | 8 +- src/giant_python/io/slap2_raster.py | 6 +- src/giant_python/models/experiment_summary.py | 14 +- src/giant_python/models/params.py | 59 +- src/giant_python/numerics/peaks.py | 2 +- src/giant_python/pipeline/reg_stats.py | 57 +- src/giant_python/pipeline/silo.py | 270 +++-- src/giant_python/pipeline/silo_baseline.py | 69 +- src/giant_python/pipeline/silo_collect.py | 49 +- src/giant_python/pipeline/silo_session.py | 62 +- src/giant_python/pipeline/silo_solve.py | 62 +- src/giant_python/pipeline/silo_spots.py | 131 ++- src/giant_python/pipeline/trial_table.py | 16 +- src/giant_python/registration/compensation.py | 6 +- src/giant_python/registration/frames.py | 12 +- src/giant_python/registration/growth.py | 32 +- src/giant_python/registration/multiroi.py | 30 +- src/giant_python/registration/outputs.py | 18 +- src/giant_python/registration/sources.py | 27 +- .../registration/stats/__init__.py | 2 +- .../registration/stats/accumulate.py | 88 +- src/giant_python/registration/stats/gain.py | 34 +- .../registration/stats/geometry.py | 91 +- src/giant_python/registration/stats/io.py | 12 +- src/giant_python/registration/stats/maps.py | 18 +- .../registration/stats/session.py | 20 +- src/giant_python/registration/stats/svd.py | 22 +- src/giant_python/registration/stats/worker.py | 38 +- src/giant_python/registration/template.py | 2 +- src/giant_python/simulation/injection.py | 60 +- src/giant_python/simulation/render.py | 4 +- src/giant_python/spine/coverage.py | 17 +- src/giant_python/spine/gains.py | 60 +- src/giant_python/spine/images.py | 18 +- src/giant_python/spine/pipeline.py | 111 ++- src/giant_python/spine/product.py | 23 +- src/giant_python/spine/qc.py | 20 +- src/giant_python/spine/rois.py | 25 +- src/giant_python/spine/summary_io.py | 90 +- src/giant_python/spine/trends.py | 86 +- src/giant_python/spine/view/__init__.py | 9 +- src/giant_python/spine/view/data.py | 138 ++- src/giant_python/spine/view/export.py | 56 +- src/giant_python/spine/view/server.py | 57 +- src/giant_python/viewer/render.py | 24 +- src/giant_python/viewer/run.py | 53 +- src/giant_python/viewer/server.py | 36 +- src/giant_python/viewer/trial.py | 80 +- tests/export/test_f0_injected.py | 150 +-- tests/export/test_f0_layout.py | 188 ++-- tests/export/test_f0_training.py | 275 ++++-- tests/raster/alignment_synthetic.py | 31 +- tests/raster/test_raster_alignment.py | 131 ++- tests/raster/test_raster_alignment_modes.py | 108 +- tests/raster/test_raster_annotations.py | 39 +- tests/raster/test_raster_baseline_map.py | 62 +- tests/raster/test_raster_container.py | 35 +- tests/raster/test_raster_f0_images.py | 104 +- tests/raster/test_raster_kinetics.py | 26 +- tests/raster/test_raster_localization.py | 62 +- tests/raster/test_raster_null.py | 151 +-- tests/raster/test_raster_peaks.py | 85 +- tests/raster/test_raster_plan.py | 163 +-- tests/raster/test_raster_refit.py | 65 +- tests/raster/test_raster_results.py | 38 +- tests/raster/test_raster_seed_acceptance.py | 152 +-- tests/raster/test_raster_seeding.py | 41 +- tests/raster/test_raster_silo_alignment.py | 78 +- tests/raster/test_raster_silo_load_ahead.py | 88 +- tests/raster/test_raster_silo_network.py | 259 +++-- tests/raster/test_raster_silo_noise_seeds.py | 16 +- tests/raster/test_raster_silo_params.py | 78 +- tests/raster/test_raster_silo_stages.py | 118 ++- tests/raster/test_raster_solver.py | 160 +-- tests/raster/test_raster_solver_baseline.py | 150 +-- .../test_raster_solver_baseline_modes.py | 143 +-- tests/raster/test_raster_solver_fits.py | 90 +- tests/raster/test_raster_solver_setup.py | 80 +- tests/raster/test_raster_spots.py | 100 +- tests/raster/test_raster_stage_files.py | 14 +- tests/raster/test_raster_summary.py | 80 +- tests/raster/test_raster_summary_model.py | 91 +- tests/raster/test_raster_trial.py | 84 +- tests/raster/test_raster_trial_data.py | 221 +++-- tests/registration/test_cli.py | 15 +- tests/registration/test_compensation.py | 12 +- tests/registration/test_curtain.py | 81 +- tests/registration/test_growth.py | 40 +- tests/registration/test_kernels.py | 25 +- tests/registration/test_reg_stats.py | 191 ++-- tests/registration/test_synthetic.py | 103 +- tests/simulation/test_injection.py | 272 +++-- tests/spine/synthetic.py | 39 +- tests/spine/test_spine_coverage.py | 115 ++- tests/spine/test_spine_gains.py | 62 +- tests/spine/test_spine_images.py | 46 +- tests/spine/test_spine_pipeline.py | 193 ++-- tests/spine/test_spine_qc.py | 60 +- tests/spine/test_spine_readout.py | 39 +- tests/spine/test_spine_trends.py | 141 +-- tests/spine/test_spine_view.py | 244 +++-- tests/trial_table/test_build_slap2.py | 123 ++- tests/viewer/synthetic.py | 21 +- tests/viewer/test_viewer_render.py | 90 +- tests/viewer/test_viewer_server.py | 12 +- uv.lock | 929 ++++++++---------- 145 files changed, 6038 insertions(+), 4277 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 51d74786..28bbc571 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,4 +108,4 @@ docstring-code-format = true ignore-init-methods = true ignore-init-module = true exclude = ["docs", "build", ".conda", ".venv", "env"] -fail-under = 100 +fail-under = 100 \ No newline at end of file diff --git a/src/giant_python/cli_silo.py b/src/giant_python/cli_silo.py index 008d844b..f706e505 100644 --- a/src/giant_python/cli_silo.py +++ b/src/giant_python/cli_silo.py @@ -192,7 +192,7 @@ def _add_science(parser: argparse.ArgumentParser) -> None: def _add_session(parser: argparse.ArgumentParser) -> None: - """The trial table and folder overrides.""" + """Add the trial table and folder overrides.""" parser.add_argument( "trial_table", help="trial_table.h5 (or the folder holding it)." ) @@ -224,9 +224,11 @@ 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 options. + + Their folder and, if ``predict``, the prediction of missing ones. + """ g = parser.add_argument_group("the F0 network's baselines") g.add_argument( "--baseline-dir", @@ -267,8 +269,10 @@ def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool): def _add_execution( parser: argparse.ArgumentParser, solver: bool, fits: bool = True ) -> None: - """How to run (SiloExecution); ``fits``: the solver's device, - precision and batches (a job file brings its own).""" + """Add parameters to run SiloExecution. + + ``fits``: the solver's device, precision and batches (a job file brings its own). + """ d = SiloExecution g = parser.add_argument_group("execution (results do not depend on it)") g.add_argument( @@ -338,7 +342,7 @@ def _add_execution( def add_silo_commands(subparsers) -> None: - """Add ``silo`` and the staged commands to ``giant``'s subparsers.""" + """Add SILo and the staged commands for the GIAnT subparsers.""" run = subparsers.add_parser( "silo", help="SILo source extraction of SLAP2 raster recordings on one " @@ -464,7 +468,7 @@ def add_silo_commands(subparsers) -> None: def _add_units(parser: argparse.ArgumentParser) -> None: - """Selection of trial-paths.""" + """Add the selection of trial-paths.""" parser.add_argument( "--paths", default=None, help="Paths, e.g. 1,2 (default: all)." ) @@ -476,7 +480,7 @@ def _add_units(parser: argparse.ArgumentParser) -> None: def _value(text: str): - """A ``--set`` value: JSON if it parses, else the text.""" + """Parse a parameter value as JSON, otherwise return the text.""" try: return json.loads(text) except ValueError: @@ -556,8 +560,10 @@ def execution_from_args(args: argparse.Namespace) -> SiloExecution: 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).""" + """Open the session of the command's trial table and folders. + + Dispatch and collect need neither registered movies nor raw data. + """ from .pipeline.silo_session import SiloSession inputs = ( diff --git a/src/giant_python/export/f0_events.py b/src/giant_python/export/f0_events.py index b59a35c0..0f03005d 100644 --- a/src/giant_python/export/f0_events.py +++ b/src/giant_python/export/f0_events.py @@ -38,8 +38,10 @@ def events(den: np.ndarray, threshold: float, keep: np.ndarray): - """``(starts, ends)`` (end exclusive) of the runs of kept frames where - ``den`` exceeds ``threshold``.""" + """Find the runs of kept frames where ``den`` exceeds ``threshold``. + + Return them as ``(starts, ends)`` (end exclusive). + """ on = np.isfinite(den) & (den > threshold) & keep if not on.any(): return np.zeros(0, np.int64), np.zeros(0, np.int64) @@ -48,8 +50,10 @@ def events(den: np.ndarray, threshold: float, keep: np.ndarray): 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).""" + """Peak of ``dF_denoised`` in each event, raw and as dF/F. + + The dF/F size is the peak over ``F0`` at the peak. + """ raw, dff = [], [] for a, b in zip(starts, ends): k = a + int(np.nanargmax(den[a:b])) @@ -77,13 +81,15 @@ def _quantiles(x: np.ndarray) -> dict: 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 + """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 frames (local to the trial) and its observed frames (bool, kept frames - with a finite trace).""" + with a finite trace). + """ hits, tot, expect = 0, 0, 0.0 w = 2 * int(window) + 1 for starts, observed in trials: @@ -126,11 +132,13 @@ 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 + """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. + """ p = run.path(d) hz = float(run.param("analyzeHz", 200.0) or 200.0) out = { diff --git a/src/giant_python/export/f0_injected.py b/src/giant_python/export/f0_injected.py index 36c820d2..d083af0a 100644 --- a/src/giant_python/export/f0_injected.py +++ b/src/giant_python/export/f0_injected.py @@ -1,5 +1,7 @@ -"""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 @@ -66,8 +68,7 @@ def _injection_settings(truth: dict): - """The truth's :class:`~giant_python.simulation.injection. - InjectionSettings`.""" + """Build the truth's :class:`~giant_python.simulation.injection.InjectionSettings`.""" from ..simulation import injection as inj return inj.InjectionSettings( @@ -79,9 +80,11 @@ def _injection_settings(truth: dict): 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.""" + """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. + """ from ..simulation import injection as inj out = [] @@ -107,8 +110,11 @@ def injected_footprints(truth_path: dict, need_model: bool): 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 the registration's frame kernel in lines. + + The kernel is ``ceil(line rate / alignHz)`` + (:func:`giant_python.registration.multiroi.open_trial`). + """ return int(math.ceil((1.0 / layout.line_period_s) / float(align_hz))) @@ -125,15 +131,17 @@ def injected_frames( 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 + """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.""" + kernel in lines. + """ from ..io.slap2_raster import ( INVALID_SAMPLE, raster_layout, @@ -229,9 +237,11 @@ def injected_frames( 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).""" + """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. + """ import h5py with h5py.File(alignment_file, "r") as f: @@ -250,9 +260,11 @@ 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).""" + """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). + """ pos = np.asarray(pos, np.float64).reshape(-1, 2) off = np.asarray(truth_path["peak_pixel_rc"], np.float64).reshape( -1, 2 @@ -362,9 +374,11 @@ def _export_trial(job, truth, settings, t_orig, device, expected): 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.""" +def _reconcile(out_dir: Path, d: int, present, summary, label, log) -> 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 @@ -379,8 +393,11 @@ 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).""" + """One trial's record. + + The record has ``error`` instead when the trial was not exported; a + failed trial loses its earlier file. + """ t0 = time.time() try: q = _export_trial(job, truth, settings, t_orig, device, expected) @@ -394,8 +411,10 @@ def _run_trial(job, truth, settings, t_orig, device, expected) -> dict: 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.""" + """Return the copy's paths and trial columns to export, each once. + + Refuses numbers the copy does not have. + """ paths = sorted(int(d) for d in truth["paths"]) if options.paths: bad = sorted(set(options.paths) - set(paths)) @@ -419,8 +438,9 @@ def export_injected( expected: bool = False, log=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 ---------- diff --git a/src/giant_python/export/f0_layout.py b/src/giant_python/export/f0_layout.py index 017dadec..6f894a48 100644 --- a/src/giant_python/export/f0_layout.py +++ b/src/giant_python/export/f0_layout.py @@ -191,7 +191,7 @@ def sharing_slots(layout) -> tuple: def layout_path(movie_path: Union[str, Path]) -> Path: - """The layout file of a registered movie. + """Return the layout file of a registered movie. ``_REGISTERED_DOWNSAMPLED-80Hz.h5`` (or ``.tif``) gives ``_F0LAYOUT.h5`` in the same folder; any other name @@ -339,8 +339,10 @@ def pulse_statistics(samples, nxt: np.ndarray, line_end=None) -> dict: dev = samples.device def rows(ch, idx): - """Samples of slots ``idx`` (zeros and valid where ``idx`` is -1: - no neighbour on the line).""" + """Return the samples of slots ``idx``. + + Zeros and valid where ``idx`` is -1: no neighbour on the line. + """ 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) @@ -403,7 +405,7 @@ def rows(ch, idx): 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 @@ -437,8 +439,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 @@ -454,8 +458,10 @@ def _keep_bursts(out: dict, ch: int, found: list) -> None: 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.""" + """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()) @@ -500,9 +506,10 @@ def per_stratum(values): 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. + """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 @@ -607,8 +614,9 @@ def burst_statistics(samples, nxt: np.ndarray) -> dict: 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. + """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 @@ -655,14 +663,13 @@ 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 ) -> 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 @@ -768,7 +775,7 @@ def trial_layout( settings: Optional[dict] = 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 ---------- @@ -795,10 +802,10 @@ 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) @@ -970,7 +977,7 @@ def read_layout(path: Union[str, Path]) -> dict: for k, v in f.attrs.items() } - def visit(name, obj): + def visit(name, obj) -> None: """Collect every dataset.""" if isinstance(obj, h5py.Dataset): out[name] = obj[()] @@ -995,7 +1002,7 @@ 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 ) -> 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`` diff --git a/src/giant_python/export/f0_mask.py b/src/giant_python/export/f0_mask.py index 80dd1eb7..d1dfd8c2 100644 --- a/src/giant_python/export/f0_mask.py +++ b/src/giant_python/export/f0_mask.py @@ -1,5 +1,7 @@ -"""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 @@ -77,7 +79,7 @@ def check(self) -> None: 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.""" return { "activityMaskK": float(self.k), "activityMaskMarginPx": float(self.margin_px), @@ -97,15 +99,18 @@ def robust_sd(x: np.ndarray) -> float: 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).""" + """Each source's noise. + + The robust SD of ``dF_ls - dF_denoised`` over the kept 200 Hz frames of + the path (``(frames, sources)`` inputs). + """ 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.""" + """Find the nearest 80 Hz frame of each 200 Hz frame line.""" ds = np.asarray(ds_lines, np.float64) x = np.asarray(lines200, np.float64) if ds.size == 1: @@ -118,7 +123,7 @@ def nearest_frames(ds_lines, lines200) -> np.ndarray: def temporal_mask( den, sigma, lines200, discard200, ds_lines, rule: MaskRule, tau200 ) -> np.ndarray: - """``(sources, frames80)`` bool: each source's masked 80 Hz frames. + """Mask each source's 80 Hz frames, ``(sources, frames80)`` bool. Parameters ---------- @@ -161,7 +166,7 @@ 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.""" n = int(np.ceil(r)) y, x = np.mgrid[-n : n + 1, -n : n + 1] return (x * x + y * y) <= r * r + 1e-9 @@ -176,8 +181,9 @@ def activity_mask( spots_rc: Optional[np.ndarray] = 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 ---------- diff --git a/src/giant_python/export/f0_qc.py b/src/giant_python/export/f0_qc.py index 3487fd94..031b639c 100644 --- a/src/giant_python/export/f0_qc.py +++ b/src/giant_python/export/f0_qc.py @@ -1,5 +1,6 @@ -"""Quality values of an F0 training trial: how the rendered activity -compares with the movie. +"""Quality values of an F0 training trial. + +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 @@ -51,23 +52,29 @@ 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. + """ 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. + """ 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. + """ ok = np.isfinite(yh) & np.isfinite(ah) if ok.sum() <= min_frames or np.std(ah[ok]) == 0: return np.nan @@ -75,8 +82,11 @@ def _corr(yh: np.ndarray, ah: np.ndarray, min_frames: int = 100) -> float: 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).""" + """Each source's peak pixel. + + The flat index of its largest footprint value; -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]): @@ -87,10 +97,12 @@ def peak_pixels(H) -> np.ndarray: 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).""" + """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). + """ n = pk.size sl, r = np.full(n, np.nan), np.full(n, np.nan) ok = pk >= 0 @@ -104,9 +116,11 @@ def peak_fit(H, X: np.ndarray, Y: np.ndarray, pk: np.ndarray): 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).""" + """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. + """ 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] @@ -119,9 +133,11 @@ def _flux_fit(H, X, Y, idx): 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``).""" + """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``). + """ 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) @@ -134,11 +150,14 @@ def disk_fit(H, X, Y, pk, shape, radius: float = 4.0): 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.""" + """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. + """ R, C = valid.shape dr, dc = np.mgrid[-3:4, -3:4] d = np.hypot(dr, dc).ravel() @@ -162,8 +181,10 @@ 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. + """ thr = matlab_prctile(x, 99) m = x[1:-1] ev = np.flatnonzero((m > thr) & (m >= x[:-2]) & (m > x[2:])) + 1 @@ -171,10 +192,12 @@ def _events(x: np.ndarray) -> np.ndarray: 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)``.""" + """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)``. + """ eta_y, eta_r, n_ev = np.zeros(25), np.zeros(25), 0 ok = np.flatnonzero(pk >= 0) if ok.size == 0: @@ -197,8 +220,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 +237,11 @@ 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. + """ filled = np.nan_to_num(sel, nan=np.nanmedian(sel)) sel = sel - median_filter(filled, size=81, mode="nearest") thr = np.nanpercentile(sel, 99) @@ -229,9 +257,11 @@ 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).""" + """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). + """ rows, cols, dist = box v = valid[rows, cols] ring = v & (dist >= 3) & (dist <= 5) @@ -269,7 +299,7 @@ def ring_event_ratios( 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 ---------- diff --git a/src/giant_python/export/f0_training.py b/src/giant_python/export/f0_training.py index c97058b3..4a250bad 100644 --- a/src/giant_python/export/f0_training.py +++ b/src/giant_python/export/f0_training.py @@ -202,8 +202,10 @@ def _settings(run: SiloRun) -> dict: 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. + + MATLAB's orientation; channels interleaved by frame. + """ path = Path(path) if path.suffix == ".h5": with h5py.File(path, "r") as f: @@ -218,8 +220,10 @@ def read_stack(path: Path, num_channels: int) -> np.ndarray: def _vec(f, name: str, n: Optional[int] = None): - """A dataset of the alignment file as a flat float64 vector (None if - missing).""" + """Read a dataset of the alignment file as a flat float64 vector. + + None if missing. + """ if name not in f: return None v = np.asarray(f[name][()], np.float64).ravel() @@ -227,7 +231,7 @@ 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.""" with h5py.File(path, "r") as f: out = { "ds_lines": _vec(f, "DSframes", n_frames), @@ -249,8 +253,11 @@ def read_alignment(path: Path, n_frames: int) -> dict: def read_varfac(path: Path, crop: tuple, mode: str) -> Optional[np.ndarray]: - """``slap2/varFacDS`` in the crop: per-pixel mean ``(rows, cols)`` or - every frame ``(frames, rows, cols)``; None without it.""" + """``slap2/varFacDS`` in the crop. + + Per-pixel mean ``(rows, cols)`` or every frame ``(frames, rows, cols)``; + None without it. + """ r0, r1, c0, c1 = crop with h5py.File(path, "r") as f: if "slap2/varFacDS" not in f: @@ -272,10 +279,12 @@ def read_varfac(path: Path, crop: tuple, mode: str) -> Optional[np.ndarray]: 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 + """Labeled pixels: the 3 x 3 median-filtered mean image above 3 x its 25th percentile. + + The filter uses zero padding, as MATLAB's ``medfilt2``; for a dim trial where nearly every valid pixel would count, the percentile over the - valid pixels instead.""" + valid pixels instead. + """ nan = np.isnan(mean_act) mf = median_filter(np.where(nan, np.inf, mean_act), 3, mode="constant") mf[~np.isfinite(mf)] = np.nan @@ -293,8 +302,10 @@ def _nanmedian(x) -> float: def _crop_box(valid: np.ndarray) -> tuple: - """``(r0, r1, c0, c1)`` (end exclusive) of the box around the valid - pixels.""" + """``(r0, r1, c0, c1)`` of the box around the valid pixels. + + End exclusive. + """ rows = np.flatnonzero(valid.any(1)) cols = np.flatnonzero(valid.any(0)) if rows.size == 0: @@ -303,8 +314,11 @@ def _crop_box(valid: np.ndarray) -> tuple: 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.""" + """Render the trial's footprints in its frame and the sources' 80 Hz traces. + + The traces are per SILo channel; also the 80 Hz discard share and the + kernel's record. + """ 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]): @@ -362,8 +376,10 @@ def _render(job: TrialJob, ds_lines, shape): def _qc(job, H, Xa, Y, valid, crop, discard): - """The QC values of the activity as written (see - :mod:`~giant_python.export.f0_qc`).""" + """Compute the QC values of the activity as written. + + See :mod:`~giant_python.export.f0_qc`. + """ shape = valid.shape pk = f0_qc.peak_pixels(H) sl, r = f0_qc.peak_fit(H, Xa, Y, pk) @@ -401,9 +417,11 @@ 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).""" + """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. + """ r0, r1, c0, c1 = crop R, C = valid.shape cc = c1 - c0 @@ -457,14 +475,18 @@ 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).""" + """Chunks of a (channel, frame, row, col) array, as the MATLAB exporter's. + + One channel, 256 frames, 64 x 64 px. + """ 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.""" + """Load the movie stack and its alignment record. + + Also the motion discards and the valid pixels. + """ st = job.settings stack = read_stack(job.movie_file, st["num_channels"]) T = stack.shape[0] @@ -482,9 +504,11 @@ def _load(job: TrialJob): 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).""" + """Compute the written channels' activity in the crop. + + ``(channels, frames, rows, cols)`` float32, computed at the footprint + pixels (zero elsewhere). + """ r0, r1, c0, c1 = crop C = shape[1] out = np.zeros((len(chans), T, r1 - r0, c1 - c0), np.float32) @@ -503,8 +527,10 @@ 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) @@ -529,7 +555,7 @@ def _write(job: TrialJob, arrays: dict, attrs: dict) -> None: def _provenance(job: TrialJob) -> dict: - """String attributes naming the run, the baseline and the exporter.""" + """Build string attributes naming the run, the baseline and the exporter.""" p = job.provenance return { "label": p.get("label", ""), @@ -545,15 +571,17 @@ def _provenance(job: TrialJob) -> dict: def _attr_value(v): - """An HDF5 attribute value (lists as float64 arrays).""" + """Convert to an HDF5 attribute value (lists as float64 arrays).""" 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``.""" + """Compute the map's mean offset (trial minus canvas) over the footprint pixels. + + The counterpart of the MATLAB exporter's searched ``shiftRC``. + """ if job.tmap is None or job.footprints is None: return [np.nan, np.nan] r = np.asarray(job.footprints[0], float) @@ -572,7 +600,7 @@ def _support(H, shape) -> np.ndarray: def _frame_arrays(al: dict, disc, Y, valid) -> dict: - """The per-frame datasets.""" + """Build the per-frame datasets.""" out = {"frame/discard": disc.astype(np.uint8)} for key in ("motion_row", "motion_col", "rec_neg_err"): if al[key] is not None: @@ -587,11 +615,13 @@ 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 - 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).""" + """With the trial's network baseline: the training target's time-mean over the baseline's. + + 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). + """ out = { "targetOverBaselineSupport": np.nan, "targetOverBaselineLabeled": np.nan, @@ -675,17 +705,21 @@ 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).""" + """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). + """ 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``).""" + """Build the trial's summary record. + + Also its attributes, without ``file``. + """ o, st = job.options, job.settings r0, r1, c0, c1 = crop ach = st["activity_channel"] @@ -722,7 +756,7 @@ 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`.""" o, st = job.options, job.settings stack, al, disc, valid = _load(job) T, _, R, C = stack.shape @@ -756,9 +790,11 @@ def _export_trial(job: TrialJob) -> dict: 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.""" + """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. + """ rule = job.options.activity_mask T = disc.size tm = None @@ -818,8 +854,10 @@ 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 its summary record. + + ``error`` instead when it could not be exported. + """ t0 = time.time() try: q = _export_trial(job) @@ -855,10 +893,12 @@ def _network_records(run: SiloRun) -> dict: 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 - not have. A repeated selector would have two workers write the same - file.""" + """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. + """ 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: @@ -881,9 +921,11 @@ 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 files of path ``d`` that a default export does not write. + + The earlier ``trial_.h5`` files of a trial SILo no longer analyses: + the reader finds files, not summaries. Returns their names. + """ keep = {Path(j.out_file).name for j in jobs} removed = [] folder = Path(out_dir) / f"Path{d}" @@ -897,8 +939,11 @@ def _remove_unscheduled(out_dir: Path, d: int, jobs: list) -> list: 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).""" + """Build the trial jobs of one path. + + ``trials``: one-based, checked by :func:`_selection`; ``None``: the + trials SILo analysed. + """ p = run.path(d) st = _settings(run) n = 0 if options.ignore_sources else p.sources.n @@ -958,12 +1003,14 @@ def _path_jobs(run, session, d, out_dir, options, prov, trials=None) -> list: def _mask_inputs(run, p, st, x) -> dict: - """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 - without a source (kinetics-rejected sources and the plan's unused - seeds).""" + """Gather 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 without a source (kinetics-rejected sources and the + plan's unused seeds). + """ out = {"sigma": None, "spots": np.zeros((0, 2))} hz = float(run.param("analyzeHz", 200.0) or 200.0) tau = run.param("tau_full", None) @@ -988,8 +1035,10 @@ def _mask_inputs(run, p, st, x) -> dict: def _ls_trace(run, d: int, c: int) -> Optional[np.ndarray]: - """``dF_ls`` of path ``d``, channel index ``c``, ``(frames, - sources)`` (None without it).""" + """``dF_ls`` of path ``d``, channel index ``c``, ``(frames, sources)``. + + None without it. + """ with h5py.File(run.experiment, "r") as f: key = f"Path{d}/sources/temporal/dF_ls" if key not in f: @@ -1012,8 +1061,10 @@ def _json_safe(v): def write_summary(out_dir: Path, summary: dict) -> None: - """``export_summary.json`` (NaN written as null, as MATLAB's - ``jsonencode``).""" + """``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)) @@ -1103,8 +1154,10 @@ def export_run( 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`).""" + """``event_statistics.json``: per path, SILo's event statistics. + + See :func:`~giant_python.export.f0_events.path_statistics`. + """ stats = { "label": label, "giantRef": options.giant_ref, @@ -1123,9 +1176,11 @@ 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 - removes its earlier file, so an option every trial would trip on - must not get that far.""" + """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. + """ if o.kernel not in ("exact", "matched", "exporter"): raise ValueError(f"unknown kernel {o.kernel!r}") if o.interp not in INTERP_ORDER: @@ -1183,7 +1238,7 @@ 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.""" for d in (run_dir, *run_dir.parents): if (d / "trial_table.h5").exists(): return d / "trial_table.h5" diff --git a/src/giant_python/extraction/band/background.py b/src/giant_python/extraction/band/background.py index cb1cdaf0..bf45d3bd 100644 --- a/src/giant_python/extraction/band/background.py +++ b/src/giant_python/extraction/band/background.py @@ -57,7 +57,7 @@ def _interp_columns( # noqa: C901 dtype, method="linear", spline_weight_cache=None, -): +) -> None: """Interpolate each multi-point column onto its selected pixels. Selected rows that coincide with a reference row are copied exactly; those diff --git a/src/giant_python/extraction/band/rois.py b/src/giant_python/extraction/band/rois.py index 849e3fea..91fcf72e 100644 --- a/src/giant_python/extraction/band/rois.py +++ b/src/giant_python/extraction/band/rois.py @@ -82,7 +82,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"]) diff --git a/src/giant_python/extraction/band/traces.py b/src/giant_python/extraction/band/traces.py index a5830a26..ac673966 100644 --- a/src/giant_python/extraction/band/traces.py +++ b/src/giant_python/extraction/band/traces.py @@ -231,7 +231,7 @@ def _backproject(x: torch.Tensor, data: torch.Tensor) -> torch.Tensor: def _validate_transient_settings( transient_options, simple_trace_extraction, analyze_hz -): +) -> None: """Validate mutually exclusive trace modes and the transient grid rate.""" if transient_options is not None: if simple_trace_extraction: diff --git a/src/giant_python/extraction/band/transient.py b/src/giant_python/extraction/band/transient.py index 4b9c9213..e8125b08 100644 --- a/src/giant_python/extraction/band/transient.py +++ b/src/giant_python/extraction/band/transient.py @@ -62,7 +62,7 @@ class TransientResult: class TransientOperator: """Causal convolution and exact adjoint without a dense temporal matrix.""" - def __init__(self, analyze_hz, tau_s, kernel=None): + def __init__(self, analyze_hz, tau_s, kernel=None) -> None: """Use a unit-peak exponential or a nonnegative causal kernel.""" _positive("analyze_hz", analyze_hz) _positive("tau_s", tau_s) diff --git a/src/giant_python/extraction/band/workflow.py b/src/giant_python/extraction/band/workflow.py index 1c0f8f03..2421078a 100644 --- a/src/giant_python/extraction/band/workflow.py +++ b/src/giant_python/extraction/band/workflow.py @@ -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 ( 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 3597dda7..c40119a6 100644 --- a/src/giant_python/extraction/raster/alignment.py +++ b/src/giant_python/extraction/raster/alignment.py @@ -111,8 +111,10 @@ 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.""" + """Weights of Keys' cubic convolution (a = -1/2) at offsets -1, 0, 1, 2. + + The offsets are from the grid point below a query, ``s`` its distance from it. + """ s2 = s * s s3 = s2 * s return ( @@ -186,28 +188,37 @@ def __call__(self, rows, cols) -> np.ndarray: def interp2_cubic(im: np.ndarray, rows, cols) -> np.ndarray: - """MATLAB ``interp2(im, cols, rows, 'cubic')`` at zero-based points (see - :class:`CubicInterpolant`).""" + """MATLAB ``interp2(im, cols, rows, 'cubic')`` at zero-based points. + + See :class:`CubicInterpolant`. + """ return CubicInterpolant(im)(rows, cols) 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.""" + """MATLAB's ``[gc, gr] = gradient(im)`` as ``(gr, gc)``. + + Central differences inside, one-sided at the edges, NaN carried. + """ 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).""" + """Rows and columns of a mask's pixels in MATLAB's ``find`` order. + + The order is column by column. + """ 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).""" + """``sqrt(max(M, 0))`` with NaN kept. + + Roughly variance-stabilized for shot noise; unscanned pixels stay NaN, not + sharp zero edges. + """ m = np.asarray(m, dtype=np.float64) with np.errstate(invalid="ignore"): s = np.sqrt(np.fmax(m, 0.0)) @@ -216,8 +227,10 @@ 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).""" + """Index of MATLAB's ``max``. + + The first largest value, NaN ignored (the first element when all are NaN). + """ if np.isnan(values).all(): return 0 return int(np.nanargmax(values)) @@ -240,7 +253,7 @@ 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``. + """Yield 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 @@ -396,7 +409,7 @@ 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. + """Make a template that most of the given images agree with. Port of ``makeConsensusTemplate.m``. Every pair of images is registered (:func:`xcorr2_nans`, twice: around zero, then around the rounded @@ -504,8 +517,10 @@ def __post_init__(self) -> None: @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).""" + """Build the rigid warp of per-trial shifts ``(trials, 2)``. + + NaN rows are for trials that were not aligned. + """ 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]) @@ -565,14 +580,16 @@ 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.""" + """Whether the trial's map is a shift (no affine or patchwise part). + + A shift is what extraction can add to the trial's motion. + """ 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`.""" if not self.is_shift(trial): raise ValueError(f"the map of trial {trial} is not a shift") return self.affine[trial, :, 2].copy() @@ -729,8 +746,10 @@ def one(plane): 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.""" + """Resample an image through one affine map (``warpImageAffine.m``). + + ``out[x] = im[a @ [x, 1]]``, zero-based, NaN outside or next to NaN. + """ return warp_trial_image(im, TrialWarp(np.asarray(a)[None]), 0, method) @@ -814,8 +833,10 @@ 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).""" + """Pick the kept trials the template is made from. + + Up to ``n_samples``, evenly spaced (``round(linspace(1, n, n_samples))``, unique). + """ kept = np.flatnonzero(keep) pick = matlab_round(np.linspace(1, kept.size, n_samples)).astype(int) return kept[np.unique(pick) - 1] @@ -901,8 +922,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 ---------- @@ -941,8 +961,10 @@ def _nanmean0(stack: np.ndarray) -> np.ndarray: 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.""" + """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] ) @@ -959,9 +981,12 @@ def _corr(a: np.ndarray, b: np.ndarray) -> float: 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``).""" + """Forward-additive Gauss-Newton refinement of an affine map. + + 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``). + """ max_iter, tol = 50, 1e-3 # tol: pixels, largest displacement change r, c = _colmajor_nonzero(~np.isnan(template)) if r.size < 500: @@ -1010,8 +1035,10 @@ def _refine_affine(s, template, 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.""" + """Right-multiply every map so that the trials' mean linear part is the identity. + + The mean mapping of ``x0`` is unchanged. + """ a_bar = tforms[trials].mean(axis=0) l_inv = np.linalg.inv(a_bar[:, :2]) b = np.eye(3) @@ -1084,8 +1111,10 @@ def align_trials_affine( 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).""" + """Build the plane's design at the centres and at the points. + + Centred, scaled coordinates; the mean with fewer than 3 centres. + """ k = nodes.shape[0] if k >= 3: mu = nodes.mean(axis=0) @@ -1101,14 +1130,18 @@ 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).""" + """MATLAB's ``pinv``. + + Singular values below ``max(size) * eps(norm)`` are dropped. + """ 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.""" + """Gaussian weights of the centres at the points, summing to 1. + + Relative to the nearest centre (so far points do not underflow). + """ d2 = (rows[:, None] - nodes[None, :, 0]) ** 2 + ( cols[:, None] - nodes[None, :, 1] ) ** 2 @@ -1149,9 +1182,11 @@ def patch_field_matrix( def patch_field_apply( nodes: np.ndarray, sigma: float, rows, cols, 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.""" + """``patch_field_matrix(nodes, sigma, rows, cols)[0] @ d`` without the matrix. + + Port of ``patchFieldApply.m``: the plane's coefficients and the centres' + departures are computed from ``d`` once. + """ 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() @@ -1170,9 +1205,10 @@ 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). + """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. Parameters ---------- @@ -1249,8 +1285,9 @@ 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``). + """Patches of about ``patch_px`` valid pixels. + + ``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 @@ -1308,8 +1345,10 @@ class PatchwiseFit: 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.""" + """Average the trials warped into the common frame at the fit pixels. + + NaN where fewer than half are seen. + """ v = np.empty((r.size, len(trials))) for k, t in enumerate(trials): u = lmat @ d[t].T @@ -1323,8 +1362,10 @@ def _patch_template(s, d, lmat, r, c, trials): 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``).""" + """Median of ``values`` per group 0..k-1. + + 0 for an empty group, as MATLAB's ``accumarray`` with ``@median``. + """ out = np.zeros(k) if values.size == 0: return out @@ -1340,8 +1381,10 @@ def _group_median(values, groups, k) -> np.ndarray: def _interp2_linear_pair(ims, rows, cols): - """:func:`interp2_linear` of two images at the same points (the weights - and indices computed once).""" + """:func:`interp2_linear` of two images at the same points. + + The weights and indices are computed once. + """ h, w = ims[0].shape rows = np.asarray(rows, dtype=np.float64) cols = np.asarray(cols, dtype=np.float64) @@ -1371,9 +1414,10 @@ def _interp2_linear_pair(ims, rows, cols): 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 + """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``. ``d`` is ``(2, K)`` (MATLAB's layout); returns the refined ``d``. The @@ -1567,8 +1611,10 @@ def align_trials_patchwise( 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.""" + """Each field's plane as a map ``(trials, 2, 3)``. + + The plane at the origin and one pixel along each axis. + """ _, _, l_p = patch_field_matrix( lay.nodes, lay.sigma, @@ -1584,8 +1630,10 @@ def _field_planes(lay, disp: np.ndarray) -> np.ndarray: 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``).""" + """Each trial's correlation with the final template over the patches. + + Also the RMS change of its field from the start (into ``info``). + """ template = lay.template(s, disp, trials) for t in trials: u = lay.lmat @ disp[t].T @@ -1597,8 +1645,10 @@ def _fit_quality(info, lay, s, disp, disp0, trials) -> None: 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.""" + """Patches on the pixels imaged in at least half of the trials. + + Imaged under the starting maps; None if fewer than 500 are. + """ seen = np.zeros(s.shape[1:]) for t in trials: seen += ~np.isnan(warp_image_affine(s[t], tforms[t], "linear")) @@ -1622,7 +1672,7 @@ 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.""" + """Compute 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] @@ -1643,7 +1693,7 @@ def __init__(self, patch, nodes) -> None: ) def template(self, s, disp, trials): - """The trials warped into the common frame at the fit pixels.""" + """Average the trials warped into the common frame at the fit pixels.""" return _patch_template(s, disp, self.lmat, self.r, self.c, trials) def refine(self, s, template, d): @@ -1662,10 +1712,12 @@ def refine(self, s, template, d): def _halves_noise(lay, s, halves, disp, trials, mean0) -> 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 - variance of the halves' difference (halves of equal size each have - twice the noise variance of the full data).""" + """Each centre's noise variance of its departure from the plane. + + The trials are refit on each half against the final template; a quarter of + the variance of the halves' difference (halves of equal size each have + twice the noise variance of the full data). + """ 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..a4f0eb9a 100644 --- a/src/giant_python/extraction/raster/annotations.py +++ b/src/giant_python/extraction/raster/annotations.py @@ -1,5 +1,6 @@ -"""Users' ROIs of a raster session: ``annotations.h5`` read, and moved into -the consensus frame. +"""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 @@ -91,7 +92,7 @@ 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``).""" if path not in f: return default raw = np.asarray(f[path][()]) @@ -104,7 +105,7 @@ def _text(f: h5py.File, path: str, default: str = "") -> str: def _array(f: h5py.File, path: str) -> Optional[np.ndarray]: - """A numeric array in MATLAB's orientation, or None.""" + """Read a numeric array in MATLAB's orientation, or None.""" if path not in f: return None a = np.asarray(f[path][()]) @@ -126,7 +127,7 @@ def _scalar(a: Optional[np.ndarray]) -> Optional[float]: def _type(raw: str) -> str: - """The ROI type without MATLAB's ``images.roi.`` prefix.""" + """Return the ROI type without MATLAB's ``images.roi.`` prefix.""" t = raw.strip().lower() return t[len("images.roi.") :] if t.startswith("images.roi.") else t @@ -193,7 +194,7 @@ def read_annotations(path) -> list: 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. + """Find the zero-based trial an annotation was drawn on, if it is known. As ``roisToConsensusFrame.m``: ``fn`` is matched whole against the stems of the registered files, then without its extension. @@ -224,9 +225,11 @@ def annotation_trial(fn: str, fn_reg_ds: Sequence[str]) -> Optional[int]: 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``).""" + """``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``). + """ pts = xy.reshape(-1, 2) rows, cols = warp.inverse(trial, pts[:, 1] - 1, pts[:, 0] - 1) moved = np.column_stack([cols + 1, rows + 1]) diff --git a/src/giant_python/extraction/raster/baseline_map.py b/src/giant_python/extraction/raster/baseline_map.py index b1ff5ad3..5c2965b4 100644 --- a/src/giant_python/extraction/raster/baseline_map.py +++ b/src/giant_python/extraction/raster/baseline_map.py @@ -66,7 +66,7 @@ def baseline_file(baseline_dir, movie_or_stem: str) -> Path: - """The network baseline file of a trial. + """Return the network baseline file of a trial. Parameters ---------- @@ -83,7 +83,7 @@ def baseline_file(baseline_dir, movie_or_stem: str) -> Path: def read_network_baseline(path) -> tuple[np.ndarray, dict]: - """A network baseline file as ``(frames, rows, cols)`` float32 counts. + """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; @@ -270,7 +270,7 @@ def map_baseline( fallback_data: np.ndarray | None = None, solver_params=None, ) -> 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 ---------- @@ -363,8 +363,9 @@ 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. + + What a container stores in ``/baseline``. Attributes ---------- @@ -387,7 +388,7 @@ class TrialBaseline: def _attr_value(v): - """An HDF5 attribute as a JSON type.""" + """Convert an HDF5 attribute to a JSON type.""" if isinstance(v, bytes): return v.decode("utf-8", "replace") if isinstance(v, np.ndarray): diff --git a/src/giant_python/extraction/raster/container.py b/src/giant_python/extraction/raster/container.py index 47787226..7dcd7f1e 100644 --- a/src/giant_python/extraction/raster/container.py +++ b/src/giant_python/extraction/raster/container.py @@ -88,7 +88,7 @@ def _jsonable(value): - """A value as JSON types: NumPy to Python, dataclasses to dicts.""" + """Convert a value to JSON types: NumPy to Python, dataclasses to dicts.""" if dataclasses.is_dataclass(value) and not isinstance(value, type): value = dataclasses.asdict(value) if isinstance(value, dict): @@ -476,7 +476,7 @@ def write_container( return path -def _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts): +def _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts) -> None: """Create the empty, resizable datasets of the network's baseline.""" g = f.create_group("baseline") kwargs = {} @@ -536,7 +536,7 @@ def _check_format(f) -> None: def _split(flat: np.ndarray, offsets: np.ndarray) -> list: - """The index lists of concatenated lists and their offsets.""" + """Split concatenated lists into index lists by their offsets.""" return [ flat[a:b].astype(np.int64) for a, b in zip(offsets[:-1], offsets[1:]) ] diff --git a/src/giant_python/extraction/raster/kinetics.py b/src/giant_python/extraction/raster/kinetics.py index b401276a..b26bae09 100644 --- a/src/giant_python/extraction/raster/kinetics.py +++ b/src/giant_python/extraction/raster/kinetics.py @@ -335,9 +335,10 @@ def mean_snr( def source_minutes( traces: Sequence[Optional[np.ndarray]], 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``. + """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``. Returns ------- @@ -358,7 +359,7 @@ 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). + """Find 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 diff --git a/src/giant_python/extraction/raster/localization.py b/src/giant_python/extraction/raster/localization.py index 0f6d2219..3457b8db 100644 --- a/src/giant_python/extraction/raster/localization.py +++ b/src/giant_python/extraction/raster/localization.py @@ -418,7 +418,7 @@ def check_inputs( def summary_image(act_im: np.ndarray, valid: np.ndarray) -> np.ndarray: - """The image SiLo seeds in: scaled, minus its 5x5 NaN-median.""" + """Compute the image SiLo seeds in: scaled, minus its 5x5 NaN-median.""" s = np.array(act_im, dtype=np.float64) top = np.nanmax(s) if np.isfinite(s).any() else np.nan if top > 0: @@ -430,10 +430,12 @@ def summary_image(act_im: np.ndarray, valid: np.ndarray) -> np.ndarray: 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.""" + """Build 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. + """ 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 diff --git a/src/giant_python/extraction/raster/null.py b/src/giant_python/extraction/raster/null.py index 1354c54c..889decf4 100644 --- a/src/giant_python/extraction/raster/null.py +++ b/src/giant_python/extraction/raster/null.py @@ -38,8 +38,10 @@ 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 for the null calibration (a trial of a few frames, or almost unimaged). + """ _N_BINS = 12 @@ -59,7 +61,7 @@ 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``.""" 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) @@ -204,8 +206,11 @@ 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.""" + """Fill rates at non-finite voxels from the nearest earlier observed frame. + + The nearest earlier observed frame of the same pixel (the next later one + before the first); 0 if never. + """ ok = np.isfinite(lam) if ok.all(): return lam @@ -221,8 +226,9 @@ def _fill_unobserved(lam: np.ndarray) -> np.ndarray: 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``. + """Per-voxel factor (frames a..b-1). + + It gives each voxel the 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 @@ -263,7 +269,7 @@ def null_movie( seed: int, block: int = 256, ) -> 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 ---------- @@ -340,8 +346,10 @@ def null_movie( 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. + """Bins of log brightness, each holding at least ``_MIN_BIN_VALUES`` null values. + + Null values are pixels x draws; the minimum holds when there are that many + in all. 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 @@ -373,9 +381,12 @@ def assign(edges): 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.""" + """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. + """ with np.errstate(divide="ignore", invalid="ignore"): lp = np.log(photons) m_map = np.interp(lp, centre, m0) diff --git a/src/giant_python/extraction/raster/peaks.py b/src/giant_python/extraction/raster/peaks.py index 9cac1685..54481755 100644 --- a/src/giant_python/extraction/raster/peaks.py +++ b/src/giant_python/extraction/raster/peaks.py @@ -107,8 +107,10 @@ def __init__(self, y: np.ndarray, x: np.ndarray) -> None: @staticmethod def _axis(lo, hi, mu, s, derivs=True): - """Integral over [lo, hi] and (with ``derivs``) its derivatives in mu - and sigma.""" + """Integral over [lo, hi] and (with ``derivs``) its derivatives. + + The derivatives are in mu and sigma. + """ 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)) @@ -120,8 +122,10 @@ def _axis(lo, hi, mu, s, derivs=True): 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.""" + """Per-axis integrals (pixels x peaks). + + With their derivatives unless ``derivs`` is False. + """ 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) @@ -182,7 +186,7 @@ def _fit(theta0, y, x, data, lb, ub): def _bounds(locs: np.ndarray, shape) -> tuple[np.ndarray, np.ndarray]: - """getActImPeaks' bounds: positions within 1.5 px of the start.""" + """GetActImPeaks' bounds: positions within 1.5 px of the start.""" n = locs.shape[0] ub = np.column_stack( [ @@ -223,7 +227,7 @@ def _rounded_index(theta: np.ndarray, shape) -> tuple[np.ndarray, np.ndarray]: def _explore(res_im, buffer_mask, exclusion, reject, fit_support, sel, th): - """getActImPeaks' search image for the next residual peak and its peak.""" + """GetActImPeaks' search image for the next residual peak and its peak.""" explored = res_im * ~buffer_mask * ~exclusion * ~reject * fit_support * sel if fit_support.any() and np.isfinite(explored).any(): top = np.nanmax(explored) @@ -451,11 +455,13 @@ def _next_to_another(theta, idx, 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 + """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.) + """ out = [] for axis in (1, 0): # rows (any column finite), then columns n = finite.shape[1 - axis] @@ -472,14 +478,17 @@ 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``. + """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`). + """ s = np.maximum(theta[:, 3], np.finfo(float).eps) if rule == "pixel": iy, ix = _rounded_index(theta, excl.shape) @@ -509,8 +518,10 @@ def _finish( 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``.""" + """Integral of a unit Gaussian over [lo, hi], elementwise. + + With ``derivs``, also its derivatives in ``mu`` and ``s``. + """ u_hi = (hi - mu) / (_SQRT2 * s) u_lo = (lo - mu) / (_SQRT2 * s) val = _SQRT_PI_2 * s * (erf(u_hi) - erf(u_lo)) @@ -532,7 +543,7 @@ class _WindowedGaussians: offsets, column offsets and widths. """ - def __init__(self, idx_im, edges, starts, window, rows): + def __init__(self, idx_im, edges, starts, window, rows) -> None: """Pair each peak with the data pixels in its window. ``idx_im`` maps a pixel to its index in the data (-1 elsewhere), @@ -620,7 +631,7 @@ def _to_offsets(theta, starts): def _from_offsets(x, starts): - """The local fit's x as ``N x 4`` [A, mu_y, mu_x, sigma] (1-based).""" + """Convert the local fit's x to ``N x 4`` [A, mu_y, mu_x, sigma] (1-based).""" n = starts.shape[0] return np.column_stack( [ @@ -633,8 +644,10 @@ def _from_offsets(x, starts): 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].""" + """GetActImPeaks' bounds as offsets. + + Within 1.5 px of the start pixel and inside the image; widths in [0, 5]. + """ n = starts.shape[0] y0, x0 = starts[:, 0] + 1.0, starts[:, 1] + 1.0 lb = np.concatenate( @@ -656,9 +669,11 @@ def _offset_bounds(starts, shape): 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, pix, sign) -> 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 @@ -670,7 +685,7 @@ class _LocalFit: 1-based ``theta`` rows with their 0-based start pixels. """ - def __init__(self, act, background, peak_th, excl, buffer_se): + def __init__(self, act, background, peak_th, excl, buffer_se) -> 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 @@ -746,7 +761,7 @@ def model_at(self, theta, starts, 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.""" + """Find the next residual peak (mask) and the fitted peaks' region.""" sel = (cover[4:-4, 4:-4] > 0) & self.finite p_im = np.zeros(self.shape, bool) p_im[pix[:, 0], pix[:, 1]] = True diff --git a/src/giant_python/extraction/raster/plan.py b/src/giant_python/extraction/raster/plan.py index 096506fb..2336fabc 100644 --- a/src/giant_python/extraction/raster/plan.py +++ b/src/giant_python/extraction/raster/plan.py @@ -51,8 +51,6 @@ ) from .localization import nanmedfilt2 from .peaks import AMPLITUDE_RULES, SEED_FITS -from .solver_setup import Subproblem -from .trial_data import RigidShift from .seeding import ( SEED_ACCEPTANCE, SEEDING_METHODS, @@ -61,6 +59,8 @@ select_source_pixels, sources_from_seeds, ) +from .solver_setup import Subproblem +from .trial_data import RigidShift ALIGNMENT_MODES = ("rigid", "affine", "patchwise") PLAN_FORMAT = "giant-python extraction plan" @@ -241,9 +241,10 @@ class TrialImages: @classmethod def from_localization(cls, localization, trial) -> "TrialImages": - """From the two results of - :func:`~giant_python.extraction.raster.trial.localize_trial` (with - the bootstrap null's images, when the localization drew them).""" + """From the two results of :func:`~giant_python.extraction.raster.trial.localize_trial`. + + With the bootstrap null's images, when the localization drew them. + """ return cls( trial.mean_im, localization.act_im, @@ -286,7 +287,7 @@ def subproblem( finv: np.ndarray, baseline: Optional[np.ndarray] = None, ) -> Subproblem: - """The group's subproblem in one trial. + """Build the group's subproblem in one trial. Parameters ---------- @@ -318,7 +319,7 @@ def subproblem( def loader_warp(warp: TrialWarp, trial: int): - """A trial's across-trial map in the form the trial loader takes. + """Return a trial's across-trial map in the form the trial loader takes. Parameters ---------- @@ -354,8 +355,10 @@ def coords(rows, cols): 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).""" + """4-connected components numbered as MATLAB's ``bwconncomp(z, 4)``. + + By their first pixel in column-major order (labels from 1). + """ labels, n = ndimage.label(zones.T) flat = labels.ravel() # column-major order of zones _, first = np.unique(flat, return_index=True) @@ -368,7 +371,7 @@ 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. + """Find a group's selected pixels (cropped) and the crop's origin. The disks of ``nhood`` around the group's sources, within ``sel``. """ @@ -580,14 +583,18 @@ 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).""" + """Rows and columns of the selected-pixel list. + + In the order of MATLAB's ``find(selPix)``: column by column. + """ 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``).""" + """One source's selected pixels as a map. + + A slice of MATLAB's ``selPix``. + """ rows, cols = self.selected_pixels() mask = np.zeros(self.shape, bool) index = self.source_pixels[source] @@ -596,8 +603,10 @@ def source_mask(self, source: int) -> np.ndarray: def _canvas(trials: Sequence, keep: np.ndarray): - """The trials' mean and activity images on one canvas (top left), - NaN elsewhere and for trials that are not kept.""" + """Place the trials' mean and activity images on one canvas (top left). + + NaN elsewhere and for trials that are not kept. + """ kept = [t for t, k in zip(trials, keep) if k] h = max(max(t.mean_im.shape[0], t.act_im.shape[0]) for t in kept) w = max(max(t.mean_im.shape[1], t.act_im.shape[1]) for t in kept) @@ -637,7 +646,7 @@ 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 image sources are seeded in, from aligned activity images. + """Combine aligned activity images into the image sources are seeded in. 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. @@ -672,7 +681,7 @@ 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. + """Build 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 @@ -707,9 +716,11 @@ def combined_null_image( def _aligned_nulls(trials, valid, warp, shape, refined) -> np.ndarray: - """The valid trials' null images in the consensus frame, - ``(trials, draws, rows, cols)``, placed and warped as the activity - images.""" + """Place the valid trials' null images in the consensus frame. + + Shape ``(trials, draws, rows, cols)``, placed and warped as the activity + images. + """ nulls = [] for t in valid: im = trials[t].null_im if trials[t] is not None else None @@ -748,8 +759,10 @@ def _aligned_nulls(trials, valid, warp, shape, refined) -> np.ndarray: 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.""" + """Read a plan file's saved PlanParams. + + Fields it predates get the values it was made with, not today's defaults. + """ saved = json.loads(text) for name, before in _PLAN_FIELDS_ADDED.items(): saved.setdefault(name, before) @@ -757,7 +770,7 @@ def _saved_params(text: str) -> dict: def _soma_canvas(soma_mask, shape, warp=None, trial=None) -> np.ndarray: - """The soma mask on the consensus canvas (top left). + """Place the soma mask on the consensus canvas (top left). With ``trial``, the mask is in that trial's registered image and is moved into the consensus frame through the trial's map. @@ -782,9 +795,11 @@ def _soma_canvas(soma_mask, shape, warp=None, trial=None) -> np.ndarray: 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.""" + """Sum the kept trials' half images over channels, on the canvas. + + MATLAB's ``Mhalves``: ``(trials, 2, rows, cols)``; NaN for trials without + them. + """ 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: @@ -804,10 +819,11 @@ def refine_alignment( params: PlanParams, halves: np.ndarray | None = None, ): - """Refine the rigid alignment of the valid trials (``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). + """Refine the rigid alignment of the valid trials. + + ``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). Parameters ---------- @@ -1091,7 +1107,7 @@ def _ragged(lists: Sequence[np.ndarray]) -> tuple[np.ndarray, np.ndarray]: def _unragged(flat: np.ndarray, ptr: np.ndarray) -> list: - """The lists of :func:`_ragged`.""" + """Split the output of :func:`_ragged` back into its lists.""" flat = np.asarray(flat, dtype=np.int64) return [flat[a:b] for a, b in zip(ptr[:-1], ptr[1:])] @@ -1211,7 +1227,7 @@ def write_plan( def _read_groups(gr, rows, cols, src_rows, src_cols) -> list: - """The subproblem groups of a plan file.""" + """Read the subproblem groups of a plan file.""" sources = _unragged(gr["source_index"][()], gr["source_ptr"][()]) pixels = _unragged(gr["pixel_index"][()], gr["pixel_ptr"][()]) groups = [] diff --git a/src/giant_python/extraction/raster/refit_test.py b/src/giant_python/extraction/raster/refit_test.py index 97627758..f0735988 100644 --- a/src/giant_python/extraction/raster/refit_test.py +++ b/src/giant_python/extraction/raster/refit_test.py @@ -257,11 +257,11 @@ def summarize(sources: list[dict], events: list[dict]) -> dict: """Medians and quartiles over sources, and the pooled recovery.""" def col(name): - """A column of the sources' rows.""" + """Return a column of the sources' rows.""" return np.array([s[name] for s in sources], dtype=np.float64) def q(name, pct): - """A percentile of a column, NaN left out.""" + """Compute a percentile of a column, NaN left out.""" v = col(name) v = v[np.isfinite(v)] return float(np.percentile(v, pct)) if v.size else float("nan") @@ -406,8 +406,10 @@ 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).""" + """``given_baseline``: the fit's baseline, before ``truth_baseline`` changed it. + + It is the true baseline when nothing changed it. + """ return truth.b if truth.b_fit is None else truth.b_fit @@ -415,19 +417,21 @@ def scale_error(scale: float): """``given_baseline``: the true baseline times ``1 + scale``.""" def given(truth, sub, rng): - """The scaled true baseline.""" + """Return the scaled true baseline.""" 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.""" + """``given_baseline``: the true baseline times a linear drift. + + The drift goes from ``1 - drift / 2`` at the first frame to ``1 + drift / 2`` + at the last. + """ def given(truth, sub, rng): - """The drifting true baseline.""" + """Return the drifting true baseline.""" 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, :] @@ -436,12 +440,14 @@ def given(truth, sub, rng): 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).""" + """``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.""" + """Return the true baseline with its ends scaled.""" b = truth.b.copy() n = b.shape[1] ends = np.zeros(n, dtype=bool) @@ -462,7 +468,7 @@ def blur_error(sigma: float): """ def given(truth, sub, rng): - """The blurred true baseline.""" + """Return the blurred true baseline.""" rows, cols = sel_coords(sub.sel) mask = np.zeros(sub.sel.shape) mask[rows, cols] = 1 @@ -488,7 +494,7 @@ def shared_component(rms: float, smooth_frames: int = 5): """ def changed(b, sub, rng): - """The baseline with the shared component.""" + """Return the baseline with the shared component.""" 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 5b4913cc..df5b0254 100644 --- a/src/giant_python/extraction/raster/results.py +++ b/src/giant_python/extraction/raster/results.py @@ -86,8 +86,10 @@ def n_frames(self) -> int: @classmethod def from_trial(cls, trial) -> "TrialRecord": - """From a loaded trial or a container (``TrialData``, - ``Container``).""" + """From a loaded trial or a container. + + Either a ``TrialData`` or a ``Container``. + """ return cls( frame_lines=np.asarray(trial.frame_lines), discard=np.asarray(trial.discard, dtype=bool), @@ -133,8 +135,10 @@ class ResultsFile: def _json_default(value): - """NumPy values in a solver's info as JSON types (the baseline modes' - per-pixel gains are arrays).""" + """NumPy values in a solver's info as JSON types. + + The baseline modes' per-pixel gains are arrays. + """ if isinstance(value, np.ndarray): return value.tolist() if isinstance(value, np.generic): @@ -213,7 +217,7 @@ def write_results( def _attr(value): - """An HDF5 attribute as a Python value.""" + """Convert an HDF5 attribute to a Python value.""" if isinstance(value, bytes): return value.decode() if isinstance(value, np.generic): @@ -339,7 +343,7 @@ def trial_outcome( def _merge(files: Sequence[ResultsFile]) -> dict: - """The subproblems of one container's results files, checked.""" + """Merge the subproblems of one container's results files, checked.""" first = files[0].attrs for f in files[1:]: for key in ("container", "container_hash", "n_subproblems"): @@ -371,22 +375,29 @@ def _merge(files: Sequence[ResultsFile]) -> dict: @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).""" + """Return the hash of how a results file was solved. + + The hash excludes its subproblem range (``solve_settings``; 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. + + Equal means same placement and results (NaN equal). + """ if not (np.array_equal(a[0], b[0]) and np.array_equal(a[1], b[1])): return False fa, fb = a[2].f0_image, b[2].f0_image diff --git a/src/giant_python/extraction/raster/seeding.py b/src/giant_python/extraction/raster/seeding.py index a51c9166..91cae394 100644 --- a/src/giant_python/extraction/raster/seeding.py +++ b/src/giant_python/extraction/raster/seeding.py @@ -59,14 +59,18 @@ 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')``).""" + """Dilation of one binary shape by another, grown to hold the result. + + As MATLAB's ``imdilate(..., 'full')``. + """ 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``.""" + """MATLAB's ``strel('periodicline', reps, offset)``. + + The points ``k * offset`` for ``k`` in ``-reps .. reps``. + """ dr, dc = offset line = np.zeros((2 * reps * abs(dr) + 1, 2 * reps * abs(dc) + 1), bool) for k in range(-reps, reps + 1): @@ -121,7 +125,7 @@ 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. + """Compute 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 @@ -194,8 +198,7 @@ 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.""" + """Median and robust SD (MATLAB's MAD scale) of null images' finite pixels.""" vals = np.asarray(null_ims, dtype=np.float64) vals = vals[np.isfinite(vals)] if vals.size < 10: @@ -388,8 +391,10 @@ def _check_acceptance(acceptance: str, null_im) -> None: 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.""" + """Return the background (None: the image's own) and threshold of a seeding. + + Recorded in ``info`` when given. + """ background = None if acceptance == "null": background, peak_th, tail = null_threshold( @@ -407,7 +412,7 @@ 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. + """Place 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', diff --git a/src/giant_python/extraction/raster/solver.py b/src/giant_python/extraction/raster/solver.py index 82d7e3ad..77422a3f 100644 --- a/src/giant_python/extraction/raster/solver.py +++ b/src/giant_python/extraction/raster/solver.py @@ -254,14 +254,14 @@ def _check_data(sub: Subproblem, mode: str = "fit") -> None: def _lstsq(h: np.ndarray, r: np.ndarray) -> np.ndarray: - """MATLAB ``h \\ r`` for a tall full-rank h.""" + r"""MATLAB ``h \\ r`` for a tall full-rank h.""" 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, 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) @@ -281,7 +281,7 @@ def __init__(self, subs, params: SolverParams, opt: SolverOptions): ) 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.""" return torch.as_tensor(a, dtype=self.dt, device=self.dev) def pixels_frames(self, arrays, fill: float) -> torch.Tensor: @@ -324,7 +324,7 @@ def member(self, t: torch.Tensor, i: int, rows: int, cols=None): return a.detach().to("cpu", torch.float64).numpy() -def _note(info, name, fit, seconds): +def _note(info, name, fit, seconds) -> None: """Record how a fit ended, per member.""" for i, d in enumerate(info): d[name] = dict( @@ -337,7 +337,7 @@ def _note(info, name, fit, seconds): def _debias(bt, z, h, b, k, s, info, name): - """The debias refit: the events found, refitted without their L1.""" + """Run the debias refit: the events found, refitted without their L1.""" p = bt.params free = s >= _EVENT_FLOOR s = torch.where(free, s, torch.zeros_like(s)) @@ -364,7 +364,7 @@ def _debias(bt, z, h, b, k, s, info, name): def _baseline_step(b, b_ext, data, sel, p, operators, info): - """The baseline after an activity fit, by ``p.baseline_mode``. + """Update 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'). @@ -552,8 +552,10 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901 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.""" + """Each channel's final baseline (pixels x frames) averaged over ``frames``. + + The average is channels x pixels; None without frames. + """ if frames is None: return None frames = np.asarray(frames, dtype=bool).ravel() @@ -778,7 +780,7 @@ def conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: def process_result( trial: TrialResult, params: SolverParams, discard: np.ndarray ) -> TrialActivity: - """A trial's activity traces (``processResult``). + """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 diff --git a/src/giant_python/extraction/raster/solver_baseline.py b/src/giant_python/extraction/raster/solver_baseline.py index aec6dd9b..9c0c2fa4 100644 --- a/src/giant_python/extraction/raster/solver_baseline.py +++ b/src/giant_python/extraction/raster/solver_baseline.py @@ -146,7 +146,7 @@ def split_freq( def initial_baseline(y: np.ndarray, params: SolverParams) -> np.ndarray: - """Starting baseline of a channel: ``splitFreq``'s low-pass, bounded. + """Compute 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 @@ -312,7 +312,7 @@ def _bvls_fallback(g, c, lb, ub): 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.""" + """Return the objective and its gradient, over the linear term's scale.""" gv = gf @ v return (0.5 * v @ gv - cf @ v) / scale, (gv - cf) / scale @@ -455,7 +455,7 @@ def kkt_residual(x): def surround_operators(sel: np.ndarray, params: SolverParams) -> list: - """The three surround filters as pixels x pixels matrices. + """Build 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. @@ -483,7 +483,7 @@ def baseline_programs( operators: list | None = None, offset: np.ndarray | None = None, ) -> dict: - """The per-pixel quadratic programs of ``fitB``. + """Form 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. @@ -574,8 +574,10 @@ 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: surround + spline. + + Plus the offset the programs were formed with, if any. + """ n_src = programs["n_sources"] sur, bs = programs["surround"], programs["spline"] d = n_src + sur.shape[0] @@ -721,7 +723,7 @@ def fit_gain( predictor: np.ndarray, min_baseline: float, ) -> tuple[np.ndarray, np.ndarray]: - """The baseline ``max(min_baseline, gain * predictor)`` per pixel. + """Fit the baseline ``max(min_baseline, gain * predictor)`` per pixel. The gains come from :func:`gain_programs`, solved by :func:`solve_box_qp`. @@ -747,7 +749,7 @@ 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 @@ -922,7 +924,7 @@ 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. + """Run 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 * diff --git a/src/giant_python/extraction/raster/solver_fits.py b/src/giant_python/extraction/raster/solver_fits.py index 757d16d3..9e48d908 100644 --- a/src/giant_python/extraction/raster/solver_fits.py +++ b/src/giant_python/extraction/raster/solver_fits.py @@ -28,7 +28,7 @@ def variance_loss(z, t, w, s0=None, order: int = 2): - """The solver's loss and its derivatives in the model T. + """Compute the solver's loss and its derivatives in the model T. Parameters ---------- @@ -76,7 +76,7 @@ def _geometric_sum(x: torch.Tensor, a: float, taps: int, back: bool): """ def shifted_add(y, z, m, c): - """y + c * (z shifted by m frames, zero-filled).""" + """Y + c * (z shifted by m frames, zero-filled).""" if m >= y.shape[-1]: return y if y.requires_grad or z.requires_grad: @@ -235,7 +235,7 @@ def model(self, s: torch.Tensor) -> torch.Tensor: return self.h @ self.kernel.conv(s) + self.b def value(self, s: torch.Tensor) -> torch.Tensor: - """The loss at S, per batch member.""" + """Return the loss at S, per batch member.""" f, _, _ = variance_loss(self.z, self.model(s), self.w, self.s0, 0) return f + self.lam * s.sum((-2, -1), dtype=torch.float64) @@ -258,7 +258,7 @@ def hess_mult(self, v: torch.Tensor) -> torch.Tensor: 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.""" return self.kernel_sq.conv_adj(self.q[:, self.pairs.self_idx]) def _tail_curvature(self): @@ -285,7 +285,7 @@ def _tail_curvature(self): return self._tail def preconditioner(self, free: torch.Tensor, diag: torch.Tensor): - """An approximate inverse of the Hessian on the free events. + """Build 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 @@ -370,7 +370,7 @@ def footprints(self, hs: torch.Tensor) -> torch.Tensor: return self.g @ hs def value(self, hs: torch.Tensor) -> torch.Tensor: - """The loss at Hs, per batch member.""" + """Return the loss at Hs, per batch member.""" t = (self.g @ hs) @ self.x + self.b return variance_loss(self.z, t, self.w, self.s0, 0)[0] @@ -387,11 +387,11 @@ def hess_mult(self, v: torch.Tensor) -> torch.Tensor: 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.""" 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.""" + """Build the inverse of the Hessian's diagonal on the free entries.""" minv = free.to(diag.dtype) / diag return lambda r: minv * r @@ -437,7 +437,7 @@ def _dot(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: def _per_member(v: torch.Tensor, like: torch.Tensor) -> torch.Tensor: - """A per-member vector shaped to broadcast against ``like``.""" + """Reshape a per-member vector to broadcast against ``like``.""" return v.reshape(-1, *([1] * (like.dim() - 1))) @@ -508,7 +508,7 @@ def _arc_search(problem, g, d, hd, q, delta, t, lo, hi, search): def _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds): - """A step that lowers the quadratic model within the bounds. + """Compute 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 diff --git a/src/giant_python/extraction/raster/solver_setup.py b/src/giant_python/extraction/raster/solver_setup.py index 2d4245f0..985bab9a 100644 --- a/src/giant_python/extraction/raster/solver_setup.py +++ b/src/giant_python/extraction/raster/solver_setup.py @@ -89,11 +89,12 @@ def _check_numbers(params) -> None: 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 - up as MATLAB does); all kept frames when the trim would leave none - (GIAnT-MATLAB's ``F0imTrim_s``, ``processAllTrials_Async.m``). + """Return 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 up as MATLAB does); all kept frames when the trim + would leave none (GIAnT-MATLAB's ``F0imTrim_s``, ``processAllTrials_Async.m``). Parameters ---------- @@ -465,7 +466,7 @@ def initial_footprints( sigma_px: float, valid_kernel: int = 3, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Starting footprints of ``extractSources``. + """Build the starting footprints of ``extractSources``. Returns ------- @@ -506,14 +507,14 @@ def _is_empty(ds: h5py.Dataset) -> bool: def _mat_scalar(g: h5py.Group, name: str, default=None): - """A numeric scalar field of a MATLAB struct, or ``default``.""" + """Read a numeric scalar field of a MATLAB struct, or ``default``.""" 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``.""" + """Read a char field of a MATLAB struct, or ``default``.""" if name not in g or _is_empty(g[name]): return default codes = np.asarray(g[name]).ravel() @@ -521,7 +522,7 @@ 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.""" + """Read the side of a saved ``validKernel``: a square of trues, odd side.""" if "validKernel" not in g or _is_empty(g["validKernel"]): return default k = np.asarray(g["validKernel"]) @@ -535,7 +536,7 @@ def _mat_valid_kernel(g: h5py.Group, default: int) -> int: def params_from_matlab(g: h5py.Group) -> SolverParams: - """The solver's parameters from a saved MATLAB ``params`` struct. + """Read 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. @@ -547,7 +548,7 @@ def params_from_matlab(g: h5py.Group) -> SolverParams: d = SolverParams() def num(name, default): - """A scalar field, or the default.""" + """Read a scalar field, or the default.""" return _mat_scalar(g, name, default) p = SolverParams( @@ -598,7 +599,7 @@ def num(name, default): 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.""" + """Find the indices of a crop's pixels in the trial's selected-pixel list.""" 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) diff --git a/src/giant_python/extraction/raster/spots.py b/src/giant_python/extraction/raster/spots.py index f0d78860..3cbd107c 100644 --- a/src/giant_python/extraction/raster/spots.py +++ b/src/giant_python/extraction/raster/spots.py @@ -109,13 +109,16 @@ class SpotSettings: n_sim: int = 20 def to_dict(self) -> dict: - """The settings as a dict.""" + """Return the settings as a dict.""" 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. + """ from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components from scipy.spatial import cKDTree @@ -146,8 +149,11 @@ 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. + """ ev = np.nan_to_num(np.asarray(events, dtype=np.float64)) if ev.ndim != 2 or ev.shape[0] < 2: return float("nan") @@ -170,8 +176,10 @@ def robust_sd(x, axis=None): 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.""" + """Weighted fit of ``A G(r, c; sigma) + b`` to one event image. + + Returns the position, its standard errors and the amplitude, or None. + """ ok = np.isfinite(img) & np.isfinite(sd) & (sd > 0) if ok.sum() < 8: return None @@ -304,8 +312,10 @@ def _logn(x, mu, T): 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`).""" + """Each event's position error covariance ``(n, 2, 2)``. + + From the fit's standard errors (:data:`ERROR_K`, :data:`ERROR_FLOOR_PX`). + """ 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 @@ -340,8 +350,10 @@ class MixtureFit: 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``.""" + """Best of ``n_init`` extreme-deconvolution EM runs with K components. + + Plus the fixed outlier component at ``center``. + """ n = x.shape[0] lo_out, _ = _logn( x, np.asarray(center, float), OUTLIER_VAR * np.eye(2)[None] + S @@ -392,9 +404,11 @@ 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. + """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 ---------- @@ -423,8 +437,10 @@ def mixture_fit( 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.""" + """BIC of one component minus the lowest BIC with more. + + NaN without such a fit; positive values favour separate clusters. + """ if len(fits) < 2: return float("nan") return float(fits[0].bic - min(f.bic for f in fits[1:])) @@ -433,9 +449,11 @@ def bic_gain(fits) -> float: 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.""" + """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. + """ pts = np.asarray(points, dtype=np.float64).reshape(-1, 2) if pts.shape[0] < 2: return float("nan") @@ -503,7 +521,7 @@ class SpotResult: 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. + """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 @@ -554,7 +572,7 @@ def event_test( def spot_label( n_sources: int, event_corr: float, test: dict, settings: SpotSettings ) -> str: - """A spot's label (:data:`LABELS`) from its tests.""" + """Assign a spot's label (:data:`LABELS`) from its tests.""" 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..98170d70 100644 --- a/src/giant_python/extraction/raster/stage_files.py +++ b/src/giant_python/extraction/raster/stage_files.py @@ -81,8 +81,10 @@ class LocalizationRecord: null_im: Optional[np.ndarray] = None def trial_images(self): - """The plan stage's input - (:class:`~giant_python.extraction.raster.plan.TrialImages`).""" + """Return the plan stage's input. + + A :class:`~giant_python.extraction.raster.plan.TrialImages`. + """ from .plan import TrialImages return TrialImages( @@ -96,7 +98,7 @@ def trial_images(self): def _value(v): - """An HDF5 attribute as a Python value.""" + """Convert an HDF5 attribute to a Python value.""" if isinstance(v, bytes): return v.decode() if isinstance(v, np.generic): @@ -174,7 +176,7 @@ def write_localization( def peaks_file(path) -> Path: - """The sidecar of a localization file's peaks fitted later.""" + """Return the sidecar of a localization file's peaks fitted later.""" path = Path(path) return path.with_name(path.stem + ".peaks.h5") @@ -189,7 +191,7 @@ def _sidecar_peaks(path) -> Optional[np.ndarray]: def localization_attrs(path) -> Optional[dict]: - """A localization file's attributes, or None if it cannot be read. + """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. """ @@ -256,8 +258,9 @@ def read_localization( 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). + """Store a trial's peaks fitted later, in the localization file's sidecar. + + The sidecar is written whole, then moved into place. Parameters ---------- diff --git a/src/giant_python/extraction/raster/summary.py b/src/giant_python/extraction/raster/summary.py index 15ca4222..18f30211 100644 --- a/src/giant_python/extraction/raster/summary.py +++ b/src/giant_python/extraction/raster/summary.py @@ -47,8 +47,9 @@ @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 held as the experiment summary's ``frame_info`` uses it. Attributes ---------- @@ -89,7 +90,7 @@ def read_alignment_record(path) -> AlignmentRecord: """ def vec(f, name): - """A dataset as a flat float64 vector, or None.""" + """Read a dataset as a flat float64 vector, or None.""" if name not in f: return None return np.asarray(f[name][()], dtype=np.float64).ravel() @@ -218,8 +219,10 @@ def _ordered(num_channels: int, activity_channel: int) -> np.ndarray: 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.""" + """MATLAB ``interp1(ds, values, lines, 'nearest', 'extrap')`` (ties to the right). + + With one registered frame: its value throughout. + """ lines = np.asarray(lines, dtype=np.float64) if ds.size == 1: return np.full(lines.shape, float(values[0])) @@ -242,8 +245,10 @@ def __init__(self, f: h5py.File) -> None: 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.""" + """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 @@ -251,15 +256,16 @@ def put(self, path: str, value) -> None: write_matlab_value(grp, name, value) def create(self, path: str, size: tuple, dtype) -> h5py.Dataset: - """An empty contiguous dataset of MATLAB size ``size``.""" + """Create an empty contiguous dataset of MATLAB size ``size``.""" parent, name = path.rsplit("/", 1) grp = self.f.require_group(parent) if parent else self.f return grp.create_dataset(name, shape=tuple(size[::-1]), dtype=dtype) def _profile_blocks(ds, images, cols_per_block: int = 64) -> None: - """Write images ``(..., rows, cols)`` as MATLAB's ``(..., rows, cols)`` - array (h5py: reversed) in blocks of columns. + """Write images ``(..., rows, cols)`` in blocks of columns. + + They are written as MATLAB's ``(..., rows, cols)`` array (h5py: reversed). ``images(c0, c1)`` returns the block's array in MATLAB orientation, ``(lead..., rows, c1 - c0)``. @@ -279,8 +285,10 @@ def _footprint_images( c0: int, c1: int, ) -> np.ndarray: - """Footprints ``(pixels, sources)`` as images ``(sources, rows, c1 - - c0)`` of columns ``c0:c1`` (zero elsewhere).""" + """Footprints ``(pixels, sources)`` as images ``(sources, rows, c1 - c0)``. + + The images are of columns ``c0:c1`` (zero elsewhere). + """ 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 @@ -583,9 +591,11 @@ 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.""" + """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. + """ 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)) @@ -598,9 +608,11 @@ def _centroids( 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``).""" + """Map a trial's own peaks (found in its registered image) to the consensus frame. + + Returns ``(n, 2)`` rows and columns: through the inverse of the trial's + map, or minus its shift (MATLAB's ``savePerTrialSummaryH5``). + """ 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]) @@ -610,12 +622,14 @@ def _peaks_to_consensus(plan, t: int, peaks: np.ndarray) -> np.ndarray: 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`` - (analyzed channels in analysis order x selected pixels); NaN for - channels not analyzed and trials without one. None when no trial has + """Gather the trials' F0 values at the selected pixels ``(trials, channels, pixels)``. + + The values 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`). + """ if not f0_trials: return None vals = np.full((n_trials, num_channels, n_pixels), np.nan, np.float32) @@ -632,12 +646,14 @@ def _f0_values(f0_trials, n_trials, n_pixels, num_channels, ordered): 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 + """Each user ROI's mean F0 and the share of its mask pixels with an F0 value. + + The mean is over its mask per channel and trial ``(rois, channels, + trials)``; the share is 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.""" + value. + """ n_trials, n_ch, _ = f0_vals.shape rows, cols = pixels h, w = shape @@ -659,9 +675,11 @@ def _user_roi_f0(masks, f0_vals, pixels, shape, activity_index): 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, masks, f0_vals, pixels, shape, activity) -> None: + """Write the per-trial summary's F0 images and the user ROIs' F0. + + The images are written in blocks of columns (nothing without F0 images). + """ if f0_vals is None: return n_trials, n_ch, _ = f0_vals.shape @@ -701,10 +719,12 @@ def _write_per_trial( f0_vals: Optional[np.ndarray] = 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. + + 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. + """ plan = result.plan h, w = plan.shape act_aligned = np.full((n_trials, h, w), np.nan) diff --git a/src/giant_python/extraction/raster/trial.py b/src/giant_python/extraction/raster/trial.py index 9d46be4c..41b578a6 100644 --- a/src/giant_python/extraction/raster/trial.py +++ b/src/giant_python/extraction/raster/trial.py @@ -34,8 +34,10 @@ 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)``.""" + """MATLAB ``medfilt1(x, n)``: zero padding. + + For even n, the median of ``x(k - n/2 : k + n/2 - 1)``. + """ 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)]) @@ -172,8 +174,10 @@ 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. + """Compute the mean image of each channel (NaN ignored) and the pixels missing. + + The pixels missing 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))`` one channel at a time: the same values (the frames are summed in the diff --git a/src/giant_python/extraction/raster/trial_data.py b/src/giant_python/extraction/raster/trial_data.py index 2150aea9..f04a5a23 100644 --- a/src/giant_python/extraction/raster/trial_data.py +++ b/src/giant_python/extraction/raster/trial_data.py @@ -213,13 +213,13 @@ def view_shape(self) -> tuple: 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.""" 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.""" + """Read the enabled ``onlineCompensation`` record of an alignment file.""" if "onlineCompensation" not in grp: return None oc = grp["onlineCompensation"] @@ -270,7 +270,7 @@ def online_compensation( line_range, kernel_lines: int, ): - """The compensation registration used and the motion to interpolate. + """Return the compensation registration used and the motion to interpolate. Port of ``onlineCompensation``. If registration undid the online motion correction, each registered frame's motion is relative to the DMD @@ -408,7 +408,7 @@ def __init__( comp: Optional[OnlineCompensation] = None, 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) @@ -626,7 +626,7 @@ class _WholePixels: Where frames are interpolated. """ - def __init__(self, tpos, shape, r_d, c_d, m_r, m_c, device): + def __init__(self, tpos, shape, r_d, c_d, m_r, m_c, 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) @@ -883,16 +883,21 @@ 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.""" + """MATLAB's ``medfilt2(a, [3 3])``. + + Zeros outside the image, and NaN wherever the window holds a NaN. + """ 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.""" + """Pixels of the global trace. + + Those brighter than three times the 25th percentile of the + median-filtered mean image of the activity channel. + """ lab = medfilt3(mean_activity) with np.errstate(invalid="ignore"): bright = lab > 3 * matlab_prctile(lab, 25) @@ -908,8 +913,11 @@ def _fit(a: np.ndarray, shape, fill) -> np.ndarray: 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.""" + """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 @@ -967,8 +975,10 @@ 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, a row without any starting from frame 0. + + MATLAB sets the first frame of such a pixel to 0 before filling. + """ ok = ok.copy() ok[~ok.any(1), 0] = True return ok @@ -1006,7 +1016,7 @@ 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, finv_part, passes: int, window: float, fill_finv) -> None: """Fill a block of rows' missing samples, in place. ``finv_part`` (the rows' variance multiplier, or None for channels @@ -1031,7 +1041,7 @@ def finish_pixels( window: float, rows: int = 512, ) -> None: - """The end of ``loadTrial``, in place: discards, outliers, gap filling. + """Run the end of ``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 @@ -1107,7 +1117,7 @@ def finish_pixels( 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``). + """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`` @@ -1185,7 +1195,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. + """Denoise a user ROI's trace 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 @@ -1272,7 +1282,7 @@ class TrialData: 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, labeled, masks, order, n_frames, qpos, dev) -> None: """Index the labeled and ROI pixels among the sampled points. ``mean_px`` is the view's mean image ``(rows, cols, channels)`` in @@ -1284,7 +1294,7 @@ def __init__(self, mean_px, labeled, masks, order, n_frames, qpos, dev): self.sum_f = np.nansum(mean_px.reshape(-1, n_ch), 0) def tensor(a): - """A NumPy array on the device.""" + """Put a NumPy array on the device.""" return torch.from_numpy(np.ascontiguousarray(a)).to(dev) self.q_lab = tensor(qpos[labeled]) @@ -1315,7 +1325,7 @@ 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.""" out = np.full(self.roi_f.shape, np.nan) for r, px in enumerate(self.roi_px): for k in range(px.shape[0]): @@ -1324,7 +1334,7 @@ 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. + """Divide the summed data by the summed mean image of the same 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 @@ -1339,8 +1349,10 @@ 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, they are continued by unit steps. + """ extra = np.arange(1, max(0, n - view.size) + 1) return np.concatenate([view, view[-1] + extra])[:n] @@ -1391,21 +1403,25 @@ def _points(need, alignment: TrialAlignment, warp): 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).""" + """Return 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). + """ 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.""" + """``(name, size, modification time)`` of every file the reader of ``dat_path`` opens. + + The files 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. + """ import re from ...io.slap2 import is_cycle_split @@ -1437,8 +1453,9 @@ def _layout_inputs(dat_path) -> tuple: def recording_layout(dat_path) -> RasterLayout: - """:func:`~giant_python.io.slap2_raster.raster_layout` of a recording, - read once per recording. + """:func:`~giant_python.io.slap2_raster.raster_layout` of a recording. + + 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 diff --git a/src/giant_python/gui/parameters_gui.py b/src/giant_python/gui/parameters_gui.py index 1fc463b2..d6894eae 100644 --- a/src/giant_python/gui/parameters_gui.py +++ b/src/giant_python/gui/parameters_gui.py @@ -95,7 +95,7 @@ def run_parameter_gui( Optional[tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]], ] = {"options": None} - def on_ok(): + def on_ok() -> None: """Validate controls and return a replacement parameter instance.""" try: updates = { @@ -128,7 +128,7 @@ 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() diff --git a/src/giant_python/gui/roi_editor.py b/src/giant_python/gui/roi_editor.py index abd5995c..fd4cdde7 100644 --- a/src/giant_python/gui/roi_editor.py +++ b/src/giant_python/gui/roi_editor.py @@ -164,7 +164,7 @@ def _edit_rois( roi_masks, roi_union, roi_records, -): +) -> None: """Append selected rectangles as polygon records and overlapping masks.""" edit_name = f"Edit ROIs z={curr_fz + 1}" edit_disp = _compose_display( diff --git a/src/giant_python/io/experiment_summary.py b/src/giant_python/io/experiment_summary.py index b0e6ed02..ed363a31 100644 --- a/src/giant_python/io/experiment_summary.py +++ b/src/giant_python/io/experiment_summary.py @@ -186,9 +186,11 @@ def _stack_optional_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``).""" + """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``. + """ 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: @@ -204,8 +206,11 @@ def _empty_geometry( 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.""" + """Raster SILo's per-source scalars as ``(sources, 1)`` arrays. + + Only the fields every source has; a field only some sources have is an + error. + """ out = {} for name, _, key, dtype in _RASTER_SOURCE_FIELDS: values = [getattr(s, name) for s in path.sources] @@ -221,7 +226,7 @@ def _source_scalars(path: PathSummary) -> dict: 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).""" out = { "profiles": _stack_required_arrays( (s.profile for s in path.sources), "Source.profile" @@ -255,9 +260,12 @@ def _source_arrays(path: PathSummary) -> dict: 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. + """ out = { "mask": _stack_required_arrays( (roi.mask for roi in rois), "UserRoi.mask" @@ -336,8 +344,11 @@ 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 as datasets, and ``labels`` and ``settings`` as JSON + attributes. + """ group = sources.create_group("spots") for key, value in spots.items(): if key in _SPOT_ATTRS: @@ -349,8 +360,11 @@ def _write_spots(sources: h5py.Group, spots: dict) -> None: 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.""" + """Write a path's ``sources`` group. + + First the band schema's datasets, then raster SILo's fields that the + model has. + """ sources = group.create_group("sources") spatial = sources.create_group("spatial") for key in ("profiles", "coords"): @@ -452,15 +466,18 @@ def write_summary(summary: ExperimentSummary, path: Union[str, Path]) -> None: def _decoded(value): - """An HDF5 attribute as a plain value (bytes decoded).""" + """Convert an HDF5 attribute to a plain value (bytes decoded).""" 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.""" + """Read the spot annotation; None without it. + + Its arrays, plus ``labels`` (list) and ``settings`` (dict) from its JSON + attributes. + """ if arrays is None: return None out = dict(arrays) diff --git a/src/giant_python/io/hdf5.py b/src/giant_python/io/hdf5.py index 8110c8a6..f68e6210 100644 --- a/src/giant_python/io/hdf5.py +++ b/src/giant_python/io/hdf5.py @@ -177,7 +177,7 @@ def _write_sequence(grp: h5py.Group, key: str, value) -> None: def _matlab_array(value) -> np.ndarray: - """A value as an array in MATLAB ``size()`` orientation (rank >= 2). + """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 diff --git a/src/giant_python/io/slap2.py b/src/giant_python/io/slap2.py index 9513d3be..a0d5d7b0 100644 --- a/src/giant_python/io/slap2.py +++ b/src/giant_python/io/slap2.py @@ -55,7 +55,7 @@ class Slap2Reader(Protocol): lineSuperPixelIDs: Any lineFastZIdxs: Any - def getLineData(self, line_indices, cycle_indices, channels=None): + def getLineData(self, line_indices, cycle_indices, channels=None) -> None: """Read a batch using the vendor reader's unchanged contract.""" @@ -128,7 +128,7 @@ def _mcos_property_sets(blob: bytes, start: int, end: int) -> list: def _mcos_object_properties(h, object_id: int) -> dict: - """Saved properties of one MCOS object of an open v7.3 MAT file. + """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 string table and segments for classes, objects and property sets; each @@ -183,7 +183,7 @@ def _wall_clock_ms(ms: float, tz: str): def _text(value) -> str: - """A MATLAB char array (uint16 codes) or string as ``str``.""" + """Convert a MATLAB char array (uint16 codes) or string to ``str``.""" if isinstance(value, np.ndarray): return "".join(map(chr, value.ravel())) if value.size else "" return str(value) @@ -192,7 +192,7 @@ def _text(value) -> str: 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. + """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 milliseconds since 1970-01-01 (a complex double: whole and fractional diff --git a/src/giant_python/io/slap2_raster.py b/src/giant_python/io/slap2_raster.py index 47d9ba1c..2f864924 100644 --- a/src/giant_python/io/slap2_raster.py +++ b/src/giant_python/io/slap2_raster.py @@ -146,12 +146,12 @@ def _line_ids(ids, n_samples: int) -> np.ndarray: def _data_files(reader) -> list: - """The ``DataFile`` objects of a reader, in cycle order.""" + """List the ``DataFile`` objects of a reader, in cycle order.""" return list(getattr(reader, "hDataFiles", None) or [reader]) def _text(value) -> str: - """A metadata string; ``slap2_utils`` gives some as character codes.""" + """Decode a metadata string; ``slap2_utils`` gives some as character codes.""" if isinstance(value, str): return value if value is None: @@ -160,7 +160,7 @@ def _text(value) -> str: def _dmd_curtain(meta, n_rows: int): - """The acquisition path's curtain and its DMD's line shear. + """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 diff --git a/src/giant_python/models/experiment_summary.py b/src/giant_python/models/experiment_summary.py index d21d17a9..47af6321 100644 --- a/src/giant_python/models/experiment_summary.py +++ b/src/giant_python/models/experiment_summary.py @@ -236,16 +236,20 @@ class ExperimentSummary: @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`.""" + """Read an experiment summary eagerly, from BandSILo or raster SILo. + + BandSILo has ``row_major`` 1 and raster SILo ``row_major`` 0; see + :func:`~giant_python.io.experiment_summary.read_summary`. + """ 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`).""" + """Write band-schema output using the shared IO codec; return None. + + See :func:`~giant_python.io.experiment_summary.write_summary`. + """ 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 91bcbbef..d55bd5dd 100644 --- a/src/giant_python/models/params.py +++ b/src/giant_python/models/params.py @@ -287,7 +287,7 @@ def _validate_growth_and_output(self) -> None: 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.""" return { "alignHz": float(self.align_hz), "maxshift": float(self.maxshift), @@ -899,7 +899,7 @@ 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.""" 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) @@ -985,7 +985,7 @@ def _solver_defaults(self) -> None: ) def _check_localization(self) -> None: - """Checks of the localization options that their type cannot do.""" + """Check the localization options in ways that their type cannot.""" _choice( "localization_baseline", self.localization_baseline, @@ -1012,16 +1012,20 @@ def _check_localization(self) -> None: @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. + + It runs 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, and with the null seed thresholds (their threshold and - scale are not the combined image's ``peak_th`` and robust SD).""" + """Seed height below which the evidence test judges a source. + + That is ``peak_th + evidence_margin``; None judges every source: without + a margin, and with the null seed thresholds (their threshold and scale + are not the combined image's ``peak_th`` and robust SD). + """ if self.evidence_margin is None or self.seed_acceptance != "image": return None return float(self.peak_th) + float(self.evidence_margin) @@ -1032,8 +1036,10 @@ def sel_radius(self) -> int: return math.ceil(2 * self.d_xy) def plan_params(self): - """The plan stage's parameters - (:class:`~giant_python.extraction.raster.plan.PlanParams`).""" + """Build the plan stage's parameters. + + A :class:`~giant_python.extraction.raster.plan.PlanParams`. + """ from ..extraction.raster.plan import PlanParams return PlanParams( @@ -1054,8 +1060,9 @@ def plan_params(self): ) def load_params(self): - """The trial loader's parameters - (:class:`~giant_python.extraction.raster.trial_data.TrialLoadParams`). + """Build the trial loader's parameters. + + A :class:`~giant_python.extraction.raster.trial_data.TrialLoadParams`. """ from ..extraction.raster.trial_data import TrialLoadParams @@ -1068,8 +1075,9 @@ def load_params(self): ) def solver_params(self): - """The subproblem solver's parameters - (:class:`~giant_python.extraction.raster.solver_setup.SolverParams`). + """Build the subproblem solver's parameters. + + A :class:`~giant_python.extraction.raster.solver_setup.SolverParams`. """ from ..extraction.raster.solver_setup import SolverParams @@ -1096,16 +1104,19 @@ 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).""" + """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" ) def localization_params(self, align_hz: float): - """The per-trial localization's parameters (a - :class:`~giant_python.extraction.raster.localization.RasterLocalizationParams`). + """Build the per-trial localization's parameters. + + A :class:`~giant_python.extraction.raster.localization.RasterLocalizationParams`. Parameters ---------- @@ -1136,7 +1147,7 @@ def localization_params(self, align_hz: float): ) def stage_settings(self, stage: str) -> dict: - """The settings one stage's outputs depend on. + """Collect 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. @@ -1173,7 +1184,7 @@ def to_matlab( end_time: str = "", save_subproblems_dir: str = "", ) -> dict: - """The ``params`` struct that GIAnT-MATLAB's SILo saves. + """Build 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 @@ -1524,8 +1535,10 @@ def __post_init__(self) -> None: raise ValueError(f"{name} must be a bool") def solver_options(self): - """The solver's options - (:class:`~giant_python.extraction.raster.solver.SolverOptions`).""" + """Build the solver's options. + + A :class:`~giant_python.extraction.raster.solver.SolverOptions`. + """ from ..extraction.raster.solver import SolverOptions return SolverOptions( diff --git a/src/giant_python/numerics/peaks.py b/src/giant_python/numerics/peaks.py index 4c637152..eaaeb5d8 100644 --- a/src/giant_python/numerics/peaks.py +++ b/src/giant_python/numerics/peaks.py @@ -549,7 +549,7 @@ 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 diff --git a/src/giant_python/pipeline/reg_stats.py b/src/giant_python/pipeline/reg_stats.py index 84618172..15ad9aef 100644 --- a/src/giant_python/pipeline/reg_stats.py +++ b/src/giant_python/pipeline/reg_stats.py @@ -36,19 +36,19 @@ def _scalar(f: h5py.File, name: str, default=None): - """A scalar of a MATLAB-layout file (``default`` if absent).""" + """Read a scalar of a MATLAB-layout file (``default`` if absent).""" 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.""" 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. + """Read what the statistics need from an alignment file. Returns ------- @@ -95,22 +95,26 @@ 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.""" 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. + """ 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. + """ return { "refOffset": _vector(grp, "refOffset"), "frameRefX": _vector(grp, "frameRefX"), @@ -121,9 +125,11 @@ 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).""" + """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. + """ from ..registration.compensation import compensation_record if source.compensation is None: @@ -139,7 +145,7 @@ def _check_compensation(dat, source, ds, saved: Optional[dict]) -> None: def registration_params(alignment: dict, table_settings: Optional[dict]): - """The settings that formed the trial's frames. + """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 @@ -161,7 +167,7 @@ def registration_params(alignment: dict, table_settings: Optional[dict]): def _source(dat, first, last, alignment, params, device): - """The trial's frame source, checked against the alignment file.""" + """Open the trial's frame source, checked against the alignment file.""" from ..registration.multiroi import open_trial from ..registration.sources import make_source @@ -189,8 +195,10 @@ def _source(dat, first, last, alignment, params, device): 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).""" + """Iterate over the ``(frame, (channels, rows, cols))`` float32 frames of a registered movie. + + The movie is HDF5 ``/data`` or TIFF pages. + """ if path.suffix == ".h5": with h5py.File(path, "r") as f: data = f[next(iter(f.keys()))] @@ -216,7 +224,7 @@ def _movie_reader(path: Path, n_channels: int): def _var_factor_reader(path: Path): - """Iterator over each frame's ``(rows, cols)`` ``varFacDS``.""" + """Iterate over each frame's ``(rows, cols)`` ``varFacDS``.""" with h5py.File(path, "r") as f: vf = f["slap2/varFacDS"] n = vf.shape[0] @@ -310,8 +318,10 @@ 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. + """ from ..registration.stats import STATS_VERSION, alignment_digest if not (out.exists() and adata.exists() and movie.exists()): @@ -358,7 +368,7 @@ def _stats_job(job: dict) -> dict: def _table_settings(path: Path) -> Optional[dict]: - """The trial table's ``motion_correction/align_params`` (or None).""" + """Read the trial table's ``motion_correction/align_params`` (or None).""" from ..io.hdf5 import load_struct_h5 try: @@ -370,7 +380,7 @@ def _table_settings(path: Path) -> Optional[dict]: def _grid(value, shape) -> np.ndarray: - """A trial-table field as an object grid of ``shape``.""" + """Reshape a trial-table field as an object grid of ``shape``.""" return np.asarray(value, dtype=object).reshape(shape) @@ -385,8 +395,11 @@ def _selected(shape, paths, trials) -> np.ndarray: 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).""" + """One job per registered trial-path that needs statistics. + + Also the results of those whose movie or alignment file is missing + (failed). + """ from ..registration.stats import stats_path shape = files.shape diff --git a/src/giant_python/pipeline/silo.py b/src/giant_python/pipeline/silo.py index 3402988b..0f1c37a1 100644 --- a/src/giant_python/pipeline/silo.py +++ b/src/giant_python/pipeline/silo.py @@ -60,15 +60,21 @@ from .silo_session import ( NO_DATA, SiloSession, - recording_ids, - attr as _attr, - file_id as _file_id, make_pool, + recording_ids, run_jobs, - stage_hash as _hash, 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, +) log = logging.getLogger(__name__) @@ -76,7 +82,7 @@ def _localize_hash(session: SiloSession, params: SiloParams, d, t, baseline): - """Settings hash of one localization.""" + """Compute the settings hash of one localization.""" return _hash( { "stage": "localize", @@ -89,7 +95,7 @@ def _localize_hash(session: SiloSession, params: SiloParams, d, t, baseline): def _baseline_file(baseline_dir, movie: Path) -> Optional[Path]: - """The network baseline of a registered movie.""" + """Return the network baseline file of a registered movie.""" if baseline_dir is None: return None stem = movie.name[: movie.name.index("_REGISTERED")] @@ -97,22 +103,28 @@ def _baseline_file(baseline_dir, movie: Path) -> Optional[Path]: 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).""" + """Return the folder of the network's baselines. + + That is ``baseline_dir``, or the session's default (``/baselines``, + where ``--f0-ckpt`` puts them). + """ 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 the table's ``fn_reg_ds``, whether or not the movie is here. + """ 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``).""" + """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``). + """ from .silo_baseline import check_baseline_record base = _baseline_file( @@ -138,8 +150,10 @@ def _network_baseline(session, params, d, t, baseline_dir) -> Path: 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).""" + """Read a stage file's record of the baseline it used. + + Files made before the network baseline was wired in used the moving median. + """ value = _attr(path, name) if isinstance(value, bytes): value = value.decode() @@ -159,8 +173,10 @@ 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).""" + """Whether the plan needs each trial's half images. + + The patchwise alignment weights its patches with them. + """ return params.inter_trial_alignment == "patchwise" @@ -170,9 +186,11 @@ def _has_halves(path) -> bool: 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.""" + """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, @@ -191,11 +209,13 @@ def check_plan_alignment(what: str, plan, params: SiloParams) -> None: def check_plan_seeding(what: str, plan, params: SiloParams) -> None: - """Refuse to collect with another seed threshold or seed acceptance - than the plan's: the summary records them, and the evidence test - judges the sources by their height above the threshold, or all of - them after the null seed thresholds (a folder made with the network's - earlier default, 8, is not collected with today's, 3).""" + """Refuse to collect with another seed threshold or seed acceptance than the plan's. + + The summary records them, and the evidence test judges the sources by their + height above the threshold, or all of them after the null seed thresholds (a + folder made with the network's earlier default, 8, is not collected with + today's, 3). + """ used, given = float(plan.params.peak_th), float(params.peak_th) if used != given: raise ValueError( @@ -215,8 +235,10 @@ 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).""" + """Refuse to extract with a footprint support other than the plan's. + + The plan's zones were made for one support (``valid_kernel``: one per run). + """ _check_same( what, int(plan.params.valid_kernel), @@ -227,13 +249,15 @@ 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 - the trials' null movies are independent draws (with one seed for all + """Return the first null seed of trial-path ``(d, t)`` (zero-based). + + Used when the run 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.""" + ``max(1000, draws)`` apart. + """ width = max(1000, int(draws)) return int(base) + width * (1 + int(t) + 100000 * int(d)) @@ -343,7 +367,7 @@ def localize_jobs( fit_peaks: bool = True, overwrite: bool = False, ) -> list: - """The localization tasks still to do (stage ``localize``). + """List the localization tasks still to do (stage ``localize``). Parameters ---------- @@ -426,10 +450,12 @@ def localize_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 - them so that the localization file is not written while the plan stage - reads it).""" + """List the peak fits still to do: localization files without peaks. + + Peaks may be 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. + """ from ..extraction.raster.stage_files import localization_attrs if not params.trial_peaks: @@ -488,8 +514,10 @@ def localize( 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``.""" + """Read the localization records of path ``d`` (None for trials without). + + The half images are read only with ``half_ims``. + """ from ..extraction.raster.stage_files import read_localization recs = [] @@ -504,7 +532,7 @@ def _plan_inputs(session: SiloSession, d: int, half_ims: bool = False): def _localization_hashes(session, d) -> dict: - """The settings hashes of path ``d``'s localization files, by trial.""" + """Read the settings hashes of path ``d``'s localization files, by trial.""" locs = {} for t in range(session.n_trials): if session.keep[d, t]: @@ -516,10 +544,11 @@ def _localization_hashes(session, d) -> dict: 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 - its localizations' settings hashes (plans made before that are not - checked).""" + """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). + """ made = _attr(session.plan_file(d), "localization_hashes") if not made: return @@ -536,7 +565,7 @@ def check_plan_localizations(session, d) -> None: def _plan_hash(session, params, d, seeds, annotations) -> str: - """Settings hash of a path's plan.""" + """Compute the settings hash of a path's plan.""" locs = _localization_hashes(session, d) return _hash( { @@ -550,9 +579,11 @@ def _plan_hash(session, params, d, seeds, annotations) -> str: 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).""" + """Add the user ROIs in the consensus frame to a plan file. + + They go to ``/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"] @@ -567,7 +598,7 @@ def write_user_rois(path: Path, labels: Sequence[str], masks) -> None: def read_user_rois(path: Path) -> tuple[list, list]: - """The user ROIs of a plan file: labels and masks.""" + """Read the user ROIs of a plan file: labels and masks.""" with h5py.File(path, "r") as f: if "user_rois" not in f: return [], [] @@ -673,10 +704,12 @@ def plan_one( return out -def _check_localizations(session: SiloSession, params: SiloParams, d: int): - """Refuse to plan path ``d`` from localizations made with another - baseline than these settings', or without the half images that a - patchwise alignment needs.""" +def _check_localizations(session: SiloSession, params: SiloParams, d: int) -> None: + """Refuse to plan path ``d`` from localizations these settings cannot use. + + That is, localizations made with another baseline than these settings', or + without the half images that a patchwise alignment needs. + """ for t in np.flatnonzero(session.keep[d]): f = session.localize_file(d, int(t)) if f.exists(): @@ -793,9 +826,12 @@ def _prepare_hash( t, baseline: Optional[Path] = None, ) -> str: - """Settings hash of a container: 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).""" + """Compute 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). + """ from ..extraction.raster.baseline_map import MIN_WEIGHT record = { @@ -819,7 +855,7 @@ def _prepare_hash( def _extraction_baseline(session, params, d, t, baseline_dir): - """The baseline file the solver's mode needs for ``(d, t)``, or 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 @@ -839,9 +875,11 @@ 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 - and step that slap2-f0 records, and its identity at prediction time - from the file's record (when it was predicted here).""" + """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 .silo_baseline import record_path network = {} @@ -859,8 +897,10 @@ def baseline_provenance(base: Path) -> dict: def localization_baseline(session: SiloSession, d: int, t: int): - """The network baseline trial-path ``(d, t)`` was localized with - (:func:`baseline_provenance`), or None.""" + """Return the network baseline trial-path ``(d, t)`` was localized with, or None. + + The baseline is described as by :func:`baseline_provenance`. + """ v = _attr(session.localize_file(d, t), "network_baseline") if isinstance(v, bytes): v = v.decode() @@ -870,7 +910,7 @@ 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. + """Read 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 @@ -895,7 +935,7 @@ def load_trial_baseline( def trial_subproblems(plan, trial, solver_params, baseline=None) -> list: - """The plan's subproblems on a loaded trial. + """Make the plan's subproblems on a loaded trial. With a solver mode that uses an external baseline, each gets the network's (``baseline``, a @@ -1032,8 +1072,10 @@ def prepare( 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.""" + """Mark a trial-path as without data. + + Its earlier container and results files are removed, 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}" @@ -1051,8 +1093,11 @@ 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 ) -> dict: - """What a container records of its settings (with the network: the - baseline source, and the identity of the baseline mapped into it).""" + """Build what a container records of its settings. + + With the network this includes the baseline source, and the identity of the + baseline mapped into it. + """ out = { "prepare": params.stage_settings("prepare"), "plan": plan_hash, @@ -1119,8 +1164,10 @@ def add(self, _future=None) -> None: 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.""" + """Return the last completion time once all ``n`` are in, or None. + + A future's result can be read before its callbacks have run. + """ with self.cond: self.cond.wait_for(lambda: len(self.times) >= self.n, timeout) return max(self.times) if self.times else None @@ -1142,8 +1189,10 @@ def _finish(p: _Pending) -> float: @dataclass class _ContainerView: - """What :func:`~.silo_solve.results_attrs` reads of a container, from a - loaded trial.""" + """What :func:`~.silo_solve.results_attrs` reads of a container. + + It is taken from a loaded trial. + """ trial: object plan: object @@ -1174,8 +1223,10 @@ def source(self): @property def params(self): - """What the container would record: its plan's hash and the - baseline's identity.""" + """What the container would record. + + That is, its plan's hash and the baseline's identity. + """ out = {"plan": self.plan_hash} if self.baseline is not None: out["baseline"] = self.baseline @@ -1183,8 +1234,9 @@ def params(self): 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. + """Solve a trial's subproblems. + + Returns futures from the pool (largest first), or results solved here. ``done`` gets each future's completion time (its done callback is attached as soon as the future exists, so a subproblem solved while the @@ -1217,7 +1269,7 @@ def _submit(subs, sp, options, pool, done: Optional[_Done] = None): def _save_container( folder, session, params, plan, ph, chash, trial, d, t, baseline=None -): +) -> None: """Write a loaded trial's container (``--save-subproblems``).""" from ..extraction.raster.container import write_container @@ -1240,9 +1292,11 @@ def _save_container( 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.""" + """Count 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. + """ total = 0 for s in subs: for a in (s.y, s.finv, s.baseline): @@ -1255,8 +1309,10 @@ 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.""" + """A trial-path the streaming driver extracts. + + It holds where its results go and the hashes they get. + """ d: int t: int @@ -1269,7 +1325,7 @@ class _Unit: def _loaded(units, load, execution: SiloExecution): - """``(unit, load(unit))`` in the units' order. + """Yield ``(unit, load(unit))`` in the units' order. ``units`` is an iterable, taken from only when a unit is about to be loaded (a generator can check each unit then). With @@ -1298,9 +1354,11 @@ 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 - when none waits or without a limit (bytes); otherwise only once a load - has given a bytes-per-line estimate and the estimate fits.""" + """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. + """ if not queued or limit is None: return True if not per_line: @@ -1310,8 +1368,11 @@ def _fits(queued: list, unit: _Unit, per_line: list, limit) -> bool: 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).""" + """Take the source's next unit. + + Returns ``(unit, None)`` for the source's next unit, ``(None, None)`` at its + end, or ``(None, error)`` if taking it raised (its check failed). + """ try: return next(source, None), None except Exception as exc: # handed on after the earlier units @@ -1319,8 +1380,10 @@ def _take(source) -> tuple: def _loaded_ahead(source, load, workers: int, limit): - """:func:`_loaded` with ``workers`` loader threads and a memory - ``limit`` in bytes (or None).""" + """Run :func:`_loaded` with ``workers`` loader threads and a memory limit. + + The memory ``limit`` is in bytes (or None). + """ from collections import deque from concurrent.futures import ThreadPoolExecutor @@ -1435,9 +1498,11 @@ def stream( # noqa: C901 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, - hashes) when the loader takes it, so that a later trial's - missing file does not stop the earlier ones.""" + """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. + """ for t in (int(x) for x in plan.valid_trials): base = _extraction_baseline( session, params, d, t, baseline_dir @@ -1613,8 +1678,11 @@ def load(u: _Unit) -> dict: 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 it was solved. + + Both times are in seconds since ``clock0``; the second is when 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() @@ -1676,7 +1744,7 @@ def _ready_paths( # noqa: C901 planned = {} timer["plan_paths"] = {} - def start(d): + def start(d) -> None: """Plan path ``d`` and fit its trials' peaks in the background.""" planned[ plan_pool.submit( @@ -1897,10 +1965,12 @@ def run_silo( 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) - does not set it. A :class:`SiloParams` is returned as it is: its - ``baseline_source`` was chosen when it was made.""" + """Default ``params``' ``baseline_source`` to 'network' when the network's baselines are given. + + This applies 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. + """ 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 3cdbaf0c..4db8ce2d 100644 --- a/src/giant_python/pipeline/silo_baseline.py +++ b/src/giant_python/pipeline/silo_baseline.py @@ -55,7 +55,7 @@ def file_sha256(path) -> str: - """A file's SHA-256 (cached per path, size and modification time).""" + """Compute a file's SHA-256 (cached per path, size and modification time).""" path = Path(path) st = path.stat() key = (str(path.resolve()), st.st_size, st.st_mtime_ns) @@ -69,22 +69,24 @@ def file_sha256(path) -> str: def checkpoint_identity(path) -> dict: - """A checkpoint's name, size and SHA-256 (cached per path, size and - modification time).""" + """Return a checkpoint's name, size and SHA-256. + + The SHA-256 is cached per path, size and modification time. + """ 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.""" + """Return the network baseline file of a registered 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. + """Find the slap2-f0 executable: ``command`` or ``slap2-f0`` on the PATH. Raises ------ @@ -102,20 +104,22 @@ 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``).""" 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).""" 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. + + That is :func:`_file_id`, with its SHA-256 when ``digest``. + """ out = _file_id(path) if digest: out["sha256"] = file_sha256(path) @@ -123,10 +127,12 @@ def _identity(path: Path, digest: bool) -> dict: def same_file(recorded: Optional[dict], path: Path) -> bool: - """Whether a recorded identity is ``path``'s: 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.""" + """Whether a recorded identity is ``path``'s. + + That is, 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. + """ if not recorded: return False now = _file_id(path) @@ -142,7 +148,7 @@ 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.""" return {n: getattr(params, n) for n in _PREDICTION_SETTINGS} @@ -183,7 +189,7 @@ 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. + """Read the record of a baseline file, checked against the run. Returns ------- @@ -246,9 +252,11 @@ def missing_baselines(session: SiloSession, baseline_dir, units=None) -> list: 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``).""" + """Return the registered movie of a trial that ``predict-registered`` reads. + + That is ``.tif`` or ``.h5``, the newer where both exist (slap2-f0's + ``registered_movies``). + """ chosen = None for ext in (".tif", ".h5"): p = Path(moco_dir) / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz{ext}" @@ -260,8 +268,11 @@ def f0_movie(moco_dir, stem: str) -> Optional[Path]: 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. + + That is, a trial with both a TIFF and an HDF5 movie whose newer one is not + SILo's. + """ for _, _, movie in todo: stem = movie.name[: movie.name.index("_REGISTERED")] other = f0_movie(session.moco_dir, stem) @@ -272,11 +283,13 @@ 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 - (: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.""" +def _check_kept(session, params, baseline_dir, units, todo, identity) -> None: + """Check that the baseline files that are kept fit the run. + + Their records must pass :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. + """ for d, t in _units(session, units): if (d, t) in todo: continue @@ -334,8 +347,10 @@ def _run(args: list, log: Path, verbose: bool): def _predict_args( exe, session, params, ckpt, baseline_dir, todo, device, out_frames ) -> list: - """The ``predict-registered`` command line for the trial-paths - ``todo`` (the run's trial preparation settings).""" + """Build the ``predict-registered`` command line for the trial-paths ``todo``. + + It uses the run's trial preparation settings. + """ keys = sorted({m.name[: m.name.index("_REGISTERED")] for _, _, m in todo}) args = [ exe, diff --git a/src/giant_python/pipeline/silo_collect.py b/src/giant_python/pipeline/silo_collect.py index 9d2370dd..2bc314f8 100644 --- a/src/giant_python/pipeline/silo_collect.py +++ b/src/giant_python/pipeline/silo_collect.py @@ -34,7 +34,7 @@ def _results_files(session: SiloSession, d: int, t: int) -> list: - """The results files of trial-path ``(d, t)``.""" + """List the results files of trial-path ``(d, t)``.""" stem = f"path{d + 1}_trial{t + 1:04d}" folder = session.results_dir if not folder.exists(): @@ -49,10 +49,12 @@ def _results_files(session: SiloSession, d: int, t: int) -> list: 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; - 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).""" + """Compute 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). + """ from .silo import ( _baseline_file, _prepare_hash, @@ -81,10 +83,13 @@ def _current( science: str, container_hash: Optional[str] = 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).""" + """Keep the results files made from the plan ``plan_hash``. + + And, when given, from 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). + """ keep, stale = [], [] for f in files: ok = ( @@ -105,7 +110,7 @@ def _current( def _outcome_loader(files: list, solver_params): - """A function that assembles a trial from its results files.""" + """Make a function that assembles a trial from its results files.""" def load(): """Read the files and assemble the trial.""" @@ -218,9 +223,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( @@ -361,9 +368,11 @@ 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.""" + """Collect the network baselines the planned paths' trials were localized with. + + These decided the seeds. Keyed ``path_trial``; empty with the + moving median. + """ from .silo import check_plan_localizations, localization_baseline out = {} @@ -380,8 +389,10 @@ def localization_baselines(session: SiloSession) -> dict: 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.""" + """Read the network baseline recorded in a trial's results files, or None. + + The files are of one container, so they record the same. + """ for f in files: value = attr(f, "network_baseline") if value: @@ -392,7 +403,7 @@ def _baseline_identity(files: list) -> Optional[dict]: def read_kept(path) -> dict: - """Sources per path in an experiment summary (debugging aid).""" + """Count sources per path in an experiment summary (debugging aid).""" 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 b07fceeb..54209492 100644 --- a/src/giant_python/pipeline/silo_session.py +++ b/src/giant_python/pipeline/silo_session.py @@ -52,15 +52,16 @@ def stage_hash(record: dict) -> str: - """Settings hash of a stage's unit.""" + """Compute the settings hash of a stage's unit.""" 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 the file's 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. @@ -75,8 +76,9 @@ 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 + """Identities (:func:`file_id`) of the files a raw recording is read from. + + These are its ``.dat`` file (all files of a CYCLE-split recording) and the ``.meta`` files whose names begin its name. Raises @@ -107,12 +109,12 @@ def recording_ids(dat: Path) -> list: def now() -> str: - """The time as MATLAB's SILo records it.""" + """Return the time as MATLAB's SILo records it.""" 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.""" + """Read an attribute of an HDF5 file, or None if absent or unreadable.""" try: with h5py.File(path, "r") as f: v = f.attrs.get(name) @@ -134,13 +136,13 @@ def _worker_init(threads: int) -> None: def _warm(_): - """A first task, so that the pool starts all its workers at once.""" + """Run a first task, so that the pool starts all its workers at once.""" time.sleep(0.5) return os.getpid() def make_pool(workers: int, threads: int) -> cf.ProcessPoolExecutor: - """A process pool whose workers use ``threads`` threads each. + """Make 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 @@ -179,14 +181,14 @@ def run_jobs(func, jobs: list, workers: int, threads: int) -> list: def _decode(value) -> str: - """A string element of an HDF5 dataset.""" + """Decode a string element of an HDF5 dataset.""" 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.""" + """Read a dataset in MATLAB orientation (strings decoded), or None.""" if name not in f: return None ds = f[name] @@ -200,7 +202,7 @@ def _read(f: h5py.File, name: str, row_major: bool): def _grid(value, shape) -> np.ndarray: - """A per-path, per-trial grid of the table's shape.""" + """Reshape a value to a per-path, per-trial grid of the table's shape.""" a = np.asarray(value) if a.size == shape[0] * shape[1]: return a.reshape(shape) @@ -368,8 +370,7 @@ 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.""" + """Trial-path ``(d, t)``'s registered movie (``.tif`` or ``.h5``), if it exists.""" name = str(self.fn_reg_ds[d, t] or "") if not name: return None @@ -390,9 +391,11 @@ def raw(self, d: int, t: int) -> Path: 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 - alignment file and the raw file exist, and registration did not - fail; read the channels and frame rate of the first kept trial. + """Set :attr:`keep` as ``verifyFiles.m`` does. + + A trial-path is kept if 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 (and registration must not have failed): the dispatch and collect @@ -450,8 +453,10 @@ def skip_file(self, d: int, t: int) -> Path: 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``).""" + """Results file of trial-path ``(d, t)``. + + Or of subproblems ``span = (a, b)``, ``a`` to ``b - 1``. + """ stem = f"path{d + 1}_trial{t + 1:04d}" if span is not None: stem += f"_s{span[0]:04d}-{span[1] - 1:04d}" @@ -469,16 +474,21 @@ 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).""" + """Mark a trial-path as not extracted. + + Writes ``*.skip.json``: the reason, the settings hash of the prepare stage + and the plan's hash. + """ path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(f"{path.name}.{os.getpid()}.partial") record = { @@ -491,8 +501,10 @@ 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).""" + """Read a hash recorded in a skip marker. + + The hash is ``settings_hash`` or ``plan_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 16467268..67794965 100644 --- a/src/giant_python/pipeline/silo_solve.py +++ b/src/giant_python/pipeline/silo_solve.py @@ -72,17 +72,20 @@ 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) - on the CPU. Subproblems are batched exactly when this is not None, - whatever the number of processes.""" + """Return the batch size the solver uses. + + That 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. + """ 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.""" + """Collect what a results file depends on besides its container and range.""" return { "stage": "solve", "settings": params.stage_settings("solve"), @@ -99,14 +102,19 @@ 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``).""" + """Hash of how subproblems are solved. + + The same for every results file of one run; recorded as + ``solve_settings``. + """ 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.""" + """Hash the settings of a results file. + + How, which container, which subproblems. + """ return stage_hash( { **_solve_record(params, options), @@ -117,9 +125,11 @@ def solve_hash(params: SiloParams, options, container_hash: str, span) -> str: 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``).""" + """Give a trial's subproblems the frames their F0 images average. + + See :func:`~giant_python.extraction.raster.solver_setup.f0_image_frames`; + only when the run makes F0 images (``params.f0_im_trim_s``). + """ from ..extraction.raster.solver_setup import f0_image_frames if params.f0_im_trim_s is None or not subs: @@ -163,8 +173,10 @@ def solve_subproblem_list(subs, params, options, pool=None) -> list: 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).""" + """Hash of the scientific solve settings alone. + + Recorded as ``solve_science``; the collect stage checks it against its own. + """ return stage_hash({"solve": params.stage_settings("solve")}) @@ -217,9 +229,11 @@ def results_attrs( def check_container(container, params: SiloParams, name: str) -> None: - """Refuse to solve a container with other baseline settings or another - footprint support than it was prepared for, or without the baseline - the solver's mode needs.""" + """Refuse to solve a container with other settings than it was prepared for. + + That is, other baseline settings or another footprint support, or without + the baseline the solver's mode needs. + """ used = (container.params or {}).get("baseline_source", "median") if used != params.baseline_source: raise ValueError( @@ -351,8 +365,10 @@ 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. + + Returns the parts' ``[start, stop)``. + """ total = float(costs.sum()) if costs.size == 0: return [] @@ -591,9 +607,11 @@ def solve_containers( 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.""" + """Make a pool of solver processes, or None to solve here. + + None when one process is asked for, or with batches; this process's + threads are then set to ``solver_threads``. + """ 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) diff --git a/src/giant_python/pipeline/silo_spots.py b/src/giant_python/pipeline/silo_spots.py index ff0e5a3f..7af48804 100644 --- a/src/giant_python/pipeline/silo_spots.py +++ b/src/giant_python/pipeline/silo_spots.py @@ -51,7 +51,7 @@ def settings_of(params: SiloParams) -> sp.SpotSettings: - """The spot settings of a run.""" + """Return the spot settings of a run.""" return sp.SpotSettings( link_px=params.spot_link_px, split_corr=params.spot_split_corr, @@ -65,16 +65,19 @@ def settings_of(params: SiloParams) -> sp.SpotSettings: def _read_pixels( path: Path, pages_per_frame: int, page0: int, rows, cols, n_frames=None ) -> np.ndarray: - """``(frames, pixels)`` float32 of a movie or baseline 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``.""" + """``(frames, pixels)`` float32 of a movie or baseline at image pixels. + + 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); it is read at the image pixels ``(rows, cols)``, NaN at + pixels outside the image: page ``page0 + k * pages_per_frame`` is frame + ``k``. + """ 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``.""" + """Take the pixels of frames ``blk`` of an image ``n_r x n_c``.""" inside = (rows >= 0) & (rows < n_r) & (cols >= 0) & (cols < n_c) v = blk[ :, np.where(inside, cols, 0), np.where(inside, rows, 0) @@ -107,7 +110,7 @@ def take(blk, n_r, n_c): def _check_pages(path, n_pages, pages_per_frame, page0, n) -> None: - """A file must hold every page of the ``n`` frames asked for.""" + """Check that a file holds every page of the ``n`` frames asked for.""" 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" @@ -115,9 +118,11 @@ def _check_pages(path, n_pages, pages_per_frame, page0, n) -> None: 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).""" + """:func:`_read_pixels` of a TIFF, one selected page at a time. + + Pages are read as :func:`~giant_python.extraction.raster.trial._read_tiff_pages` + reads them: one series or a series per page. + """ import tifffile with tifffile.TiffFile(path) as tf: @@ -136,8 +141,10 @@ 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).""" + """Each pixel's running median over ``window`` frames. + + NaN is filled from the nearest valid frame first. + """ y = x.astype(np.float64) for j in range(y.shape[1]): v = y[:, j] @@ -155,8 +162,10 @@ def _running_median(x: np.ndarray, window: int) -> np.ndarray: 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).""" + """Canvas position of trial-image positions. + + This is the inverse of ``warp.coords``, by fixed-point iteration. + """ r = np.asarray(r_t, dtype=np.float64).copy() c = np.asarray(c_t, dtype=np.float64).copy() pr, pc = r.copy(), c.copy() @@ -173,9 +182,11 @@ def _to_canvas(warp, t: int, r_t, c_t, iters: int = 30): 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.""" + """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. + """ from ..extraction.raster.baseline_map import baseline_file if not session.keep[d, t] or t >= warp.n_trials or not warp.aligned[t]: @@ -195,8 +206,10 @@ def _trial_inputs(session, d, t, warp, baseline_dir): 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.""" + """Each spot's centre in trial ``t``'s image and its window's pixels. + + Returns ``(centres, slices, rows, cols)`` with ``rows[slices[j]]`` spot j's. + """ centres, slices, rows, cols = [], [], [], [] i0 = 0 for s in spots: @@ -223,8 +236,10 @@ def _windows(warp, t, spots, settings): 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.""" + """Compute the movie minus its baseline at the pixels ``(frames, pixels)``. + + NaN at SILo's motion discards and outside the image. + """ movie, bfile, align_hz, rne = inputs x = _read_pixels( movie, session.num_channels, params.activity_channel - 1, rows, cols @@ -247,9 +262,10 @@ def _delta_f(session, params, inputs, rows, cols): 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).""" + """Events (canvas positions and errors) of each spot in one trial (a pool task). + + Or what :func:`_trial_inputs` gives when it cannot be tested. + """ 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: @@ -287,9 +303,11 @@ def _spot_events( 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).""" + """Events (canvas positions and errors) of each multi-source spot of path ``d``. + + ``d`` is zero-based. Events come from every trial that can be tested (the + trials in ``pool`` when given; the result does not depend on it). + """ jobs = [ (session, params, settings, d, t, warp, spots, baseline_dir) for t in range(session.n_trials) @@ -322,21 +340,23 @@ def _spot_events( class SummaryWarp: - """The across-trial maps a summary records (``frame_info``), with - :class:`~giant_python.extraction.raster.alignment.TrialWarp`'s + """The across-trial maps a summary records (``frame_info``). + + It has :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).""" + edge values beyond it). + """ def __init__(self, affine: np.ndarray, field=None) -> None: - """Maps ``(trials, 2, 3)`` and fields ``(trials, 2, rows, cols)``.""" + """Hold 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).""" + """Read a path's maps from ``experiment_summary.h5`` (None without).""" with h5py.File(summary, "r") as f: fi = f"{name}/frame_info" if f"{fi}/trial_alignment_affine" not in f: @@ -382,14 +402,16 @@ def coords(self, trial: int, rows, cols): def _event_test_job(job): - """One spot's event test (a pool task).""" + """Run one spot's event test (a pool task).""" 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).""" + """Run the spots' event tests, in ``pool`` when given. + + The results do not depend on it: each spot has its own seed. + """ 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)) @@ -418,12 +440,14 @@ 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.""" + """``params`` with the signal settings the summary's run recorded (:data:`_RECORDED`). + + Also whether that run used the network's baselines + (``localizationBaseline``, ``baselineMode``); the spot settings stay. + """ def value(g, key): - """A recorded scalar, or None.""" + """Read a recorded scalar, or None.""" if g is None or key not in g: return None v = np.asarray(g[key][()]).ravel() @@ -448,8 +472,10 @@ def value(g, key): 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).""" + """Return the largest path number of a summary. + + Its paths need not all be there: a path without results is left out. + """ with h5py.File(summary, "r") as f: ids = [ int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit() @@ -465,8 +491,9 @@ def annotate_spots( 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. + + Write them into ``experiment_summary.h5``. Parameters ---------- @@ -538,8 +565,10 @@ 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.""" + """Group, test, label and write one path's spots (``d`` zero-based). + + Return 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: @@ -635,7 +664,7 @@ def _write( code = {k: i for i, k in enumerate(sp.LABELS)} def row(v, dt): - """A MATLAB row vector.""" + """Make a MATLAB row vector.""" return np.asarray(v, dtype=dt)[None, :] s.create_dataset( @@ -674,9 +703,11 @@ def row(v, dt): 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.""" + """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. + """ with h5py.File(summary, "r") as f: key = f"Path{d}/sources/spots" if key not in f: diff --git a/src/giant_python/pipeline/trial_table.py b/src/giant_python/pipeline/trial_table.py index 3dc0ac68..3354c399 100644 --- a/src/giant_python/pipeline/trial_table.py +++ b/src/giant_python/pipeline/trial_table.py @@ -129,8 +129,10 @@ def _later_cycle_file(name: str) -> bool: 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. + """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 @@ -266,7 +268,7 @@ 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.""" @@ -295,7 +297,7 @@ def find(pattern): def _json_array(value) -> np.ndarray: - """A JSON number or array as MATLAB's ``jsondecode`` gives it.""" + """Convert a JSON number or array as MATLAB's ``jsondecode`` gives it.""" arr = np.asarray(value, dtype=np.float64) if arr.ndim == 0: return arr.reshape(1, 1) @@ -305,7 +307,7 @@ def _json_array(value) -> np.ndarray: def read_reference_stack(path: Union[str, Path]) -> dict: - """A SLAP2 reference stack, as ``buildTrialTableSLAP2`` stores it. + """Read a SLAP2 reference stack, as ``buildTrialTableSLAP2`` stores it. Parameters ---------- @@ -379,7 +381,7 @@ 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, first, last, start, end) -> None: """Append one trial.""" self.files.append(files) self.first.append(first) @@ -678,7 +680,7 @@ def trim_trial_table( 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.""" + """Select the kept trials (columns) of a per-path, per-trial array.""" arr = np.asarray(value) return arr.reshape(2, -1)[:, keep] if arr.size == 2 * n_in else arr diff --git a/src/giant_python/registration/compensation.py b/src/giant_python/registration/compensation.py index 12f9d43f..0eb1c7b4 100644 --- a/src/giant_python/registration/compensation.py +++ b/src/giant_python/registration/compensation.py @@ -65,7 +65,7 @@ class LineOffsets: 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. + """Y on the DMD: each change of the header y applied ``lead`` earlier. Parameters ---------- @@ -141,7 +141,7 @@ def line_offsets( def frame_offsets( offsets: LineOffsets, times, dt: int, lines_per_cycle: int ) -> np.ndarray: - """The offset each frame mostly saw (``frameOnlineOffsets``). + """Compute the offset each frame mostly saw (``frameOnlineOffsets``). Parameters ---------- @@ -198,7 +198,7 @@ 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 ---------- diff --git a/src/giant_python/registration/frames.py b/src/giant_python/registration/frames.py index e243b557..1814a75e 100644 --- a/src/giant_python/registration/frames.py +++ b/src/giant_python/registration/frames.py @@ -93,7 +93,7 @@ def __init__( 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) @@ -196,7 +196,7 @@ def _accumulate(self, local, w, channels, band=None): ) return num, den - def _accumulate_band(self, local, w, used, channels, group, num, den): + def _accumulate_band(self, local, w, used, channels, group, num, den) -> None: """Add one band of frames' sums to ``num`` and ``den`` (in place).""" dev = self.device if not used.any(): @@ -262,7 +262,7 @@ def _channels(self, channels) -> list: 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. + """Yield sums of 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 @@ -329,7 +329,7 @@ class PixelFormer(FrameFormer): sums, whose fixed order of additions registration keeps. """ - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: """Map every place of the padded line layout to its pixel.""" super().__init__(*args, **kwargs) has = self._pix_flat >= 0 @@ -349,7 +349,7 @@ def __init__(self, *args, **kwargs): ) def pixel_sums(self, times, dt: int, channels=None, shift_fn=None): - """Sums of frames, grouped by the displacement of their samples. + """Yield sums of frames, grouped by the displacement of their samples. Parameters ---------- @@ -417,7 +417,7 @@ def _add_frames(self, total, group, part) -> None: else: total.index_add_(1, torch.from_numpy(group).to(self.device), part) - def _pixel_band(self, local, w, used, channels, group, num, den): + def _pixel_band(self, local, w, used, channels, group, num, den) -> None: """Add one band of frames' sums to ``num`` and ``den`` (in place).""" if not used.any() or self._slot_pix.numel() == 0: return diff --git a/src/giant_python/registration/growth.py b/src/giant_python/registration/growth.py index 583c5946..31d49268 100644 --- a/src/giant_python/registration/growth.py +++ b/src/giant_python/registration/growth.py @@ -73,7 +73,7 @@ class FrameCache: def __init__( self, source, ds, chunk: int = 64, max_device_bytes: float = 3e9 - ): + ) -> None: """Form and store all frames.""" self.window = source.window self.device = source.former.device @@ -91,7 +91,7 @@ def __init__( self.freshness[a:b] = f.to(store) def __len__(self) -> int: - """Number of frames.""" + """Return the number of frames.""" return self.freshness.shape[0] def present(self) -> np.ndarray: @@ -113,12 +113,12 @@ def batch(self, idx): ) def moving(self, idx): - """Matching image ``sqrt(sum of channels)`` and freshness.""" + """Return the matching image ``sqrt(sum of channels)`` and freshness.""" 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``.""" + """Register the channels and variance factor of frame ``k``.""" vals, fresh = self.batch([k]) fimg = self.window.image(fresh[0], 0.0) out = [] @@ -179,7 +179,7 @@ class GrowthQC: 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).""" return { "peakCorr": self.peak, "peakMargin": self.margin, @@ -194,7 +194,7 @@ 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.""" return cls( peak=np.full(n, np.nan), margin=np.full(n, np.nan), @@ -205,7 +205,7 @@ 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``. @@ -264,7 +264,7 @@ def __init__( candidates, dtype=torch.float32, independent=None, - ): + ) -> None: """Set up per-frame state.""" self.cache = cache self.state = state @@ -337,13 +337,13 @@ def _match(self, items): return motion, peak, margin, edge def _init_of(self, motion): - """Rounded, clamped starting shift from a motion estimate.""" + """Round and clamp a motion estimate to a starting shift.""" 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, motions, peaks, margins, anchors, kinds, roots) -> None: """Record aligned frames and add them to the template.""" ks = np.asarray(ks, dtype=np.int64) if ks.size == 0: @@ -364,7 +364,7 @@ def _accept(self, ks, motions, peaks, margins, anchors, kinds, roots): imgs = self.cache.registered_sum(ks, motions, self.m) self.state.update(imgs) - def _withdraw(self, ks): + def _withdraw(self, ks) -> 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 +372,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( @@ -399,7 +399,7 @@ def _plausible(self, k: int, motion) -> bool: return False return True - def try_seeds(self, ks): + def try_seeds(self, ks) -> None: """Wide-search seed candidates; accept those passing the checks.""" # each frame once: a frame matched twice would be added twice ks = list( @@ -540,7 +540,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() @@ -592,7 +592,7 @@ def _jump_limit(self) -> float: return float(self.p.junction_jump_px) return max(1.0, self._step_limit()) - def _check_junctions(self, ks): + def _check_junctions(self, ks) -> None: """Resolve junctions formed by newly aligned frames.""" limit = self._jump_limit() for k in ks: @@ -627,7 +627,7 @@ def _chain(self, order, start): prev = mot[0] return motion, peak, margin - def _resolve(self, k: int, g: int, jump: float): + 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 diff --git a/src/giant_python/registration/multiroi.py b/src/giant_python/registration/multiroi.py index d9a7c7cc..79a1ee48 100644 --- a/src/giant_python/registration/multiroi.py +++ b/src/giant_python/registration/multiroi.py @@ -99,7 +99,7 @@ class TrialRegistration: class Timer: """Wall time of consecutive phases (synchronizing CUDA at each mark).""" - def __init__(self, device): + def __init__(self, device) -> None: """Start timing.""" self.device = torch.device(device) self.times = {} @@ -258,7 +258,7 @@ def __init__( var_deflate: int = 1, stats=None, stats_path=None, - ): + ) -> None: """Open the movie and the alignment file.""" ho, wo = out_shape self.stats = stats @@ -364,9 +364,11 @@ def _write_stats(self, fields: dict): 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).""" + """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: @@ -545,7 +547,7 @@ def alignment_fields( params, failed: bool, ): - """The ALIGNMENTDATA struct, as MultiRoiRegistration saves it.""" + """Build the ALIGNMENTDATA struct, as MultiRoiRegistration saves it.""" m = int(params.maxshift) window = source.window h, w = window.shape @@ -623,10 +625,12 @@ 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 + """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. + """ from .stats import new_accumulator try: @@ -640,9 +644,11 @@ def trial_stats( 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.""" + """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. + """ layout = source.former.layout m = int(params.maxshift) h, w = source.window.shape diff --git a/src/giant_python/registration/outputs.py b/src/giant_python/registration/outputs.py index bf5bb794..0e0391f3 100644 --- a/src/giant_python/registration/outputs.py +++ b/src/giant_python/registration/outputs.py @@ -49,9 +49,11 @@ 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).""" + """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. + """ with h5py.File(adata_path, "r") as f: if "slap2/unlitMasked" not in f: return False @@ -59,7 +61,7 @@ def unlit_masked(adata_path) -> bool: def settings_record(params) -> dict: - """The settings that produced a trial's outputs, as saved with them. + """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, @@ -88,7 +90,7 @@ 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() @@ -139,7 +141,7 @@ class _ChunkedFrames: filter, so any reader (MATLAB's ``h5read`` included) decompresses them. """ - def __init__(self, group, name, n_frames, shape, level: int): + def __init__(self, group, name, n_frames, shape, level: int) -> None: """Create the dataset ``(n_frames, cols, rows)`` (MATLAB layout).""" rows, cols = shape self.level = int(level) @@ -200,7 +202,7 @@ def __init__( n_pages: int, tiff: bool = True, deflate: int = 1, - ): + ) -> None: """Open the temporary file.""" self.path = Path(path) self.tmp = partial_path(self.path) @@ -291,7 +293,7 @@ def __init__( var_shape, 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) diff --git a/src/giant_python/registration/sources.py b/src/giant_python/registration/sources.py index 0389df68..cf229861 100644 --- a/src/giant_python/registration/sources.py +++ b/src/giant_python/registration/sources.py @@ -96,7 +96,7 @@ class PlainFrames: compensation: Optional[LineOffsets] = None - def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int): + def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int) -> None: """Trim the window to the valid pixels' bounding box.""" if not valid.any(): raise ValueError("the first initial frame has no samples") @@ -120,8 +120,10 @@ def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int): ) def frames(self, times): - """``(channels, frames, pixels)`` values and ``(frames, pixels)`` - freshness at the window's pixels.""" + """Form ``(channels, frames, pixels)`` values and ``(frames, pixels)`` freshness. + + Both are at the window's pixels. + """ vals, fresh = self.former.frames(times, self.dt) return vals[:, :, self.pixels], fresh[:, self.pixels] @@ -147,7 +149,7 @@ class CompensatedFrames: def __init__( self, former: FrameFormer, offsets: LineOffsets, dt: int, times - ): + ) -> None: """Trim to the raster's extent and list every reachable pixel.""" self.former = former self.compensation = offsets @@ -221,8 +223,10 @@ 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.""" + """Form ``(channels, frames, pixels)`` values and ``(frames, pixels)`` freshness. + + Both are at the window's pixels, samples moved per line. + """ times = np.asarray(times, dtype=np.int64).ravel() refs = self.references(times) n_ch = self.former.layout.num_channels @@ -251,7 +255,7 @@ def shifts(lines): def _window_pixels(former: FrameFormer, init, dt: int) -> np.ndarray: - """The former's pixels whose bounding box is the registration window. + """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 @@ -270,9 +274,10 @@ def _window_pixels(former: FrameFormer, init, dt: int) -> np.ndarray: 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. + """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, @@ -306,7 +311,7 @@ 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. + """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..549a5bac 100644 --- a/src/giant_python/registration/stats/__init__.py +++ b/src/giant_python/registration/stats/__init__.py @@ -49,7 +49,7 @@ def new_accumulator(source, ds, margin: int, n_channels: int): - """The statistics accumulator of a trial. + """Create the statistics accumulator of a trial. Parameters ---------- diff --git a/src/giant_python/registration/stats/accumulate.py b/src/giant_python/registration/stats/accumulate.py index d729066e..1f09f5a4 100644 --- a/src/giant_python/registration/stats/accumulate.py +++ b/src/giant_python/registration/stats/accumulate.py @@ -75,10 +75,12 @@ def _widen(buf: torch.Tensor, cap: int, fill) -> torch.Tensor: 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. - def __init__(self, n_channels: int, device): + Stored with spare pixel capacity. + """ + + def __init__(self, n_channels: int, device) -> None: """No sums yet.""" self.c = n_channels self.device = device @@ -87,7 +89,7 @@ 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.""" if name not in self.data: self.data[name] = torch.zeros( (self.c, self.cap), dtype=torch.float64, device=self.device @@ -104,11 +106,13 @@ 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 @@ -151,8 +155,10 @@ def extend(self, n_new: int) -> None: 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.""" + """Sum rows ``lo .. hi`` (inclusive) from a cumulative sum with a leading zero row. + + ``lo`` and ``hi`` are row indices per centre. + """ return cs[hi + 1] - cs[lo] @@ -162,8 +168,10 @@ def _cumsum0(x: torch.Tensor) -> torch.Tensor: def _timed(fn): - """Time a method into ``self.timing`` when ``self.profile`` is set - (synchronizing the device; for measuring the cost only).""" + """Time a method into ``self.timing`` when ``self.profile`` is set. + + Synchronizes the device; for measuring the cost only. + """ @functools.wraps(fn) def wrapper(self, *args, **kwargs): @@ -200,7 +208,7 @@ class TrialStatsAccumulator: Channels per frame. """ - def __init__(self, geometry, gains, n_channels: int): + def __init__(self, geometry, gains, n_channels: int) -> None: """Empty sums for ``geometry.ds.size`` frames.""" self.geo = geometry self.gains = list(gains) @@ -356,10 +364,12 @@ def _geometry(self, g0: int, g1: int) -> None: 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.""" + """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. + """ lag = self.n_lags g_new, rp_new = out["G"][1:], out["Rp"] if self.lagbuf is None or g0 == 0: @@ -371,8 +381,10 @@ 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). + """ 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 +419,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]) @@ -441,8 +452,10 @@ 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`. + """ if self.n_added != self.n_frames: raise ValueError( f"{self.n_added} of {self.n_frames} frames were added" @@ -459,7 +472,7 @@ def _maps(self) -> dict: class _BlockChannel: """One channel's sums over one block (frames ``[b0, b1)``).""" - def __init__(self, owner, ch, rows: dict, span): + def __init__(self, owner, ch, rows: dict, span) -> None: """Rows of the span ``[s0, ...)`` for channel ``ch``.""" self.o = owner self.ch = ch @@ -512,8 +525,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 +552,11 @@ 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. + """ a = self.rows.start nb = (self.b1 - self.b0) // BIN_T n = self.v.shape[1] @@ -592,8 +609,9 @@ def _fast(self) -> None: 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). + """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 @@ -626,9 +644,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..1f30cc67 100644 --- a/src/giant_python/registration/stats/gain.py +++ b/src/giant_python/registration/stats/gain.py @@ -120,16 +120,18 @@ 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). + """ 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).""" return { k: getattr(self, k) for k in ( @@ -144,10 +146,13 @@ 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). + """ 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() @@ -180,8 +185,7 @@ 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 ---------- @@ -202,8 +206,7 @@ def slot_sums(samples: torch.Tensor, channel: int) -> np.ndarray: 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 @@ -231,7 +234,7 @@ 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).""" order = np.lexsort((slot_pos, slot_line)) nxt = np.full(slot_line.size, -1, dtype=np.int64) a, b = order[:-1], order[1:] @@ -241,8 +244,7 @@ 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 ------- @@ -335,7 +337,7 @@ 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 diff --git a/src/giant_python/registration/stats/geometry.py b/src/giant_python/registration/stats/geometry.py index fd6b4cf2..b83626c9 100644 --- a/src/giant_python/registration/stats/geometry.py +++ b/src/giant_python/registration/stats/geometry.py @@ -128,9 +128,11 @@ def bilinear_corners(motion_r: float, motion_c: float, margin: int): 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)``.""" + """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)``. + """ out = 1.0 for f in frac: out *= 1.0 + f * (1 - f) / ((1 - f) ** 2 + f**2) @@ -138,9 +140,10 @@ def spatial_factor(frac) -> float: 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`). + """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 @@ -226,7 +229,7 @@ class FrameGeometry: Registered frame shape. """ - def __init__(self, source, ds, margin: int): + def __init__(self, source, ds, margin: int) -> None: """Pixel tables of the window and the frames' kernel range.""" self.source = source self.former = source.former @@ -308,8 +311,11 @@ def _slot_directions(self): 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. + """ lay = self.former.layout n = int((lay.line_fast_z[lay.slot_line - 1] == 1).sum()) dirs = self.slot_dirs[1] @@ -321,9 +327,11 @@ def _pair_shares(self) -> dict: } 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)``).""" + """``(P, n_win + 1)`` float32: slots on line ``l`` of the window pixel. + + Those whose next sample is at ``pixel + delta`` (displacement + ``(dr, dc)``). + """ key = (int(dr), int(dc), tuple(delta)) if key not in self._adjacent: lay = self.former.layout @@ -352,8 +360,10 @@ 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. + """ key = (int(dr), int(dc)) if key not in self._incidence: p = self.former.layout.lines_per_cycle @@ -457,10 +467,12 @@ def _precompute(self) -> dict: 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. + """ total = None for key, (rows, single, pair) in self.tables.items(): r = rows[a:b] @@ -484,10 +496,12 @@ def _raw(self, which: int, a: int, b: int) -> torch.Tensor: 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).""" + """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). + """ flat = t.reshape(-1, t.shape[-1]) m = self.incidence(*key) imgs = [(flat @ m).reshape(t.shape[:2] + (m.shape[1],))] @@ -503,8 +517,9 @@ def _images(self, key, t: torch.Tensor, which: int) -> torch.Tensor: # ----------------------------------------------------- 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). + """Each frame's bilinear offsets, coefficients and fractions. + + As :func:`bilinear_corners`, for many frames. Parameters ---------- @@ -537,8 +552,10 @@ def corners(self, motion: np.ndarray, present: np.ndarray): 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).""" + """``(n, 4, n_idx)`` window-list index of each output pixel's raw neighbours. + + ``n_win`` outside the window or where unsampled. + """ h, w = self.window.shape big_w = self.out_shape[1] rr = torch.div(out_idx, big_w, rounding_mode="floor") @@ -554,8 +571,9 @@ def corner_index(self, out_idx: torch.Tensor, off: np.ndarray): 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. + """Products of the corner coefficients of frames ``t`` and ``t + l``. + + At the raw pixels the two share. Returns ------- @@ -645,10 +663,11 @@ def _corner_rows(self, k: int): 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`).""" + """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] @@ -713,9 +732,11 @@ def registered(self, f0, f1, f_ext, out_idx, motion, present, varfac): 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.""" + """``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. + """ raw = self._raw(2, f0 + a, f0 + b) lag3 = raw.shape[0] acc = None diff --git a/src/giant_python/registration/stats/io.py b/src/giant_python/registration/stats/io.py index 4770e228..76b02aa0 100644 --- a/src/giant_python/registration/stats/io.py +++ b/src/giant_python/registration/stats/io.py @@ -34,7 +34,7 @@ def stats_path(movie_path: Union[str, Path]) -> Path: - """The statistics file of a registered movie. + """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 @@ -49,8 +49,10 @@ def stats_path(movie_path: Union[str, Path]) -> Path: 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.""" + """SHA-256 of the frame times and motion (float64). + + These identify the registration the statistics were made from. + """ h = hashlib.sha256() for a in (ds_frames, motion_r, motion_c): h.update(np.ascontiguousarray(a, dtype=np.float64).ravel().tobytes()) @@ -104,7 +106,7 @@ def write_stats(path: Union[str, Path], result: dict, attrs: dict) -> None: def _attr(v): - """A file attribute as a Python value (JSON decoded where it is).""" + """Convert a file attribute to a Python value (JSON decoded where it is).""" if isinstance(v, bytes): v = v.decode() if isinstance(v, str) and v[:1] in "[{": @@ -118,7 +120,7 @@ def _attr(v): def read_stats(path: Union[str, Path]) -> dict: - """A statistics file, with maps as ``(channels, rows, cols)``. + """Read a statistics file, with maps as ``(channels, rows, cols)``. Returns ------- diff --git a/src/giant_python/registration/stats/maps.py b/src/giant_python/registration/stats/maps.py index a0b857b8..7f4ae8bc 100644 --- a/src/giant_python/registration/stats/maps.py +++ b/src/giant_python/registration/stats/maps.py @@ -41,7 +41,7 @@ def _np(t: torch.Tensor) -> np.ndarray: - """A tensor as a float64 NumPy array.""" + """Convert a tensor to a float64 NumPy array.""" return t.detach().double().cpu().numpy() @@ -105,7 +105,7 @@ def slow_maps(a: dict, mu, g: dict) -> dict: 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.""" + """Compute the expectation of the block-mean variance from its sums.""" return np.where(ok, (vb - (vb + 2 * cb) / jj) / (jj - 1), np.nan) q = expect(a["vb"], a["cb"]) @@ -122,8 +122,10 @@ 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).""" + """Second and third central moments of the fast part and their photon-noise expectations. + + Means over the pixel's centres. + """ nf = a["nf"] ok = nf >= MIN_FRAMES nn = np.maximum(nf, 1) @@ -193,11 +195,13 @@ def sigma8_map(a: dict, mu, g: dict) -> np.ndarray: 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 + """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). + """ n8 = np.maximum(a["n8"], 1) v = a["v8"] * (g["g2"] * kappa + 2 * g["c2"] * lam) with np.errstate(invalid="ignore"): diff --git a/src/giant_python/registration/stats/session.py b/src/giant_python/registration/stats/session.py index 2d932688..2d44aa5a 100644 --- a/src/giant_python/registration/stats/session.py +++ b/src/giant_python/registration/stats/session.py @@ -51,8 +51,10 @@ 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. + """ out = {} with np.errstate(invalid="ignore", divide="ignore"): for name, (inputs, fn) in NORMALISED.items(): @@ -64,12 +66,14 @@ def _normalised(m: dict) -> dict: def _resample( img: np.ndarray, warp, trial: int, shape, coords=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). + """ from ...extraction.raster.alignment import warp_trial_image canvas = np.full((img.shape[0],) + tuple(shape), np.nan) diff --git a/src/giant_python/registration/stats/svd.py b/src/giant_python/registration/stats/svd.py index 9128aa53..5c8c4ded 100644 --- a/src/giant_python/registration/stats/svd.py +++ b/src/giant_python/registration/stats/svd.py @@ -53,8 +53,10 @@ def _stack_bins(bins: list, n_idx: int) -> np.ndarray: 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). + """``(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 ---------- @@ -73,14 +75,18 @@ 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. + """ 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`).""" + """Photon-noise SD of each 2 x 2 bin's mean ``(n_space,)``. + + From its pixels' shares (:func:`.maps.bin_var8`). + """ return np.sqrt(bin_var[members].sum(-1) / 16) @@ -164,7 +170,7 @@ 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).""" nan = np.full((c, k), np.nan) return { "time_courses": np.full((c, k, nb), np.nan), @@ -205,7 +211,7 @@ def _channel(out, ch, full, idx, shape, sigma8, bin_var, k) -> None: def shared_modes(bins, idx, shape, sigma8, bin_var, k=N_COMPONENTS) -> dict: - """The trial's top shared modes per channel. + """Compute the trial's top shared modes per channel. Parameters ---------- diff --git a/src/giant_python/registration/stats/worker.py b/src/giant_python/registration/stats/worker.py index d9ac4c5e..ef99a418 100644 --- a/src/giant_python/registration/stats/worker.py +++ b/src/giant_python/registration/stats/worker.py @@ -32,8 +32,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,7 +51,7 @@ class StatsWorker: a thread. """ - def __init__(self, setup, device="cpu"): + def __init__(self, setup, device="cpu") -> None: """Start the worker with ``setup``.""" self.seconds = 0.0 self.failed = False @@ -74,9 +76,11 @@ def _call(self, name: str, *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.""" + """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. + """ if self._pool is None: done = Future() done.set_result(self._step(fn, None, None, *args)) @@ -119,9 +123,11 @@ def _step(self, fn, ready, tensors, *args): 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.""" + """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] @@ -130,9 +136,11 @@ def add(self, k: int, regs, var_factor, motion) -> None: ) 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. + """ if self._done is None and self.failed: self._done = Future() self._done.set_result(FAILED) @@ -143,8 +151,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..2bee4040 100644 --- a/src/giant_python/registration/template.py +++ b/src/giant_python/registration/template.py @@ -149,7 +149,7 @@ class TemplateState: Pixels with fewer contributions are NaN in the template. """ - def __init__(self, total, count, initial, min_samples: int): + def __init__(self, total, count, initial, min_samples: int) -> None: """Store the sums and compute the template.""" self.total = total self.count = count diff --git a/src/giant_python/simulation/injection.py b/src/giant_python/simulation/injection.py index 7ce43b42..745c204a 100644 --- a/src/giant_python/simulation/injection.py +++ b/src/giant_python/simulation/injection.py @@ -121,7 +121,7 @@ def _rng(seed: int, *key: int) -> np.random.Generator: - """An independent generator for one purpose (``key``) of a seed.""" + """Make 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) ) @@ -328,7 +328,7 @@ def peak_delay_s(tau_s: float, rise_s: float = 0.0) -> float: 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. + """Compute the indicator's response to an event at time 0, with a peak of 1. Parameters ---------- @@ -414,11 +414,11 @@ def concat(cls, parts: Sequence["Events"]) -> "Events": ) def __len__(self) -> int: - """Number of events.""" + """Return the number of events.""" return int(self.source.size) def select(self, mask) -> "Events": - """The events where ``mask`` is true.""" + """Select the events where ``mask`` is true.""" return Events( self.source[mask], self.trial[mask], @@ -593,7 +593,7 @@ def __init__( sigma_px: float = 1.33, radius_sigmas: float = 4.0, sigma_c_px: Optional[float] = 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)) @@ -630,7 +630,7 @@ class ImageFootprint: kind = "image" - def __init__(self, image, center: Optional[Sequence[float]] = None): + def __init__(self, image, center: Optional[Sequence[float]] = None) -> None: """Normalize the image and find its support radius.""" img = np.asarray(image, dtype=np.float64) if img.ndim != 2 or np.nanmin(img) < 0 or np.nanmax(img) <= 0: @@ -686,7 +686,7 @@ def peak_pixels(positions: np.ndarray, footprints: Sequence) -> np.ndarray: def footprint_patch(footprint, position, half: int) -> Tuple[np.ndarray, list]: - """A footprint on the integer pixels around a position. + """Sample a footprint on the integer pixels around a position. Returns ------- @@ -909,8 +909,10 @@ def place_sources( 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.""" + """Subtract an image's Gaussian background (0 without data). + + Also returns its data mask. + """ 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) @@ -918,8 +920,10 @@ def _highpass(x: np.ndarray, sigma: float) -> Tuple[np.ndarray, np.ndarray]: 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).""" + """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). + """ h, w = a.shape ra = slice(max(0, -dr), min(h, h - dr)) ca = slice(max(0, -dc), min(w, w - dc)) @@ -943,8 +947,10 @@ def _vertex(c_m: float, c_0: float, c_p: float) -> float: 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).""" + """Crop or NaN-pad an image at its bottom and right to ``shape``. + + Registered grids share their top-left corner, as in SILo. + """ 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] @@ -1059,7 +1065,7 @@ def read_alignment(path: Union[str, Path]) -> Alignment: """ def vec(ds): - """A dataset as a flat float vector.""" + """Read a dataset as a flat float vector.""" return np.asarray(ds[()], dtype=np.float64).ravel() with h5py.File(path, "r") as f: @@ -1246,7 +1252,7 @@ def __init__( footprints: Sequence, traces: np.ndarray, photon_scale: float = PHOTON_SCALE, - ): + ) -> None: """Find the (slot, source) pairs within reach.""" self.layout = layout self.geometry = geometry @@ -1292,7 +1298,7 @@ def lines(self, cycles: np.ndarray) -> np.ndarray: 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. + """Compute the expected extra raw counts of the reachable slots. Parameters ---------- @@ -1477,7 +1483,7 @@ def inject_samples( def meta_path(dat: Union[str, Path]) -> Path: - """The ``.meta`` file of a ``.dat`` file (as GIAnT's ``loadMetadata``).""" + """Return the ``.meta`` file of a ``.dat`` file (as GIAnT's ``loadMetadata``).""" dat = Path(dat) m = re.search(r"DMD\d", dat.stem) if m is None: @@ -1546,7 +1552,7 @@ def _recording_files(names, keep, paths, data_dir: Path) -> dict: def _relocated(layout: RasterLayout, dest: Path) -> RasterLayout: - """The same layout with its files in ``dest``.""" + """Return the same layout with its files in ``dest``.""" files = tuple(str(dest / Path(p).name) for p in layout.files) return replace(layout, files=files) @@ -1566,7 +1572,7 @@ def write_copy_table( save_dir: Path, paths: Optional[Sequence[int]] = 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 @@ -1601,7 +1607,7 @@ def write_copy_table( def _grid(value, n_paths: int, n: int) -> np.ndarray: - """A per-path, per-trial value as a ``(paths, trials)`` array.""" + """Shape a per-path, per-trial value as a ``(paths, trials)`` array.""" return np.asarray(value).reshape(n_paths, n) @@ -2067,9 +2073,11 @@ def _path_gain(settings: InjectionSettings, layout: RasterLayout): 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).""" + """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. + """ files = {t: set(ctx["files"][t]) for t in cells} def ranges(t): @@ -2402,7 +2410,7 @@ def inject_session( def _code_version() -> str: - """The package version.""" + """Return the package version.""" from .. import __version__ return f"giant_python {__version__}" @@ -2583,7 +2591,7 @@ 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)`` @@ -2811,7 +2819,7 @@ def build_parser() -> argparse.ArgumentParser: def _settings_from_args(args) -> Tuple[InjectionSettings, PlacementSettings]: - """Settings of ``inject``.""" + """Build the settings of ``inject``.""" settings = InjectionSettings( size_classes=tuple(args.sizes), class_weights=( diff --git a/src/giant_python/simulation/render.py b/src/giant_python/simulation/render.py index 0ee436fd..10bb0997 100644 --- a/src/giant_python/simulation/render.py +++ b/src/giant_python/simulation/render.py @@ -34,7 +34,7 @@ def _source(former: FrameFormer, alignment: Alignment, times, dt: int): - """The frame source matching the alignment's window and compensation.""" + """Build the frame source matching the alignment's window and compensation.""" layout = former.layout m = alignment.margin h, w = (s - 2 * m for s in alignment.shape) @@ -110,7 +110,7 @@ def iter_registered_frames( offset_rc=(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. + """Yield registered frames of ``samples``, a chunk of frames at a time. Parameters ---------- diff --git a/src/giant_python/spine/coverage.py b/src/giant_python/spine/coverage.py index 19cff504..8fb0a43f 100644 --- a/src/giant_python/spine/coverage.py +++ b/src/giant_python/spine/coverage.py @@ -83,7 +83,7 @@ def unimaged_pixels( skipped: list = [] def result(): - """The mask, and the skipped trials if asked for.""" + """Return the mask, and the skipped trials if asked for.""" if with_skipped: return out, np.asarray(skipped, np.int64) return out @@ -156,9 +156,12 @@ def _dark(chans: list, missing: np.ndarray, frac: float) -> np.ndarray: 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.""" + """One trial's dark pixels at the scan's edge, dilated. + + 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. + """ from scipy import ndimage # the frame's border counts as the scan's edge too @@ -175,8 +178,10 @@ def _edge_band(dark: np.ndarray, missing: np.ndarray, dilate: int): 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. + + The share is 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..7aab918c 100644 --- a/src/giant_python/spine/gains.py +++ b/src/giant_python/spine/gains.py @@ -42,8 +42,10 @@ 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.""" + """Read the rows and columns of a plan's selected-pixel list. + + Also returns the frame shape. + """ with h5py.File(plan_path, "r") as f: sel = f["sources/sel"][()].astype(bool) cols, rows = np.nonzero(sel.T) @@ -51,7 +53,7 @@ def selected_pixels(plan_path) -> tuple[np.ndarray, np.ndarray, tuple]: def _attr(f: h5py.File, name: str): - """A file's attribute as a string (None if absent).""" + """Read a file's attribute as a string (None if absent).""" v = f.attrs.get(name) if v is None: return None @@ -59,13 +61,15 @@ def _attr(f: h5py.File, name: str): def plan_file(work_dir, path: int) -> Path: - """The work folder's plan of a path.""" + """Return the work folder's plan of a path.""" 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``.""" + """Read the plan's settings hash. + + Its results files record it as ``plan_hash``. + """ with h5py.File(plan_path, "r") as f: h = _attr(f, "settings_hash") if h is None: @@ -74,8 +78,10 @@ def plan_hash(plan_path) -> str: 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. + """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 @@ -111,9 +117,11 @@ def current_results(files, plan: str) -> list: 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.""" + """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. + """ ns = f.attrs.get("n_subproblems") if ns is None: return n_sub @@ -127,8 +135,11 @@ def _n_subproblems(path, f: h5py.File, n_sub): 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.""" + """Read a subproblem's pixels and gains. + + The gains are ``baseline_step.gain`` of its ``info`` record, checked as + :func:`trial_gains` describes. + """ step = json.loads(g.attrs["info"]).get("baseline_step") if not step or "gain" not in step: raise ValueError( @@ -218,10 +229,12 @@ 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`).""" + """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`). + """ d = Path(work_dir) / "results" stem = f"path{path}_trial{trial + 1:04d}" files = sorted( @@ -239,9 +252,11 @@ def results_files(work_dir, path: int, trial: int) -> list: 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.""" + """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. + """ for path in files: with h5py.File(path, "r") as f: v = _attr(f, "network_baseline") @@ -251,8 +266,9 @@ def recorded_baseline(files): 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. + """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 ---------- diff --git a/src/giant_python/spine/images.py b/src/giant_python/spine/images.py index 7ecc7b34..4238568e 100644 --- a/src/giant_python/spine/images.py +++ b/src/giant_python/spine/images.py @@ -35,14 +35,15 @@ def trim_frames(trim_s: float, align_hz: float) -> int: - """Frames left out at each end of a trial: ``round(trim_s * - align_hz)``.""" + """Frames left out at each end of a trial: ``round(trim_s * align_hz)``.""" return int(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.""" + """Whether :func:`kept_frames` dropped the trim (a trial too short to trim). + + That is, a kept frame lies within ``n_trim`` frames of either end. + """ keep = np.asarray(keep, bool).ravel() if n_trim <= 0: return False @@ -57,7 +58,7 @@ 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. + """Select 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 @@ -175,8 +176,9 @@ def to_consensus( def file_identity(path) -> dict: - """Resolved path, name, size and modification time of a file (its - identity for caching). + """Return the resolved path, name, size and modification time of a file. + + These are its identity for caching. The path keeps files of other folders apart, such as copies that kept their modification times. @@ -302,7 +304,7 @@ def network_f0_stack( def stack_key(*parts) -> str: - """A short hash of JSON-serializable parts and arrays (cache keys).""" + """Hash JSON-serializable parts and arrays into a short cache key.""" h = hashlib.sha1() for p in parts: if isinstance(p, np.ndarray): diff --git a/src/giant_python/spine/pipeline.py b/src/giant_python/spine/pipeline.py index 732a4428..e95031f6 100644 --- a/src/giant_python/spine/pipeline.py +++ b/src/giant_python/spine/pipeline.py @@ -75,7 +75,7 @@ def _stem(name) -> str | None: - """A registered movie's trial stem (``E1T1DMD1``), or None.""" + """Return a registered movie's trial stem (``E1T1DMD1``), or None.""" name = str(name) if name is not None else "" if _REGISTERED not in name: return None @@ -85,9 +85,11 @@ def _stem(name) -> str | None: 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.""" + """Fill ``report`` from the report stored in a reused summary file. + + Keeps what this call already found, such as the network images' cache + keys, and passes its notes to ``say`` again. + """ with h5py.File(out, "r") as f: v = f.attrs.get("report") if v is None: @@ -102,7 +104,7 @@ def _replay_report(out: Path, report: dict, say) -> None: def _trials_and_window(n: int, images: dict, nfr, say): - """The trials read out and the images that set the windows. + """Choose the trials read out and the images that set the windows. 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. @@ -141,9 +143,11 @@ def _trials_and_window(n: int, images: dict, nfr, say): def _not_covered(r: dict, images: dict, window: list, used) -> dict: - """Per image that does not set the windows: how many windows it leaves - without a value in some trial used where the window images have one - (only images that leave some).""" + """Per image that does not set the windows: how many windows it leaves without a value. + + Windows without a value in some trial used where the window images have + one (only images that leave some). + """ if used.size == 0: return {} ref = np.ones(r[window[0]][used].shape, bool) @@ -160,8 +164,9 @@ def _not_covered(r: dict, images: dict, window: list, used) -> dict: 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. + """Compute the normalized sizes of every image's source readouts. + + See :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 @@ -192,12 +197,13 @@ def _normalize(r: dict, images: dict, window: list, used) -> dict: def _trends( n, norm: dict, acq, opts: dict, workers, say, note, activity_channel=1 ) -> 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 - 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``; + """Run 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 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``; :func:`~giant_python.spine.qc.structural_change`), when the run has a channel other than ``activity_channel``. @@ -295,8 +301,10 @@ def _trends( def _check_coverage_settings(frac, dilate, min_window, max_share) -> None: - """Refuse settings of the not-imaged pixels and windows that cannot - work (ValueError).""" + """Refuse settings of the not-imaged pixels and windows that cannot work. + + Raises ValueError. + """ if not 0 <= frac < 1: raise ValueError(f"unimaged_frac must be in [0, 1), not {frac}") if int(dilate) != dilate or dilate < 0: @@ -312,10 +320,12 @@ def _check_coverage_settings(frac, dilate, min_window, max_share) -> None: 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).""" + """Every image without the pixels its trial did not image, and those pixels. + + :func:`~giant_python.spine.coverage.unimaged_pixels`, from the mean + images; ``opts`` = (frac, dilate, max_share). The pixels are + ``(trials, rows, cols)`` (None when not looked for). + """ frac, dilate, max_share = opts if frac <= 0: return images, None @@ -360,10 +370,12 @@ def _leave_out_unimaged(n, images: dict, opts: tuple, report, note): 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, r, rs, valid, images, min_window, report, note) -> None: + """NaN sizes for the sources whose window keeps less than ``min_window`` of their weight. + + 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) @@ -381,8 +393,10 @@ 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).""" + """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 [ k for k, v in norm.items() @@ -391,9 +405,11 @@ def _sized_images(norm: dict) -> list: 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.""" + """Compute 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. + """ try: # the index base only moves an affine map's translation, which the # column removes @@ -404,10 +420,12 @@ 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, image, rec, rs, opts, report, note) -> None: + """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``. + """ arr = rec["arrays"] call = np.asarray(arr["call"], bool) d = np.asarray(arr["resid_d"], np.float64) @@ -460,14 +478,15 @@ def table_trials(table_path, path: int) -> tuple[list, np.ndarray]: def _base_name(name) -> str: - """The last part of a path written on any system.""" + """Return the last part of a path written on any system.""" 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. + """Write ``dest`` through a temporary file of its own in the same folder. + + ``write(tmp)`` writes it, then it is 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 @@ -498,8 +517,10 @@ def _write_atomic(dest, write) -> None: 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.""" + """Cache key of a path's network F0 stack. + + Its inputs' identities, the map, the frame and the settings. + """ ids = [] for stem in stems: if stem is None: @@ -535,7 +556,7 @@ def cached_f0_stack( settings: dict, progress=None, ) -> tuple[F0Stack, str, bool]: - """A path's network F0 stack, from the cache when its key matches. + """Get a path's network F0 stack, from the cache when its key matches. Returns ------- @@ -576,7 +597,7 @@ def cached_f0_stack( progress=progress, ) - def write(tmp): + def write(tmp) -> None: """Write the stack to ``tmp``.""" with h5py.File(tmp, "w") as f: f.create_dataset( @@ -777,7 +798,7 @@ def make_spine_summary( # noqa: C901 if baseline_dir is not None: shape = run.shape(n) - def prog(t, total, stem, n=n): + def prog(t, total, stem, n=n) -> None: """Report a trial's start.""" say(f"Path{n}: network F0 image {t + 1}/{total} ({stem})") @@ -828,8 +849,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) -> None: + """Add a note about the readout: shown, and stored with it.""" notes.append(msg) say(msg) diff --git a/src/giant_python/spine/product.py b/src/giant_python/spine/product.py index aafe088b..d8dca5bf 100644 --- a/src/giant_python/spine/product.py +++ b/src/giant_python/spine/product.py @@ -1,5 +1,6 @@ -"""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. + +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):: @@ -113,7 +114,7 @@ def _code_version() -> str: - """The installed GIAnT-Python version.""" + """Return the installed GIAnT-Python version.""" try: from importlib.metadata import version @@ -155,15 +156,17 @@ def read_roiset(g: h5py.Group, shape: tuple) -> RoiSet: def _attr_str(v) -> str | None: - """A string attribute as str (None when absent).""" + """Decode a string attribute as str (None when absent).""" if v is None: return None return v.decode() if isinstance(v, bytes) else str(v) def _write_root_attrs(f, settings, inputs, run_dir, report) -> None: - """The file's attributes (format, provenance, settings, inputs and the - readout's report).""" + """Write the file's attributes. + + Format, provenance, settings, inputs and the readout's report. + """ f.attrs["format"] = FORMAT f.attrs["format_version"] = FORMAT_VERSION f.attrs["code_version"] = _code_version() @@ -187,8 +190,10 @@ def _write_trends(g: h5py.Group, trends: dict) -> None: def _write_path_attrs(g: h5py.Group, p: dict) -> None: - """A path group's attributes (frame size, trials, activity channel and - default image).""" + """Write a path group's attributes. + + Frame size, trials, activity channel and default image. + """ g.attrs["rows"], g.attrs["cols"] = p["shape"] g.attrs["n_trials"] = len(p["trials"]["table_index"]) g.attrs["activity_channel"] = int(p.get("activity_channel", 1)) @@ -208,7 +213,7 @@ def _write_unimaged(g: h5py.Group, unimaged) -> None: def write_product( path, paths: dict, settings: dict, inputs: dict, run_dir, report=None -): +) -> None: """Write a ``spine_summary`` file. Parameters diff --git a/src/giant_python/spine/qc.py b/src/giant_python/spine/qc.py index fcae4a14..2ccc8fd4 100644 --- a/src/giant_python/spine/qc.py +++ b/src/giant_python/spine/qc.py @@ -38,8 +38,10 @@ def primary_image(names, activity_channel: int) -> str | None: - """The default image among ``names`` (see the module's notes); None - when none of them is one of the candidates.""" + """Pick the default image among ``names`` (see the module's notes). + + None when none of them is one of the candidates. + """ names = list(names) for pat in PRIMARY_ORDER: name = pat.format(a=int(activity_channel)) @@ -49,8 +51,10 @@ def primary_image(names, activity_channel: int) -> str | None: def structural_image(names, activity_channel: int) -> str | None: - """The first mean image of a channel other than the activity channel - (``mean_ch``, lowest ``c``), or None.""" + """Pick the first mean image of a channel other than the activity channel, or None. + + The image is ``mean_ch``, lowest ``c``. + """ chans = [] for name in names: if name.startswith("mean_ch") and name[7:].isdigit(): @@ -63,8 +67,9 @@ def structural_image(names, activity_channel: int) -> str | None: def window_motion( tmap, rois: RoiSet, valid: np.ndarray, trials, shape ) -> np.ndarray: - """Each window's movement beyond its trial's overall shift, as a - spread across ``trials`` (pixels; see the module's notes). + """Each window's movement beyond its trial's overall shift. + + Given as a spread across ``trials`` (pixels; see the module's notes). Parameters ---------- @@ -134,8 +139,7 @@ def window_motion( def structural_change(norm, ok, k) -> np.ndarray: - """A structural channel's change beyond its shared trend at given - splits. + """Measure a structural channel's change beyond its shared trend at given splits. Parameters ---------- diff --git a/src/giant_python/spine/rois.py b/src/giant_python/spine/rois.py index 7ae167f0..d4cb6495 100644 --- a/src/giant_python/spine/rois.py +++ b/src/giant_python/spine/rois.py @@ -63,7 +63,7 @@ class RoiSet: meta: dict = field(default_factory=dict) def __len__(self) -> int: - """Number of ROIs.""" + """Return the number of ROIs.""" return int(self.ids.size) def pixels(self, k: int) -> tuple[np.ndarray, np.ndarray]: @@ -82,8 +82,10 @@ def image(self, k: int) -> np.ndarray: def _from_images( kind: str, weights: np.ndarray, ids, labels, min_rel: float ) -> RoiSet: - """An :class:`RoiSet` from dense weight images ``(R, rows, cols)``, - keeping pixels above ``min_rel`` of each image's maximum.""" + """Build an :class:`RoiSet` from dense weight images ``(R, rows, cols)``. + + Keeps pixels above ``min_rel`` of each image's maximum. + """ weights = np.nan_to_num(np.asarray(weights, dtype=np.float64)) n, h, w = weights.shape rr, cc = np.mgrid[0:h, 0:w] @@ -121,7 +123,7 @@ def _from_images( def sources_roiset(profiles: np.ndarray, min_rel: float = 0.0) -> RoiSet: - """Sources' mean footprints as windows. + """Build windows from the sources' mean footprints. Parameters ---------- @@ -137,8 +139,7 @@ def sources_roiset(profiles: np.ndarray, min_rel: float = 0.0) -> RoiSet: def masks_roiset(masks: np.ndarray, labels: list) -> RoiSet: - """User ROIs (boolean masks ``(rois, rows, cols)``) as windows of - weight 1.""" + """User ROIs (boolean masks ``(rois, rows, cols)``) as windows of weight 1.""" masks = np.asarray(masks, dtype=bool) if len(labels) != masks.shape[0]: raise ValueError(f"{masks.shape[0]} masks but {len(labels)} labels") @@ -165,8 +166,10 @@ def disks_roiset( def nearest(roiset: RoiSet, rows, cols, max_dist: float) -> np.ndarray: - """For each point, the ROI whose centroid is nearest, within - ``max_dist`` pixels (-1 where none is).""" + """For each point, the ROI whose centroid is nearest. + + Only ROIs within ``max_dist`` pixels count (-1 where none is). + """ rows = np.asarray(rows, dtype=np.float64).ravel() cols = np.asarray(cols, dtype=np.float64).ravel() out = np.full(rows.size, -1, np.int64) @@ -182,8 +185,10 @@ def nearest(roiset: RoiSet, rows, cols, max_dist: float) -> np.ndarray: def read_marks(path) -> list: - """Marks from a ``spine_marks.csv`` file, as dicts (``Path`` as int, - ``Row0``/``Col0`` as float).""" + """Read marks from a ``spine_marks.csv`` file, as dicts. + + ``Path`` is read as int, ``Row0``/``Col0`` as float. + """ out = [] with open(path, newline="", encoding="utf-8") as fh: for row in csv.DictReader(fh): diff --git a/src/giant_python/spine/summary_io.py b/src/giant_python/spine/summary_io.py index 511e387e..b307d2d4 100644 --- a/src/giant_python/spine/summary_io.py +++ b/src/giant_python/spine/summary_io.py @@ -32,7 +32,7 @@ def _row_major(f: h5py.File) -> bool: def read_array(ds: h5py.Dataset, row_major: bool, index=()) -> np.ndarray: - """A dataset in MATLAB's dimension order. + """Read a dataset in MATLAB's dimension order. Parameters ---------- @@ -59,10 +59,12 @@ def read_array(ds: h5py.Dataset, row_major: bool, index=()) -> np.ndarray: def _per_trial(read, edges, n_sources: int, mean: bool) -> np.ndarray: - """Per-trial mean (``mean``) or number of positive frames of a - ``(sources, frames)`` trace, reading each trial's frames with + """Per-trial mean (``mean``) or number of positive frames of a trace. + + The trace is ``(sources, frames)``, each trial's frames read with ``read(start, stop)``; ``(trials, sources)``, NaN for a trial without - frames and for a source without any value in a trial.""" + frames and for a source without any value in a trial. + """ res = np.full((len(edges) - 1, n_sources), np.nan) for t in range(len(edges) - 1): if edges[t + 1] == edges[t]: @@ -80,7 +82,7 @@ def _per_trial(read, edges, n_sources: int, mean: bool) -> np.ndarray: def _strings(ds: h5py.Dataset) -> list: - """A cell array or array of strings as a list of str.""" + """Read a cell array or array of strings as a list of str.""" data = np.asarray(ds[()]).ravel() out = [] for v in data: @@ -120,8 +122,9 @@ def n_trials(self) -> int: @property def aligned(self) -> np.ndarray: - """Which trials have a map (bool per trial), as - :attr:`~giant_python.extraction.raster.alignment.TrialWarp.aligned`. + """Which trials have a map (bool per trial). + + As :attr:`~giant_python.extraction.raster.alignment.TrialWarp.aligned`. """ if self.displacement is not None: d = self.displacement.reshape(self.displacement.shape[0], -1) @@ -131,8 +134,10 @@ def aligned(self) -> np.ndarray: def grid_coords( self, trial: int, shape: tuple[int, int] ) -> tuple[np.ndarray, np.ndarray]: - """Positions in the trial's registered image of every pixel of the - ``(rows, cols)`` consensus grid (zero-based).""" + """Positions in the trial's registered image of every consensus pixel. + + One per pixel of the ``(rows, cols)`` consensus grid (zero-based). + """ rr = np.arange(shape[0], dtype=np.float64)[:, None] cc = np.arange(shape[1], dtype=np.float64)[None, :] rr, cc = np.broadcast_arrays(rr, cc) @@ -152,8 +157,10 @@ def grid_coords( class RunSummary: - """One SILo run's summaries (``experiment_summary.h5`` and, when there, - ``per_trial_summary.h5``). + """One SILo run's summaries. + + These are ``experiment_summary.h5`` and, when there, + ``per_trial_summary.h5``. Parameters ---------- @@ -162,8 +169,7 @@ class RunSummary: """ def __init__(self, run_dir) -> None: - """Open a run folder; raise ValueError without an experiment - summary.""" + """Open a run folder; raise ValueError without an experiment summary.""" self.run_dir = Path(run_dir) self.experiment_path = self.run_dir / EXPERIMENT_SUMMARY self.per_trial_path = self.run_dir / PER_TRIAL_SUMMARY @@ -178,11 +184,11 @@ def __init__(self, run_dir) -> None: ) def _exp(self) -> h5py.File: - """The experiment summary, open for reading.""" + """Open the experiment summary for reading.""" return h5py.File(self.experiment_path, "r") def _per_trial(self) -> h5py.File: - """The per-trial summary, open for reading.""" + """Open the per-trial summary for reading.""" if not self.per_trial_path.is_file(): raise ValueError(f"no {PER_TRIAL_SUMMARY} in {self.run_dir}") return h5py.File(self.per_trial_path, "r") @@ -200,14 +206,12 @@ def has(self, path: int, name: str) -> bool: return f"Path{path}/{name}" in f def array(self, path: int, name: str, index=()) -> np.ndarray: - """``Path/`` of the experiment summary, in MATLAB's - dimension order.""" + """``Path/`` of the experiment summary, in MATLAB's dimension order.""" with self._exp() as f: return read_array(f[f"Path{path}/{name}"], self._row_major, index) def per_trial_array(self, path: int, name: str, index=()) -> np.ndarray: - """``Path/`` of the per-trial summary, in MATLAB's - dimension order.""" + """``Path/`` of the per-trial summary, in MATLAB's dimension order.""" with self._per_trial() as f: row_major = _row_major(f) return read_array(f[f"Path{path}/{name}"], row_major, index) @@ -218,28 +222,30 @@ def shape(self, path: int) -> tuple[int, int]: return int(m.shape[-2]), int(m.shape[-1]) def n_channels(self, path: int) -> int: - """Number of channels of a path's images.""" + """Return the number of channels of a path's images.""" return int(self.array(path, "visualizations/mean_im").shape[0]) def trial_num_frames(self, path: int) -> np.ndarray: - """Each trial's number of extraction frames (0 for trials that were - not extracted).""" + """Each trial's number of extraction frames. + + 0 for trials that were not extracted. + """ return self.array(path, "frame_info/trial_num_frames").ravel() def n_trials(self, path: int) -> int: - """Number of trials of a path.""" + """Return the number of trials of a path.""" return int(self.trial_num_frames(path).size) def mean_im(self, path: int) -> np.ndarray: - """The path's mean image, ``(channels, rows, cols)``.""" + """Return the path's mean image, ``(channels, rows, cols)``.""" return self.array(path, "visualizations/mean_im")[:, 0] def act_im(self, path: int) -> np.ndarray: - """The path's activity image, ``(rows, cols)``.""" + """Return the path's activity image, ``(rows, cols)``.""" return self.array(path, "visualizations/act_im")[0] def per_trial_images(self, path: int, name: str, channel=None): - """A per-trial image stack, ``(trials, rows, cols)``. + """Read a per-trial image stack, ``(trials, rows, cols)``. Parameters ---------- @@ -257,13 +263,15 @@ def per_trial_images(self, path: int, name: str, channel=None): return self.per_trial_array(path, key, (slice(None), int(channel), 0)) def profiles(self, path: int) -> np.ndarray: - """The sources' mean footprints, ``(sources, rows, cols)``.""" + """Return the sources' mean footprints, ``(sources, rows, cols)``.""" p = self.array(path, "sources/spatial/profiles") return np.asarray(p[:, 0], dtype=np.float32) def user_rois(self, path: int) -> tuple[list, np.ndarray]: - """User ROIs: labels and masks ``(rois, rows, cols)`` in the - consensus frame (empty when the run has none).""" + """User ROIs: labels and masks ``(rois, rows, cols)`` in the consensus frame. + + Empty when the run has none. + """ if not self.has(path, "user_rois/mask"): return [], np.zeros((0,) + self.shape(path), bool) with self._exp() as f: @@ -272,8 +280,9 @@ def user_rois(self, path: int) -> tuple[list, np.ndarray]: return labels, masks def trial_map(self, path: int, affine_base: int | None = None) -> TrialMap: - """Each trial's map from the consensus frame to its registered - image (from ``frame_info``). + """Each trial's map from the consensus frame to its registered image. + + Read from ``frame_info``. Parameters ---------- @@ -311,8 +320,10 @@ def trial_map(self, path: int, affine_base: int | None = None) -> TrialMap: return TrialMap(affine, None) def param(self, name: str, default=None): - """A scalar setting of the run (the summary's ``params/``), - or ``default`` if it is not recorded.""" + """Return a scalar setting of the run, or ``default`` if it is not recorded. + + The setting is the summary's ``params/``. + """ with self._exp() as f: key = f"params/{name}" if key not in f: @@ -321,14 +332,17 @@ def param(self, name: str, default=None): return float(v[0]) if v.size else default def activity_channel(self) -> int: - """The run's activity channel (one-based file channel, the - summary's ``params/activityChannel``; 1 if it is not recorded).""" + """Return the run's activity channel (one-based file channel). + + The summary's ``params/activityChannel``; 1 if it is not recorded. + """ return int(self.param("activityChannel", 1)) def activity(self, path: int) -> dict: - """Per-trial activity of each source: the mean of ``dF_ls`` and the - number of frames with an event, in the run's activity channel, - ``(trials, sources)``. + """Per-trial activity of each source, ``(trials, sources)``. + + The mean of ``dF_ls`` and the number of frames with an event, in the + run's activity channel. The summaries keep the temporal traces in file-channel order, so the channel is :meth:`activity_channel`. NaN for trials that were not diff --git a/src/giant_python/spine/trends.py b/src/giant_python/spine/trends.py index 8e5cd3cd..f9594b93 100644 --- a/src/giant_python/spine/trends.py +++ b/src/giant_python/spine/trends.py @@ -1,5 +1,6 @@ -"""Trend tests of normalized spine sizes: ports of GIAnT-MATLAB's -``spineTrends.m`` and ``spineTrendsResid.m``. +"""Trend tests of normalized spine sizes. + +Ports of GIAnT-MATLAB's ``spineTrends.m`` and ``spineTrendsResid.m``. The input is a source's normalized size across the trials of a session (:func:`~giant_python.spine.readout.norm_log`). Two statistics look for a @@ -72,8 +73,9 @@ def trial_blocks(acquisition, unknown_consecutive: bool = True) -> np.ndarray: - """Blocks of consecutive acquisition numbers, as ``spineTrends.m``: - a new block starts where the number jumps by more than 1. + """Blocks of consecutive acquisition numbers, as ``spineTrends.m``. + + A new block starts where the number jumps by more than 1. A trial without a number (negative, as :func:`~giant_python.spine.pipeline.table_trials` reports it) is a @@ -105,11 +107,12 @@ def trial_blocks(acquisition, unknown_consecutive: bool = True) -> np.ndarray: def image_blocks(path_blocks, rows) -> np.ndarray: - """Blocks of a subset of a path's trials (an image's trials with - values): a new block starts where the path's block changes or where - the subset skips a trial, so that no brief run or neighbour reaches - across a block boundary or a missing trial, whatever the order of the - acquisition numbers. + """Blocks of a subset of a path's trials (an image's trials with values). + + A new block starts where the path's block changes or where the subset + skips a trial, so that no brief run or neighbour reaches across a block + boundary or a missing trial, whatever the order of the acquisition + numbers. Parameters ---------- @@ -135,11 +138,13 @@ def image_blocks(path_blocks, rows) -> np.ndarray: def check_trend_settings( n_perm, fdr_q, max_brief, seed, min_change=0.1 ) -> None: - """Refuse settings the tests cannot use (ValueError): ``n_perm`` must - be at least 0, ``max_brief`` at least 1, ``fdr_q`` in (0, 1], - ``seed`` at least 0 (numpy's seed sequences take no negative + """Refuse settings the tests cannot use (ValueError). + + ``n_perm`` must be at least 0, ``max_brief`` at least 1, ``fdr_q`` in + (0, 1], ``seed`` at least 0 (numpy's seed sequences take no negative numbers) and ``min_change`` in [0, 1) (a shrinking spine cannot change - by 100% or more).""" + by 100% or more). + """ if not 0 <= min_change < 1: raise ValueError(f"min_change must be in [0, 1), not {min_change}") if int(n_perm) != n_perm or n_perm < 0: @@ -155,7 +160,7 @@ def check_trend_settings( def step_stat(x: np.ndarray): - """The largest ``|t|`` of a step over all splits, per row. + """Find the largest ``|t|`` of a step over all splits, per row. Parameters ---------- @@ -205,7 +210,7 @@ def step_stat(x: np.ndarray): def step_at(x: np.ndarray, k): - """The step statistic at given splits (``spineTrends.m``'s ``stepAt``). + """Compute the step statistic at given splits (``spineTrends.m``'s ``stepAt``). Parameters ---------- @@ -240,8 +245,9 @@ def step_at(x: np.ndarray, k): def _kth_without(srt, removed, j: int) -> np.ndarray: - """Per row, the ``j``-th smallest (zero-based) of the sorted values - ``srt`` once the elements of ranks ``removed`` are taken out. + """Per row, the ``j``-th smallest (zero-based) of the sorted values ``srt``. + + The elements of ranks ``removed`` are taken out first. The answer is the sorted element at the smallest index ``i`` with ``i - #{removed <= i} = j``, which the iteration @@ -258,8 +264,11 @@ def _kth_without(srt, removed, j: int) -> np.ndarray: def _median_without(srt, removed, m: int) -> np.ndarray: - """Per row, the median of the ``m`` sorted values left once the elements - of ranks ``removed`` are taken out (as ``median`` of what is left).""" + """Per row, the median of the ``m`` sorted values left. + + The values are those left once the elements of ranks ``removed`` are + taken out (as ``median`` of what is left). + """ if m <= 0: return np.full(srt.shape[0], np.nan) if m % 2: @@ -271,7 +280,7 @@ def _median_without(srt, removed, m: int) -> np.ndarray: def brief_stat(x: np.ndarray, blocks, max_len: int = 3): - """The strongest transient change of 1 to ``max_len`` trials, per row. + """Find the strongest transient change of 1 to ``max_len`` trials, per row. Parameters ---------- @@ -371,7 +380,7 @@ def bh_adjust(p) -> np.ndarray: def shared_mode(x: np.ndarray): - """The trend shared by the rows: the first right singular vector. + """Find the trend shared by the rows: the first right singular vector. Parameters ---------- @@ -411,11 +420,13 @@ def _corr(x: np.ndarray, v: np.ndarray) -> np.ndarray: def trial_orders(seed: int, source: int, n_perm: int, n_trials: int): - """The random trial orders of one source: ``(n_perm, n_trials)`` indices - from numpy's generator seeded with ``(seed, source)``, so that the - orders, and the step and brief p-values, do not depend on which other - sources are tested (the beyond-trend p does, through the shared trend - estimated from all tested sources).""" + """Draw the random trial orders of one source: ``(n_perm, n_trials)`` indices. + + The indices come from numpy's generator seeded with ``(seed, source)``, so + that the orders, and the step and brief p-values, do not depend on which + other sources are tested (the beyond-trend p does, through the shared + trend estimated from all tested sources). + """ if n_perm <= 0: return np.zeros((0, n_trials), np.int64) return np.concatenate( @@ -424,8 +435,10 @@ def trial_orders(seed: int, source: int, n_perm: int, n_trials: int): def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): - """:func:`trial_orders` in chunks of up to ``rows`` orders (the same - orders: the generator permutes row after row).""" + """:func:`trial_orders` in chunks of up to ``rows`` orders. + + The same orders: the generator permutes row after row. + """ rng = np.random.default_rng([int(seed), int(source)]) done = 0 while done < n_perm: @@ -460,9 +473,11 @@ def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): def _perm_p( x, resid, t_obs, seed, source, n_perm, blocks, max_brief, rows=None ): - """One source's permutation p-values of the step, brief and resid - tests (``t_obs``: the observed statistics, in that order), from the - trial orders in chunks of ``rows`` (default: about a million cells).""" + """One source's permutation p-values of the step, brief and resid tests. + + ``t_obs``: the observed statistics, in that order. From the trial orders + in chunks of ``rows`` (default: about a million cells). + """ if rows is None: rows = max(1, _ORDER_CELLS // max(1, x.size)) hits = np.zeros(3, np.int64) @@ -482,8 +497,11 @@ def _perm_p( def _permute( out, idx, x, resid, seed, n_perm, blocks, max_brief, workers, progress ) -> None: - """Fill ``out``'s step, brief and resid p-values of the sources ``idx`` - (rows of ``x`` and ``resid``), in threads (numpy releases the GIL).""" + """Fill ``out``'s step, brief and resid p-values of the sources ``idx``. + + The sources are rows of ``x`` and ``resid``; in threads (numpy releases + the GIL). + """ import os from concurrent.futures import ThreadPoolExecutor @@ -521,7 +539,7 @@ def trend_tests( blocks=None, min_change: float = 0.1, ) -> dict: - """The step, brief and beyond-trend tests of every source. + """Run the step, brief and beyond-trend tests of every source. Parameters ---------- diff --git a/src/giant_python/spine/view/__init__.py b/src/giant_python/spine/view/__init__.py index 976cc92c..c551112a 100644 --- a/src/giant_python/spine/view/__init__.py +++ b/src/giant_python/spine/view/__init__.py @@ -1,3 +1,6 @@ -"""The spine viewer: ``giant spine view`` (:mod:`.server`, a local page) -and ``giant spine export-html`` (:mod:`.export`, one self-contained page), -both reading ``spine_summary`` files through :mod:`.data`.""" +"""The spine viewer: ``giant spine view`` and ``giant spine export-html``. + +``giant spine view`` (:mod:`.server`) is a local page and ``giant spine export-html`` +(:mod:`.export`) one self-contained page, both reading ``spine_summary`` files +through :mod:`.data`. +""" diff --git a/src/giant_python/spine/view/data.py b/src/giant_python/spine/view/data.py index 3bdf1726..546cfae7 100644 --- a/src/giant_python/spine/view/data.py +++ b/src/giant_python/spine/view/data.py @@ -49,7 +49,7 @@ def _decode(v): - """A string attribute as str.""" + """Convert a string attribute to str.""" return v.decode() if isinstance(v, bytes) else str(v) @@ -63,8 +63,10 @@ def _nanmean(a: np.ndarray, axis=0) -> np.ndarray: def blur_nan(img: np.ndarray, sigma: float = BLUR_SIGMA) -> np.ndarray: - """Gaussian blur that ignores NaN (normalized convolution), with - MATLAB ``imgaussfilt``'s radius ``ceil(2 sigma)``; NaN stays NaN.""" + """Gaussian blur that ignores NaN (normalized convolution). + + With MATLAB ``imgaussfilt``'s radius ``ceil(2 sigma)``; NaN stays NaN. + """ from scipy.ndimage import gaussian_filter m = np.isfinite(img) @@ -91,8 +93,11 @@ def robust_z(img: np.ndarray) -> np.ndarray: def late_trials(blocks: np.ndarray) -> np.ndarray: - """The 'late' trials of the mean's change view: the last block of - consecutive acquisition numbers, or with one block the second half.""" + """Select the 'late' trials of the mean's change view. + + The last block of consecutive acquisition numbers, or with one block the + second half. + """ blocks = np.asarray(blocks) if blocks.size and blocks.max() > blocks.min(): return blocks == blocks.max() @@ -116,12 +121,14 @@ def _nbytes(val) -> int: class _Lru: - """A least-recently-used cache bounded by the bytes of its arrays; a - value being made is made once, and concurrent requests for it wait for + """A least-recently-used cache bounded by the bytes of its arrays. + + A value being made is made once, and concurrent requests for it wait for it. The newest value is always kept, even when it alone exceeds the - budget.""" + budget. + """ - def __init__(self, max_bytes: int): + def __init__(self, max_bytes: int) -> None: """Keep values up to ``max_bytes`` in total.""" self.max_bytes = int(max_bytes) self.d: OrderedDict = OrderedDict() @@ -130,14 +137,14 @@ def __init__(self, max_bytes: int): self.making: dict = {} def _hit(self, key): - """``(True, value)`` if ``key`` is cached (call with the lock).""" + """Return ``(True, value)`` if ``key`` is cached (call with the lock).""" if key in self.d: self.d.move_to_end(key) return True, self.d[key] return False, None def get(self, key, make): - """The value of ``key``, made with ``make()`` if absent.""" + """Return the value of ``key``, made with ``make()`` if absent.""" with self.lock: hit, val = self._hit(key) if hit: @@ -172,7 +179,7 @@ def get(self, key, make): if entry[1] == 0 and self.making.get(key) is entry: del self.making[key] - def clear(self): + def clear(self) -> None: """Forget everything.""" with self.lock: self.d.clear() @@ -188,7 +195,7 @@ class SpineProduct: def __init__( self, path, name: str | None = None, cache_bytes: int = 2 * 1024**3 - ): + ) -> None: """Open ``path`` (checked for the format).""" self.file = Path(path) self.name = name or self.file.stem @@ -204,7 +211,7 @@ def __init__( self.small() def small(self) -> dict: - """The product without its images, re-read if the file changed.""" + """Return the product without its images, re-read if the file changed.""" mt = self.file.stat().st_mtime_ns with self._lock: if mt != self._mtime: @@ -285,7 +292,7 @@ def path(self, n: int) -> dict: # ---- images and what the views derive from them ---- def _stack(self, n: int, image: str) -> np.ndarray: - """A per-trial image stack (float32).""" + """Read a per-trial image stack (float32).""" with h5py.File(self.file, "r") as f: key = f"Path{n}/images/{image}" if key not in f: @@ -293,10 +300,12 @@ def _stack(self, n: int, image: str) -> np.ndarray: return f[key][()].astype(np.float32) def normalized(self, n: int, image: str) -> dict: - """Path ``n``'s image stack, each trial divided by its median over - the pixels with a value in every trial that has values, and the - mean of those trials (``stack``, ``mean``, ``medians``, - ``trials``).""" + """Path ``n``'s image stack, each trial divided by its median, and their mean. + + The median is over the pixels with a value in every trial that has + values, and the mean is of those trials (``stack``, ``mean``, + ``medians``, ``trials``). + """ def make(): """Read and normalize.""" @@ -333,9 +342,11 @@ def make(): return self._cache.get((self._gen, "norm", n, image), make) def change_prep(self, n: int, image: str) -> dict: - """The change views' inputs: the blurred normalized trials, their - mean, the brightness and the trials with values (``blurred``, - ``mean``, ``brightness``, ``trials``).""" + """Return the change views' inputs. + + The blurred normalized trials, their mean, the brightness and the + trials with values (``blurred``, ``mean``, ``brightness``, ``trials``). + """ def make(): """Blur and set the brightness.""" @@ -390,9 +401,11 @@ def blocks(self, n: int) -> np.ndarray: return trial_blocks_of(self.path(n)["trials"]["acquisition"]) def change(self, n: int, image: str, trial: int, vs: str) -> np.ndarray: - """``(2, rows, cols)``: the relative change (NaN where there is - none) and the brightness. ``trial`` -1: the late trials against - the earlier ones; ``vs`` 'average' or 'previous'.""" + """``(2, rows, cols)``: the relative change and the brightness. + + The change is NaN where there is none. ``trial`` -1: the late trials + against the earlier ones; ``vs`` 'average' or 'previous'. + """ cp = self.change_prep(n, image) bl = cp["blurred"] trials = cp["trials"] @@ -415,7 +428,7 @@ def change(self, n: int, image: str, trial: int, vs: str) -> np.ndarray: return np.stack([c, cp["brightness"]]).astype(np.float32) def field(self, n: int, image: str, trial: int, view: str, vs: str): - """The field image of a view: ``(layers, rows, cols)`` float32. + """Return the field image of a view: ``(layers, rows, cols)`` float32. ``view`` 'image' (one layer: the normalized trial, or their mean for ``trial`` -1), 'change' (two layers, :meth:`change`) or @@ -437,9 +450,11 @@ def field(self, n: int, image: str, trial: int, view: str, vs: str): class SpineStore: """The products and marks behind the viewer's API.""" - def __init__(self, products, marks=None, crop_half: int = CROP_HALF): - """``products``: (name or None, file) pairs; ``marks``: the marks - CSV (created on the first mark; None: no marks).""" + def __init__(self, products, marks=None, crop_half: int = CROP_HALF) -> None: + """``products``: (name or None, file) pairs; ``marks``: the marks CSV. + + The marks CSV is created on the first mark; None: no marks. + """ self.products = [SpineProduct(f, name) for name, f in products] names = [p.name for p in self.products] if len(set(names)) != len(names): @@ -450,7 +465,7 @@ def __init__(self, products, marks=None, crop_half: int = CROP_HALF): self._marks_lock = threading.Lock() def product(self, i: int) -> SpineProduct: - """The ``i``-th product.""" + """Return the ``i``-th product.""" if not 0 <= i < len(self.products): raise LookupError(f"no product {i}") return self.products[i] @@ -511,9 +526,11 @@ def meta(self) -> dict: } def sources(self, i: int, n: int) -> dict: - """Path ``n``'s sources: positions, normalized sizes per image, - trend tests, activity and marks (JSON, (trials, sources) arrays as - lists of rows).""" + """Path ``n``'s sources. + + Positions, normalized sizes per image, trend tests, activity and marks + (JSON, (trials, sources) arrays as lists of rows). + """ p = self.product(i).path(n) rs = p["rois"].get("sources") if rs is None: @@ -570,10 +587,12 @@ def sources(self, i: int, n: int) -> dict: } def roi(self, i: int, n: int, k: int) -> dict: - """Source ``k``'s window around its centre: weights and the pixels - the windows are restricted to, on a ``2 h + 1`` square grid whose - top-left pixel is ``origin`` (pixels outside the frame: weight 0, - not valid).""" + """Source ``k``'s window around its centre. + + Weights and the pixels the windows are restricted to, on a ``2 h + 1`` + square grid whose top-left pixel is ``origin`` (pixels outside the + frame: weight 0, not valid). + """ p = self.product(i).path(n) rs = p["rois"]["sources"] if not 0 <= k < len(rs): @@ -594,9 +613,11 @@ def roi(self, i: int, n: int, k: int) -> dict: } def crops(self, i, n, k, image, view, vs) -> np.ndarray: - """Source ``k``'s crops of an image: ``(layers, 1 + trials, s, s)``, - the mean first (for the change view the late against the early - trials), then each trial (NaN where it has no value).""" + """Source ``k``'s crops of an image: ``(layers, 1 + trials, s, s)``. + + The mean first (for the change view the late against the early + trials), then each trial (NaN where it has no value). + """ pr = self.product(i) p = pr.path(n) rs = p["rois"]["sources"] @@ -626,9 +647,11 @@ def _read_marks(self) -> list: return read_marks(self.marks_path) def marks_for(self, i: int, n: int) -> dict: - """Path ``n``'s marks, attached to the product's sources: per - source index the label, note and time (the newest mark wins when - two land on one source), and the marks with no source here.""" + """Path ``n``'s marks, attached to the product's sources. + + Per source index the label, note and time (the newest mark wins when + two land on one source), and the marks with no source here. + """ p = self.product(i).path(n) rs = p["rois"].get("sources") mine = [m for m in self._read_marks() if m["Path"] == n] @@ -658,9 +681,10 @@ def marks_for(self, i: int, n: int) -> dict: def set_mark( self, i: int, n: int, k: int, label, note: str, row=None, col=None ): - """Mark source ``k`` (``label`` '' clears its marks; None keeps the - label the source has, Unsure if none, and sets the note), keyed by - its position; returns the path's marks. + """Mark source ``k``, keyed by its position; returns the path's marks. + + ``label`` '' clears its marks; None keeps the label the source has, + Unsure if none, and sets the note. ``row`` and ``col``, when given, are the source's position as the caller has it: if source ``k`` is no longer there (the summary was @@ -710,8 +734,11 @@ def set_mark( def _check_position(rs, k: int, row, col) -> None: - """Refuse (ValueError) a mark whose caller sees source ``k`` at another - position than the summary has it (the summary was rewritten).""" + """Refuse (ValueError) a mark whose caller sees source ``k`` at another position. + + That is, at another position than the summary has it (the summary was + rewritten). + """ if row is None or col is None: return moved = np.hypot( @@ -725,8 +752,11 @@ def _check_position(rs, k: int, row, col) -> None: def _kept_label(marks: list) -> str: - """The label a note alone keeps: the newest of a source's marks (the - later row on equal times), Unsure without one.""" + """Return the label a note alone keeps. + + The newest of a source's marks (the later row on equal times), Unsure + without one. + """ label, best = "Unsure", None for m in marks: if best is None or m.get("Updated", "") >= best: @@ -735,13 +765,15 @@ def _kept_label(marks: list) -> str: def _centre(r, c) -> tuple: - """The integer pixel nearest a centroid.""" + """Return the integer pixel nearest a centroid.""" return int(np.floor(r + 0.5)), int(np.floor(c + 0.5)) def _crop(img: np.ndarray, r0: int, c0: int, hw: int, fill) -> np.ndarray: - """The ``2 hw + 1`` square of ``img`` centred on ``(r0, c0)``, with - ``fill`` outside the frame.""" + """Crop the ``2 hw + 1`` square of ``img`` centred on ``(r0, c0)``. + + ``fill`` is used outside the frame. + """ s = 2 * hw + 1 out = np.full((s, s), fill, dtype=np.float64) h, w = img.shape diff --git a/src/giant_python/spine/view/export.py b/src/giant_python/spine/view/export.py index 631f3366..ff1d8228 100644 --- a/src/giant_python/spine/view/export.py +++ b/src/giant_python/spine/view/export.py @@ -1,6 +1,6 @@ -"""``giant spine export-html``: one self-contained page of a -``spine_summary`` file, for reading away from the data (a private web page, -a file to send). +"""``giant spine export-html``: one self-contained page of a ``spine_summary`` file. + +For reading away from the data (a private web page, a file to send). The page is the viewer's own (:mod:`.server`'s ``page.html``) with the data embedded, gzip-compressed and base64-encoded: per path the sources' sizes, @@ -31,8 +31,7 @@ def field_key(n: int, image: str, trial: int, view: str, vs: str) -> str: - """Key of a field image in the page's data (as the page's - ``fieldKey``).""" + """Key of a field image in the page's data (as the page's ``fieldKey``).""" if view == "activity": return f"{n}||-1|activity|" v = vs if view == "change" and trial >= 0 else "" @@ -69,9 +68,11 @@ def _pack_layer(a: np.ndarray, lo=None, hi=None) -> dict: def pack(arr: np.ndarray, kind: str) -> dict: - """An array ``(layers, ...)`` for the page: ``kind`` 'image' (one - layer, percentile range), 'change' (relative change and brightness) - or 'activity' (z, -5 to 30).""" + """Pack an array ``(layers, ...)`` for the page. + + ``kind`` 'image' (one layer, percentile range), 'change' (relative + change and brightness) or 'activity' (z, -5 to 30). + """ arr = np.asarray(arr, np.float32) if kind == "change": layers = [_pack_layer(arr[0], -0.5, 0.5), _pack_layer(arr[1], 0, 1)] @@ -83,9 +84,11 @@ def pack(arr: np.ndarray, kind: str) -> dict: def primary_image(names, recorded: str | None = None) -> str | None: - """The image the table leads with (the viewer's default): the - summary's own default (``recorded``, its ``primary_image``) when it has - sizes for it, else the first of the preferred images.""" + """Choose the image the table leads with (the viewer's default). + + The summary's own default (``recorded``, its ``primary_image``) when it + has sizes for it, else the first of the preferred images. + """ if recorded and recorded in names: return recorded for nm in _PREFER: @@ -95,17 +98,21 @@ def primary_image(names, recorded: str | None = None) -> str | None: def pick_sources(src: dict, image: str | None, top: int) -> list: - """Source indices for the crops: the marked ones and ``top`` more: - the calls of ``image`` first, then the smallest q over its step, brief + """Source indices for the crops: the marked ones and ``top`` more. + + The calls of ``image`` first, then the smallest q over its step, brief and beyond-trend tests; ties (q at the floor of the permutations) go - to the larger statistic among the tests that give that q.""" + to the larger statistic among the tests that give that q. + """ picked = [int(k) for k in src.get("marks", {}).get("by_source", {})] tr = src.get("trends", {}).get(image) if image else None if tr and top > 0: def arr(key, missing): - """A per-source list as floats, None and NaN as ``missing`` - (infinite statistics stay infinite).""" + """Return a per-source list as floats, None and NaN as ``missing``. + + Infinite statistics stay infinite. + """ v = np.array([np.nan if x is None else x for x in tr[key]], float) return np.where(np.isnan(v), missing, v) @@ -133,7 +140,7 @@ def arr(key, missing): def _select_paths(available: dict, paths, product) -> dict: - """The requested paths of a summary (ValueError for one it lacks).""" + """Select the requested paths of a summary (ValueError for one it lacks).""" unknown = [n for n in paths if n not in available] if unknown: raise ValueError( @@ -145,16 +152,21 @@ def _select_paths(available: dict, paths, product) -> dict: def _crop_images(names: list, crop_images) -> list: - """The images a path's crops are made in: those asked for that the path - has (none of them: no crops), else its F0 images, else all.""" + """Choose the images a path's crops are made in. + + Those asked for that the path has (none of them: no crops), else its F0 + images, else all. + """ if crop_images: return [x for x in crop_images if x in names] return [x for x in names if x.startswith("f0")] or names -def _check_choices(store, paths: dict, sources, crop_images, product): - """Refuse source numbers and crop images that none of the chosen paths - has (ValueError), rather than writing a page without them.""" +def _check_choices(store, paths: dict, sources, crop_images, product) -> None: + """Refuse source numbers and crop images that none of the chosen paths has. + + Raises ValueError, rather than writing a page without them. + """ name = Path(product).name if crop_images: have = {x["name"] for info in paths.values() for x in info["images"]} diff --git a/src/giant_python/spine/view/server.py b/src/giant_python/spine/view/server.py index c42a00cb..71787ea4 100644 --- a/src/giant_python/spine/view/server.py +++ b/src/giant_python/spine/view/server.py @@ -81,8 +81,7 @@ def route(store: SpineStore, path: str, q: dict): class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of ``store`` (set by - :func:`make_handler`). + """Serves the page and the API of ``store`` (set by :func:`make_handler`). Every request must name a trusted host (``allowed``, set by :func:`make_server`: the loopback names and the bound host at the @@ -94,10 +93,10 @@ class _Handler(BaseHTTPRequestHandler): store: SpineStore allowed: frozenset = frozenset() - def log_message(self, *a): + def log_message(self, *a) -> None: """Quiet.""" - def _send(self, code: int, body: bytes, ctype: str, headers=None): + def _send(self, code: int, body: bytes, ctype: str, headers=None) -> None: """Send one response.""" self.send_response(code) self.send_header("Content-Type", ctype) @@ -108,12 +107,12 @@ def _send(self, code: int, body: bytes, ctype: str, headers=None): self.end_headers() self.wfile.write(body) - def _json(self, obj, code: int = 200, headers=None): + def _json(self, obj, code: int = 200, headers=None) -> None: """Send JSON (non-finite floats as null).""" body = json.dumps(json_safe(obj), allow_nan=False).encode() self._send(code, body, "application/json", headers) - def _guard(self, fn): + def _guard(self, fn) -> None: """Run ``fn`` and answer errors as JSON.""" try: fn() @@ -127,19 +126,21 @@ def _guard(self, fn): self._json({"error": f"{type(e).__name__}: {e}"}, 500) def _untrusted_host(self) -> bool: - """Whether the request's ``Host`` is not one of ``allowed`` (an - empty ``allowed`` trusts every host: a server bound to all - interfaces).""" + """Whether the request's ``Host`` is not one of ``allowed``. + + An empty ``allowed`` trusts every host: a server bound to all + interfaces. + """ if not self.allowed: return False return self.headers.get("Host", "").lower() not in self.allowed - 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(): + def go() -> None: """Answer it.""" if self._untrusted_host(): self._json({"error": "untrusted Host"}, 403) @@ -157,9 +158,11 @@ def go(): self._guard(go) def _cross_origin(self) -> bool: - """Whether the request comes from a page of another origin: its - ``Origin`` (or ``Referer``) is not ``http://`` and a trusted host - (with ``allowed`` empty, not the request's own ``Host``).""" + """Whether the request comes from a page of another origin. + + That is, its ``Origin`` (or ``Referer``) is not ``http://`` and a + trusted host (with ``allowed`` empty, not the request's own ``Host``). + """ src = self.headers.get("Origin") or self.headers.get("Referer") if not src: return False @@ -170,13 +173,15 @@ def _cross_origin(self) -> bool: return o.netloc.lower() not in self.allowed return o.netloc.lower() != self.headers.get("Host", "").lower() - def do_POST(self): - """Set a mark (JSON from a page of this server only: a page of - another origin cannot send JSON without a preflight, which this - server does not answer, and its Origin is refused).""" + def do_POST(self) -> None: + """Set a mark (JSON from a page of this server only). + + A page of another origin cannot send JSON without a preflight, which + this server does not answer, and its Origin is refused. + """ u = urlparse(self.path) - def go(): + def go() -> None: """Answer it.""" if self._untrusted_host(): self._json({"error": "untrusted Host"}, 403) @@ -213,7 +218,7 @@ def go(): def make_handler(store: SpineStore): - """The request handler class serving ``store``.""" + """Build the request handler class serving ``store``.""" return type("Handler", (_Handler,), {"store": store}) @@ -221,7 +226,7 @@ def make_handler(store: SpineStore): def make_server(store: SpineStore, host="127.0.0.1", port=DEFAULT_PORT): - """An HTTP server for ``store`` (not started). + """Create an HTTP server for ``store`` (not started). It answers only requests whose ``Host`` is a loopback name or ``host`` at the bound port; bound to all interfaces (``0.0.0.0``, ``::``), it @@ -235,10 +240,12 @@ def make_server(store: SpineStore, host="127.0.0.1", port=DEFAULT_PORT): def allowed_hosts(host: str, port: int) -> frozenset: - """The ``Host`` values a server bound to ``host`` and ``port`` - trusts: the loopback names and ``host``, with the port (and without + """Return the ``Host`` values a server bound to ``host`` and ``port`` trusts. + + These are the loopback names and ``host``, with the port (and without it at port 80, which browsers leave out); empty (every name) when - bound to all interfaces.""" + bound to all interfaces. + """ if host in ("0.0.0.0", "::", "[::]", ""): return frozenset() names = {_bracket(h) for h in set(_LOOPBACK) | {host.lower()}} @@ -255,7 +262,7 @@ class _Server6(ThreadingHTTPServer): def _bracket(host: str) -> str: - """An IPv6 literal in brackets, as URLs and Host headers write it.""" + """Put an IPv6 literal in brackets, as URLs and Host headers write it.""" host = host.strip("[]") return f"[{host}]" if ":" in host else host diff --git a/src/giant_python/viewer/render.py b/src/giant_python/viewer/render.py index d57e9680..46c8a4d9 100644 --- a/src/giant_python/viewer/render.py +++ b/src/giant_python/viewer/render.py @@ -45,7 +45,7 @@ def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float): - """The kernel's time constant in lines (the exporter's ``dt``). + """Return the kernel's time constant in lines (the exporter's ``dt``). ``ceil(mean(diff(DSframes)))``; with one registered frame, the 200 Hz frame spacing times ``ratio`` (analysis rate over movie rate). @@ -154,8 +154,10 @@ def interp_weights(lines200: np.ndarray, keep: np.ndarray, ds_lines): def frame_dt200(lines200: np.ndarray, default: float) -> float: - """The 200 Hz frames' own kernel ``dt`` in lines, - ``ceil(mean(diff(lines)))`` (``default`` with fewer than 2 frames).""" + """Return the 200 Hz frames' own kernel ``dt`` in lines. + + ``ceil(mean(diff(lines)))`` (``default`` with fewer than 2 frames). + """ lines200 = np.asarray(lines200, dtype=np.float64).ravel() if lines200.size < 2: return float(default) @@ -170,8 +172,7 @@ def exact_weights( dt200: float, reach: float, ): - """Weights that turn 200 Hz frames into the movie's 80 Hz frames - without smoothing twice. + """Weights that turn 200 Hz frames into the movie's 80 Hz frames without smoothing twice. Both frame rates are weighted means of the same samples with ``exp(-|dline| / dt)``, whose spectrum is ``1 / (1 + dt**2 w**2)``. @@ -227,8 +228,7 @@ def kernel_weights( dt80: float, lines_per_cycle: float = 0, ): - """A time kernel's weights from a trial's 200 Hz frames to its 80 Hz - frames. + """Compute a time kernel's weights from a trial's 200 Hz frames to its 80 Hz frames. Parameters ---------- @@ -299,7 +299,7 @@ class TrialMap: field : ndarray of shape (2, rows, cols), optional """ - def __init__(self, affine: np.ndarray, field: np.ndarray | None = None): + def __init__(self, affine: np.ndarray, field: np.ndarray | None = None) -> None: """Store the map.""" self.affine = np.asarray(affine, dtype=np.float64).reshape(2, 3) self.field = None if field is None else np.asarray(field, np.float64) @@ -357,8 +357,10 @@ def inverse(self, rt, ct, iters: int = 20, tol: float = 1e-6): def _patch(rows, cols, vals, margin: int): - """A footprint's dense canvas patch with a zero margin; returns the - patch and its origin ``(row, col)``.""" + """Build a footprint's dense canvas patch with a zero margin. + + Returns the patch and its origin ``(row, col)``. + """ r0, c0 = int(rows.min()) - margin, int(cols.min()) - margin h = int(rows.max()) - r0 + margin + 1 w = int(cols.max()) - c0 + margin + 1 @@ -412,7 +414,7 @@ def place_footprints( sigma: float = 0.0, interp_order: int = 1, ) -> sparse.csr_matrix: - """A trial's footprints moved into its registered frame. + """Move a trial's footprints into its registered frame. Parameters ---------- diff --git a/src/giant_python/viewer/run.py b/src/giant_python/viewer/run.py index 92eca7b8..083a8c57 100644 --- a/src/giant_python/viewer/run.py +++ b/src/giant_python/viewer/run.py @@ -28,7 +28,7 @@ def _mat(f, name: str): - """A summary dataset in MATLAB orientation, or None.""" + """Read a summary dataset in MATLAB orientation, or None.""" if name not in f: return None a = f[name][()] @@ -36,7 +36,7 @@ def _mat(f, name: str): def _scalar(v): - """An HDF5 value as a Python scalar or string.""" + """Convert an HDF5 value to a Python scalar or string.""" a = np.asarray(v) if a.dtype.kind in "SO": x = a.ravel()[0] if a.size else "" @@ -47,7 +47,7 @@ def _scalar(v): def find_summaries(run_dir) -> Path: - """The folder holding a run's ``experiment_summary.h5``.""" + """Find the folder holding a run's ``experiment_summary.h5``.""" run_dir = Path(run_dir) for d in (run_dir, run_dir / "source_extraction"): if (d / "experiment_summary.h5").exists(): @@ -62,7 +62,7 @@ def find_summaries(run_dir) -> Path: def _plan_file(run_dir: Path, summaries: Path, d: int) -> Optional[Path]: - """The plan file of path ``d`` (one-based), if the run kept it.""" + """Find the plan file of path ``d`` (one-based), if the run kept it.""" for p in ( run_dir / "work" / "plan" / f"path{d}.h5", summaries / "silo" / "plan" / f"path{d}.h5", @@ -73,9 +73,11 @@ def _plan_file(run_dir: Path, summaries: Path, d: int) -> Optional[Path]: def footprint_width(profile: np.ndarray, r0: float, c0: float, radius=6): - """RMS width per axis (px) of a footprint image over the disk of - ``radius`` px around its source pixel ``(r0, c0)``, values clipped at - 0 (the measure of the footprint-support comparisons).""" + """RMS width per axis (px) of a footprint image around its source pixel. + + It is taken over the disk of ``radius`` px around ``(r0, c0)``, values + clipped at 0 (the measure of the footprint-support comparisons). + """ r0, c0 = int(round(r0)), int(round(c0)) rr, cc = np.mgrid[-radius : radius + 1, -radius : radius + 1] m = rr**2 + cc**2 <= radius**2 @@ -131,7 +133,7 @@ def n(self) -> int: def _vec(a, n: int, fill=np.nan) -> np.ndarray: - """A summary vector as float64 of length ``n``.""" + """Return a summary vector as float64 of length ``n``.""" if a is None: return np.full(n, fill) return np.asarray(a, dtype=np.float64).ravel()[:n] @@ -188,7 +190,7 @@ def offsets(self) -> np.ndarray: return np.concatenate([[0], np.cumsum(self.n_frames)]).astype(int) def trial_span(self, t: int) -> slice: - """The concatenated frames of trial ``t`` (zero-based).""" + """Return the concatenated frames of trial ``t`` (zero-based).""" o = self.offsets return slice(int(o[t]), int(o[t + 1])) @@ -207,7 +209,7 @@ class SiloRun: Label shown on the page (default: the folder's name). """ - def __init__(self, run_dir, name: Optional[str] = None): + def __init__(self, run_dir, name: Optional[str] = None) -> None: """Open the run and read its parameters.""" self.run_dir = Path(run_dir) self.summaries = find_summaries(self.run_dir) @@ -232,7 +234,7 @@ def __init__(self, run_dir, name: Optional[str] = None): self._lock = threading.Lock() def param(self, name: str, default=None): - """A value of the run's ``params`` (MATLAB names).""" + """Return a value of the run's ``params`` (MATLAB names).""" v = self.params.get(name, default) return default if v is None or v == "" else v @@ -242,7 +244,7 @@ def activity_channel(self) -> int: return int(self.param("activityChannel", 1)) - 1 def describe(self) -> dict: - """The run's settings that the page shows.""" + """Return the run's settings that the page shows.""" keys = ( "baselineSource", "baselineMode", @@ -315,8 +317,11 @@ def _read_path(self, d: int) -> PathData: ) def traces(self, d: int) -> dict: - """The activity channel's traces of path ``d``: name to array - ``(total frames, kept sources)`` (dF_denoised, dF_ls, events, F0).""" + """Return the activity channel's traces of path ``d``. + + A dict from name to array ``(total frames, kept sources)`` (dF_denoised, + dF_ls, events, F0). + """ p = self.path(d) with self._lock: if not p._traces: @@ -337,8 +342,10 @@ def _read_traces(self, d: int) -> dict: return out def profile_patch(self, d: int, s: int, half: int = 7): - """Source ``s``'s mean footprint (``sources/spatial/profiles``) - around its pixel: ``(patch, row0, col0)``.""" + """Source ``s``'s mean footprint (``sources/spatial/profiles``) around its pixel. + + Returned as ``(patch, row0, col0)``. + """ p = self.path(d) r0, c0 = (int(v) for v in p.sources.pixel[s]) ra = slice(max(0, r0 - half), min(p.shape[0], r0 + half + 1)) @@ -349,8 +356,10 @@ def profile_patch(self, d: int, s: int, half: int = 7): return patch, ra.start, ca.start def footprints(self, d: int) -> list: - """Each trial's footprints of path ``d`` on the canvas, as - ``(rows, cols, sources, values)`` (None for a trial without).""" + """Each trial's footprints of path ``d`` on the canvas. + + Given as ``(rows, cols, sources, values)`` (None for a trial without). + """ p = self.path(d) with self._lock: if p._footprints is None: @@ -358,8 +367,10 @@ def footprints(self, d: int) -> list: return p._footprints def trial_centroids(self, d: int) -> np.ndarray: - """Per-trial footprint centroids ``(trials, sources, 2)`` (NaN - where a trial has none).""" + """Per-trial footprint centroids ``(trials, sources, 2)``. + + NaN where a trial has none. + """ self.footprints(d) return self.path(d)._trial_rc @@ -418,7 +429,7 @@ def _read_maps(f, fi: str, n_trials: int): def _read_sources(f, g: str, shape) -> Sources: - """A path's kept and rejected sources from the experiment summary.""" + """Read a path's kept and rejected sources from the experiment summary.""" rc = _rc(_mat(f, f"{g}/sources/spatial/coords")) n = rc.shape[0] pixel = _rc(_mat(f, f"{g}/visualizations/act_im_peaks")) diff --git a/src/giant_python/viewer/server.py b/src/giant_python/viewer/server.py index 6f57c124..3350fd53 100644 --- a/src/giant_python/viewer/server.py +++ b/src/giant_python/viewer/server.py @@ -71,7 +71,7 @@ def _json_safe(o): def _r(a, nd: int = 3) -> list: - """An array as nested lists rounded to ``nd`` decimals.""" + """Round an array to ``nd`` decimals as nested lists.""" return np.round(np.asarray(a, dtype=np.float64), nd).tolist() @@ -100,7 +100,7 @@ def __init__( cache_trials=2, blur=0.0, kernel="matched", - ): + ) -> None: """Check that the runs fit together.""" if not runs: raise ValueError("give at least one run") @@ -134,14 +134,14 @@ def __init__( self.progress: dict = {} def run(self, name: str) -> SiloRun: - """The run called ``name``.""" + """Return the run called ``name``.""" for r in self.runs: if r.name == name: return r raise KeyError(name) def meta(self) -> dict: - """What the page lists: runs, paths, trials.""" + """List what the page shows: runs, paths, trials.""" paths = [] for d in self.paths: p = self.runs[0].path(d) @@ -217,7 +217,7 @@ def sources(self, d: int) -> dict: return {"shape": list(self.runs[0].path(d).shape), "runs": out} def image(self, d: int, run: str, kind: str, trial: int) -> np.ndarray: - """An image of the canvas as float32 ``(rows, cols)``.""" + """Return an image of the canvas as float32 ``(rows, cols)``.""" p = self.run(run).path(d) if kind == "act": img = p.act_im @@ -263,7 +263,7 @@ def source(self, d: int, run: str, s: int) -> dict: } def source_traces(self, d: int, run: str, s: int) -> np.ndarray: - """A source's four traces ``(4, frames)`` float32.""" + """Return a source's four traces ``(4, frames)`` float32.""" tr = self.run(run).traces(d) n = self.run(run).path(d).lines.size out = np.full((len(TRACES), n), np.nan, np.float32) @@ -321,7 +321,7 @@ def _load(self, d: int, t: int): return tr def trial_static(self, d: int, t: int) -> dict: - """What the page needs once per trial-path.""" + """Return what the page needs once per trial-path.""" tr = self.trial(d, t) runs = {} for r in tr.runs: @@ -390,15 +390,17 @@ def _route(store: Store, path: str, q: dict): class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of ``store`` (set by - :func:`make_handler`).""" + """Serves the page and the API of ``store``. + + The ``store`` is set by :func:`make_handler`. + """ store: Store - def log_message(self, *a): + def log_message(self, *a) -> None: """Quiet.""" - def _send(self, code: int, body: bytes, ctype: str, headers=None): + def _send(self, code: int, body: bytes, ctype: str, headers=None) -> None: """Send one response.""" self.send_response(code) self.send_header("Content-Type", ctype) @@ -409,12 +411,12 @@ def _send(self, code: int, body: bytes, ctype: str, headers=None): self.end_headers() self.wfile.write(body) - def _json(self, obj, code: int = 200, headers=None): + def _json(self, obj, code: int = 200, headers=None) -> None: """Send JSON (non-finite floats as null).""" body = json.dumps(_json_safe(obj), allow_nan=False).encode() self._send(code, body, "application/json", headers) - 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()} @@ -439,7 +441,7 @@ def do_GET(self): def make_handler(store: Store): - """The request handler class serving ``store``.""" + """Build the request handler class serving ``store``.""" return type("Handler", (_Handler,), {"store": store}) @@ -456,7 +458,7 @@ def _run_args(items) -> list: def _default_table(run_dir: Path) -> Optional[Path]: - """A trial table in or above a run folder.""" + """Find a trial table in or above a run folder.""" for d in (run_dir, run_dir.parent, run_dir.parent.parent): if (d / "trial_table.h5").exists(): return d / "trial_table.h5" @@ -464,7 +466,7 @@ def _default_table(run_dir: Path) -> Optional[Path]: def make_store(args) -> Store: - """The store for parsed ``giant view`` arguments.""" + """Build the store for parsed ``giant view`` arguments.""" runs = [SiloRun(d, name) for name, d in _run_args(args.runs)] table = args.table or _default_table(runs[0].run_dir) if table is None: @@ -479,7 +481,7 @@ def make_store(args) -> Store: def make_server(store: Store, host="127.0.0.1", port=DEFAULT_PORT): - """An HTTP server for ``store`` (not started).""" + """Build an HTTP server for ``store`` (not started).""" return ThreadingHTTPServer((host, port), make_handler(store)) diff --git a/src/giant_python/viewer/trial.py b/src/giant_python/viewer/trial.py index 5cf15ed8..155086f0 100644 --- a/src/giant_python/viewer/trial.py +++ b/src/giant_python/viewer/trial.py @@ -54,7 +54,7 @@ class Session: table's ``datadr``; without them the kernel reaches 3 dt). """ - def __init__(self, table, moco_dir=None, baseline_dir=None, data_dir=None): + def __init__(self, table, moco_dir=None, baseline_dir=None, data_dir=None) -> None: """Read the table's file names.""" table = Path(table) if table.is_dir(): @@ -88,13 +88,15 @@ def __init__(self, table, moco_dir=None, baseline_dir=None, data_dir=None): @staticmethod def _name(value) -> str: - """A table file name without its folder.""" + """Return a table file name without its folder.""" return PurePath(str(value).replace("\\", "/")).name def movie_file(self, d: int, t: int) -> Path: - """The registered movie of path ``d``, trial ``t`` (zero-based): - found by its stem as ``.tif`` or ``.h5``, as SILo finds it - (:meth:`SiloSession.movie`); the table's name if neither exists.""" + """Find the registered movie of path ``d``, trial ``t`` (zero-based). + + It is found by its stem as ``.tif`` or ``.h5``, as SILo finds it + (:meth:`SiloSession.movie`); the table's name if neither exists. + """ name = self._name(self.fn_reg_ds[d, t]) stem = PurePath(name).stem for ext in (".tif", ".h5"): @@ -104,7 +106,7 @@ def movie_file(self, d: int, t: int) -> Path: return self.moco_dir / name def alignment_file(self, d: int, t: int) -> Path: - """The alignment file of path ``d``, trial ``t`` (zero-based).""" + """Return the alignment file of path ``d``, trial ``t`` (zero-based).""" return self.moco_dir / self._name(self.fn_adata[d, t]) def has_movie(self, d: int, t: int) -> bool: @@ -117,7 +119,7 @@ def has_movie(self, d: int, t: int) -> bool: ) def baseline_file(self, d: int, t: int) -> Optional[Path]: - """The trial's network baseline, if there is one.""" + """Find the trial's network baseline, if there is one.""" if self.baseline_dir is None: return None name = self._name(self.fn_reg_ds[d, t]) @@ -128,7 +130,7 @@ def baseline_file(self, d: int, t: int) -> Optional[Path]: return p if p.exists() else None def ds_lines(self, d: int, t: int) -> np.ndarray: - """The registered frames' lines (``DSframes``) of a trial.""" + """Read the registered frames' lines (``DSframes``) of a trial.""" key = (d, t) if key not in self._ds: with h5py.File(self.alignment_file(d, t), "r") as f: @@ -152,8 +154,10 @@ def lines_per_cycle(self, d: int, t: int) -> int: def read_channel(path: Path, num_channels: int, channel: int) -> np.ndarray: - """One channel of a registered movie as ``(frames, rows, cols)`` - float32 (zero-based channel; channels interleaved by frame).""" + """One channel of a registered movie as ``(frames, rows, cols)`` float32. + + Zero-based channel; channels interleaved by frame. + """ if path.suffix == ".h5": with h5py.File(path, "r") as f: ds = f[next(iter(f.keys()))] # (pages, MATLAB cols, rows) @@ -257,13 +261,15 @@ def layers(self) -> list: return out def span(self, t: int, avg: int) -> tuple: - """The frames ``[lo, hi)`` a mean of ``avg`` frames at ``t`` uses.""" + """Return the frames ``[lo, hi)`` a mean of ``avg`` frames at ``t`` uses.""" lo = min(max(t - (avg - 1) // 2, 0), self.T - 1) return lo, min(max(lo + avg, lo + 1), self.T) def _stack(self, frames, pixels, kernel=None) -> list: - """Every layer's values ``(frames, pixels)`` at the given frames - (a slice) and pixels (an index array or a slice).""" + """Every layer's values ``(frames, pixels)`` at the given frames and pixels. + + The frames are a slice; the pixels an index array or a slice. + """ kernel = kernel or self.kernel if kernel not in KERNELS: raise KeyError(f"kernel {kernel}") @@ -288,8 +294,10 @@ def _stack(self, frames, pixels, kernel=None) -> list: return out def frame(self, t: int, avg: int, kernel=None) -> np.ndarray: - """Each layer's mean over ``avg`` frames at ``t``: ``(layers, - valid pixels)`` float32, NaN-aware.""" + """Each layer's mean over ``avg`` frames at ``t``. + + ``(layers, valid pixels)`` float32, NaN-aware. + """ lo, hi = self.span(t, avg) blocks = self._stack(slice(lo, hi), slice(None), kernel) out = np.empty((len(blocks), self.N), np.float32) @@ -299,9 +307,10 @@ def frame(self, t: int, avg: int, kernel=None) -> np.ndarray: return out def trace(self, r: int, c: int, rad: int, kernel=None) -> tuple: - """Each layer's mean over the valid pixels within ``rad`` rows and - columns of ``(r, c)``: ``(layers, frames)`` float32, and the - number of pixels.""" + """Each layer's mean over the valid pixels within ``rad`` rows and columns of ``(r, c)``. + + Returns ``(layers, frames)`` float32, and the number of pixels. + """ near = (np.abs(self.rows - r) <= rad) & (np.abs(self.cols - c) <= rad) k = np.flatnonzero(near) out = np.full((len(self.layers), self.T), np.nan, np.float32) @@ -312,7 +321,7 @@ def trace(self, r: int, c: int, rad: int, kernel=None) -> tuple: return out, int(k.size) def busiest_frame(self, run: int = 0) -> int: - """The frame with the most rendered activity of a run.""" + """Find the frame with the most rendered activity of a run.""" r = self.runs[run] x = r.x80[self.kernel] if not r.rendered or x.size == 0: @@ -350,12 +359,14 @@ def _marker_rc(tmap, rc: np.ndarray) -> np.ndarray: def run_layer(run: SiloRun, session: Session, d: int, t: int, ctx: dict): - """One run's activity in trial ``t`` of path ``d`` (one-based path, - zero-based trial). ``ctx`` holds the trial's ``shape``, valid flat - pixel indices ``flat``, ``ds_lines``, the movie's kernel ``dt``, the - lines per cycle ``lpc`` and ``blur``; the time kernels come from the - run's own 200 Hz frame lines (:func:`render_dt`), and the run's 80 Hz - discard share under the exporter's kernel is added to ``ctx``.""" + """One run's activity in trial ``t`` of path ``d`` (one-based path, zero-based trial). + + ``ctx`` holds the trial's ``shape``, valid flat pixel indices ``flat``, + ``ds_lines``, the movie's kernel ``dt``, the lines per cycle ``lpc`` and + ``blur``; the time kernels come from the run's own 200 Hz frame lines + (:func:`render_dt`), and the run's 80 Hz discard share under the + exporter's kernel is added to ``ctx``. + """ p = run.path(d) n = p.sources.n tmap = p.maps[t] if t < len(p.maps) else None @@ -425,7 +436,7 @@ def _read_alignment(path: Path, n_frames: int): def render_dt(kernel: str, dt80: int, lines200: np.ndarray) -> float: - """The time constant (lines) the 200 Hz traces are averaged with. + """Return the time constant (lines) the 200 Hz traces are averaged with. ``exporter``: the movie's own ``dt``, as the exporter does. The 200 Hz frames are already averaged with their own kernel (``dt200 = @@ -454,8 +465,7 @@ def load_trial( blur: float = 0.0, kernel: str = "matched", ) -> TrialMovie: - """Load trial ``t`` (zero-based) of path ``d`` (one-based) with every - run's activity. + """Load trial ``t`` (zero-based) of path ``d`` (one-based) with every run's activity. The movie is NaN at SILo's motion discards (``recNegErr``, as ``loadAndProcessTrialAsync``) and at the frames whose kernel weight @@ -538,7 +548,7 @@ def load_trial( def _read_baseline(path: Optional[Path], shape: tuple, flat: np.ndarray): - """A network baseline at the valid pixels, float16 ``(frames, N)``.""" + """Read a network baseline at the valid pixels, float16 ``(frames, N)``.""" if path is None: return None T, R, C = shape @@ -551,8 +561,10 @@ def _read_baseline(path: Optional[Path], shape: tuple, flat: np.ndarray): def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: - """Indices of the ``n`` largest local maxima of ``x`` at least ``gap`` - samples apart (largest first).""" + """Return indices of the ``n`` largest local maxima of ``x`` at least ``gap`` samples apart. + + The indices are ordered largest first. + """ x = np.nan_to_num(np.asarray(x, np.float64), nan=-np.inf) if x.size < 3: return np.zeros(0, int) @@ -569,8 +581,10 @@ def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: def source_events(run: SiloRun, session: Session, d: int, s: int, n=30): - """A source's largest denoised events over all trials, as movie - frames: list of ``{trial, frame, line, value}`` (largest first).""" + """Find a source's largest denoised events over all trials, as movie frames. + + Returns a list of ``{trial, frame, line, value}`` (largest first). + """ p = run.path(d) x = run.traces(d)["dF_denoised"][:, s] hz = float(run.param("analyzeHz", 200.0)) diff --git a/tests/export/test_f0_injected.py b/tests/export/test_f0_injected.py index 674a89c3..0691eaa3 100644 --- a/tests/export/test_f0_injected.py +++ b/tests/export/test_f0_injected.py @@ -1,8 +1,11 @@ -"""GFP kind of the F0 training data (giant export-f0-injected) on a -synthetic recording with injected events.""" +"""GFP kind of the F0 training data (giant export-f0-injected). + +The tests run on a synthetic recording with injected events. +""" from dataclasses import replace from pathlib import Path +from typing import Any import h5py import numpy as np @@ -12,6 +15,7 @@ from giant_python.export.f0_injected import export_injected from giant_python.export.f0_training import ExportOptions from giant_python.io import slap2_raster +from giant_python.io.slap2_raster import RasterLayout from giant_python.pipeline.register import register_multiroi from giant_python.registration import multiroi from giant_python.simulation import injection as inj @@ -30,11 +34,19 @@ @pytest.fixture(scope="module") -def copy(tmp_path_factory): - """A synthetic recording, registered as two trials, a copy with bright - injected events, the copy registered and compared (positions on the - copy's grid); the raster layouts patched while the module's tests run - (the synthetic files have no real header).""" +def copy(tmp_path_factory: pytest.TempPathFactory): + """Build a synthetic recording and a registered copy with injected events. + + The recording is registered as two trials; the copy gets bright injected + events and is registered and compared (positions on the copy's grid). The + raster layouts stay patched while the module's tests run (the synthetic + files have no real header). + + Yields + ------ + Path + The copy's folder. + """ root = tmp_path_factory.mktemp("gfpkind") path = root / "rec" / "inj_DMD1-TRIAL000001.dat" path.parent.mkdir() @@ -49,12 +61,8 @@ def copy(tmp_path_factory): table = registered_table(layout, reg, True, [(1, 4800), (4801, 9700)]) out = root / "copy" mp.setattr(inj, "raster_layout", lambda p: layout) - inj.inject_session( - table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT - ) - copy_layout = replace( - layout, files=(str(out / "raw" / Path(layout.files[0]).name),) - ) + inj.inject_session(table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT) + copy_layout = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) mp.setattr(multiroi, "raster_layout", lambda p: copy_layout) register_multiroi( out / "trial_table.h5", @@ -68,13 +76,13 @@ def copy(tmp_path_factory): mp.undo() -def test_activity_is_the_injected_photons(copy, tmp_path): - """The activity holds the injected photons as drawn: their sum matches - the noiseless expectation within Poisson noise, nothing is injected - far from the sources, and the file has the training layout.""" - s = export_injected( - copy, tmp_path / "out", ExportOptions(label="syn"), expected=True - ) +def test_activity_is_the_injected_photons(copy: Path, tmp_path: Path) -> None: + """The activity holds the injected photons as drawn. + + Their sum matches the noiseless expectation within Poisson noise, nothing + is injected far from the sources, and the file has the training layout. + """ + s = export_injected(copy, tmp_path / "out", ExportOptions(label="syn"), expected=True) assert [q["trial"] for q in s["trials"]] == [1, 2] truth = inj.read_truth(copy / inj.TRUTH_NAME)["paths"][1] for q in s["trials"]: @@ -96,14 +104,14 @@ def test_activity_is_the_injected_photons(copy, tmp_path): np.testing.assert_array_equal(pr, np.rint(pos[:, 0]).astype(int) - r0) np.testing.assert_array_equal(pc, np.rint(pos[:, 1]).astype(int) - c0) assert sup.any() and np.abs(a[:, ~sup]).max() < 1e-2 * a.max() - assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx( - e[:, sup].sum(), rel=0.05 - ) + assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx(e[:, sup].sum(), rel=0.05) + +def test_cli_and_selection(copy: Path, tmp_path: Path) -> None: + """Giant export-f0-injected writes the chosen trial. -def test_cli_and_selection(copy, tmp_path): - """giant export-f0-injected writes the chosen trial; trials the copy - does not have are refused.""" + Trials the copy does not have are refused. + """ out = tmp_path / "out" rc = main(["export-f0-injected", str(copy), str(out), "--trials", "2"]) assert rc == 0 @@ -114,10 +122,12 @@ def test_cli_and_selection(copy, tmp_path): assert e.value.code == 2 -def test_target_is_the_original_on_the_copys_grid(copy, tmp_path): - """movie - activity equals the original's samples formed with the - copy's registration (its kernel and resampling weights): the injected - events leave nothing in the target.""" +def test_target_is_the_original_on_the_copys_grid(copy: Path, tmp_path: Path) -> None: + """Movie - activity equals the original's samples on the copy's grid. + + The samples are formed with the copy's registration (its kernel and + resampling weights): the injected events leave nothing in the target. + """ from giant_python.export.f0_injected import kernel_lines from giant_python.io.slap2_raster import read_raster_samples from giant_python.simulation.render import iter_registered_frames @@ -126,23 +136,17 @@ def test_target_is_the_original_on_the_copys_grid(copy, tmp_path): q = s["trials"][0] truth = inj.read_truth(copy / inj.TRUTH_NAME) layout = slap2_raster.raster_layout("unused") # the patched layout - al = inj.read_alignment( - copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5" - ) + al = inj.read_alignment(copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") with h5py.File(q["file"], "r") as f: m, a = f["movie"][0], f["activity"][0] r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) dt = float(f.attrs["movieDtLines"]) disc = f["frame/discard"][()].astype(bool) assert dt == kernel_lines(layout, 80.0) - orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype( - np.float32 - ) + orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype(np.float32) times = np.asarray(al.ds_frames, np.int64)[: m.shape[0]] ref = np.full((times.size,) + al.shape, np.nan, np.float32) - for idx, frames, _ in iter_registered_frames( - layout, orig, 0, al, times, int(dt) - ): + for idx, frames, _ in iter_registered_frames(layout, orig, 0, al, times, int(dt)): ref[idx] = frames[0].numpy() R, C = m.shape[1:] ref = ref[:, r0 : r0 + R, c0 : c0 + C] @@ -153,33 +157,35 @@ def test_target_is_the_original_on_the_copys_grid(copy, tmp_path): @pytest.mark.parametrize("channels", [(0,), (3,)]) -def test_channels_outside_the_movie_are_refused(copy, tmp_path, channels): +def test_channels_outside_the_movie_are_refused( + copy: Path, tmp_path: Path, channels: tuple[int, ...] +) -> None: """Channels are one-based and within the alignment file's numChannels.""" with pytest.raises(ValueError, match="channels"): - export_injected( - copy, tmp_path / "out", ExportOptions(channels=channels) - ) + export_injected(copy, tmp_path / "out", ExportOptions(channels=channels)) + +def test_footprints_rebuilt_from_the_truth() -> None: + """Gaussian footprints come back with their recorded widths and radius. -def test_footprints_rebuilt_from_the_truth(): - """Gaussian footprints come back with their recorded widths and radius; - an image footprint is refused when its model is needed.""" + An image footprint is refused when its model is needed. + """ from giant_python.export.f0_injected import injected_footprints g = {"kind": "gaussian", "sigma_rc": [1.0, 2.0], "radius_px": 8.0} fp = injected_footprints({"footprint": {"params": [g]}}, True)[0] assert fp.sigma == (1.0, 2.0) and fp.radius == pytest.approx(8.0) img = {"kind": "image", "center_rc": [1.0, 1.0], "radius_px": 3.0} - assert injected_footprints({"footprint": {"params": [img]}}, False) == [ - None - ] + assert injected_footprints({"footprint": {"params": [img]}}, False) == [None] with pytest.raises(ValueError, match="image"): injected_footprints({"footprint": {"params": [img]}}, True) -def test_default_export_reconciles_and_selection_keeps(copy, tmp_path): - """A default export removes earlier trial files it does not write; an - export of chosen trials leaves them.""" +def test_default_export_reconciles_and_selection_keeps(copy: Path, tmp_path: Path) -> None: + """A default export removes earlier trial files it does not write. + + An export of chosen trials leaves them. + """ out = tmp_path / "out" (out / "Path1").mkdir(parents=True) (out / "Path1" / "trial_007.h5").write_bytes(b"old") @@ -193,15 +199,23 @@ def test_default_export_reconciles_and_selection_keeps(copy, tmp_path): ] -def test_ragged_copy_and_bounded_reads(copy, tmp_path, monkeypatch): - """A column without a recording on the path is skipped (no error); a - trial reads only the cycles its frames' kernels reach.""" +def test_ragged_copy_and_bounded_reads(copy: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A column without a recording on the path is skipped (no error). + + A trial reads only the cycles its frames' kernels reach. + """ import giant_python.export.f0_injected as fi real = inj.read_truth - def ragged(path): - """The truth without trial 1 on path 1.""" + def ragged(path: str | Path): + """Read the truth without trial 1 on path 1. + + Returns + ------- + dict + The truth, with trial 1 removed from path 1's ``trials_detail``. + """ t = real(path) t["paths"][1]["trials_detail"].pop(1) # trial 1 not on this path return t @@ -210,8 +224,14 @@ def ragged(path): ranges = [] real_read = slap2_raster.read_raster_samples - def spy(layout, cycles, *a, **k): - """Record the cycles read.""" + def spy(layout: RasterLayout, cycles: tuple[int, int], *a: Any, **k: Any): + """Record the cycles read. + + Returns + ------- + np.ndarray + The samples from the real ``read_raster_samples``. + """ ranges.append(tuple(cycles)) return real_read(layout, cycles, *a, **k) @@ -224,7 +244,7 @@ def spy(layout, cycles, *a, **k): assert all(c1 - c0 < layout.num_cycles for c0, c1 in ranges) -def test_peaks_of_an_empty_source_list(): +def test_peaks_of_an_empty_source_list() -> None: """A copy without placed sources has no peaks (no index error).""" from giant_python.export.f0_injected import peak_positions @@ -236,10 +256,12 @@ def test_peaks_of_an_empty_source_list(): assert peak_positions(pth, np.zeros((0, 2))).shape == (0, 2) -def test_moved_copy_duplicate_channels_and_stale_paths(copy, tmp_path): - """A copy moved to another folder exports from its own raw files; a - repeated injected channel gets the activity in every occurrence; a - full export clears trial files of paths the copy does not have.""" +def test_moved_copy_duplicate_channels_and_stale_paths(copy: Path, tmp_path: Path) -> None: + """A copy moved to another folder exports from its own raw files. + + A repeated injected channel gets the activity in every occurrence; a full + export clears trial files of paths the copy does not have. + """ import shutil moved = tmp_path / "moved" diff --git a/tests/export/test_f0_layout.py b/tests/export/test_f0_layout.py index ba00754f..8b197f63 100644 --- a/tests/export/test_f0_layout.py +++ b/tests/export/test_f0_layout.py @@ -23,14 +23,13 @@ from giant_python.registration import multiroi from giant_python.registration.stats.gain import next_slots -from ..registration.synthetic import make_layout, online_offsets -from ..registration.synthetic import write_recording +from ..registration.synthetic import make_layout, online_offsets, write_recording MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: - """A one-trial trial table of the recording ``dat``.""" + """Write a one-trial trial table of the recording ``dat``.""" table = tmp_path / "trial_table.h5" save_struct_h5( table, @@ -51,8 +50,10 @@ def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: @pytest.fixture(scope="module") def registered(tmp_path_factory): - """A registered synthetic trial (moving scene, some invalid samples): - the layout, its trial table and its output folder.""" + """Register a synthetic trial (moving scene, some invalid samples). + + Gives the layout, its trial table and its output folder. + """ from giant_python.pipeline.register import register_multiroi root = tmp_path_factory.mktemp("layout") @@ -72,22 +73,24 @@ def registered(tmp_path_factory): @pytest.fixture def patched(registered, monkeypatch): - """The recording's layout, read by the exporter.""" + """Serve the recording's layout to the exporter.""" monkeypatch.setattr(multiroi, "raster_layout", lambda path: registered[0]) return registered def _movie(path: Path, n_channels: int) -> np.ndarray: - """A registered movie as ``(channels, frames, rows, cols)``.""" + """Read a registered movie as ``(channels, frames, rows, cols)``.""" with h5py.File(path, "r") as f: pages = f[next(iter(f.keys()))][()] pages = pages.reshape(-1, n_channels, *pages.shape[1:]) return np.swapaxes(pages, -1, -2).transpose(1, 0, 2, 3) -def test_file_reproduces_the_registered_movie(patched, tmp_path): - """Frames formed from the file and the raw samples of its slots are - registration's, missing pixels included.""" +def test_file_reproduces_the_registered_movie(patched, tmp_path) -> None: + """Frames formed from the file and its slots' raw samples are registration's. + + Missing pixels included. + """ layout, table, root = patched out = tmp_path / "layouts" res = export_layouts(table, out) @@ -113,7 +116,7 @@ def test_file_reproduces_the_registered_movie(patched, tmp_path): np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) -def test_slots_and_their_statistics(patched, tmp_path): +def test_slots_and_their_statistics(patched, tmp_path) -> None: """The file's slots are the window's, with their means and zeros.""" layout, table, _ = patched export_layouts(table, tmp_path) @@ -150,7 +153,7 @@ def test_slots_and_their_statistics(patched, tmp_path): assert 0.97 < lay["slots/valid_share"].mean() < 0.99 -def test_existing_files_are_kept_and_selection(patched, tmp_path): +def test_existing_files_are_kept_and_selection(patched, tmp_path) -> None: """A second run keeps the file; ``--overwrite`` and the selection.""" from giant_python.cli import main @@ -170,9 +173,11 @@ def test_existing_files_are_kept_and_selection(patched, tmp_path): assert layout_path("a/movie.h5") == Path("a/movie_F0LAYOUT.h5") -def test_missing_alignment_and_old_versions(patched, tmp_path): - """A trial without its alignment file fails; other versions are - refused.""" +def test_missing_alignment_and_old_versions(patched, tmp_path) -> None: + """A trial without its alignment file fails. + + Other versions are refused. + """ from giant_python.cli import main _, table, _ = patched @@ -187,10 +192,12 @@ def test_missing_alignment_and_old_versions(patched, tmp_path): read_layout(out) -def test_compensated_registration_is_reproduced(tmp_path, monkeypatch): - """A registration that undid the online correction: the file holds the - lines' offsets and the frames' own, and frames formed from it, every - sample moved by its line's offset, are registration's.""" +def test_compensated_registration_is_reproduced(tmp_path, monkeypatch) -> None: + """A registration that undid the online correction is reproduced. + + The file holds the lines' offsets and the frames' own, and frames formed + from it, every sample moved by its line's offset, are registration's. + """ from giant_python.pipeline.register import register_multiroi layout = make_layout(tmp_path / "comp_DMD1-TRIAL000001.dat", 500) @@ -255,10 +262,12 @@ def test_compensated_registration_is_reproduced(tmp_path, monkeypatch): assert np.abs(off - want)[both].max() > 1.0 -def test_version_3_files_are_read(patched, tmp_path): - """A file of version 3 (no slot positions; registrations without - online compensation) is read with its slots' positions, and gives the - same frames.""" +def test_version_3_files_are_read(patched, tmp_path) -> None: + """A file of version 3 is read with its slots' positions. + + Version 3 has no slot positions (registrations without online + compensation); such a file gives the same frames. + """ layout, table, root = patched export_layouts(table, tmp_path) out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" @@ -289,9 +298,11 @@ def test_version_3_files_are_read(patched, tmp_path): def _shared_pulses(rate, nxt, rng, p_split=0.35, k=5.0, theta=22.0): - """Compound-Poisson samples ``(slots, cycles)`` whose pulses (gamma - heights) are split with the next slot on the line with probability - ``p_split``, by a uniform fraction.""" + """Compound-Poisson samples ``(slots, cycles)`` with pulses shared with the next slot. + + The pulses (gamma heights) are split with the next slot on the line with + probability ``p_split``, by a uniform fraction. + """ n_slots, n_cycles = rate.shape out = np.zeros((n_slots, n_cycles)) counts = rng.poisson(rate) @@ -307,9 +318,11 @@ def _shared_pulses(rate, nxt, rng, p_split=0.35, k=5.0, theta=22.0): return np.round(out) -def test_pulse_statistics_recover_the_pulses(): - """Heights, split probability and split fractions of simulated shared - pulses, measured on the dim pairs only.""" +def test_pulse_statistics_recover_the_pulses() -> None: + """Heights, split probability and split fractions of simulated shared pulses. + + Measured on the dim pairs only. + """ rng = np.random.default_rng(0) n_lines, per_line, n_cycles = 40, 30, 4000 slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) @@ -347,10 +360,13 @@ def test_pulse_statistics_recover_the_pulses(): assert abs(np.nanmean(stats["mean"][0, slot_line <= 30]) - 1.1) < 0.1 -def test_pairs_next_to_unseen_samples_are_left_out(): - """A line with a sample that is not a raster slot: a pulse split with - it would be counted truncated, so the pair before the gap is not used; - a pair needs a slot before it, so none starts a run either.""" +def test_pairs_next_to_unseen_samples_are_left_out() -> None: + """A line with a sample that is not a raster slot. + + A pulse split with it would be counted truncated, so the pair before the + gap is not used; a pair needs a slot before it, so none starts a run + either. + """ rng = np.random.default_rng(2) # one line of eight samples; the one at position 4 is not a raster slot slot_line = np.ones(7, dtype=np.int64) @@ -383,10 +399,12 @@ def test_pairs_next_to_unseen_samples_are_left_out(): ) -def test_run_starts_are_not_measured(): - """The sample before a run is not recorded but passes parts of its - pulses on: counted on the run's first slot they would look like small - unsplit pulses.""" +def test_run_starts_are_not_measured() -> None: + """The sample before a run is not recorded but passes parts of its pulses on. + + Counted on the run's first slot they would look like small unsplit + pulses. + """ rng = np.random.default_rng(6) n_cycles = 6000 # the recorded run is the last six samples of a line of eight @@ -405,10 +423,12 @@ def test_run_starts_are_not_measured(): assert (first < 25).mean() > 5 * max(low, 0.01) -def test_layout_file_marks_line_ends(patched, tmp_path): - """``slots/next`` links consecutive samples of neighbouring pixels, and - ``slots/line_end`` marks the slots that nothing follows which could - share a pulse: a line's last sample, or one before a jump.""" +def test_layout_file_marks_line_ends(patched, tmp_path) -> None: + """``slots/next`` links consecutive samples of neighbouring pixels. + + ``slots/line_end`` marks the slots that nothing follows which could share + a pulse: a line's last sample, or one before a jump. + """ from giant_python.export.f0_layout import LAYOUT_VERSION, sharing_slots layout, table, _ = patched @@ -435,10 +455,12 @@ def test_layout_file_marks_line_ends(patched, tmp_path): assert np.array_equal(lay["slots/next"] < 0, end[idx]) -def test_pulses_are_not_measured_across_jumps(): - """A pair whose samples are not neighbouring pixels shares no pulse and - is not a pair; the slots on either side of the jump are measured as - the ends of their runs.""" +def test_pulses_are_not_measured_across_jumps() -> None: + """A pair whose samples are not neighbouring pixels shares no pulse. + + It is not a pair; the slots on either side of the jump are measured as the + ends of their runs. + """ rng = np.random.default_rng(4) n_cycles = 4000 # one line of 8 samples: pixels 0-3 of a row, then a jump to 20-23 @@ -483,9 +505,11 @@ class Layout: assert m2 / (m1 + m2) < n2 / (n1 + n2) -def test_pulse_statistics_without_dim_pairs(): - """Bright pairs, in which pulses coincide, are never used: a recording - without dim pairs gets empty histograms.""" +def test_pulse_statistics_without_dim_pairs() -> None: + """Bright pairs, in which pulses coincide, are never used. + + A recording without dim pairs gets empty histograms. + """ rng = np.random.default_rng(1) slot_line = np.repeat(np.arange(1, 21), 20) slot_pos = np.tile(np.arange(20), 20) @@ -510,9 +534,11 @@ def test_pulse_statistics_without_dim_pairs(): def _bursts(rate, nxt, rng, lengths=(0.5, 0.35, 0.12, 0.03)): - """Samples ``(slots, cycles)`` of events that occupy 1-4 consecutive - slots with the given probabilities, every part 40 + 10 x its place in - the burst (so that a part tells where in its burst it is).""" + """Draw samples ``(slots, cycles)`` of events that occupy 1-4 consecutive slots. + + The lengths have the given probabilities, every part 40 + 10 x its place + in the burst (so that a part tells where in its burst it is). + """ n_slots, n_cycles = rate.shape out = np.zeros((n_slots, n_cycles)) counts = rng.poisson(rate) @@ -527,9 +553,11 @@ def _bursts(rate, nxt, rng, lengths=(0.5, 0.35, 0.12, 0.03)): return out -def test_burst_cells(): - """The type of a burst: its length, total and, for two samples, the - smaller part's share.""" +def test_burst_cells() -> None: + """The type of a burst. + + Its length, total and, for two samples, the smaller part's share. + """ from giant_python.export.f0_layout import N_CELLS, burst_cells assert N_CELLS == 162 @@ -542,11 +570,13 @@ def test_burst_cells(): assert burst_cells(np.zeros((0, 2))).shape == (0,) -def test_burst_library_and_counts_by_stratum(patched, tmp_path): - """The library's counts are the events' length distribution and its - examples are whole events, part by part; the counts by stratum tell - events whose rate follows brightness from events at a constant rate; - the file holds both.""" +def test_burst_library_and_counts_by_stratum(patched, tmp_path) -> None: + """The library's counts are the events' length distribution. + + Its examples are whole events, part by part; the counts by stratum tell + events whose rate follows brightness from events at a constant rate; the + file holds both. + """ from giant_python.export.f0_layout import ( BURST_EXAMPLES, N_CELLS, @@ -620,9 +650,11 @@ def test_burst_library_and_counts_by_stratum(patched, tmp_path): def _level_case(rng, visits, n_cycles=3000): - """A raster whose pixels are sampled ``visits`` times per cycle, on - lines of two brightnesses that change together from cycle to cycle, - and the moments its events have per unit of mean.""" + """Simulate a raster whose pixels are sampled ``visits`` times per cycle. + + It has lines of two brightnesses that change together from cycle to cycle; + also returns the moments its events have per unit of mean. + """ per_line, n_pairs = 60, 24 n_lines = n_pairs * visits slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) @@ -650,10 +682,12 @@ def _level_case(rng, visits, n_cycles=3000): @pytest.mark.parametrize("visits", [2, 1]) -def test_level_statistics_measure_the_events(visits): - """The moments by level are those of the events, per unit of mean, at - every brightness, also where the brightness changes between cycles - (two visits per cycle) and for a raster without second visits.""" +def test_level_statistics_measure_the_events(visits) -> None: + """The moments by level are those of the events, per unit of mean. + + At every brightness, also where the brightness changes between cycles (two + visits per cycle) and for a raster without second visits. + """ from giant_python.export.f0_layout import LEVEL_EDGES, level_statistics rng = np.random.default_rng(5 + visits) @@ -692,10 +726,12 @@ def test_level_statistics_measure_the_events(visits): assert empty["level_samples"].sum() == 0 -def test_level_statistics_second_observation_is_on_a_later_line(): - """A line that samples its pixels twice in a row: the second sample of - a pixel on the same line can share pulses with the first, so it is not - taken as the second observation; the next line's is.""" +def test_level_statistics_second_observation_is_on_a_later_line() -> None: + """A line that samples its pixels twice in a row. + + The second sample of a pixel on the same line can share pulses with the + first, so it is not taken as the second observation; the next line's is. + """ from giant_python.export.f0_layout import _second_visits, level_statistics rng = np.random.default_rng(13) @@ -735,11 +771,13 @@ def test_level_statistics_second_observation_is_on_a_later_line(): np.testing.assert_allclose(per_mean[:, 1], cov / total, rtol=0.06) -def test_level_statistics_skip_the_visits_of_another_plane(): - """Lines of another plane that sample the same pixels between a - pixel's two visits are no visits: marked by a negative pixel, they do - not stand in as the next visit (which would leave no revisits and send - the measurement to the next cycle).""" +def test_level_statistics_skip_the_visits_of_another_plane() -> None: + """Lines of another plane between a pixel's two visits are no visits. + + Those lines sample the same pixels; marked by a negative pixel, they do not + stand in as the next visit (which would leave no revisits and send the + measurement to the next cycle). + """ from giant_python.export.f0_layout import _second_visits, level_statistics rng = np.random.default_rng(9) diff --git a/tests/export/test_f0_training.py b/tests/export/test_f0_training.py index cc0b7f26..ada54b05 100644 --- a/tests/export/test_f0_training.py +++ b/tests/export/test_f0_training.py @@ -18,7 +18,7 @@ @pytest.fixture(scope="module", params=["rigid", "patchwise"]) def session(request, tmp_path_factory): - """A synthetic session (rigid or patchwise maps) of 600 frames.""" + """Build a synthetic session (rigid or patchwise maps) of 600 frames.""" root = tmp_path_factory.mktemp(f"syn_{request.param}") return write_session(root, request.param, n80=N80) @@ -36,10 +36,11 @@ def _export(syn, out, **kw): ) -def test_layout_matches_the_training_reader(session, tmp_path): - """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile - reads them (the reader is not a dependency: its contract is checked - here).""" +def test_layout_matches_the_training_reader(session, tmp_path) -> None: + """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile reads them. + + The reader is not a dependency: its contract is checked here. + """ s = _export(session, tmp_path, kernel="exporter") assert [q["trial"] for q in s["trials"]] == [1, 2] for q in s["trials"]: @@ -83,10 +84,12 @@ def test_layout_matches_the_training_reader(session, tmp_path): ) -def test_target_is_the_baseline(session, tmp_path): - """With the movie's own kernel and cubic placement the noiseless - target (movie - activity) is the baseline to 2% of the activity's - peak; QC says the activity matches the movie.""" +def test_target_is_the_baseline(session, tmp_path) -> None: + """With the movie's own kernel and cubic placement the noiseless target is the baseline. + + The target (movie - activity) is the baseline to 2% of the activity's + peak; QC says the activity matches the movie. + """ s = _export(session, tmp_path, kernel="exporter", interp="cubic") for q in s["trials"]: with h5py.File(q["file"], "r") as f: @@ -102,9 +105,11 @@ def test_target_is_the_baseline(session, tmp_path): assert q["targetOverBaselineSupport"] == pytest.approx(1.0, abs=1e-3) -def test_linear_placement_blurs_the_peaks(session, tmp_path): - """Bilinear placement keeps the flux but lowers the peak pixels (the - viewer's rendering); cubic keeps both.""" +def test_linear_placement_blurs_the_peaks(session, tmp_path) -> None: + """Bilinear placement keeps the flux but lowers the peak pixels (the viewer's rendering). + + Cubic placement keeps both. + """ lin = _export(session, tmp_path / "lin", kernel="exporter") cub = _export(session, tmp_path / "cub", kernel="exporter", interp="cubic") for a, b in zip(lin["trials"], cub["trials"]): @@ -113,9 +118,11 @@ def test_linear_placement_blurs_the_peaks(session, tmp_path): assert a["eventResidualFraction"] > b["eventResidualFraction"] -def test_exact_kernel_is_sharper(session, tmp_path): - """The exact kernel keeps the activity's total and sharpens its - peaks against the MATLAB exporter's kernel.""" +def test_exact_kernel_is_sharper(session, tmp_path) -> None: + """The exact kernel keeps the activity's total and sharpens its peaks. + + The peaks are compared against the MATLAB exporter's kernel. + """ e = _export(session, tmp_path / "e", kernel="exporter", interp="cubic") x = _export(session, tmp_path / "x", kernel="exact", interp="cubic") for qe, qx in zip(e["trials"], x["trials"]): @@ -130,9 +137,11 @@ def test_exact_kernel_is_sharper(session, tmp_path): assert ax.max() > ae.max() -def test_summary_and_skipped_trial(tmp_path): - """export_summary.json holds every trial (NaN as null); a trial - without an across-trial map is reported, not written.""" +def test_summary_and_skipped_trial(tmp_path) -> None: + """export_summary.json holds every trial (NaN as null). + + A trial without an across-trial map is reported, not written. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) out = tmp_path / "out" _export(syn, out) # a first export writes both trials @@ -154,9 +163,11 @@ def test_summary_and_skipped_trial(tmp_path): assert len(j["trials"]) == N_TRIALS and j["options"]["kernel"] == "exact" -def test_default_export_reconciles_trial_files(tmp_path): - """A default export removes earlier trial files it does not write and - lists them; an export with chosen trials leaves other files alone.""" +def test_default_export_reconciles_trial_files(tmp_path) -> None: + """A default export removes earlier trial files it does not write and lists them. + + An export with chosen trials leaves other files alone. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) out = tmp_path / "out" folder = out / "Path1" @@ -177,9 +188,11 @@ def test_default_export_reconciles_trial_files(tmp_path): assert j["removed"] == s["removed"] -def test_repeated_selectors_export_once(tmp_path): - """Repeated paths and trials give one job each (two workers never - write the same file).""" +def test_repeated_selectors_export_once(tmp_path) -> None: + """Repeated paths and trials give one job each. + + Two workers never write the same file. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) s = _export( syn, tmp_path / "out", paths=(1, 1), trials=(2, 2, 1), workers=2 @@ -197,10 +210,11 @@ def test_repeated_selectors_export_once(tmp_path): {"paths": (2,)}, ], ) -def test_selectors_outside_the_run_are_refused(tmp_path, kw): - """Trials outside 1..the table's trials and paths the run does not - have are refused before any job starts; the CLI reports a usage - error.""" +def test_selectors_outside_the_run_are_refused(tmp_path, kw) -> None: + """Trials outside 1..the table's trials and paths the run does not have are refused. + + They are refused before any job starts; the CLI reports a usage error. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) with pytest.raises(ValueError, match="trials|paths"): _export(syn, tmp_path / "out", **kw) @@ -225,7 +239,7 @@ def test_selectors_outside_the_run_are_refused(tmp_path, kw): @pytest.fixture(scope="module") def exported(tmp_path_factory): - """A synthetic session exported once (default options).""" + """Export a synthetic session once (default options).""" root = tmp_path_factory.mktemp("bad_options") syn = write_session(root / "syn", "rigid", n80=200) _export(syn, root / "out") @@ -245,10 +259,12 @@ def exported(tmp_path_factory): ({"interp": "nearest"}, None), ], ) -def test_invalid_options_keep_earlier_files(exported, kw, cli): - """An option every trial would fail on is refused before any trial, - so a rerun with it leaves the earlier export in place; the CLI - reports a usage error.""" +def test_invalid_options_keep_earlier_files(exported, kw, cli) -> None: + """An option every trial would fail on is refused before any trial. + + So a rerun with it leaves the earlier export in place; the CLI reports a + usage error. + """ syn, out = exported files = sorted((out / "Path1").glob("trial_*.h5")) assert len(files) == N_TRIALS @@ -275,7 +291,7 @@ def test_invalid_options_keep_earlier_files(exported, kw, cli): assert [f.stat().st_mtime_ns for f in files] == stamps -def test_ignore_sources(tmp_path): +def test_ignore_sources(tmp_path) -> None: """Without sources: zero activity, no sources group, no QC.""" syn = write_session(tmp_path / "syn", "rigid", n80=200) s = _export(syn, tmp_path / "out", ignore_sources=True) @@ -287,8 +303,8 @@ def test_ignore_sources(tmp_path): assert not f["mask/footprint_support"][()].any() -def test_cli(tmp_path): - """giant export-f0 writes the trials and returns 0.""" +def test_cli(tmp_path) -> None: + """Giant export-f0 writes the trials and returns 0.""" syn = write_session(tmp_path / "syn", "rigid", n80=200) out = tmp_path / "out" rc = main( @@ -313,7 +329,7 @@ def test_cli(tmp_path): assert f.attrs["label"] == "syn" and f.attrs["kernel"] == "matched" -def test_movmedian_omitnan(): +def test_movmedian_omitnan() -> None: """The running median ignores NaN and shrinks at the ends.""" rng = np.random.default_rng(0) x = rng.normal(size=(3, 300)) @@ -327,9 +343,11 @@ def test_movmedian_omitnan(): assert np.isnan(m[2]).all() -def test_event_residual_and_peaks(): - """The event-triggered residual is 0 when the activity is the movie's - signal and 1 when no activity is removed.""" +def test_event_residual_and_peaks() -> None: + """The event-triggered residual is 0 when the activity is the movie's signal. + + It is 1 when no activity is removed. + """ from scipy import sparse T = 400 @@ -349,8 +367,11 @@ def test_event_residual_and_peaks(): def _two_channels(syn) -> None: - """Rewrite the synthetic movies with a second channel (2 x the first - + 5), interleaved by frame, and set ``numChannels`` 2.""" + """Rewrite the synthetic movies with a second channel. + + The second channel is 2 x the first + 5, interleaved by frame; also set + ``numChannels`` 2. + """ for mf in sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")): with h5py.File(mf, "r+") as f: a = f["mov"][()] # (pages, cols, rows) @@ -363,9 +384,11 @@ def _two_channels(syn) -> None: f["params/numChannels"][...] = 2 -def test_written_channels_and_mean_image(tmp_path): - """The mean image follows the written channels, as movie and - activity do (the reader indexes all three alike).""" +def test_written_channels_and_mean_image(tmp_path) -> None: + """The mean image follows the written channels, as movie and activity do. + + The reader indexes all three alike. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) _two_channels(syn) s = _export(syn, tmp_path / "c2", channels=(2,)) @@ -383,9 +406,11 @@ def test_written_channels_and_mean_image(tmp_path): np.testing.assert_allclose(mi[0], 2 * mi[1] + 5, rtol=1e-4) -def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path): - """The mean image leaves out the discarded frames and is NaN outside - the valid pixels, as slap2-f0 computes it at inference.""" +def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path) -> None: + """The mean image leaves out the discarded frames and is NaN outside the valid pixels. + + This is as slap2-f0 computes it at inference. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) alf = sorted(syn["moco"].glob("*_ALIGNMENTDATA.h5"))[0] with h5py.File(alf, "r+") as f: @@ -415,10 +440,12 @@ def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path): assert not valid[:, col - c0].any() and np.isnan(mi[:, col - c0]).all() -def test_sources_without_traces_are_refused(tmp_path): - """Sources without dF_denoised traces would give zero activity (the - target would keep every event): the trials are reported, not - written.""" +def test_sources_without_traces_are_refused(tmp_path) -> None: + """Sources without dF_denoised traces would give zero activity. + + The target would keep every event, so the trials are reported, not + written. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) es = syn["run"] / "source_extraction" / "experiment_summary.h5" with h5py.File(es, "r+") as f: @@ -430,7 +457,7 @@ def test_sources_without_traces_are_refused(tmp_path): @pytest.mark.parametrize("channels", [(0,), (3,), (1, 2)]) -def test_channels_outside_the_movie_are_refused(tmp_path, channels): +def test_channels_outside_the_movie_are_refused(tmp_path, channels) -> None: """Channels are one-based and within numChannels (1 here).""" syn = write_session(tmp_path / "syn", "rigid", n80=200) with pytest.raises(ValueError, match="channels"): @@ -456,8 +483,10 @@ def test_channels_outside_the_movie_are_refused(tmp_path, channels): def _noisy_traces(syn, sd: float = 2.0) -> None: - """Give the synthetic run noisy dF_ls (noise SD ``sd`` around - dF_denoised) and an events trace at the denoised trace's jumps.""" + """Give the synthetic run noisy dF_ls (noise SD ``sd`` around dF_denoised). + + Also give it an events trace at the denoised trace's jumps. + """ es = syn["run"] / "source_extraction" / "experiment_summary.h5" with h5py.File(es, "r+") as f: g = f["Path1/sources/temporal"] @@ -469,9 +498,11 @@ def _noisy_traces(syn, sd: float = 2.0) -> None: def _plan_file(syn, unused=((8.0, 40.0),)) -> None: - """A minimal SILo plan file for path 1: the sources' seeds plus - ``unused`` seeds without a source (as giant silo keeps it in - source_extraction/silo/plan).""" + """Write a minimal SILo plan file for path 1. + + It holds the sources' seeds plus ``unused`` seeds without a source (as + giant silo keeps it in source_extraction/silo/plan). + """ plan = syn["run"] / "source_extraction" / "silo" / "plan" / "path1.h5" plan.parent.mkdir(parents=True, exist_ok=True) rc = np.vstack([CENTRES, np.asarray(unused, float)]) @@ -484,9 +515,11 @@ def _plan_file(syn, unused=((8.0, 40.0),)) -> None: g["cols"] = pix[:, 1] -def test_temporal_mask_rule(): - """A crossing masks its frames, the widening after it and the shared - frames on both sides; nothing else.""" +def test_temporal_mask_rule() -> None: + """A crossing masks its frames, the widening after it and the shared frames on both sides. + + Nothing else is masked. + """ from giant_python.export.f0_mask import MaskRule, temporal_mask n200 = 500 @@ -506,10 +539,12 @@ def test_temporal_mask_rule(): assert f.min() == first and f.max() == last and f.size == last - first + 1 -def test_mask_widening_uses_the_activity_channel_decay(): - """The widening's decay constant is the activity channel's (SILo's - ``tau_full``, else ``tau_s`` times the frame rate), not channel 2's - ``tau2``.""" +def test_mask_widening_uses_the_activity_channel_decay() -> None: + """The widening's decay constant is the activity channel's, not channel 2's ``tau2``. + + The activity channel's is SILo's ``tau_full``, else ``tau_s`` times the + frame rate. + """ from types import SimpleNamespace from giant_python.export.f0_training import _mask_inputs @@ -517,12 +552,12 @@ def test_mask_widening_uses_the_activity_channel_decay(): class Run: """A run with only the given params (as SiloRun.param reads them).""" - def __init__(self, params): + def __init__(self, params) -> None: """Keep the params.""" self.params = params def param(self, name, default=None): - """A param, the default when missing or empty.""" + """Return a param, the default when missing or empty.""" v = self.params.get(name, default) return default if v is None or v == "" else v @@ -551,10 +586,12 @@ def param(self, name, default=None): assert m["tau_seconds"] == pytest.approx(0.024) -def test_activity_mask_written(tmp_path): - """mask/activity covers the sources' activity, never pixels far from a - footprint, and leaves quiet stretches; spots add to it; the rule and - the masked shares are recorded.""" +def test_activity_mask_written(tmp_path) -> None: + """mask/activity covers the sources' activity, never pixels far from a footprint. + + It also leaves quiet stretches; spots add to it; the rule and the masked + shares are recorded. + """ from scipy import ndimage from giant_python.export.f0_mask import MaskRule @@ -599,7 +636,7 @@ def test_activity_mask_written(tmp_path): assert not am[~near][:, sup].any() -def test_mask_and_event_stats_off_by_default(tmp_path): +def test_mask_and_event_stats_off_by_default(tmp_path) -> None: """Without the options neither the mask nor the statistics file.""" syn = write_session(tmp_path / "syn", "rigid", n80=200) s = _export(syn, tmp_path / "out") @@ -608,10 +645,12 @@ def test_mask_and_event_stats_off_by_default(tmp_path): assert not (tmp_path / "out" / "event_statistics.json").exists() -def test_event_statistics(tmp_path): - """event_statistics.json: events are crossings of k noise SDs (SILo's - small noise events in its events trace do not count); rate, sizes and - the synchrony against chance.""" +def test_event_statistics(tmp_path) -> None: + """event_statistics.json: events are crossings of k noise SDs. + + SILo's small noise events in its events trace do not count; the file + also holds rate, sizes and the synchrony against chance. + """ syn = write_session(tmp_path / "syn", "rigid", n80=300) es = syn["run"] / "source_extraction" / "experiment_summary.h5" with h5py.File(es, "r+") as f: @@ -650,7 +689,7 @@ def test_event_statistics(tmp_path): "bad", [{"k": 0}, {"margin_px": -1}, {"share_frames": 1.5}, {"spots": "all"}], ) -def test_invalid_mask_rule_refused(tmp_path, bad): +def test_invalid_mask_rule_refused(tmp_path, bad) -> None: """An invalid mask rule is refused before any trial.""" from giant_python.export.f0_mask import MaskRule @@ -659,8 +698,8 @@ def test_invalid_mask_rule_refused(tmp_path, bad): _export(syn, tmp_path / "out", activity_mask=MaskRule(**bad)) -def test_cli_mask_and_event_stats(tmp_path): - """giant export-f0 --activity-mask --event-stats writes both.""" +def test_cli_mask_and_event_stats(tmp_path) -> None: + """Giant export-f0 --activity-mask --event-stats writes both.""" syn = write_session(tmp_path / "syn", "rigid", n80=300) _noisy_traces(syn) out = tmp_path / "out" @@ -687,11 +726,13 @@ def test_cli_mask_and_event_stats(tmp_path): assert (out / "event_statistics.json").exists() -def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path): - """With 200 Hz frames wider than the movie's (dt200 > dt80) the exact - and matched kernels cannot match the movie: the trials are reported, - not written with interpolated (too smooth) activity; the MATLAB - exporter's kernel still exports.""" +def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path) -> None: + """The exact and matched kernels cannot match the movie when 200 Hz frames are wider. + + With 200 Hz frames wider than the movie's (dt200 > dt80) the trials are + reported, not written with interpolated (too smooth) activity; the + MATLAB exporter's kernel still exports. + """ syn = write_session(tmp_path / "syn", "rigid", n80=200) es = syn["run"] / "source_extraction" / "experiment_summary.h5" with h5py.File(es, "r+") as f: @@ -724,9 +765,11 @@ def _set_traces(syn, den, ls=None) -> None: g["dF_ls"][...] = ls -def test_event_statistics_per_trial_and_observed_time(tmp_path): - """An event across a trial boundary counts once in each trial; a - trial without traces adds no observation time.""" +def test_event_statistics_per_trial_and_observed_time(tmp_path) -> None: + """An event across a trial boundary counts once in each trial. + + A trial without traces adds no observation time. + """ syn = write_session(tmp_path / "syn", "rigid", n80=300) n1, n2 = _trial_frames(syn)[:2] es = syn["run"] / "source_extraction" / "experiment_summary.h5" @@ -747,9 +790,11 @@ def test_event_statistics_per_trial_and_observed_time(tmp_path): assert s1["ratePerMin"] == pytest.approx(2 / s1["observedMinutes"]) -def test_mask_refuses_active_sources_without_noise(tmp_path): - """A source with activity but no dF_ls (no noise estimate) would stay - unmasked: the trial is refused.""" +def test_mask_refuses_active_sources_without_noise(tmp_path) -> None: + """A source with activity but no dF_ls (no noise estimate) would stay unmasked. + + The trial is refused. + """ from giant_python.export.f0_mask import MaskRule syn = write_session(tmp_path / "syn", "rigid", n80=200) @@ -764,9 +809,11 @@ def test_mask_refuses_active_sources_without_noise(tmp_path): assert "no noise estimate" in q["error"] and "[0]" in q["error"] -def test_mask_fractions_count_finite_samples(tmp_path): - """The masked shares count only finite samples of the activity - channel (a valid pixel may miss some frames).""" +def test_mask_fractions_count_finite_samples(tmp_path) -> None: + """The masked shares count only finite samples of the activity channel. + + A valid pixel may miss some frames. + """ from giant_python.export.f0_mask import MaskRule syn = write_session(tmp_path / "syn", "rigid", n80=300) @@ -792,10 +839,11 @@ def test_mask_fractions_count_finite_samples(tmp_path): assert q["activityMaskFraction"] == pytest.approx(am[ok].mean()) -def test_event_statistics_unavailable_and_stale_file(tmp_path): - """An active source without a noise estimate is reported as - unavailable, not as zero events; a rerun without --event-stats removes - the earlier statistics.""" +def test_event_statistics_unavailable_and_stale_file(tmp_path) -> None: + """An active source without a noise estimate is reported as unavailable, not as zero events. + + A rerun without --event-stats removes the earlier statistics. + """ syn = write_session(tmp_path / "syn", "rigid", n80=300) es = syn["run"] / "source_extraction" / "experiment_summary.h5" with h5py.File(es, "r") as f: @@ -814,9 +862,12 @@ def test_event_statistics_unavailable_and_stale_file(tmp_path): assert not (out / "event_statistics.json").exists() -def test_mask_seeds_refused_without_a_map(tmp_path): - """With --mask-spots seeds, a trial whose seeds cannot be placed (no - across-trial map) is refused rather than written without them.""" +def test_mask_seeds_refused_without_a_map(tmp_path) -> None: + """With --mask-spots seeds, a trial whose seeds cannot be placed is refused. + + Such a trial (no across-trial map) is refused rather than written + without them. + """ from giant_python.export.f0_mask import MaskRule syn = write_session(tmp_path / "syn", "rigid", n80=200) @@ -844,9 +895,11 @@ def test_mask_seeds_refused_without_a_map(tmp_path): assert all("error" not in q for q in s["trials"]) -def test_mask_seeds_refused_without_a_plan_file(tmp_path): - """Without SILo's plan file the unused seeds are unknown, not absent: - --mask-spots seeds is refused; the default (no spots) exports.""" +def test_mask_seeds_refused_without_a_plan_file(tmp_path) -> None: + """Without SILo's plan file the unused seeds are unknown, not absent. + + --mask-spots seeds is refused; the default (no spots) exports. + """ from giant_python.export.f0_mask import MaskRule syn = write_session(tmp_path / "syn", "rigid", n80=200) @@ -857,9 +910,11 @@ def test_mask_seeds_refused_without_a_plan_file(tmp_path): assert all("error" not in q for q in s["trials"]) -def test_event_statistics_without_denoised_traces_or_f0(tmp_path): - """Without dF_denoised the path is reported as unavailable; without F0 - the counts and raw sizes remain and dF/F is null.""" +def test_event_statistics_without_denoised_traces_or_f0(tmp_path) -> None: + """Without dF_denoised the path is reported as unavailable. + + Without F0 the counts and raw sizes remain and dF/F is null. + """ from giant_python.export.f0_events import path_statistics from giant_python.viewer.run import SiloRun @@ -879,9 +934,11 @@ def test_event_statistics_without_denoised_traces_or_f0(tmp_path): assert "dF_denoised" in p["unavailable"] and p["sources"] == [] -def test_synchrony_counts_only_observed_partners(): - """A partner without a trace around an event neither coincides nor - counts towards chance; with full traces chance follows the rates.""" +def test_synchrony_counts_only_observed_partners() -> None: + """A partner without a trace around an event neither coincides nor counts towards chance. + + With full traces chance follows the rates. + """ from giant_python.export.f0_events import synchrony T = 1000 diff --git a/tests/raster/alignment_synthetic.py b/tests/raster/alignment_synthetic.py index ebe47a0c..eefce5ef 100644 --- a/tests/raster/alignment_synthetic.py +++ b/tests/raster/alignment_synthetic.py @@ -1,8 +1,10 @@ -"""Synthetic trials for the across-trial alignment tests (a port of the -scenario of GIAnT-MATLAB's ``TestTrialAlignment.m``, with numpy's random -numbers): a labeled neuron (dendrites with spines, an unscanned band and a +"""Synthetic trials for the across-trial alignment tests. + +A port of the scenario of GIAnT-MATLAB's ``TestTrialAlignment.m``, with numpy's +random numbers: a labeled neuron (dendrites with spines, an unscanned band and a hole) seen through known affine maps and, optionally, smooth bends, with -shot-like noise in two halves per trial.""" +shot-like noise in two halves per trial. +""" from __future__ import annotations @@ -16,8 +18,7 @@ def neuron(rng: np.random.Generator, size=SIZE): - """Mean image of a labeled neuron and its scanned pixels (NaN outside - them).""" + """Mean image of a labeled neuron and its scanned pixels (NaN outside them).""" h, w = size rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) truth = np.full(size, 5.0) @@ -59,10 +60,12 @@ def trials( bend_px: float = 0.25, affine_sd: float = 0.003, ): - """Trial mean images ``(trials, rows, cols)``, their halves ``(trials, 2, - rows, cols)``, the true fields ``(trials, 2, rows, cols)`` (consensus - pixel ``x`` is at ``x + U(x)`` in the trial) and the rigid starting maps - ``(trials, 2, 3)``.""" + """Trial mean images, their halves, the true fields and the rigid starting maps. + + Mean images ``(trials, rows, cols)``, halves ``(trials, 2, rows, cols)``, + true fields ``(trials, 2, rows, cols)`` (consensus pixel ``x`` is at + ``x + U(x)`` in the trial) and rigid starting maps ``(trials, 2, 3)``. + """ h, w = truth.shape rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) filled = np.where(np.isnan(truth), 5.0, truth) @@ -108,9 +111,11 @@ def trials( def field_error(coords, u, a0, truth, scan): - """RMS error of fitted maps relative to the trials' mean map, weighted by - image structure; and the same for the rigid start. ``coords(t, r, c)`` - gives the fitted positions.""" + """RMS error of fitted maps relative to the trials' mean map. + + Weighted by image structure; and the same for the rigid start. + ``coords(t, r, c)`` gives the fitted positions. + """ n_trials = u.shape[0] sel = ndimage.binary_erosion(scan, np.ones((5, 5)), border_value=0) rows, cols = np.nonzero(sel) diff --git a/tests/raster/test_raster_alignment.py b/tests/raster/test_raster_alignment.py index 977d9e5d..ae61458d 100644 --- a/tests/raster/test_raster_alignment.py +++ b/tests/raster/test_raster_alignment.py @@ -20,14 +20,16 @@ def _scene(shape=(60, 80), n_blobs=25, seed=0): - """A smooth image of Gaussian blobs, with a function to shift it.""" + """Build a smooth image of Gaussian blobs, with a function to shift it.""" rng = np.random.default_rng(seed) centres = rng.uniform([8, 8], [shape[0] - 8, shape[1] - 8], (n_blobs, 2)) amps = rng.uniform(1, 3, n_blobs) def render(shift=(0.0, 0.0)): - """The scene moved by ``shift``: pixel p shows scene point - p - shift.""" + """Render the scene moved by ``shift``. + + Pixel p shows scene point p - shift. + """ rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) im = np.full(shape, 0.2) for (r0, c0), a in zip(centres, amps): @@ -40,19 +42,23 @@ def render(shift=(0.0, 0.0)): return render -def test_matlab_round_halves_away_from_zero(): - """MATLAB rounds 2.5 to 3 and -2.5 to -3; the largest double below a - half rounds down.""" +def test_matlab_round_halves_away_from_zero() -> None: + """MATLAB rounds 2.5 to 3 and -2.5 to -3. + + The largest double below a half rounds down. + """ np.testing.assert_array_equal( matlab_round([2.5, -2.5, 3.5, 0.5, 0.49999999999999994, -0.2]), [3, -3, 4, 1, 0, 0], ) -def test_interp2_linear_is_matlabs(): - """Values from MATLAB R2024b's interp2 on the same image: a point on a - grid row or column ignores the next one (so a NaN there does not - spread), fractional points next to a NaN are NaN, outside is NaN.""" +def test_interp2_linear_is_matlabs() -> None: + """Values from MATLAB R2024b's interp2 on the same image. + + A point on a grid row or column ignores the next one (so a NaN there does + not spread), fractional points next to a NaN are NaN, outside is NaN. + """ v = np.array( [[1, 2, 3], [4, NAN, 6], [7, 8, 9], [10, 11, 12]], dtype=float ) @@ -84,10 +90,12 @@ def test_interp2_linear_is_matlabs(): assert np.isnan(interp2_linear(v, NAN, 1.0)) -def test_xcorr2_nans_finds_shifts(): - """A frame moved by a known amount against the template: the motion is - the frame's shift, to a fraction of a pixel, and the correlation is - near 1. NaN borders and a NaN hole do not matter.""" +def test_xcorr2_nans_finds_shifts() -> None: + """A frame moved by a known amount against the template. + + The motion is the frame's shift, to a fraction of a pixel, and the + correlation is near 1. NaN borders and a NaN hole do not matter. + """ render = _scene() template = render() template[:3] = NAN @@ -104,9 +112,11 @@ def test_xcorr2_nans_finds_shifts(): np.testing.assert_allclose(motion, (2.0, -3.0), atol=0.05) -def test_xcorr2_nans_edge_of_search_and_errors(): - """A maximum on the edge of the search is returned whole (no parabola); - shapes must agree.""" +def test_xcorr2_nans_edge_of_search_and_errors() -> None: + """A maximum on the edge of the search is returned whole (no parabola). + + Shapes must agree. + """ render = _scene() motion, _ = xcorr2_nans(render((3.0, 0.0)), render(), (0, 0), 2) np.testing.assert_array_equal(motion, [2.0, 0.0]) @@ -114,10 +124,12 @@ def test_xcorr2_nans_edge_of_search_and_errors(): xcorr2_nans(np.zeros((4, 5)), np.zeros((5, 4)), (0, 0), 1) -def test_xcorr2_nans_wrapping_matches_the_rolled_masks(): - """Where shifted pixels leave the image the mask is rolled as MATLAB's - circshift (the general path); it must agree with the index lookup on - an image where nothing wraps, and run where it does.""" +def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: + """Where shifted pixels leave the image the mask is rolled as MATLAB's circshift. + + This is the general path; it must agree with the index lookup on an image + where nothing wraps, and run where it does. + """ render = _scene((30, 40), 12, seed=3) template, frame = render(), render((1.0, -1.0)) motion, r = xcorr2_nans(frame, template, (1, -1), 2) @@ -127,9 +139,11 @@ def test_xcorr2_nans_wrapping_matches_the_rolled_masks(): assert np.isfinite(wrapped).all() -def test_dftregistration_clipped_whole_shifts(): - """A circularly shifted image is registered by minus its shift, and a - shift outside the clip window is not found.""" +def test_dftregistration_clipped_whole_shifts() -> None: + """A circularly shifted image is registered by minus its shift. + + A shift outside the clip window is not found. + """ rng = np.random.default_rng(1) ref = rng.normal(size=(64, 48)) moved = np.roll(ref, (5, -7), axis=(0, 1)) @@ -141,11 +155,13 @@ def test_dftregistration_clipped_whole_shifts(): assert abs(out[2]) <= 5 and abs(out[3]) <= 5 -def test_dftregistration_clipped_odd_sizes_as_matlab(): - """On an odd axis MATLAB's midpoint test (``rloc > fix(m/2)`` on the - one-based index) returns a shift of half the axis as its negative alias: - values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 - image moved circularly.""" +def test_dftregistration_clipped_odd_sizes_as_matlab() -> None: + """On an odd axis MATLAB returns a shift of half the axis as its negative alias. + + MATLAB's midpoint test (``rloc > fix(m/2)`` on the one-based index) does + this: values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 + image moved circularly. + """ rng = np.random.default_rng(4) matlab = { (5, 7): { @@ -172,9 +188,8 @@ def test_dftregistration_clipped_odd_sizes_as_matlab(): assert out[2:] == expect, (shape, moved_by) -def test_template_samples(): - """Up to 20 kept trials, evenly spaced as MATLAB's - round(linspace(1, n, 20)).""" +def test_template_samples() -> None: + """Up to 20 kept trials, evenly spaced as MATLAB's round(linspace(1, n, 20)).""" keep = np.array([True, False, True, True]) np.testing.assert_array_equal(template_samples(keep), [0, 2, 3]) many = template_samples(np.ones(50, bool)) @@ -183,9 +198,11 @@ def test_template_samples(): np.testing.assert_array_equal(many[:5] + 1, [1, 4, 6, 9, 11]) -def test_consensus_template_of_shifted_copies(): - """Copies of one scene are averaged on the reference; one image gives - itself on the larger canvas.""" +def test_consensus_template_of_shifted_copies() -> None: + """Copies of one scene are averaged on the reference. + + One image gives itself on the larger canvas. + """ render = _scene() shifts = [(0, 0), (1, 0), (0, -2), (1, 1), (-1, 2)] stack = np.stack([render(s) for s in shifts]) @@ -204,7 +221,7 @@ def test_consensus_template_of_shifted_copies(): assert np.isnan(alone[:3]).all() and np.isnan(alone[:, -3:]).all() -def test_consensus_template_without_overlap_is_nan(): +def test_consensus_template_without_overlap_is_nan() -> None: """Images that share no pixels give no template.""" a = np.full((20, 20), NAN) b = a.copy() @@ -213,7 +230,7 @@ def test_consensus_template_without_overlap_is_nan(): assert np.isnan(make_consensus_template(np.stack([a, b]), 2)).all() -def test_trial_warp_coordinates(): +def test_trial_warp_coordinates() -> None: """Shifts and affine maps; MATLAB's one-based affine round-trips.""" warp = TrialWarp.from_shifts([[0.5, -1.25], [NAN, NAN]]) np.testing.assert_array_equal(warp.aligned, [True, False]) @@ -239,9 +256,11 @@ def test_trial_warp_coordinates(): ) -def test_patchwise_warp_is_not_a_shift(): - """A warp with patch centres is not a shift, whatever its affine part, - and maps through its field (zero displacements: the identity).""" +def test_patchwise_warp_is_not_a_shift() -> None: + """A warp with patch centres is not a shift, whatever its affine part. + + It maps through its field (zero displacements: the identity). + """ nodes = np.array([[0, 0], [5, 1], [2, 9.0]]) warp = TrialWarp(np.eye(2, 3)[None], nodes=nodes, sigma=3.0) assert not warp.is_shift(0) and warp.is_patchwise @@ -250,10 +269,11 @@ def test_patchwise_warp_is_not_a_shift(): np.testing.assert_allclose(c, [2.0, 7.0], atol=1e-12) -def test_warp_trial_image(): - """A whole shift moves the image exactly (NaN where it leaves the - trial's image); channels are resampled alike; fractional shifts - interpolate.""" +def test_warp_trial_image() -> None: + """A whole shift moves the image exactly (NaN where it leaves the trial's image). + + Channels are resampled alike; fractional shifts interpolate. + """ rng = np.random.default_rng(2) im = rng.normal(size=(6, 7)) warp = TrialWarp.from_shifts([[1.0, -2.0], [0.5, 0.0]]) @@ -269,10 +289,12 @@ def test_warp_trial_image(): warp_trial_image(im, warp, 0, method="nearest") -def test_align_trials_recovers_shifts(): - """Trials that show one scene at known offsets are aligned to within a - tenth of a pixel of each other; trials that are not kept, or without an - activity image, are left out.""" +def test_align_trials_recovers_shifts() -> None: + """Trials that show one scene at known offsets are aligned to each other. + + They agree to within a tenth of a pixel; trials that are not kept, or + without an activity image, are left out. + """ render = _scene((70, 90), 30, seed=5) true = np.array( [[0.0, 0.0], [1.3, -0.6], [-2.2, 1.9], [0.4, 3.1], [0, 0], [0, 0]] @@ -294,11 +316,14 @@ def test_align_trials_recovers_shifts(): align_trials(m, act, np.zeros(6, bool)) -def test_mask_to_consensus(): - """A mask drawn on a trial moves by minus the trial's shift, rounded as - MATLAB's shiftRoiData (halves away from zero); pixels leaving the frame - are dropped; an unknown or unaligned trial only crops or pads; an - affine map takes the nearest trial pixel (roisToConsensusFrame).""" +def test_mask_to_consensus() -> None: + """A mask drawn on a trial moves by minus the trial's shift. + + The shift is rounded as MATLAB's shiftRoiData (halves away from zero); + pixels leaving the frame are dropped; an unknown or unaligned trial only + crops or pads; an affine map takes the nearest trial pixel + (roisToConsensusFrame). + """ mask = np.zeros((6, 8), bool) mask[2, 3] = mask[5, 7] = True warp = TrialWarp.from_shifts( diff --git a/tests/raster/test_raster_alignment_modes.py b/tests/raster/test_raster_alignment_modes.py index d575e107..def89cfc 100644 --- a/tests/raster/test_raster_alignment_modes.py +++ b/tests/raster/test_raster_alignment_modes.py @@ -1,10 +1,11 @@ -"""Tests of the affine and patchwise across-trial alignments (ports of -GIAnT-MATLAB's ``TestTrialAlignment.m``) and of their helpers.""" +"""Tests of the affine and patchwise across-trial alignments and of their helpers. + +The alignment tests are ports of GIAnT-MATLAB's ``TestTrialAlignment.m``. +""" import numpy as np import pytest - from giant_python.extraction.raster.alignment import ( CubicInterpolant, TrialWarp, @@ -25,15 +26,17 @@ from .alignment_synthetic import field_error, neuron, trials -def test_cubic_reproduces_quadratics_and_grid_values(): - """Keys' convolution with MATLAB's boundary rows is exact for - quadratics, also next to the edges, and returns the image on the - grid; NaN outside the image.""" +def test_cubic_reproduces_quadratics_and_grid_values() -> None: + """Keys' convolution with MATLAB's boundary rows is exact for quadratics. + + Also next to the edges, and returns the image on the grid; NaN outside + the image. + """ rng = np.random.default_rng(0) rr, cc = np.mgrid[0:9, 0:11].astype(float) def f(r, c): - """A quadratic surface.""" + """Evaluate a quadratic surface.""" return ( 1 + 0.3 * r - 0.2 * c + 0.05 * r * r - 0.04 * r * c + 0.02 * c**2 ) @@ -47,10 +50,12 @@ def f(r, c): assert np.isnan(out).all() -def test_cubic_nan_reaches_its_whole_stencil(): - """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN, also - a grid point next to it (MATLAB's interp2), unlike linear - interpolation; the cubic warp falls back to linear there.""" +def test_cubic_nan_reaches_its_whole_stencil() -> None: + """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN. + + Also a grid point next to it (MATLAB's interp2), unlike linear + interpolation; the cubic warp falls back to linear there. + """ im = np.arange(80, dtype=float).reshape(8, 10) im[4, 5] = np.nan assert np.isnan(interp2_cubic(im, 4.0, 4.0)) # on the grid, next to it @@ -63,7 +68,7 @@ def test_cubic_nan_reaches_its_whole_stencil(): np.testing.assert_array_equal(np.isnan(cub), np.isnan(lin)) -def test_gradient_is_matlabs(): +def test_gradient_is_matlabs() -> None: """Central differences inside, one-sided differences at the edges.""" im = np.array([[0.0, 1, 4, 9], [1, 3, 5, 7], [2, 2, 2, 2]]) g_r, g_c = matlab_gradient(im) @@ -72,9 +77,11 @@ def test_gradient_is_matlabs(): np.testing.assert_array_equal(g_r[1], [1, 0.5, -1, -3.5]) -def test_field_reproduces_affine_map(): - """Displacements at the centres that follow an affine map give that - map everywhere, also far outside the centres.""" +def test_field_reproduces_affine_map() -> None: + """Displacements at the centres that follow an affine map give that map everywhere. + + Also far outside the centres. + """ rng = np.random.default_rng(1) nodes = np.column_stack( [rng.random(12) * 200 + 50, rng.random(12) * 400 + 50] @@ -94,9 +101,11 @@ def test_field_reproduces_affine_map(): assert np.nanmax(np.abs(out - ref)) < 1e-9 -def test_field_apply_matches_field_matrix(): - """Evaluating a bent field without the field matrix gives the same - displacements, also with fewer than 3 centres (their mean).""" +def test_field_apply_matches_field_matrix() -> None: + """Evaluating a bent field without the field matrix gives the same displacements. + + Also with fewer than 3 centres (their mean). + """ rng = np.random.default_rng(2) nodes = np.column_stack( [rng.random(40) * 200 + 50, rng.random(40) * 400 + 50] @@ -117,7 +126,7 @@ def test_field_apply_matches_field_matrix(): ) -def test_inverse_undoes_bent_field(): +def test_inverse_undoes_bent_field() -> None: """trialWarpInverse: back to the consensus points to 1e-5 px.""" rng = np.random.default_rng(3) nodes = np.column_stack( @@ -136,9 +145,11 @@ def test_inverse_undoes_bent_field(): assert (r2[0], c2[0]) == (2.75, 5.5) -def test_matlab_conversion_of_a_field(): - """MATLAB's one-based centres and affine maps convert to zero-based; - displacements stay; the map of a point moves with the base.""" +def test_matlab_conversion_of_a_field() -> None: + """MATLAB's one-based centres and affine maps convert to zero-based. + + Displacements stay; the map of a point moves with the base. + """ rng = np.random.default_rng(4) nodes1 = np.column_stack( [rng.random(8) * 50 + 10, rng.random(8) * 80 + 10] @@ -157,9 +168,11 @@ def test_matlab_conversion_of_a_field(): np.testing.assert_allclose(warp.to_matlab(), a1) -def test_kmeans_finds_separated_clusters(): - """Three well separated clusters are found from k-means++ starts; an - empty cluster restarts at the farthest point.""" +def test_kmeans_finds_separated_clusters() -> None: + """Three well separated clusters are found from k-means++ starts. + + An empty cluster restarts at the farthest point. + """ rng = np.random.default_rng(5) centres = np.array([[0.0, 0], [50, 0], [0, 50]]) x = np.vstack([c + rng.standard_normal((200, 2)) for c in centres]) @@ -179,7 +192,7 @@ def test_kmeans_finds_separated_clusters(): assert sorted(np.bincount(labels, minlength=3)) == [1, 1, 1] -def test_patch_size_is_bounded(): +def test_patch_size_is_bounded() -> None: """A patch needs at least one pixel; one pixel per patch at most.""" valid = np.zeros((6, 8), bool) valid[1:4, 2:6] = True @@ -192,9 +205,8 @@ def test_patch_size_is_bounded(): PlanParams(align_patch_px=0.5) -def test_patches_have_their_size(): - """About patch_px pixels each, none under half of it, centred on their - pixels.""" +def test_patches_have_their_size() -> None: + """About patch_px pixels each, none under half of it, centred on their pixels.""" valid = np.zeros((120, 160), bool) valid[10:100, 20:150] = True valid[40:60, 60:90] = False @@ -212,15 +224,17 @@ def test_patches_have_their_size(): @pytest.fixture(scope="module") def synthetic_neuron(): - """The labeled neuron of MATLAB's test and its scanned pixels.""" + """Build the labeled neuron of MATLAB's test and its scanned pixels.""" rng = np.random.default_rng(1) truth, scan = neuron(rng) return truth, scan, rng -def test_affine_recovers_known_maps(synthetic_neuron): - """The relative maps between trials are recovered to 0.05 px, much - better than the rigid start.""" +def test_affine_recovers_known_maps(synthetic_neuron) -> None: + """The relative maps between trials are recovered to 0.05 px. + + Much better than the rigid start. + """ truth, scan, rng = synthetic_neuron m, _, u, a0 = trials(truth, scan, False, rng) a, info = align_trials_affine(m, a0) @@ -230,10 +244,12 @@ def test_affine_recovers_known_maps(synthetic_neuron): assert np.all(info.corr > 0.9) -def test_patchwise_recovers_bends(synthetic_neuron): - """Smooth bends (over ~40 px) on top of affine maps: recovered to 0.08 - px, much better than the rigid start and beyond an affine fit; no - patch under half the target size.""" +def test_patchwise_recovers_bends(synthetic_neuron) -> None: + """Smooth bends (over ~40 px) on top of affine maps are recovered to 0.08 px. + + Much better than the rigid start and beyond an affine fit; no patch under + half the target size. + """ truth, scan, rng = synthetic_neuron m, mh, u, a0 = trials(truth, scan, True, rng) fit, info = align_trials_patchwise(m, a0, mh, 1500) @@ -252,9 +268,8 @@ def test_patchwise_recovers_bends(synthetic_neuron): assert np.isfinite(plane.coords(0, 1.0, 1.0)[0]) -def test_patchwise_adds_nothing_without_bends(synthetic_neuron): - """Affine maps only: the patchwise field is as good as the affine - fit.""" +def test_patchwise_adds_nothing_without_bends(synthetic_neuron) -> None: + """Affine maps only: the patchwise field is as good as the affine fit.""" truth, scan, rng = synthetic_neuron m, mh, u, a0 = trials(truth, scan, False, rng) fit, _ = align_trials_patchwise(m, a0, mh, 1500) @@ -263,9 +278,12 @@ def test_patchwise_adds_nothing_without_bends(synthetic_neuron): assert err < 0.05 -def test_patchwise_given_patches_and_without_halves(): - """Given its own patches back, the fit is the same; without halves the - departures are kept as fitted (weight 1) and the fit still runs.""" +def test_patchwise_given_patches_and_without_halves() -> None: + """Given its own patches back, the fit is the same. + + Without halves the departures are kept as fitted (weight 1) and the fit + still runs. + """ rng = np.random.default_rng(7) truth, scan = neuron(rng, (70, 90)) m, mh, _, a0 = trials(truth, scan, True, rng, n_trials=3) @@ -281,7 +299,7 @@ def test_patchwise_given_patches_and_without_halves(): assert np.isfinite(plain.disp).all() -def test_too_few_trials_or_pixels_keep_the_start(): +def test_too_few_trials_or_pixels_keep_the_start() -> None: """With fewer than 2 trials to fit, the maps are the starting ones.""" m = np.random.default_rng(6).random((2, 30, 40)) a0 = np.array([np.eye(2, 3), np.full((2, 3), np.nan)]) diff --git a/tests/raster/test_raster_annotations.py b/tests/raster/test_raster_annotations.py index 432c18ab..f6b03b14 100644 --- a/tests/raster/test_raster_annotations.py +++ b/tests/raster/test_raster_annotations.py @@ -1,5 +1,7 @@ -"""Tests of reading SILo's annotations.h5 and moving ROIs to the consensus -frame (loadAnnotationsH5, roisToConsensusFrame, shiftRoiData).""" +"""Tests of reading SILo's annotations.h5 and moving ROIs to the consensus frame. + +MATLAB functions: loadAnnotationsH5, roisToConsensusFrame, shiftRoiData. +""" import h5py import numpy as np @@ -19,21 +21,20 @@ SHAPE = (12, 16) # MATLAB rows x cols of the annotation image -def _text(f, path, value): - """A string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" +def _text(f, path, value) -> None: + """Write a string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" f.create_dataset( path, data=np.array([[ord(c)] for c in value], dtype=np.uint16) ) -def _matlab(f, path, value): - """A numeric array as MATLAB's h5write stores it (dimensions - reversed).""" +def _matlab(f, path, value) -> None: + """Write a numeric array as MATLAB's h5write stores it (dimensions reversed).""" f.create_dataset(path, data=np.ascontiguousarray(np.asarray(value).T)) def write_annotations(path, zero_indexed=True): - """A file with two paths in MATLAB's layout; returns the masks.""" + """Write a file with two paths in MATLAB's layout and return the masks.""" masks = [] with h5py.File(path, "w") as f: _matlab(f, "row_major", np.uint8([[0]])) @@ -70,7 +71,7 @@ def write_annotations(path, zero_indexed=True): @pytest.mark.parametrize("zero_indexed", [True, False]) -def test_read_annotations(tmp_path, zero_indexed): +def test_read_annotations(tmp_path, zero_indexed) -> None: """Strings, masks (MATLAB orientation) and geometry are read back.""" path = tmp_path / "annotations.h5" masks = write_annotations(path, zero_indexed) @@ -90,7 +91,7 @@ def test_read_annotations(tmp_path, zero_indexed): assert [a.path for a in paths] == [1, 2] -def test_annotation_trial(): +def test_annotation_trial() -> None: """The annotation's file is matched with or without its extension.""" fns = ["E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", "E1T2DMD1_X.h5"] assert annotation_trial("E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz", fns) == 0 @@ -100,9 +101,11 @@ def test_annotation_trial(): assert annotation_trial("", fns) is None -def test_rois_to_consensus_shift(tmp_path): - """Masks move by minus the trial's rounded shift, geometry exactly; a - trial that is not known or not aligned leaves them in place.""" +def test_rois_to_consensus_shift(tmp_path) -> None: + """Masks move by minus the trial's rounded shift, geometry exactly. + + A trial that is not known or not aligned leaves them in place. + """ path = tmp_path / "annotations.h5" masks = write_annotations(path) ann = read_annotations(path)[0] @@ -125,9 +128,11 @@ def test_rois_to_consensus_shift(tmp_path): rois_to_consensus(ann, ["a.tif", "b.tif"], warp, shape) -def test_soma_mask_and_session(tmp_path): - """Soma masks are the union of the ROIs labelled SOMA; a session - without a file has no annotations.""" +def test_soma_mask_and_session(tmp_path) -> None: + """Soma masks are the union of the ROIs labelled SOMA. + + A session without a file has no annotations. + """ rois = [ UserRoi("soma", "polygon", np.eye(4, dtype=bool)), UserRoi("Spine", "circle", np.ones((4, 4), bool)), @@ -147,7 +152,7 @@ def test_soma_mask_and_session(tmp_path): assert got[0] is None and got[1].path == 2 and got[2].path == 3 -def test_text_is_utf16(tmp_path): +def test_text_is_utf16(tmp_path) -> None: """MATLAB stores text as UTF-16 code units, surrogate pairs included.""" label = "soma é😀" codes = np.frombuffer(label.encode("utf-16-le"), dtype=" None: """The file is named from the trial's stem or its movie's name.""" assert baseline_file("d", "E1T2DMD1").name == "E1T2DMD1_BASELINE-80Hz.h5" name = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" assert baseline_file("d", name).name == "E1T2DMD1_BASELINE-80Hz.h5" -def test_read_network_baseline_orientation(tmp_path): - """slap2-f0 writes (frame, MATLAB col, MATLAB row); reading gives - (frame, row, col).""" +def test_read_network_baseline_orientation(tmp_path) -> None: + """slap2-f0 writes (frame, MATLAB col, MATLAB row). + + Reading gives (frame, row, col). + """ stack = np.random.default_rng(0).random((4, 3, 5)).astype(np.float32) path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" with h5py.File(path, "w") as f: @@ -44,7 +48,7 @@ def test_read_network_baseline_orientation(tmp_path): assert attrs["checkpoint"] == "x.pt" -def test_read_network_baseline_rejects_other_shapes(tmp_path): +def test_read_network_baseline_rejects_other_shapes(tmp_path) -> None: """A /baseline that is not three-dimensional is refused.""" path = tmp_path / "b.h5" with h5py.File(path, "w") as f: @@ -53,7 +57,7 @@ def test_read_network_baseline_rejects_other_shapes(tmp_path): read_network_baseline(path) -def test_bilinear_is_exact_on_a_plane(): +def test_bilinear_is_exact_on_a_plane() -> None: """A plane is sampled exactly at sub-pixel positions.""" stack = _plane(3, 6, 7) rc = np.array([[0.0, 0.0], [2.5, 3.25], [4.9, 5.1], [5.0, 6.0]]) @@ -63,9 +67,11 @@ def test_bilinear_is_exact_on_a_plane(): np.testing.assert_allclose(weight, 1.0) -def test_bilinear_renormalizes_over_neighbours_with_values(): - """Neighbours without a value are left out; too little weight left - gives NaN.""" +def test_bilinear_renormalizes_over_neighbours_with_values() -> None: + """Neighbours without a value are left out. + + Too little weight left gives NaN. + """ stack = np.full((2, 4, 4), 7.0) stack[:, 1, 2] = np.nan # (1.2, 1.2): the NaN corner (1, 2) carries 0.8 * 0.2 of the weight @@ -80,9 +86,11 @@ def test_bilinear_renormalizes_over_neighbours_with_values(): np.testing.assert_allclose(values, 7.0) -def test_bilinear_outside_the_frame(): - """Neighbours outside the stack have no value; a whole-pixel position - on the last row needs no neighbour beyond it.""" +def test_bilinear_outside_the_frame() -> None: + """Neighbours outside the stack have no value. + + A whole-pixel position on the last row needs no neighbour beyond it. + """ stack = _plane(1, 3, 3) values, weight = sample_bilinear( stack, np.array([[2.0, 1.0], [2.4, 1.0], [-1.0, -1.0]]) @@ -95,7 +103,7 @@ def test_bilinear_outside_the_frame(): assert weight[2] == 0 -def test_bilinear_per_frame_nans(): +def test_bilinear_per_frame_nans() -> None: """A neighbour missing in one frame only is left out of that frame.""" stack = _plane(3, 3, 3) stack[1, 1, 1] = np.nan @@ -109,7 +117,7 @@ def test_bilinear_per_frame_nans(): sample_bilinear(stack, np.array([[1.0, 1.0]]), 0.0) -def test_interp_frames_linear_in_lines(): +def test_interp_frames_linear_in_lines() -> None: """Linear in line number, NaN samples left out, ends held.""" src = np.array([10.0, 30.0, 50.0, 70.0]) vals = np.array([[1.0, 3.0, 5.0, 7.0], [1.0, np.nan, 5.0, 7.0]]) @@ -128,7 +136,7 @@ def test_interp_frames_linear_in_lines(): def _registration(n_r=12, n_c=14, lines_80=100, lines_200=40, n_lines=8000): - """A synthetic network baseline: a plane times a slow time course. + """Build a synthetic network baseline: a plane times a slow time course. Returns the stack (counts), the registered frames' lines, the extraction frames' lines and the true value as a function of @@ -138,7 +146,7 @@ def _registration(n_r=12, n_c=14, lines_80=100, lines_200=40, n_lines=8000): fl = np.arange(1, n_lines, lines_200, dtype=np.float64) def truth(r, c, line): - """The baseline in counts.""" + """Return the baseline in counts.""" return (200 + 8 * r + 3 * c) * (1 + 0.1 * np.sin(line / 2000.0)) r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") @@ -146,7 +154,7 @@ def truth(r, c, line): return stack, ds, fl, truth -def test_map_baseline_space_time_units(): +def test_map_baseline_space_time_units() -> None: """Space, time and units of the mapping, against the known field.""" stack, ds, fl, truth = _registration() rc = np.array([[3.4, 5.7], [0.0, 0.0], [11.0, 13.0], [6.5, 2.25]]) @@ -164,9 +172,11 @@ def test_map_baseline_space_time_units(): np.testing.assert_allclose(mapped.values[:, ~inner], tail, 1e-6) -def test_map_baseline_missing_pixels_and_fallback(): - """Pixels without a network value are flagged; with the data given - they get its starting baseline.""" +def test_map_baseline_missing_pixels_and_fallback() -> None: + """Pixels without a network value are flagged. + + With the data given they get its starting baseline. + """ stack, ds, fl, _ = _registration() stack[:, :, :4] = np.nan rc = np.array([[5.0, 1.0], [5.0, 3.6], [5.0, 3.4], [5.0, 8.0]]) @@ -188,7 +198,7 @@ def test_map_baseline_missing_pixels_and_fallback(): map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data[:, :5]) -def test_map_baseline_dropped_frames_are_interpolated_over(): +def test_map_baseline_dropped_frames_are_interpolated_over() -> None: """Dropped registered frames do not enter the time interpolation.""" stack, ds, fl, truth = _registration() bad = stack.copy() @@ -210,7 +220,7 @@ def test_map_baseline_dropped_frames_are_interpolated_over(): map_baseline(bad, rc, ds, fl, 1.0, drop_frames=np.ones_like(drop)) -def test_map_baseline_checks_inputs(): +def test_map_baseline_checks_inputs() -> None: """Mismatched frames and a bad photon scale are refused.""" stack, ds, fl, _ = _registration() rc = np.zeros((1, 2)) @@ -221,7 +231,7 @@ def test_map_baseline_checks_inputs(): map_baseline(stack, rc, ds, fl, scale) -def test_interp_frames_in_blocks(): +def test_interp_frames_in_blocks() -> None: """Interpolating in blocks gives the same rows.""" rng = np.random.default_rng(11) vals = rng.random((37, 20)) diff --git a/tests/raster/test_raster_container.py b/tests/raster/test_raster_container.py index 7d3c1b85..23a8f4bf 100644 --- a/tests/raster/test_raster_container.py +++ b/tests/raster/test_raster_container.py @@ -1,5 +1,7 @@ """Tests of the container: one trial-path's inputs of source extraction.""" +from typing import NoReturn + import h5py import numpy as np import pytest @@ -21,7 +23,7 @@ def make_trial(n_frames=40, seed=0): - """A small trial with two blobs of selected pixels and three sources. + """Make a small trial with two blobs of selected pixels and three sources. Returns the trial, the sources and each subproblem's pixels and sources: the two blobs' subproblems share the pixels of column 7. @@ -56,7 +58,7 @@ def make_trial(n_frames=40, seed=0): @pytest.mark.parametrize("compression", ["lzf", "gzip", None]) -def test_round_trip_is_exact(tmp_path, compression): +def test_round_trip_is_exact(tmp_path, compression) -> None: """Everything written is read back unchanged, whole or by subproblem.""" trial, sources_rc, pixels, sources, sel = make_trial() params = {"loader": TrialLoadParams(), "lambda": 0.9, "k": np.arange(3.0)} @@ -136,7 +138,7 @@ def test_round_trip_is_exact(tmp_path, compression): assert f.attrs["format_version"] == FORMAT_VERSION -def test_baseline_is_reserved_and_can_be_filled(tmp_path): +def test_baseline_is_reserved_and_can_be_filled(tmp_path) -> None: """The F0 network's baseline has empty, resizable datasets.""" trial, sources_rc, pixels, sources, _ = make_trial() path = write_container( @@ -162,7 +164,7 @@ def test_baseline_is_reserved_and_can_be_filled(tmp_path): ) -def test_settings_hash_ignores_key_order_only(): +def test_settings_hash_ignores_key_order_only() -> None: """The same settings hash alike however they are ordered or typed.""" a = {"lambda": 0.9, "loader": TrialLoadParams(), "k": np.array([1.0, 2.0])} b = { @@ -183,7 +185,7 @@ def test_settings_hash_ignores_key_order_only(): assert settings_hash({}) != settings_hash({"lambda": 0.9}) -def test_subproblem_lists_are_checked(tmp_path): +def test_subproblem_lists_are_checked(tmp_path) -> None: """Index lists must match, increase and stay inside their lists.""" trial, sources_rc, pixels, sources, _ = make_trial() path = tmp_path / "trial.h5" @@ -218,9 +220,11 @@ def test_subproblem_lists_are_checked(tmp_path): read_subproblem(source, k) -def test_empty_grouping_and_foreign_files(tmp_path): - """A container may hold no subproblems, or an empty one; other HDF5 - files and newer formats are refused.""" +def test_empty_grouping_and_foreign_files(tmp_path) -> None: + """A container may hold no subproblems, or an empty one. + + Other HDF5 files and newer formats are refused. + """ trial, sources_rc, pixels, sources, _ = make_trial() path = write_container( tmp_path / "none.h5", trial, sources_rc[:0], [], [], SHAPE @@ -251,9 +255,11 @@ def test_empty_grouping_and_foreign_files(tmp_path): @pytest.mark.parametrize("compression", ["lzf", None]) -def test_trial_without_selected_pixels_round_trips(tmp_path, compression): - """A path without sources has no selected pixels: its container holds - the frames and traces, and empty data.""" +def test_trial_without_selected_pixels_round_trips(tmp_path, compression) -> None: + """A path without sources has no selected pixels. + + Its container holds the frames and traces, and empty data. + """ full, *_ = make_trial() n_f = full.frame_lines.size trial = TrialData( @@ -291,9 +297,8 @@ def test_trial_without_selected_pixels_round_trips(tmp_path, compression): read_subproblem(path, 0) -def test_interrupted_write_leaves_the_old_container(tmp_path, monkeypatch): - """A failed write keeps an existing container and no partial file under - its name.""" +def test_interrupted_write_leaves_the_old_container(tmp_path, monkeypatch) -> None: + """A failed write keeps an existing container and no partial file under its name.""" trial, sources_rc, pixels, sources, _ = make_trial() path = write_container( tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE @@ -301,7 +306,7 @@ def test_interrupted_write_leaves_the_old_container(tmp_path, monkeypatch): before = path.read_bytes() from giant_python.extraction.raster import container - def fail(*args, **kwargs): + def fail(*args, **kwargs) -> NoReturn: """Stand in for a failure late in the write.""" raise OSError("disk full") diff --git a/tests/raster/test_raster_f0_images.py b/tests/raster/test_raster_f0_images.py index 139af8f4..dfda6371 100644 --- a/tests/raster/test_raster_f0_images.py +++ b/tests/raster/test_raster_f0_images.py @@ -1,6 +1,9 @@ -"""Tests of SILo's per-trial F0 images (``f0_im_trim_s``): the frames they -average, the solver's per-subproblem image, results files, assembly over -subproblems and the summaries (GIAnT-MATLAB's spine-size branch).""" +"""Tests of SILo's per-trial F0 images (``f0_im_trim_s``). + +Covers the frames they average, the solver's per-subproblem image, results +files, assembly over subproblems and the summaries (GIAnT-MATLAB's spine-size +branch). +""" import argparse from dataclasses import replace @@ -28,15 +31,21 @@ from giant_python.models.params import SiloParams from giant_python.spine.summary_io import RunSummary -from .test_raster_solver import PARAMS, _placed, _result -from .test_raster_solver import fixture # noqa: F401 (a pytest fixture) -from .test_raster_summary import C, H, N_TRIALS, W, alignment, make_plan +from .test_raster_solver import ( + PARAMS, + _placed, + _result, + fixture, # noqa: F401 (a pytest fixture) +) +from .test_raster_summary import N_TRIALS, C, H, W, alignment, make_plan from .test_raster_summary import outcome as summary_outcome -def test_f0_image_frames_trim_the_kept_frames(): - """Kept frames less the trim at each end; all kept frames when the - trim leaves none; no trim keeps every kept frame.""" +def test_f0_image_frames_trim_the_kept_frames() -> None: + """Kept frames less the trim at each end. + + All kept frames when the trim leaves none; no trim keeps every kept frame. + """ discard = np.zeros(20, bool) discard[[5, 6]] = True fr = f0_image_frames(discard, 0.02, 200.0) # 4 frames each end @@ -52,9 +61,12 @@ def test_f0_image_frames_trim_the_kept_frames(): assert fr[3:17].all() and not fr[:3].any() and not fr[17:].any() -def test_solver_averages_its_final_baseline(fixture): # noqa: F811 - """The F0 image is the final baseline (as kept with keep_baseline) - averaged over the given frames, per channel and pixel.""" +def test_solver_averages_its_final_baseline(fixture) -> None: # noqa: F811 + """The F0 image is the final baseline averaged over the given frames. + + The final baseline is as kept with keep_baseline; averaged per channel and + pixel. + """ sub, _ = fixture n_t = sub.y.shape[2] frames = np.zeros(n_t, bool) @@ -75,14 +87,16 @@ def test_solver_averages_its_final_baseline(fixture): # noqa: F811 def _with_image(result, image): - """``result`` with an F0 image.""" + """Return ``result`` with an F0 image.""" return replace(result, f0_image=np.asarray(image, float)) -def test_assembly_averages_shared_pixels(): - """Pixels held by several subproblems get the mean of their images, in - movie units; pixels held by none are NaN; without an image in every - subproblem there is none.""" +def test_assembly_averages_shared_pixels() -> None: + """Pixels held by several subproblems get the mean of their images. + + In movie units; pixels held by none are NaN; without an image in every + subproblem there is none. + """ subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) b = _with_image(_result(2, 2, 6, 2.0), [[10, 20], [30, 40]]) @@ -103,7 +117,7 @@ def test_assembly_averages_shared_pixels(): def _record(n_t=6): - """A trial record of ``n_t`` frames.""" + """Build a trial record of ``n_t`` frames.""" return TrialRecord( frame_lines=np.arange(n_t) + 1, discard=np.zeros(n_t, bool), @@ -113,9 +127,12 @@ def _record(n_t=6): ) -def test_results_files_keep_the_image(tmp_path): - """The image goes into the results file and back; a result without one - reads back without one, and the two do not count as equal.""" +def test_results_files_keep_the_image(tmp_path) -> None: + """The image goes into the results file and back. + + A result without one reads back without one, and the two do not count as + equal. + """ a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) b = _result(3, 1, 6, 1.0) attrs = {"n_subproblems": 2, "n_pixels": 6, "n_sources": 5} @@ -136,8 +153,10 @@ def test_results_files_keep_the_image(tmp_path): def _f0_outcome(t, n_px, scale): - """The summary tests' trial outcome with an F0 image: the analysis - channel ``c`` of pixel ``p`` holds ``scale * (100 c + p + 1)``.""" + """Build the summary tests' trial outcome with an F0 image. + + The analysis channel ``c`` of pixel ``p`` holds ``scale * (100 c + p + 1)``. + """ out = summary_outcome(t, n_px) img = scale * ( 100.0 * np.arange(C)[:, None] + np.arange(n_px)[None, :] + 1 @@ -146,11 +165,14 @@ def _f0_outcome(t, n_px, scale): return out -def test_summaries_hold_the_f0_images(tmp_path): - """The per-trial F0 images (file channel order, NaN outside the - selected pixels and for trials without one), their mean over trials - and the user ROIs' F0 with coverage, in MATLAB's layout, read back by - the spine readout's reader.""" +def test_summaries_hold_the_f0_images(tmp_path) -> None: + """The summaries hold the per-trial F0 images and the user ROIs' F0. + + The per-trial F0 images (file channel order, NaN outside the selected + pixels and for trials without one), their mean over trials and the user + ROIs' F0 with coverage, in MATLAB's layout, read back by the spine + readout's reader. + """ plan = make_plan() n_px = plan.n_pixels result = PathResult( @@ -201,7 +223,7 @@ def test_summaries_hold_the_f0_images(tmp_path): ) -def test_no_f0_images_without_them(tmp_path): +def test_no_f0_images_without_them(tmp_path) -> None: """Trials without F0 images give no F0 datasets.""" plan = make_plan() n_px = plan.n_pixels @@ -222,14 +244,14 @@ def test_no_f0_images_without_them(tmp_path): assert "F0imTrim_s" not in g["params"] -def test_trial_outcome_carries_the_image(): +def test_trial_outcome_carries_the_image() -> None: """A trial's processed activity keeps the assembled F0 image.""" from giant_python.extraction.raster.results import trial_outcome class File: """A results file in memory.""" - def __init__(self, results, attrs): + def __init__(self, results, attrs) -> None: """Hold the parts :func:`trial_outcome` reads.""" self.record = _record() self.results = results @@ -252,10 +274,12 @@ def __init__(self, results, attrs): np.testing.assert_allclose(out.activity.f0_image, 2.0 * a.f0_image) -def test_settings_and_options(): - """The trim is a solve-stage setting recorded only when F0 images are - made (results files made without them stay current then); the command - line turns them off or sets the trim, not both.""" +def test_settings_and_options() -> None: + """The trim is a solve-stage setting recorded only when F0 images are made. + + Results files made without them stay current then; the command line turns + them off or sets the trim, not both. + """ assert "f0_im_trim_s" not in SiloParams(f0_im_trim_s=None).stage_settings( "solve" ) @@ -265,7 +289,7 @@ def test_settings_and_options(): SiloParams(f0_im_trim_s=-1.0) def args(**kw): - """A namespace with the F0-image options.""" + """Build a namespace with the F0-image options.""" return argparse.Namespace( **{"f0_im_trim_s": None, "no_f0_images": False, **kw} ) @@ -277,9 +301,11 @@ def args(**kw): params_from_args(args(f0_im_trim_s=0.5, no_f0_images=True)) -def test_results_without_images_assemble_without(tmp_path): - """Results of a run without F0 images (or older files) give a trial - without an image.""" +def test_results_without_images_assemble_without(tmp_path) -> None: + """Results of a run without F0 images give a trial without an image. + + Also for older files. + """ r = SubproblemResult( footprints=np.ones((2, 1)), events=np.zeros((2, 1, 6)), diff --git a/tests/raster/test_raster_kinetics.py b/tests/raster/test_raster_kinetics.py index 2460daac..3ce9bc21 100644 --- a/tests/raster/test_raster_kinetics.py +++ b/tests/raster/test_raster_kinetics.py @@ -32,16 +32,18 @@ def ref(): return {k: f[k][()] for k in f} -def test_islocalmax_matches_matlab(ref): +def test_islocalmax_matches_matlab(ref) -> None: """Maxima, runs of equal values and MinSeparation as MATLAB's.""" for i, sep in enumerate(ref["seps"]): got = islocalmax(ref["Y"], sep) np.testing.assert_array_equal(got, ref["M"][i].astype(bool)) -def test_islocalmax_rules(): - """Ends are never maxima; a run's centre is marked; a closer, more - prominent maximum replaces the last one kept.""" +def test_islocalmax_rules() -> None: + """Ends are never maxima; a run's centre is marked. + + A closer, more prominent maximum replaces the last one kept. + """ y = np.array([5.0, 1, 3, 3, 3, 3, 1, 0, 4, 0, 2, 9]) assert np.flatnonzero(islocalmax(y)).tolist() == [3, 8] # 3 (run 2..5) and 8 are 3 apart from the run's end; 8 is more prominent @@ -52,7 +54,7 @@ def test_islocalmax_rules(): np.testing.assert_array_equal(islocalmax(two)[1], islocalmax(y[::-1])) -def test_kinetics_scores_match_matlab(ref): +def test_kinetics_scores_match_matlab(ref) -> None: """Scores and event counts of sourceKinetics; the sources kept.""" traces = list(ref["LS"]) + [None] score, n_events = source_kinetics(traces, 0.024, 200.0) @@ -64,7 +66,7 @@ def test_kinetics_scores_match_matlab(ref): np.testing.assert_array_equal(test.rejected, np.flatnonzero(~test.keep)) -def test_movmean_omitnan(): +def test_movmean_omitnan() -> None: """Window placement of MATLAB's movmean (even and odd), NaN left out.""" x = np.array([[1.0, np.nan, 3, 4, 5, 6]]) np.testing.assert_allclose( @@ -77,9 +79,11 @@ def test_movmean_omitnan(): assert np.isnan(movmean_omitnan(np.full((1, 4), np.nan), 3)).all() -def test_source_minutes(ref): - """Minutes of each source's frames that were not discarded, over the - trials with traces; the rate the evidence test compares.""" +def test_source_minutes(ref) -> None: + """Minutes of each source's frames that were not discarded, over the trials with traces. + + This gives the rate the evidence test compares. + """ from giant_python.extraction.raster.kinetics import ( source_minutes, weak_sources, @@ -107,7 +111,7 @@ def test_source_minutes(ref): np.testing.assert_allclose(twice, 2 * minutes) -def test_kinetics_edge_cases(): +def test_kinetics_edge_cases() -> None: """No traces, a short time constant and threshold 0 keep everything.""" score, n = source_kinetics([None], 0.024, 200.0) assert score.size == 0 and n.size == 0 @@ -121,7 +125,7 @@ def test_kinetics_edge_cases(): assert test.keep.all() -def test_weak_sources_and_mean_snr(): +def test_weak_sources_and_mean_snr() -> None: """The evidence test's criteria, each off at 0.""" from giant_python.extraction.raster.kinetics import ( mean_snr, diff --git a/tests/raster/test_raster_localization.py b/tests/raster/test_raster_localization.py index 467f2985..2650b74b 100644 --- a/tests/raster/test_raster_localization.py +++ b/tests/raster/test_raster_localization.py @@ -20,7 +20,7 @@ def _fixture(): - """The synthetic trial and GIAnT-MATLAB's results on it. + """Read the synthetic trial and GIAnT-MATLAB's results on it. HDF5 holds MATLAB's (rows, cols, frames) arrays as (frames, cols, rows). """ @@ -53,7 +53,7 @@ def _seed_offsets(py, ml): @pytest.mark.parametrize("kind", ["movmedian", "external"]) -def test_matches_matlab(kind): +def test_matches_matlab(kind) -> None: """Activity image, summary and seeds agree with GIAnT-MATLAB.""" movie, vf, base, ref = _fixture() r = localize_sources( @@ -79,7 +79,7 @@ def test_matches_matlab(kind): assert np.mean(_seed_offsets(py, ml) < 0.1) >= 0.9 -def test_peak_port_on_matlab_summary(): +def test_peak_port_on_matlab_summary() -> None: """Seeds from MATLAB's own summary image agree with MATLAB's seeds.""" from giant_python.extraction.raster.peaks import get_act_im_peaks @@ -92,8 +92,8 @@ def test_peak_port_on_matlab_summary(): assert np.mean(_seed_offsets(py, ml) < 0.25) >= near -def test_moving_windows_match_matlab(): - """smoothdata movmean/movmedian with 'omitnan' and an even window.""" +def test_moving_windows_match_matlab() -> None: + """Smoothdata movmean/movmedian with 'omitnan' and an even window.""" x = np.array([1, np.nan, 3, 4, np.nan, 6, 7, 8, 9, 10], np.float32) mean = movmean_nan(x[:, None], 4).ravel() med = movmedian_nan(x[:, None], 4).ravel() @@ -106,7 +106,7 @@ def test_moving_windows_match_matlab(): ) -def test_no_surround_is_the_gaussian_alone(): +def test_no_surround_is_the_gaussian_alone() -> None: """surround=False: the spatial filter is the Gaussian, without the DoG.""" rng = np.random.default_rng(0) z = rng.standard_normal((40, 30, 32)).astype(np.float32) @@ -132,7 +132,7 @@ def test_no_surround_is_the_gaussian_alone(): np.testing.assert_allclose(sk, want, rtol=1e-5, atol=1e-9) -def test_soft_threshold_ignores_noise_maxima(): +def test_soft_threshold_ignores_noise_maxima() -> None: """Maxima below soft_th add nothing; a strong event still scores.""" rng = np.random.default_rng(1) z = rng.standard_normal((300, 24, 24)).astype(np.float32) @@ -147,7 +147,7 @@ def test_soft_threshold_ignores_noise_maxima(): assert np.unravel_index(np.argmax(sk_ev), sk_ev.shape) == (12, 12) -def test_params_validation(): +def test_params_validation() -> None: """Unknown option values are rejected.""" with pytest.raises(ValueError): RasterLocalizationParams(null="signflip") @@ -163,41 +163,49 @@ def test_params_validation(): RasterLocalizationParams(soft_th=-1) -def test_external_baseline_shape_checked(): +def test_external_baseline_shape_checked() -> None: """An external baseline must have the movie's shape.""" movie = np.ones((50, 10, 10), np.float32) with pytest.raises(ValueError): localize_sources(movie, None, baseline=np.ones((50, 10, 9))) -def test_var_factor_shape_checked(): - """The variance factor must have the movie's shape: a transposed one - of the same size, or a single frame, is rejected rather than reshaped.""" +def test_var_factor_shape_checked() -> None: + """The variance factor must have the movie's shape. + + A transposed one of the same size, or a single frame, is rejected rather + than reshaped. + """ movie = np.ones((50, 10, 12), np.float32) for vf in (np.ones((50, 12, 10)), np.ones((10, 12))): with pytest.raises(ValueError, match="var_factor"): localize_sources(movie, vf) -def test_no_variance_floor_needs_an_external_baseline(): - """Without the floor, the moving median's low bias at low counts would - blow up dim pixels' Z-scores, so an external baseline is required.""" +def test_no_variance_floor_needs_an_external_baseline() -> None: + """Without the floor, an external baseline is required. + + The moving median's low bias at low counts would blow up dim pixels' + Z-scores. + """ movie = np.ones((50, 10, 10), np.float32) p = RasterLocalizationParams(variance_floor=False) with pytest.raises(ValueError, match="external baseline"): localize_sources(movie, None, p) -def test_moving_mean_keeps_precision_on_long_recordings(): +def test_moving_mean_keeps_precision_on_long_recordings() -> None: """Prefix sums in float64: no drift over a long float32 recording.""" x = np.full((24000, 2), 1.1, np.float32) out = movmean_nan(x, 8) np.testing.assert_allclose(out[-50:], np.float32(1.1), rtol=1e-6) -def test_no_floor_with_a_uniform_external_baseline(): - """A spatially uniform baseline (no pixel above the 90th percentile of - brightness) still gives a finite activity image without the floor.""" +def test_no_floor_with_a_uniform_external_baseline() -> None: + """A spatially uniform baseline still gives a finite activity image without the floor. + + Uniform here means no pixel above the 90th percentile of brightness. + """ rng = np.random.default_rng(3) base = np.full((600, 20, 20), 9.0, np.float32) movie = (base + 3 * rng.standard_normal(base.shape)).astype(np.float32) @@ -207,9 +215,11 @@ def test_no_floor_with_a_uniform_external_baseline(): assert loc.info["Vk"] > 0 -def test_no_valid_pixels_keeps_find_peaks_false(): - """The early return for a trial without valid pixels honours - ``find_peaks``: peaks are None when seeding was not requested.""" +def test_no_valid_pixels_keeps_find_peaks_false() -> None: + """The early return for a trial without valid pixels honours ``find_peaks``. + + Peaks are None when seeding was not requested. + """ movie = np.full((50, 10, 10), np.nan, np.float32) with pytest.warns(UserWarning): loc = localize_sources(movie, find_peaks=False) @@ -218,9 +228,11 @@ def test_no_valid_pixels_keeps_find_peaks_false(): assert localize_sources(movie).peaks.shape == (0, 4) -def test_pixels_mostly_missing_leave_the_variance_model(): - """As MATLAB (``varIM(nanFrac > 0.4) = nan``): valid pixels missing - more than 40% of frames do not change Vb.""" +def test_pixels_mostly_missing_leave_the_variance_model() -> None: + """Valid pixels missing more than 40% of frames do not change Vb. + + As MATLAB (``varIM(nanFrac > 0.4) = nan``). + """ rng = np.random.default_rng(5) t = 600 movie = (20 + 3 * rng.standard_normal((t, 20, 20))).astype(np.float32) diff --git a/tests/raster/test_raster_null.py b/tests/raster/test_raster_null.py index e93456ca..1a15ed8f 100644 --- a/tests/raster/test_raster_null.py +++ b/tests/raster/test_raster_null.py @@ -20,10 +20,12 @@ def _gradient_movie( rng, t=1500, rows=40, cols=90, gain=8.0, margin=0, photons=None ): - """Pure photon noise with brightness 0.03-30 photons across the columns - (or the given photons per column), filtered as image formation does - (correlations in time and space); with a margin of unimaged (NaN) pixels - around it, as SLAP2 frames have.""" + """Pure photon noise with brightness 0.03-30 photons across the columns. + + Brightness is the given photons per column, if any. The noise is filtered + as image formation does (correlations in time and space); with a margin of + unimaged (NaN) pixels around it, as SLAP2 frames have. + """ if photons is None: photons = np.exp(np.linspace(np.log(0.03), np.log(30), cols)) b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) @@ -53,7 +55,7 @@ def _gradient_movie( return movie.astype(np.float32), base, noise, photons -def test_kernels_give_the_correlations(): +def test_kernels_give_the_correlations() -> None: """The fitted kernels' autocorrelations are the requested ones.""" k = temporal_kernel(0.6, 0.25) ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() @@ -63,7 +65,7 @@ def test_kernels_give_the_correlations(): assert np.isclose(k.sum(), 1) and np.isclose(s.sum(), 1) -def test_noise_model_recovers_gain_and_correlations(): +def test_noise_model_recovers_gain_and_correlations() -> None: """A null movie's measured model is the model it was drawn with.""" rng = np.random.default_rng(0) movie, base, noise, _ = _gradient_movie(rng) @@ -81,7 +83,7 @@ def test_noise_model_recovers_gain_and_correlations(): assert 1.0 <= m["q"] < 1.3 -def test_null_mean_is_the_baseline_and_skew_is_poisson(): +def test_null_mean_is_the_baseline_and_skew_is_poisson() -> None: """Null noise has the baseline's mean, gain x b variance, Poisson skew.""" rng = np.random.default_rng(1) movie, base, noise, photons = _gradient_movie(rng, t=3000, cols=6) @@ -108,10 +110,13 @@ def _tail(x): return m, np.quantile(x, 0.995) - m -def test_bootstrap_calibrates_dim_and_bright_pixels(): - """On a trial of pure photon noise, the calibrated image has the same - centre and upper tail at every brightness; uncalibrated, dim pixels' - tail is heavier.""" +def test_bootstrap_calibrates_dim_and_bright_pixels() -> None: + """The calibrated image has the same centre and tail at every brightness. + + On a trial of pure photon noise, the calibrated image has the same centre + and upper tail at every brightness; uncalibrated, dim pixels' tail is + heavier. + """ rng = np.random.default_rng(2) movie, base, _, photons = _gradient_movie(rng, rows=80, margin=6) p_raw = RasterLocalizationParams(variance_floor=False) @@ -150,10 +155,12 @@ def _ar1(rng, t, n, rho=0.6): lambda t: t % 3 != 2, # 0, 1, 3, 4, 6, 7...: lag 2 spans a gap ], ) -def test_lag_correlations_use_recorded_frame_indices(kept): - """Lags are counted in recorded frames: pairs are matched by their - original indices, also across a discarded frame between them, and - never across a gap that changes the lag.""" +def test_lag_correlations_use_recorded_frame_indices(kept) -> None: + """Lags are counted in recorded frames. + + Pairs are matched by their original indices, also across a discarded + frame between them, and never across a gap that changes the lag. + """ rng = np.random.default_rng(4) t, n = 3000, 400 r = _ar1(rng, t, n) @@ -163,9 +170,11 @@ def test_lag_correlations_use_recorded_frame_indices(kept): np.testing.assert_allclose(m["rho"][:2], [0.6, 0.36], atol=0.03) -def test_null_variance_around_discarded_frames(): - """Discarded frames (NaN baseline, as an external baseline gives) keep - their latent noise: the frames next to them get the full variance.""" +def test_null_variance_around_discarded_frames() -> None: + """Discarded frames (NaN baseline, as an external baseline gives) keep their latent noise. + + The frames next to them get the full variance. + """ t, rows, cols, gain = 4000, 20, 20, 8.0 noise = dict( gain=gain, @@ -197,9 +206,12 @@ def test_null_variance_around_discarded_frames(): assert abs(var_far / (gain * 2.0 * gain) - 1) < 0.05 # gain x b -def test_null_variance_next_to_bright_structures(): - """Where brightness changes across the spatial kernel, every pixel keeps - the variance gain x b, and the measured model is still the drawn one.""" +def test_null_variance_next_to_bright_structures() -> None: + """Every pixel keeps the variance gain x b next to bright structures. + + Where brightness changes across the spatial kernel, every pixel keeps the + variance gain x b, and the measured model is still the drawn one. + """ t, rows, cols, gain = 3000, 30, 30, 8.0 photons = np.where((np.arange(cols) // 3) % 2 == 0, 30.0, 0.3) b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) @@ -233,7 +245,7 @@ def test_null_variance_next_to_bright_structures(): np.testing.assert_allclose(m["rho"][:3], [0.6, 0.25, 0.23], atol=0.03) -def test_bootstrap_on_a_uniform_baseline(): +def test_bootstrap_on_a_uniform_baseline() -> None: """A trial of one brightness is calibrated with a single bin.""" rng = np.random.default_rng(6) t, rows, cols = 1200, 30, 30 @@ -245,9 +257,11 @@ def test_bootstrap_on_a_uniform_baseline(): assert loc.info["null"]["m0"].size == 1 -def test_temporal_kernel_stays_finite_for_negative_lag2(): - """A negative lag-2 correlation whose best unconstrained taps sum to 0 - (``[-0.4, -0.1, 0, 1, 0, -0.1, -0.4]``) gives a finite kernel.""" +def test_temporal_kernel_stays_finite_for_negative_lag2() -> None: + """A negative lag-2 correlation whose best unconstrained taps sum to 0 gives a finite kernel. + + The taps are ``[-0.4, -0.1, 0, 1, 0, -0.1, -0.4]``. + """ k = temporal_kernel(0.08 / 1.34, -0.2 / 1.34) assert np.isfinite(k).all() and np.isclose(k.sum(), 1) assert np.abs(k).max() < 2.0 @@ -259,9 +273,12 @@ def test_temporal_kernel_stays_finite_for_negative_lag2(): assert abs(ac[1] - t1) < 0.02 and abs(ac[2] - t2) < 0.02 -def test_null_variance_follows_a_fast_changing_baseline(): - """Where the baseline changes within the temporal kernel (here every - 2 frames, 30 or 0.3 photons), each frame keeps the variance gain x b.""" +def test_null_variance_follows_a_fast_changing_baseline() -> None: + """Each frame keeps the variance gain x b where the baseline changes fast. + + Where the baseline changes within the temporal kernel (here every 2 + frames, 30 or 0.3 photons), each frame keeps the variance gain x b. + """ t, rows, cols, gain = 4000, 12, 12, 8.0 noise = dict( gain=gain, @@ -294,9 +311,11 @@ def test_null_variance_follows_a_fast_changing_baseline(): assert abs(ratio - 1) < 0.1 -def test_calibration_of_zero_brightness_is_the_dimmest_bin(): - """Pixels with zero or negative baseline take the dimmest bin's centre - and scale (not the middle bin's); NaN brightness takes the middle.""" +def test_calibration_of_zero_brightness_is_the_dimmest_bin() -> None: + """Pixels with zero or negative baseline take the dimmest bin's centre and scale. + + They do not take the middle bin's; NaN brightness takes the middle. + """ centre = np.log([0.1, 1.0, 10.0]) m0, s0 = np.array([1.0, 2.0, 3.0]), np.array([10.0, 20.0, 30.0]) photons = np.array([0.0, -1.0, np.nan, 0.01, 1.0, 100.0]) @@ -305,9 +324,11 @@ def test_calibration_of_zero_brightness_is_the_dimmest_bin(): np.testing.assert_array_equal(s, [10, 10, 20, 10, 20, 30]) -def test_null_has_no_noise_at_zero_baselines(): - """A zero-baseline pixel next to bright ones gets no null noise (its - variance gain x b is 0), not its neighbours' mixed in.""" +def test_null_has_no_noise_at_zero_baselines() -> None: + """A zero-baseline pixel next to bright ones gets no null noise. + + Its variance gain x b is 0; it does not get its neighbours' mixed in. + """ t, rows, cols, gain = 2000, 16, 16, 8.0 noise = dict( gain=gain, @@ -341,10 +362,12 @@ def test_null_has_no_noise_at_zero_baselines(): np.testing.assert_allclose(bright.mean(), 1, rtol=0.1) -def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch): - """The data's variance follows the per-frame variance factor, so the - noise model and the null movies get it unsmoothed (the Z-score keeps - MATLAB's smoothed one).""" +def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch) -> None: + """The data's variance follows the per-frame variance factor. + + So the noise model and the null movies get it unsmoothed (the Z-score + keeps MATLAB's smoothed one). + """ import giant_python.extraction.raster.null as null_mod rng = np.random.default_rng(10) @@ -375,9 +398,11 @@ def spy_movie(baseline, var_factor, *a, **k): assert set(np.unique(got[np.isfinite(got)])) == {1.0, 3.0} -def test_bins_hold_enough_null_values(): - """A small field of view gets fewer brightness bins, so no bin's 99.5th - percentile rests on a few dozen values.""" +def test_bins_hold_enough_null_values() -> None: + """A small field of view gets fewer brightness bins. + + So no bin's 99.5th percentile rests on a few dozen values. + """ rng = np.random.default_rng(11) movie, base, _, _ = _gradient_movie(rng, t=1200, rows=12, cols=30) p = RasterLocalizationParams( @@ -388,10 +413,12 @@ def test_bins_hold_enough_null_values(): assert loc.info["null"]["m0"].size <= max(1, n_ok // 500) -def test_bins_keep_the_minimum_with_tied_brightness(): - """Ties collapse equal-count edges; a few pixels below a tied block - would form a bin of their own. Bins merge until each holds 500 null - values, and tied pixels are never split.""" +def test_bins_keep_the_minimum_with_tied_brightness() -> None: + """Ties collapse equal-count edges. + + A few pixels below a tied block would form a bin of their own. Bins merge + until each holds 500 null values, and tied pixels are never split. + """ rng = np.random.default_rng(12) lp = np.concatenate( [ @@ -410,10 +437,12 @@ def test_bins_keep_the_minimum_with_tied_brightness(): assert counts2.min() >= 500 and counts2.size >= counts.size -def test_tied_brightness_end_to_end(): - """Half the columns at one brightness and two darker ones: every bin of - the calibration has at least 500 null values, so the dimmest bin's 99.5th - percentile is not set by a single maximum.""" +def test_tied_brightness_end_to_end() -> None: + """Half the columns at one brightness and two darker ones. + + Every bin of the calibration has at least 500 null values, so the dimmest + bin's 99.5th percentile is not set by a single maximum. + """ rng = np.random.default_rng(13) cols = 60 photons = np.r_[ @@ -432,10 +461,12 @@ def test_tied_brightness_end_to_end(): @pytest.mark.parametrize("t", [1, 5]) -def test_trial_too_short_for_the_null_is_left_out(t): - """A trial of a few frames (no pixel has enough frames for the noise - model) is left out of localization with a warning, as a trial without - valid pixels, instead of failing SILo.""" +def test_trial_too_short_for_the_null_is_left_out(t) -> None: + """A trial of a few frames is left out of localization with a warning. + + No pixel has enough frames for the noise model; the trial is left out as + a trial without valid pixels, instead of failing SILo. + """ rng = np.random.default_rng(9) base = np.full((t, 30, 30), 16.0, np.float32) movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) @@ -447,7 +478,7 @@ def test_trial_too_short_for_the_null_is_left_out(t): assert loc.peaks.shape == (0, 4) -def test_noise_model_raises_null_unavailable(): +def test_noise_model_raises_null_unavailable() -> None: """The noise model's refusal is a NullUnavailable (a ValueError).""" from giant_python.extraction.raster.null import NullUnavailable @@ -459,11 +490,13 @@ def test_noise_model_raises_null_unavailable(): assert issubclass(NullUnavailable, ValueError) -def test_trial_without_calibration_pixels_is_left_out(): - """A trial whose noise model can be measured but whose null calibration - has no eligible pixel (a 2-pixel-wide imaged stripe: no pixel has a full - 3 x 3 neighbourhood) is left out of localization, as a trial without - valid pixels.""" +def test_trial_without_calibration_pixels_is_left_out() -> None: + """A trial whose null calibration has no eligible pixel is left out of localization. + + Its noise model can be measured, but its null calibration has no eligible + pixel (a 2-pixel-wide imaged stripe: no pixel has a full 3 x 3 + neighbourhood); it is left out as a trial without valid pixels. + """ from giant_python.extraction.raster.null import noise_model rng = np.random.default_rng(4) diff --git a/tests/raster/test_raster_peaks.py b/tests/raster/test_raster_peaks.py index 49b46952..faee124e 100644 --- a/tests/raster/test_raster_peaks.py +++ b/tests/raster/test_raster_peaks.py @@ -1,7 +1,6 @@ """Tests of the getActImPeaks port (raster SiLo seeds).""" import numpy as np - import pytest from giant_python.extraction.raster.peaks import ( @@ -13,7 +12,7 @@ ) -def test_ordfilt_matches_matlab(): +def test_ordfilt_matches_matlab() -> None: """MATLAB ordfilt2(A, 9 or 8, ones(3)): zero padding, NaN windows.""" a = np.array([[np.nan, 1, -2], [2, 3, -1], [-5, np.nan, 4]]) nan = np.nan @@ -28,7 +27,7 @@ def test_ordfilt_matches_matlab(): ) -def test_jacobian_matches_finite_differences(): +def test_jacobian_matches_finite_differences() -> None: """The analytical Jacobian of the integrated Gaussians is right.""" yy, xx = np.mgrid[1:12, 1:14] model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) @@ -48,7 +47,7 @@ def test_jacobian_matches_finite_differences(): np.testing.assert_array_equal(model.value(theta), (vy * vx) @ a) -def test_finds_separated_gaussians(): +def test_finds_separated_gaussians() -> None: """Two blobs on noise are found at their centres (0-based).""" rng = np.random.default_rng(0) yy, xx = np.mgrid[:40, :50] @@ -64,7 +63,7 @@ def test_finds_separated_gaussians(): ) -def test_fit_falls_back_when_svd_fails(monkeypatch): +def test_fit_falls_back_when_svd_fails(monkeypatch) -> None: """A LAPACK SVD failure in the default solver retries with lsmr.""" import giant_python.extraction.raster.peaks as peaks @@ -94,7 +93,7 @@ def flaky(*args, **kwargs): np.testing.assert_allclose(theta[0], [3.0, 7.4, 8.2, 1.2], atol=1e-3) -def test_exclusion_mask_and_empty(): +def test_exclusion_mask_and_empty() -> None: """No seeds inside the exclusion mask; none in pure noise.""" rng = np.random.default_rng(1) yy, xx = np.mgrid[:30, :30] @@ -106,10 +105,12 @@ def test_exclusion_mask_and_empty(): assert get_act_im_peaks(rng.standard_normal((30, 30)), 8).shape == (0, 4) -def test_no_fitted_centre_inside_the_exclusion_mask(): - """A source whose centre is just inside the mask seeds on its unmasked - flank, and its fit moves back into the mask: it is dropped. A source - clear of the mask is kept.""" +def test_no_fitted_centre_inside_the_exclusion_mask() -> None: + """A source whose centre is just inside the mask is dropped. + + It seeds on its unmasked flank, and its fit moves back into the mask: it + is dropped. A source clear of the mask is kept. + """ rng = np.random.default_rng(2) yy, xx = np.mgrid[:30, :40] img = 0.05 * rng.standard_normal((30, 40)) @@ -124,19 +125,23 @@ def test_no_fitted_centre_inside_the_exclusion_mask(): assert unmasked.shape[0] == 2 -def test_eval_budget_matches_matlab_iterations(): - """MATLAB's 5000 evaluations with finite differences allow - (5000 - 1) // (n + 1) iterations; the budget here allows as many steps - (one evaluation each, plus the start), down to one step at n = 2500.""" +def test_eval_budget_matches_matlab_iterations() -> None: + """MATLAB's 5000 evaluations with finite differences allow (5000 - 1) // (n + 1) iterations. + + The budget here allows as many steps (one evaluation each, plus the + start), down to one step at n = 2500. + """ for n in (4, 40, 400, 2500, 4998): assert _eval_budget(n) - 1 == (5000 - 1) // (n + 1) assert _eval_budget(2500) == 2 # one step (was 1: none) assert _eval_budget(5000) == 1 # MATLAB cannot take a step either -def test_rounding_is_matlabs(): - """Halves round away from zero as in MATLAB (numpy rounds them to even), - so a centre at exactly k + 0.5 lands on MATLAB's pixel.""" +def test_rounding_is_matlabs() -> None: + """Halves round away from zero as in MATLAB (numpy rounds them to even). + + So a centre at exactly k + 0.5 lands on MATLAB's pixel. + """ from giant_python.extraction.raster.peaks import _rounded_index theta = np.array([[1.0, 4.5, 2.5, 0.35], [1.0, 3.5, 7.49, 0.35]]) @@ -146,7 +151,7 @@ def test_rounding_is_matlabs(): def _windowed(shape, starts, window, rows=None): - """A windowed model on a gap-free image, and the edges it uses.""" + """Build a windowed model on a gap-free image, and the edges it uses.""" cols, rws = np.nonzero(np.ones(shape, bool).T) idx = np.full(shape, -1, np.int64) idx[rws, cols] = np.arange(rws.size) @@ -156,10 +161,12 @@ def _windowed(shape, starts, window, rows=None): return model, rws[rows] + 1.0, cols[rows] + 1.0 -def test_windowed_model_is_the_integrated_model_within_its_window(): - """With windows covering the image, the windowed model is the dense one - (positions as offsets from the start pixels); its Jacobian, dense and - sparse, matches finite differences.""" +def test_windowed_model_is_the_integrated_model_within_its_window() -> None: + """With windows covering the image, the windowed model is the dense one. + + Positions are offsets from the start pixels; its Jacobian, dense and + sparse, matches finite differences. + """ starts = np.array([[4, 6], [9, 3]]) # 0-based start pixels theta = np.array([[3.0, 5.4, 7.2, 0.7], [1.5, 9.8, 4.1, 1.1]]) model, ys, xs = _windowed((12, 14), starts, 20) @@ -192,10 +199,12 @@ def test_windowed_model_is_the_integrated_model_within_its_window(): @pytest.mark.parametrize("dense_max", [400, 0]) @pytest.mark.parametrize("merge_px", [0.0, 1.5]) -def test_local_fit_finds_separated_gaussians(merge_px, dense_max, monkeypatch): - """The local fit finds the blobs the MATLAB fit finds, at their - centres, with the dense (SVD) solver of small fits and with the sparse - (lsmr) one of large fits.""" +def test_local_fit_finds_separated_gaussians(merge_px, dense_max, monkeypatch) -> None: + """The local fit finds the blobs the MATLAB fit finds, at their centres. + + With the dense (SVD) solver of small fits and with the sparse (lsmr) one + of large fits. + """ import giant_python.extraction.raster.peaks as peaks monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) @@ -214,8 +223,10 @@ def test_local_fit_finds_separated_gaussians(merge_px, dense_max, monkeypatch): def _split_prone_image(): - """Two sources as activity images show them: a peak narrower than a - pixel on a wider base, on unit noise.""" + """Two sources as activity images show them. + + A peak narrower than a pixel on a wider base, on unit noise. + """ rng = np.random.default_rng(0) yy, xx = np.mgrid[:30, :30] img = rng.standard_normal((30, 30)) @@ -225,9 +236,11 @@ def _split_prone_image(): return img -def test_local_fit_falls_back_when_svd_fails(monkeypatch): - """A LAPACK SVD failure in a local fit's dense solver retries with the - sparse one, and the seeds are found.""" +def test_local_fit_falls_back_when_svd_fails(monkeypatch) -> None: + """A LAPACK SVD failure in a local fit's dense solver retries with the sparse one. + + And the seeds are found. + """ import giant_python.extraction.raster.peaks as peaks calls = [] @@ -247,9 +260,11 @@ def flaky(*args, **kwargs): @pytest.mark.parametrize("fit", ["matlab", "local"]) -def test_merge_keeps_one_seed_per_split_peak(fit): - """MATLAB's rule fits each source as several peaks less than 1.5 px - apart; merge_px 1.5 keeps one per source, at the source.""" +def test_merge_keeps_one_seed_per_split_peak(fit) -> None: + """MATLAB's rule fits each source as several peaks less than 1.5 px apart. + + merge_px 1.5 keeps one per source, at the source. + """ img = _split_prone_image() assert get_act_im_peaks(img, 3, fit=fit).shape[0] > 2 pk = get_act_im_peaks(img, 3, fit=fit, merge_px=1.5) @@ -260,7 +275,7 @@ def test_merge_keeps_one_seed_per_split_peak(fit): ) -def test_seed_fit_options_are_checked(): +def test_seed_fit_options_are_checked() -> None: """Unknown fits and negative merge distances raise.""" img = _split_prone_image() with pytest.raises(ValueError): diff --git a/tests/raster/test_raster_plan.py b/tests/raster/test_raster_plan.py index 722721d9..a985bf01 100644 --- a/tests/raster/test_raster_plan.py +++ b/tests/raster/test_raster_plan.py @@ -43,9 +43,11 @@ def _blobs(shape, centres, amps, sigma, shift): def _peaks(shape, centres, amp, sigma, shift): - """Narrow peaks at ``centres + shift``: Gaussians integrated over each - pixel, the model that seeding fits (activity images are sharper than - the PSF, and a sampled Gaussian would leave residual peaks).""" + """Narrow peaks at ``centres + shift``: Gaussians integrated over each pixel. + + This is the model that seeding fits (activity images are sharper than + the PSF, and a sampled Gaussian would leave residual peaks). + """ def axis(n, mu): """Integral of the Gaussian over each of n pixels.""" @@ -61,8 +63,11 @@ def axis(n, mu): def _synthetic_trials(shape=(64, 84), seed=0): - """Five trials of one scene at SHIFTS, with an imaged region, two - channels, and activity images that peak at SOURCES.""" + """Five trials of one scene at SHIFTS. + + With an imaged region, two channels, and activity images that peak at + SOURCES. + """ rng = np.random.default_rng(seed) scene_c = rng.uniform([6, 6], [shape[0] - 6, shape[1] - 6], (40, 2)) scene_a = rng.uniform(50, 150, 40) @@ -88,7 +93,7 @@ def _synthetic_trials(shape=(64, 84), seed=0): @pytest.fixture(scope="module") def synthetic_plan(): - """The plan of the synthetic path, and its intermediates.""" + """Plan the synthetic path, and keep its intermediates.""" details = {} plan = plan_path( _synthetic_trials(), params=PlanParams(peak_th=12.0), details=details @@ -96,11 +101,12 @@ def synthetic_plan(): return plan, details -def test_plan_params(): - """Radii follow MATLAB (selRadius = ceil(2 dXY); zones of - ceil(1.5 sigma + (validKernel - 1) / 2): MATLAB's 3 x 3 gives - ceil(1.5 sigma + 1), the default 5 x 5 one more); options are - validated.""" +def test_plan_params() -> None: + """Radii follow MATLAB; options are validated. + + selRadius = ceil(2 dXY); zones of ceil(1.5 sigma + (validKernel - 1) / 2): + MATLAB's 3 x 3 gives ceil(1.5 sigma + 1), the default 5 x 5 one more. + """ p = PlanParams() assert p.valid_kernel == 5 assert p.sel_radius == 6 and p.zone_radius == 4 @@ -115,10 +121,12 @@ def test_plan_params(): PlanParams(d_xy=0) -def test_group_sources_zones_and_order(): - """Sources whose zones (5 x 5 squares for radius 3) touch form a group; - groups come in MATLAB's order, by the first pixel of their zone column - by column; pixels are the group's disks within the selected pixels.""" +def test_group_sources_zones_and_order() -> None: + """Sources whose zones (5 x 5 squares for radius 3) touch form a group. + + Groups come in MATLAB's order, by the first pixel of their zone column + by column; pixels are the group's disks within the selected pixels. + """ sel = np.ones((40, 60), bool) sel[:, 30] = False # (row, col): b and c touch through adjacent zones (5 columns apart); @@ -149,9 +157,11 @@ def test_group_sources_zones_and_order(): group_sources(rows, cols, np.zeros_like(sel), 3, 6) -def test_combined_activity_image(): - """The trials' mean (NaN where any trial is NaN), scaled to a maximum - of 10 to 100, minus its 5 x 5 NaN-median.""" +def test_combined_activity_image() -> None: + """The trials' mean (NaN where any trial is NaN), scaled and median-subtracted. + + Scaled to a maximum of 10 to 100, minus its 5 x 5 NaN-median. + """ rng = np.random.default_rng(1) act = rng.uniform(0.001, 0.002, (3, 12, 14)) act[:, 6, 7] = 0.04 @@ -167,9 +177,11 @@ def test_combined_activity_image(): assert all(np.isnan(x).all() for x in empty) -def test_plan_of_a_synthetic_path(synthetic_plan): - """Shifts, valid trials, sources, selected pixels and groups of a path - with known sources.""" +def test_plan_of_a_synthetic_path(synthetic_plan) -> None: + """Shifts, valid trials, sources, selected pixels and groups of a path. + + The path has known sources. + """ plan, details = synthetic_plan assert plan.shape == (64, 84) and plan.n_trials == 5 np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) @@ -234,10 +246,12 @@ def test_plan_of_a_synthetic_path(synthetic_plan): assert details["med_im"].shape == plan.shape -def test_plan_leaves_out_bad_and_missing_trials(): - """A trial that was not localized, one that is not kept, one without an - activity image and one that does not match the others are not valid; - sources are seeded from the rest.""" +def test_plan_leaves_out_bad_and_missing_trials() -> None: + """Bad and missing trials are not valid; sources are seeded from the rest. + + Not valid: a trial that was not localized, one that is not kept, one + without an activity image and one that does not match the others. + """ trials = _synthetic_trials() shape = trials[0].act_im.shape noise = np.random.default_rng(7).uniform(10, 30, shape) @@ -262,10 +276,11 @@ def test_plan_leaves_out_bad_and_missing_trials(): plan_path([None, None]) -def test_plan_soma_mask_and_given_seeds(): - """No source is seeded in the soma mask (smaller masks sit top left); - given seeds replace the seeding; modes that are not ported are - refused.""" +def test_plan_soma_mask_and_given_seeds() -> None: + """No source is seeded in the soma mask (smaller masks sit top left). + + Given seeds replace the seeding; modes that are not ported are refused. + """ trials = _synthetic_trials() soma = np.zeros((40, 45), bool) soma[:25, :30] = True # covers the source at (14, 16) @@ -303,9 +318,11 @@ def test_plan_soma_mask_and_given_seeds(): plan_path(trials, params=PlanParams(peak_method="wmf")) -def test_plan_of_trials_of_different_sizes(synthetic_plan): - """Trials of different sizes share one canvas (top left, NaN beyond), - as in MATLAB; their mean images must have the same channels.""" +def test_plan_of_trials_of_different_sizes(synthetic_plan) -> None: + """Trials of different sizes share one canvas (top left, NaN beyond), as in MATLAB. + + Their mean images must have the same channels. + """ plan, _ = synthetic_plan trials = _synthetic_trials() # nothing is imaged in the rows and columns cut off here @@ -323,10 +340,12 @@ def test_plan_of_trials_of_different_sizes(synthetic_plan): plan_path(trials) -def test_plan_with_a_trial_without_images(synthetic_plan): - """A kept trial whose images are all NaN (nothing was imaged often - enough) does not enter the template, so the other trials are planned - as without it; in MATLAB it would leave the path without sources.""" +def test_plan_with_a_trial_without_images(synthetic_plan) -> None: + """A kept trial whose images are all NaN does not enter the template. + + Nothing was imaged often enough in it, so the other trials are planned + as without it; in MATLAB it would leave the path without sources. + """ plan, _ = synthetic_plan trials = _synthetic_trials() shape = trials[0].act_im.shape @@ -347,9 +366,11 @@ def test_plan_with_a_trial_without_images(synthetic_plan): plan_path([blank, blank]) -def test_plan_without_sources(): - """A path whose activity images hold nothing above threshold has no - sources, pixels or groups, and still writes and reads.""" +def test_plan_without_sources() -> None: + """A path whose activity images hold nothing above threshold has no sources. + + It has no sources, pixels or groups, and still writes and reads. + """ trials = _synthetic_trials() plan = plan_path(trials, params=PlanParams(peak_th=1e6)) assert plan.n_sources == 0 and plan.n_pixels == 0 and plan.groups == [] @@ -404,9 +425,11 @@ def _assert_plans_equal(a: ExtractionPlan, b: ExtractionPlan) -> None: np.testing.assert_array_equal(x, y) -def test_write_and_read_plan(tmp_path, synthetic_plan): - """A plan survives the file; several paths share a file by group; a - file that is not a plan, or a newer version, is refused.""" +def test_write_and_read_plan(tmp_path, synthetic_plan) -> None: + """A plan survives the file; several paths share a file by group. + + A file that is not a plan, or a newer version, is refused. + """ plan, _ = synthetic_plan fn = tmp_path / "extraction_plan.h5" write_plan(fn, plan) @@ -432,7 +455,7 @@ def test_write_and_read_plan(tmp_path, synthetic_plan): def _matlab_case(case): - """The inputs of one fixture case and MATLAB's results on them. + """Read the inputs of one fixture case and MATLAB's results on them. The fixture holds a 72 x 96 window of five trials of one imaging path (780125) and what ``SILo.m`` and ``extractTrial.m`` (GIAnT-MATLAB main @@ -473,11 +496,13 @@ def _lists(ref, name): @pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_plan_matches_matlab(case): - """Every step but the Gaussian fit of the seeds reproduces MATLAB: the - template, shifts, valid trials, aligned and combined images to rounding - error; given MATLAB's seeds, the sources, their pixels and the - subproblems exactly.""" +def test_plan_matches_matlab(case) -> None: + """Every step but the Gaussian fit of the seeds reproduces MATLAB. + + The template, shifts, valid trials, aligned and combined images to + rounding error; given MATLAB's seeds, the sources, their pixels and the + subproblems exactly. + """ trials, params, ref = _matlab_case(case) details = {} plan = plan_path( @@ -533,13 +558,15 @@ def test_plan_matches_matlab(case): @pytest.mark.parametrize( "case, same_pixel", [("all_trials", 0.85), ("one_trial_out", 1.0)] ) -def test_own_seeds_are_close_to_matlabs(case, same_pixel): - """Seeding MATLAB's combined activity image with this package's fit - gives nearly MATLAB's sources. They are not identical: the Gaussian fit - is ill-conditioned for peaks narrower than a pixel and MATLAB's - lsqcurvefit stops on a tolerance or on its evaluation limit, so where - it ends depends on the optimizer (at a threshold of 3 SDs MATLAB finds - 21 sources in this window and this package 20).""" +def test_own_seeds_are_close_to_matlabs(case, same_pixel) -> None: + """Seeding with this package's fit gives nearly MATLAB's sources. + + The seeds are fit on MATLAB's combined activity image. They are not + identical: the Gaussian fit is ill-conditioned for peaks narrower than a + pixel and MATLAB's lsqcurvefit stops on a tolerance or on its evaluation + limit, so where it ends depends on the optimizer (at a threshold of 3 SDs + MATLAB finds 21 sources in this window and this package 20). + """ trials, params, ref = _matlab_case(case) plan = plan_path(trials, params=params) matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) @@ -551,12 +578,15 @@ def test_own_seeds_are_close_to_matlabs(case, same_pixel): @pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_default_seeding_on_matlabs_window(case): - """The default seeding (local fits, merging residual peaks within - 1.5 px) on MATLAB's combined activity image: every MATLAB source is - within 1 px of a source here, and every source here within 1 px of a - MATLAB source; only sources next to another are merged (all trials: 16 - of MATLAB's 21). Without merging the local fit gives MATLAB's count.""" +def test_default_seeding_on_matlabs_window(case) -> None: + """The default seeding on MATLAB's combined activity image is close to MATLAB's. + + The default seeding uses local fits, merging residual peaks within + 1.5 px: every MATLAB source is within 1 px of a source here, and every + source here within 1 px of a MATLAB source; only sources next to another + are merged (all trials: 16 of MATLAB's 21). Without merging the local fit + gives MATLAB's count. + """ import dataclasses trials, params, ref = _matlab_case(case) @@ -582,10 +612,13 @@ def test_default_seeding_on_matlabs_window(case): def test_plans_written_before_the_seed_options_read_as_matlabs( tmp_path, synthetic_plan -): - """A plan file without the seed fields (written before they existed) - reads back with MATLAB's seed fit and no merging, the settings it was - made with; a current plan keeps its own.""" +) -> None: + """A plan file without the seed fields reads back with MATLAB's seed fit. + + Such a file was written before the fields existed; it reads back with + MATLAB's seed fit and no merging, the settings it was made with; a + current plan keeps its own. + """ import json import h5py diff --git a/tests/raster/test_raster_refit.py b/tests/raster/test_raster_refit.py index 50c6e106..13ea94a7 100644 --- a/tests/raster/test_raster_refit.py +++ b/tests/raster/test_raster_refit.py @@ -37,9 +37,12 @@ PARAMS = SolverParams(valid_kernel=3) -def test_find_events(): - """Peaks above 2% of the largest, at least the lag after the previous - peak (kept or not), away from the trial's ends.""" +def test_find_events() -> None: + """Peaks above 2% of the largest are events. + + They are at least the lag after the previous peak (kept or not), away from + the trial's ends. + """ x = np.zeros(60) x[[2, 10, 14, 17, 30, 31, 44, 55]] = [5, 4, 3, 6, 0.05, 2, 1, 9] # frame 2 is within 5 of the start; 14 and 17 follow a peak within the @@ -55,7 +58,7 @@ def test_find_events(): def _truth(x, h=None): - """A truth with the given activity, flat baseline and F0.""" + """Build a truth with the given activity, flat baseline and F0.""" n_src, n_t = x.shape if h is None: h = np.array([[0.5], [0.3], [0.2]])[:, :n_src] @@ -68,9 +71,11 @@ def _truth(x, h=None): ) -def test_score_refit_of_a_perfect_and_a_scaled_refit(): - """A refit equal to the truth recovers everything; a refit at half the - size and with one event missing is scored as such.""" +def test_score_refit_of_a_perfect_and_a_scaled_refit() -> None: + """A refit equal to the truth recovers everything. + + A refit at half the size and with one event missing is scored as such. + """ k = np.exp(-np.arange(12) / 4.8) x = np.zeros((1, 120)) for t, a in ((20, 2.0), (60, 8.0), (95, 1.0)): @@ -108,7 +113,7 @@ def test_score_refit_of_a_perfect_and_a_scaled_refit(): assert 0.3 < summary["pooled"] < 0.5 -def test_score_refit_of_a_silent_source(): +def test_score_refit_of_a_silent_source() -> None: """A source without true activity has no events and NaN recovery.""" truth = _truth(np.zeros((1, 50))) src, ev = score_refit(truth, np.zeros((1, 50)), truth.f0, truth.x, 4.8) @@ -117,10 +122,12 @@ def test_score_refit_of_a_silent_source(): assert np.isnan(summarize(src, ev)["pooled"]) -def test_refit_test_on_a_real_subproblem(): - """The refit of data redrawn from a real subproblem's fit (a dim one, - 5 s long, most events below one unit) recovers the events it finds; - the same seed gives the same data.""" +def test_refit_test_on_a_real_subproblem() -> None: + """The refit of data redrawn from a real subproblem's fit recovers the events it finds. + + The subproblem is a dim one, 5 s long, most events below one unit; the same + seed gives the same data. + """ with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( y=f["in/y"][()].astype(np.float64), @@ -154,7 +161,7 @@ def test_refit_test_on_a_real_subproblem(): def _crop_truth(n_t=40): - """A truth on a 4 x 5 crop with a baseline that varies over pixels.""" + """Build a truth on a 4 x 5 crop with a baseline that varies over pixels.""" sel = np.ones((4, 5), bool) sub = Subproblem( y=np.ones((1, 20, n_t)), @@ -173,7 +180,7 @@ def _crop_truth(n_t=40): return sub, truth -def test_baseline_errors(): +def test_baseline_errors() -> None: """Scale, drift, trial-edge and blur errors of the true baseline.""" sub, truth = _crop_truth() rng = np.random.default_rng(0) @@ -196,9 +203,11 @@ def test_baseline_errors(): np.testing.assert_allclose(blurred.mean(), b.mean(), rtol=0.05) -def test_shared_component(): - """A shared fast change of the given root mean square, the same for - every pixel, reproducible from its generator.""" +def test_shared_component() -> None: + """A shared fast change of the given root mean square. + + It is the same for every pixel, reproducible from its generator. + """ sub, truth = _crop_truth(n_t=4000) change = shared_component(0.02) b1 = change(truth.b, sub, np.random.default_rng(5)) @@ -211,10 +220,12 @@ def test_shared_component(): np.testing.assert_array_equal(b1, b2) -def test_refit_test_with_a_given_baseline(): - """The refit can get the true baseline, or one with an error; the - truth's baseline can carry a shared change that the given one lacks; - the truth fits can be passed in.""" +def test_refit_test_with_a_given_baseline() -> None: + """The refit can get the true baseline, or one with an error. + + The truth's baseline can carry a shared change that the given one lacks; + the truth fits can be passed in. + """ with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( y=f["in/y"][()][:1].astype(np.float64), @@ -267,16 +278,18 @@ def test_refit_test_with_a_given_baseline(): refit_test([sub], PARAMS, opt, fits=[fit, fit]) -def test_edge_error_scales_overlapping_ends_once(): +def test_edge_error_scales_overlapping_ends_once() -> None: """In a trial shorter than both windows, every frame is scaled once.""" sub, truth = _crop_truth(n_t=10) b = edge_error(0.1, 6)(truth, sub, np.random.default_rng(0)) np.testing.assert_allclose(b, 1.1 * truth.b) -def test_refit_keeps_the_subproblems_own_baseline(): - """Without a given_baseline the refit keeps each subproblem's own - external baseline, so network modes can be refitted.""" +def test_refit_keeps_the_subproblems_own_baseline() -> None: + """Without a given_baseline the refit keeps each subproblem's own baseline. + + It keeps the external baseline, so network modes can be refitted. + """ with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( y=f["in/y"][()][:1].astype(np.float64), @@ -294,7 +307,7 @@ def test_refit_keeps_the_subproblems_own_baseline(): refit_test([sub], gain, opt, seed=1) -def test_truth_baseline_gets_a_copy(): +def test_truth_baseline_gets_a_copy() -> None: """An in-place change of the true baseline leaves the fit unchanged.""" with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( diff --git a/tests/raster/test_raster_results.py b/tests/raster/test_raster_results.py index 9e43f677..699b0e7b 100644 --- a/tests/raster/test_raster_results.py +++ b/tests/raster/test_raster_results.py @@ -1,5 +1,8 @@ -"""Tests of results files: solved subproblems of a trial-path, written by -the solve stage and assembled by the collect stage.""" +"""Tests of results files. + +Solved subproblems of a trial-path, written by the solve stage and assembled +by the collect stage. +""" import numpy as np import pytest @@ -22,7 +25,7 @@ def record(seed=0): - """A trial's record.""" + """Build a trial's record.""" rng = np.random.default_rng(seed) return TrialRecord( frame_lines=np.arange(1, N_T + 1) * 40, @@ -60,7 +63,7 @@ def solved(seed=1): def attrs(**kw): - """A results file's attributes.""" + """Build a results file's attributes.""" a = dict( settings_hash="h", container="path1_trial0001.h5", @@ -77,7 +80,7 @@ def attrs(**kw): return a -def test_round_trip(tmp_path): +def test_round_trip(tmp_path) -> None: """The record, every result and the attributes come back.""" rec, res = record(), solved() write_results(tmp_path / "r.h5", rec, res, attrs()) @@ -101,9 +104,11 @@ def test_round_trip(tmp_path): assert not list(tmp_path.glob("*.partial")) -def test_assembly_does_not_depend_on_the_split(tmp_path): - """One file or one per subproblem: the same trial, equal to - assembleResults and processResult of the results.""" +def test_assembly_does_not_depend_on_the_split(tmp_path) -> None: + """One file or one per subproblem: the same trial. + + Equal to assembleResults and processResult of the results. + """ rec, res = record(), solved() p = SolverParams() write_results(tmp_path / "all.h5", rec, res, attrs()) @@ -118,7 +123,7 @@ def test_assembly_does_not_depend_on_the_split(tmp_path): class Place: """What assemble_results reads of a subproblem.""" - def __init__(self, pix, src): + def __init__(self, pix, src) -> None: """Placement only.""" self.pixels, self.sources = pix, src @@ -141,9 +146,12 @@ def __init__(self, pix, src): np.testing.assert_array_equal(got.record.global_f, rec.global_f) -def test_incomplete_or_conflicting_results_raise(tmp_path): - """A missing subproblem, two different results of one, and files of - two containers are errors.""" +def test_incomplete_or_conflicting_results_raise(tmp_path) -> None: + """Incomplete or conflicting results are errors. + + A missing subproblem, two different results of one, and files of two + containers are errors. + """ rec, res = record(), solved() p = SolverParams() write_results(tmp_path / "a.h5", rec, {0: res[0], 1: res[1]}, attrs()) @@ -192,7 +200,7 @@ def test_incomplete_or_conflicting_results_raise(tmp_path): ) -def test_trial_not_extracted(tmp_path): +def test_trial_not_extracted(tmp_path) -> None: """A trial too short to extract has its record and no sources.""" rec = record() write_results(tmp_path / "s.h5", rec, {}, attrs(extracted=0)) @@ -201,13 +209,13 @@ def test_trial_not_extracted(tmp_path): assert out.record.n_frames == N_T -def test_subproblem_results(): +def test_subproblem_results() -> None: """Placements of solved subproblems, with their container indices.""" class Sub: """A subproblem's placement.""" - def __init__(self, k): + def __init__(self, k) -> None: """Pixels and sources of subproblem ``k``.""" self.pixels, self.sources = np.array([k]), np.array([k]) diff --git a/tests/raster/test_raster_seed_acceptance.py b/tests/raster/test_raster_seed_acceptance.py index e8c9bd97..1bb8e5a2 100644 --- a/tests/raster/test_raster_seed_acceptance.py +++ b/tests/raster/test_raster_seed_acceptance.py @@ -1,6 +1,8 @@ -"""Tests of the seed threshold set from the combined image's null -(``seed_acceptance='null'``, GIAnT-Python#51) and the null images that -carry it from the localize stage to the plan stage.""" +"""Tests of the seed threshold set from the combined image's null. + +That is ``seed_acceptance='null'`` (GIAnT-Python#51); also tests of the null +images that carry it from the localize stage to the plan stage. +""" import numpy as np import pytest @@ -32,9 +34,11 @@ def _noise_field(rng, shape=(120, 140), sigma=1.3): return ndimage.gaussian_filter(rng.standard_normal(shape), sigma) -def test_candidate_statistic_is_the_seeding_rule(): - """Maxima whose second-largest neighbour exceeds a threshold are exactly - get_act_im_peaks' candidates.""" +def test_candidate_statistic_is_the_seeding_rule() -> None: + """Maxima whose second-largest neighbour exceeds a threshold are the candidates. + + They are exactly get_act_im_peaks' candidates. + """ rng = np.random.default_rng(0) im = _noise_field(rng) im[:3] = np.nan @@ -53,10 +57,13 @@ def test_candidate_statistic_is_the_seeding_rule(): assert not excl[tuple(rc.T)].any() -def test_null_threshold_gives_the_expected_false_seeds(): - """A threshold set on one null field for 2 false candidates per field - is crossed about twice per field on independent fields of the same - noise; a lax target is read off the null, a strict one extrapolated.""" +def test_null_threshold_gives_the_expected_false_seeds() -> None: + """A null threshold gives about the requested false candidates per field. + + A threshold set on one null field for 2 false candidates per field is + crossed about twice per field on independent fields of the same noise; a + lax target is read off the null, a strict one extrapolated. + """ rng = np.random.default_rng(1) fields = [_noise_field(rng) for _ in range(41)] (mu, sd), th, info = null_threshold(np.stack(fields[:4]), 2.0) @@ -78,9 +85,11 @@ def test_null_threshold_gives_the_expected_false_seeds(): null_threshold(np.zeros((20, 20)), 1.0) -def test_background_override(): - """The image's own median and robust SD as the background reproduce - MATLAB's threshold; a doubled scale with half the threshold too.""" +def test_background_override() -> None: + """The image's own median and robust SD as the background reproduce MATLAB's threshold. + + A doubled scale with half the threshold does too. + """ rng = np.random.default_rng(2) im = _noise_field(rng, (60, 60)) * 0.2 for r, c in ((15, 15), (30, 44), (45, 20)): @@ -100,9 +109,11 @@ def test_background_override(): get_act_im_peaks(im, 5.0, background=(0.0, 0.0)) -def test_seed_sources_with_the_null(): - """acceptance='null' seeds at the null's threshold and reports it; it - needs the null image.""" +def test_seed_sources_with_the_null() -> None: + """acceptance='null' seeds at the null's threshold and reports it. + + It needs the null image. + """ rng = np.random.default_rng(3) im = _noise_field(rng, (80, 80)) g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) @@ -133,9 +144,11 @@ def test_seed_sources_with_the_null(): assert info == {"peak_th": 3.0, "background": None} -def test_combined_null_is_combined_like_the_image(): - """Null images equal to the activity images combine to the combined - activity image (same scale, mask and median subtraction).""" +def test_combined_null_is_combined_like_the_image() -> None: + """Null images equal to the activity images combine to the combined activity image. + + Same scale, mask and median subtraction. + """ rng = np.random.default_rng(4) act = np.stack( [np.abs(_noise_field(rng, (30, 40))) * 50 for _ in range(4)] @@ -163,9 +176,11 @@ def _trials(rng, n=3, shape=(48, 52), null=True): return out -def test_plan_with_null_acceptance(): - """The plan seeds with the trials' null images and reports the - threshold; without null images it refuses.""" +def test_plan_with_null_acceptance() -> None: + """The plan seeds with the trials' null images and reports the threshold. + + Without null images it refuses. + """ rng = np.random.default_rng(5) trials = _trials(rng) det = {} @@ -190,7 +205,7 @@ def test_plan_with_null_acceptance(): PlanParams(seed_false_per_field=0) -def test_null_images_round_trip(tmp_path): +def test_null_images_round_trip(tmp_path) -> None: """Localization files keep the null images when given.""" rng = np.random.default_rng(6) act = rng.random((6, 7)) @@ -217,10 +232,12 @@ def test_null_images_round_trip(tmp_path): assert read_localization(path).null_im is None -def test_silo_params_null_acceptance(): - """The localization keeps null images exactly when the seeding needs - them (unless set); both need the bootstrap null; defaults leave the - stage hashes and MATLAB's fields alone.""" +def test_silo_params_null_acceptance() -> None: + """The localization keeps null images exactly when the seeding needs them (unless set). + + Both need the bootstrap null; defaults leave the stage hashes and MATLAB's + fields alone. + """ default = SiloParams() assert default.seed_acceptance == "image" assert default.localization_keep_null is False @@ -251,10 +268,12 @@ def test_silo_params_null_acceptance(): SiloParams(**bad) -def test_silo_params_evidence_test(): - """The evidence test is off by default with MATLAB's baseline (on with - the network's: min_source_event_rate 2 per minute) and reaches only the - collect stage's settings when on.""" +def test_silo_params_evidence_test() -> None: + """The evidence test is off by default with MATLAB's baseline. + + It is on with the network's (min_source_event_rate 2 per minute) and + reaches only the collect stage's settings when on. + """ default = SiloParams() assert default.min_source_snr == 0 and default.min_source_event_rate == 0 assert "min_source_snr" not in default.stage_settings("collect") @@ -272,9 +291,11 @@ def test_silo_params_evidence_test(): SiloParams(**bad) -def test_seed_heights(): - """A source's seed height: the second-largest 3 x 3 value around its - pixel, in robust SDs above the image's median (NaN left out).""" +def test_seed_heights() -> None: + """A source's seed height: the second-largest 3 x 3 value around its pixel. + + In robust SDs above the image's median (NaN left out). + """ from giant_python.extraction.raster.peaks import _MAD_SCALE from giant_python.extraction.raster.seeding import seed_heights @@ -298,10 +319,12 @@ def test_seed_heights(): assert np.isnan(seed_heights(np.ones((5, 5)), [2], [2])).all() -def test_silo_params_evidence_margin(): - """The evidence test judges sources seeded below peak_th + 2 by - default; the margin enters the collect hash and the params struct only - when the test is on, so MATLAB's settings keep both.""" +def test_silo_params_evidence_margin() -> None: + """The evidence test judges sources seeded below peak_th + 2 by default. + + The margin enters the collect hash and the params struct only when the + test is on, so MATLAB's settings keep both. + """ m = SiloParams() assert m.evidence_margin == 2.0 and not m.evidence_test assert "evidence_margin" not in m.stage_settings("collect") @@ -323,9 +346,11 @@ def test_silo_params_evidence_margin(): assert p.evidence_test and p.evidence_judge_below is None -def test_null_sd_acceptance(): - """acceptance='null_sd' counts peak_th in robust SDs of the null; the - plan and SiloParams accept it with the null images.""" +def test_null_sd_acceptance() -> None: + """acceptance='null_sd' counts peak_th in robust SDs of the null. + + The plan and SiloParams accept it with the null images. + """ rng = np.random.default_rng(7) im = _noise_field(rng, (80, 80)) g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) @@ -357,10 +382,13 @@ def test_null_sd_acceptance(): ) -def test_amplitude_rule_pixel_keeps_sharp_peaks(): - """MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a - sharp peak whose own pixel is well above the threshold; 'pixel' keeps - it, and drops a peak whose own pixel is below.""" +def test_amplitude_rule_pixel_keeps_sharp_peaks() -> None: + """The 'pixel' amplitude rule keeps sharp peaks that MATLAB's test drops. + + MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a sharp + peak whose own pixel is well above the threshold; 'pixel' keeps it, and + drops a peak whose own pixel is below. + """ from giant_python.extraction.raster.peaks import _finish theta = np.array([[0.9, 10.0, 10.0, 0.3], [0.1, 20.0, 20.0, 0.3]]) @@ -378,9 +406,11 @@ def test_amplitude_rule_pixel_keeps_sharp_peaks(): assert "seed_amplitude_rule" not in SiloParams().stage_settings("plan") -def test_null_images_from_localization_and_empty_plans(): - """The in-memory adapter carries the localization's null images; a - plan without valid trials has no seeds in the null modes too.""" +def test_null_images_from_localization_and_empty_plans() -> None: + """The in-memory adapter carries the localization's null images. + + A plan without valid trials has no seeds in the null modes too. + """ from types import SimpleNamespace rng = np.random.default_rng(9) @@ -411,10 +441,12 @@ def test_null_images_from_localization_and_empty_plans(): assert plan.valid_trials.size == 0 and plan.seeds.shape == (0, 4) -def test_trial_null_seeds_are_independent(): - """With kept null images every trial-path draws its own null movies - (distinct seeds, apart by more than a trial's draws); the default - calibration's seed is not used for them.""" +def test_trial_null_seeds_are_independent() -> None: + """With kept null images every trial-path draws its own null movies. + + Distinct seeds, apart by more than a trial's draws; the default + calibration's seed is not used for them. + """ from giant_python.pipeline.silo import trial_null_seed seeds = {trial_null_seed(0, d, t) for d in range(3) for t in range(200)} @@ -424,9 +456,11 @@ def test_trial_null_seeds_are_independent(): assert trial_null_seed(7, 0, 0) == trial_null_seed(0, 0, 0) + 7 -def test_pixel_rule_uses_the_fits_pixel_edges(): - """Beside a gap in the imaged columns the fits' pixel is wider, and the - 'pixel' rule integrates the same wider pixel.""" +def test_pixel_rule_uses_the_fits_pixel_edges() -> None: + """Beside a gap in the imaged columns the fits' pixel is wider. + + The 'pixel' rule integrates the same wider pixel. + """ from giant_python.extraction.raster.peaks import _finish, _pixel_bounds finite = np.ones((20, 20), bool) @@ -443,9 +477,11 @@ def test_pixel_rule_uses_the_fits_pixel_edges(): assert unit.shape[0] == 0 and wide.shape[0] == 1 -def test_trial_null_seeds_leave_room_for_many_draws(): - """With more draws than the default block, blocks widen so that no two - trial-paths share a seed.""" +def test_trial_null_seeds_leave_room_for_many_draws() -> None: + """With more draws than the default block, blocks widen. + + So no two trial-paths share a seed. + """ from giant_python.pipeline.silo import trial_null_seed draws = 2500 diff --git a/tests/raster/test_raster_seeding.py b/tests/raster/test_raster_seeding.py index b2cc3ba5..7afb3a95 100644 --- a/tests/raster/test_raster_seeding.py +++ b/tests/raster/test_raster_seeding.py @@ -16,7 +16,7 @@ FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" -def test_disk_strel_matches_matlab(): +def test_disk_strel_matches_matlab() -> None: """strel('disk', r).Neighborhood of MATLAB R2024b for r = 0 .. 39.""" with h5py.File(FIXTURE, "r") as f: g = f["strel_disk"] @@ -26,9 +26,12 @@ def test_disk_strel_matches_matlab(): ) -def test_disk_strel_shapes(): - """MATLAB's disk is smaller than its radius says: radius 3 is a full - 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's selRadius).""" +def test_disk_strel_shapes() -> None: + """MATLAB's disk is smaller than its radius says. + + Radius 3 is a full 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's + selRadius). + """ assert disk_strel(0).shape == (1, 1) np.testing.assert_array_equal( disk_strel(1), [[0, 1, 0], [1, 1, 1], [0, 1, 0]] @@ -49,10 +52,12 @@ def test_disk_strel_shapes(): disk_strel(5, 5) -def test_sources_from_seeds_rounds_and_prunes(): - """Positions round as MATLAB's (halves up in its one-based - coordinates), the first seed of a pixel wins, order is kept, and - positions are clamped to the image.""" +def test_sources_from_seeds_rounds_and_prunes() -> None: + """Positions round as MATLAB's (halves up in its one-based coordinates). + + The first seed of a pixel wins, order is kept, and positions are clamped + to the image. + """ seeds = np.array( [ [5.0, 3.5, 7.49, 0.4], # MATLAB 4.5, 8.49 -> pixel (5, 8) @@ -70,10 +75,12 @@ def test_sources_from_seeds_rounds_and_prunes(): assert all(x.size == 0 for x in empty) -def test_select_source_pixels(): - """A source's pixels are MATLAB's disk within the image and the valid - pixels, in column-major order; sources that lose their own pixel or - nearly all pixels are pruned.""" +def test_select_source_pixels() -> None: + """A source's pixels are MATLAB's disk within the image and the valid pixels. + + They are in column-major order; sources that lose their own pixel or + nearly all pixels are pruned. + """ valid = np.ones((30, 40), bool) valid[:, 25:] = False valid[12, 10] = False @@ -104,10 +111,12 @@ def test_select_source_pixels(): assert more.pixels[0].size == 6 and more.keep[0] -def test_seed_sources(): - """The default method seeds blobs; the soma mask excludes them; unknown - and unported methods are refused; an image without usable pixels gives - no seeds.""" +def test_seed_sources() -> None: + """The default method seeds blobs; the soma mask excludes them. + + Unknown and unported methods are refused; an image without usable pixels + gives no seeds. + """ rng = np.random.default_rng(0) im = rng.normal(0, 0.3, (40, 50)) rr, cc = np.mgrid[:40, :50] diff --git a/tests/raster/test_raster_silo_alignment.py b/tests/raster/test_raster_silo_alignment.py index c09e0044..67702139 100644 --- a/tests/raster/test_raster_silo_alignment.py +++ b/tests/raster/test_raster_silo_alignment.py @@ -1,6 +1,8 @@ -"""The affine and patchwise across-trial alignments in giant silo's stages: -half images in the localization files, staged and streamed runs, the -plan's maps in the summaries, ROIs and per-trial peaks.""" +"""The affine and patchwise across-trial alignments in giant silo's stages. + +Half images in the localization files, staged and streamed runs, the plan's +maps in the summaries, ROIs and per-trial peaks. +""" from dataclasses import replace @@ -51,14 +53,17 @@ @pytest.fixture -def halves(fake): # noqa: F811 - """The fake session's localization (half images when asked).""" +def halves(fake) -> None: # noqa: F811 + """Provide the fake session's localization (half images when asked).""" + +def test_patchwise_streamed_and_staged_runs_agree(tmp_path, halves) -> None: + """Patchwise alignment: the streaming driver and the stages agree. -def test_patchwise_streamed_and_staged_runs_agree(tmp_path, halves): - """Under patchwise alignment the streaming driver and the stages give - the same results and summaries; the localization files hold the half - images, the plans a patchwise field, the summary its displacements.""" + Under patchwise alignment the streaming driver and the stages give the + same results and summaries; the localization files hold the half images, + the plans a patchwise field, the summary its displacements. + """ table = make_session(tmp_path / "streamed") silo.run_silo(table, PATCHWISE, EX) s1 = SiloSession.open(table) @@ -88,11 +93,13 @@ def test_patchwise_streamed_and_staged_runs_agree(tmp_path, halves): ) -def test_localize_redoes_files_without_halves(tmp_path, halves): - """Files localized for a rigid plan lack the half images: a patchwise - plan refuses them and the patchwise localize stage redoes them. Rigid - and affine runs accept files with and without half images and redo - neither, so existing localizations stay usable.""" +def test_localize_redoes_files_without_halves(tmp_path, halves) -> None: + """Files localized for a rigid plan lack the half images. + + A patchwise plan refuses them and the patchwise localize stage redoes + them. Rigid and affine runs accept files with and without half images and + redo neither, so existing localizations stay usable. + """ s = SiloSession.open(make_session(tmp_path)) rigid = replace(PATCHWISE, inter_trial_alignment="rigid") affine = replace(PATCHWISE, inter_trial_alignment="affine") @@ -116,9 +123,11 @@ def test_localize_redoes_files_without_halves(tmp_path, halves): assert all(r.half_ims is not None for r in silo._plan_inputs(s, 0, True)) -def test_later_stages_refuse_another_alignment(tmp_path, halves): - """Prepare and collect use the plan's maps and record the settings: - another alignment, or another patch size for patchwise, is refused.""" +def test_later_stages_refuse_another_alignment(tmp_path, halves) -> None: + """Prepare and collect use the plan's maps and record the settings. + + Another alignment, or another patch size for patchwise, is refused. + """ s = SiloSession.open(make_session(tmp_path)) silo.localize(s, PATCHWISE, EX) silo.plan(s, PATCHWISE, EX) @@ -139,10 +148,12 @@ def test_later_stages_refuse_another_alignment(tmp_path, halves): @pytest.mark.parametrize("mode", ["affine", "patchwise"]) -def test_plan_with_a_refined_alignment(tmp_path, mode): - """The valid trials get the refined maps (the same valid trials as - rigid); the aligned images are warped through them; the shifts are the - displacements at the canvas centre; the plan file keeps the maps.""" +def test_plan_with_a_refined_alignment(tmp_path, mode) -> None: + """The valid trials get the refined maps (the same valid trials as rigid). + + The aligned images are warped through them; the shifts are the + displacements at the canvas centre; the plan file keeps the maps. + """ trials = _synthetic_trials() for t in trials: t.half_ims = np.stack([t.mean_im, t.mean_im * 1.01]) @@ -185,9 +196,8 @@ def test_plan_with_a_refined_alignment(tmp_path, mode): assert back.params.align_patch_px == 600 -def test_localization_file_keeps_half_images(tmp_path): - """The half images round-trip as float32; files without them read as - None.""" +def test_localization_file_keeps_half_images(tmp_path) -> None: + """The half images round-trip as float32; files without them read as None.""" rng = np.random.default_rng(0) mean = rng.random((5, 6, 2)) halves = rng.random((2, 5, 6, 2)) @@ -213,7 +223,7 @@ def test_localization_file_keeps_half_images(tmp_path): def _bent_warp(n_trials=2, shape=(40, 50)): - """An affine map with a bent field on top, per trial.""" + """Build an affine map with a bent field on top, per trial.""" rng = np.random.default_rng(1) nodes = rng.uniform([5, 5], [shape[0] - 5, shape[1] - 5], (6, 2)) affine = np.zeros((n_trials, 2, 3)) @@ -226,9 +236,12 @@ def _bent_warp(n_trials=2, shape=(40, 50)): return TrialWarp(affine, nodes, 8.0, disp) -def test_rois_through_a_full_map(): - """Masks take the trial mask's value at each consensus pixel's mapped - position; geometry goes through the inverse map (one-based [x, y]).""" +def test_rois_through_a_full_map() -> None: + """ROIs go through a full map. + + Masks take the trial mask's value at each consensus pixel's mapped + position; geometry goes through the inverse map (one-based [x, y]). + """ warp = _bent_warp() mask = np.zeros((40, 50), bool) mask[18:23, 20:26] = True @@ -249,15 +262,14 @@ def test_rois_through_a_full_map(): np.testing.assert_allclose([c[0] + 1, r[0] + 1], center, atol=1e-6) -def test_per_trial_peaks_into_the_consensus_frame(): - """Through the inverse of a non-shift map, minus the shift of a rigid - one.""" +def test_per_trial_peaks_into_the_consensus_frame() -> None: + """Through the inverse of a non-shift map, minus the shift of a rigid one.""" class Plan: """What _peaks_to_consensus reads of a plan.""" - def __init__(self, warp, shifts): - """A warp and its shifts.""" + def __init__(self, warp, shifts) -> None: + """Store a warp and its shifts.""" self.warp, self.shifts = warp, shifts peaks = np.array([[1.0, 10.0, 12.0, 0.5], [2.0, 30.5, 40.25, 0.5]]) diff --git a/tests/raster/test_raster_silo_load_ahead.py b/tests/raster/test_raster_silo_load_ahead.py index e71265df..d8efd9cb 100644 --- a/tests/raster/test_raster_silo_load_ahead.py +++ b/tests/raster/test_raster_silo_load_ahead.py @@ -1,5 +1,7 @@ -"""Loading trials ahead of the solver in the streamed run -(``SiloExecution.load_workers``, ``load_memory_gb``).""" +"""Loading trials ahead of the solver in the streamed run. + +Options ``SiloExecution.load_workers`` and ``load_memory_gb``. +""" import threading import time @@ -32,15 +34,17 @@ def _units(n, lines=100.0): ] -def test_loaded_keeps_order_and_limits(monkeypatch): - """Units come back in order whatever finishes first; at most - ``load_workers`` load at once; with a memory limit only one loads until - a load has measured the bytes per line, then as many as fit.""" +def test_loaded_keeps_order_and_limits(monkeypatch) -> None: + """Units come back in order whatever finishes first. + + At most ``load_workers`` load at once; with a memory limit only one loads + until a load has measured the bytes per line, then as many as fit. + """ active, most, started = [0], [0], [] lock = threading.Lock() def load(u): - """A load that takes longer for earlier units.""" + """Simulate a load that takes longer for earlier units.""" with lock: active[0] += 1 most[0] = max(most[0], active[0]) @@ -67,16 +71,18 @@ def load(u): assert started == [0] -def test_loaded_waits_for_a_measured_load_and_takes_units_lazily(): - """A load without ``nbytes`` (a trial too short to extract) gives no - estimate: with a memory limit the loads stay one at a time until a load - reports its bytes. Units are taken from the iterable only when they are - about to be loaded.""" +def test_loaded_waits_for_a_measured_load_and_takes_units_lazily() -> None: + """A load without ``nbytes`` (a trial too short to extract) gives no estimate. + + With a memory limit the loads stay one at a time until a load reports + its bytes. Units are taken from the iterable only when they are about to + be loaded. + """ active, most, taken = [0], [0], [] lock = threading.Lock() def load(u): - """The first unit is short (no subproblems, no bytes).""" + """Load a unit; the first unit is short (no subproblems, no bytes).""" with lock: active[0] += 1 most[0] = max(most[0], active[0]) @@ -88,7 +94,7 @@ def load(u): return {"nbytes": 1000} def lazy(units): - """The units, noting when each is taken.""" + """Yield the units, noting when each is taken.""" for u in units: taken.append(u.t) yield u @@ -108,9 +114,11 @@ def lazy(units): assert taken == [0] -def test_loaded_hands_on_earlier_units_before_a_failed_check(): - """With several loaders, an error raised while taking a unit (its - check) reaches the caller after the units taken before it.""" +def test_loaded_hands_on_earlier_units_before_a_failed_check() -> None: + """With several loaders, an error raised while taking a unit (its check) is deferred. + + It reaches the caller after the units taken before it. + """ def units(): """Two units, then a failing check.""" @@ -130,11 +138,13 @@ def units(): @pytest.mark.parametrize("load_workers", [1, 3]) def test_streamed_run_checks_later_trials_when_it_reaches_them( tmp_path, fake, monkeypatch, load_workers # noqa: F811 -): - """A later trial whose check fails (here its baseline) does not stop - the earlier trials from being extracted and written, with one loader - or several (the trial waiting for its results is written before the - error is raised).""" +) -> None: + """A later trial whose check fails (here its baseline) does not stop the earlier trials. + + The earlier trials are extracted and written, with one loader or several + (the trial waiting for its results is written before the error is + raised). + """ s = make_session(tmp_path / "s") real = silo._extraction_baseline calls = [] @@ -158,9 +168,11 @@ def failing(session, params, d, t, baseline_dir): assert written == list(range(session.n_trials - 1)) -def test_loaded_passes_on_errors(): - """A load's error reaches the caller at its unit; later loads are not - waited for beyond the running ones.""" +def test_loaded_passes_on_errors() -> None: + """A load's error reaches the caller at its unit. + + Later loads are not waited for beyond the running ones. + """ def load(u): """Fails on the second unit.""" @@ -174,9 +186,12 @@ def load(u): next(gen) -def test_options_are_checked(): - """Worker counts are positive integers, the limit positive; the loader - options come after the earlier fields, which keep their positions.""" +def test_options_are_checked() -> None: + """Worker counts are positive integers, the limit positive. + + The loader options come after the earlier fields, which keep their + positions. + """ with pytest.raises(ValueError): SiloExecution(load_workers=0) with pytest.raises(ValueError): @@ -191,9 +206,8 @@ def test_options_are_checked(): @pytest.mark.parametrize("memory", [None, 1e-9]) def test_streamed_run_loading_ahead_is_the_same( tmp_path, fake, memory # noqa: F811 -): - """Loading three trials ahead gives the results files and summaries of - loading one at a time.""" +) -> None: + """Loading three trials ahead gives the results files and summaries of loading one at a time.""" one = make_session(tmp_path / "one") r1 = silo.run_silo(one, PARAMS, replace(EX, load_workers=1)) ahead = make_session(tmp_path / "ahead") @@ -201,7 +215,7 @@ def test_streamed_run_loading_ahead_is_the_same( r2 = silo.run_silo(ahead, PARAMS, ex) def loaded(report): - """The units the run loaded.""" + """Return the units the run loaded.""" return [tuple(e["unit"]) for e in report["trials"] if "load" in e] assert loaded(r1) == loaded(r2) and loaded(r1) @@ -219,10 +233,12 @@ def loaded(report): ) -def test_held_bytes_count_what_a_loaded_trial_keeps(): - """The memory of a loaded trial waiting for the solver: its - subproblems' data, variance multipliers and baselines, and its - traces.""" +def test_held_bytes_count_what_a_loaded_trial_keeps() -> None: + """The memory of a loaded trial waiting for the solver. + + That is its subproblems' data, variance multipliers and baselines, and + its traces. + """ from types import SimpleNamespace y = np.zeros((2, 10, 50), np.float32) diff --git a/tests/raster/test_raster_silo_network.py b/tests/raster/test_raster_silo_network.py index 7608e4cb..fbb53e4d 100644 --- a/tests/raster/test_raster_silo_network.py +++ b/tests/raster/test_raster_silo_network.py @@ -13,6 +13,7 @@ import subprocess from dataclasses import asdict, replace from pathlib import Path +from typing import NoReturn import h5py import numpy as np @@ -61,7 +62,7 @@ @pytest.fixture -def fake(monkeypatch): +def fake(monkeypatch) -> None: """Synthetic localization and loading (as in the stages' tests).""" monkeypatch.setattr(trial_mod, "localize_trial", stages.fake_localize) monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) @@ -73,8 +74,10 @@ def fake(monkeypatch): def _baseline_stack(d, t, n_frames, level=50.0): - """A smooth baseline in movie counts, (frames, rows, cols), with a - corner without values (NaN, as outside the valid pixels).""" + """Build a smooth baseline in movie counts, (frames, rows, cols). + + It has a corner without values (NaN, as outside the valid pixels). + """ r, c = np.mgrid[:H, :W] img = level * (1 + 0.2 * np.sin(r / 5.0 + d) * np.cos(c / 7.0 + t)) ramp = 1 + 0.05 * np.linspace(-1, 1, n_frames) @@ -84,8 +87,10 @@ def _baseline_stack(d, t, n_frames, level=50.0): def write_baselines(root: Path, folder: Path, level=50.0) -> Path: - """Baseline files of every trial-path, laid out as slap2-f0 writes - them: ``/baseline`` (frame, col, row) float16, with its attributes.""" + """Write baseline files of every trial-path, laid out as slap2-f0 writes them. + + ``/baseline`` (frame, col, row) float16, with its attributes. + """ folder.mkdir(parents=True, exist_ok=True) moco = root / "motion_correction" for d in range(N_PATHS): @@ -104,9 +109,11 @@ def write_baselines(root: Path, folder: Path, level=50.0) -> Path: return folder -def test_params_baseline_source(): - """'network' sets the localization settings and N1; each can still be - set; MATLAB's algorithm keeps its settings, hashes and params struct.""" +def test_params_baseline_source() -> None: + """'network' sets the localization settings and N1; each can still be set. + + MATLAB's algorithm keeps its settings, hashes and params struct. + """ m = SiloParams() assert (m.peak_th, m.localization_baseline, m.baseline_mode) == ( 3.0, @@ -152,9 +159,12 @@ def test_params_baseline_source(): SiloParams(baseline_mode="guess") -def test_trial_baseline_is_map_baseline(tmp_path): - """The pipeline's two steps (space and units at the registration's - frames, then time and the fallback) give map_baseline's values.""" +def test_trial_baseline_is_map_baseline(tmp_path) -> None: + """The pipeline's two steps give map_baseline's values. + + The two steps: space and units at the registration's frames, then time + and the fallback. + """ rng = np.random.default_rng(3) n_t, n_r, n_c = 9, 20, 16 stack = (40 + 10 * rng.random((n_t, n_r, n_c))).astype(np.float32) @@ -192,9 +202,11 @@ def test_trial_baseline_is_map_baseline(tmp_path): ) -def test_container_holds_the_baseline(tmp_path): - """A container stores the baseline at the registration's frames; its - subproblems get it for a mode that uses it, from memory or the file.""" +def test_container_holds_the_baseline(tmp_path) -> None: + """A container stores the baseline at the registration's frames. + + Its subproblems get it for a mode that uses it, from memory or the file. + """ trial = fake_load( "x_DMD1-TRIAL000001.dat", 1, @@ -254,10 +266,13 @@ def test_container_holds_the_baseline(tmp_path): read_container(bare).subproblem(0, sp) -def test_network_streamed_and_staged_runs_agree(tmp_path, fake): - """With the network's baseline (N1), the streamed run, one job and - three jobs give the same results and summaries; the summaries record - the baseline; the baseline changes the results.""" +def test_network_streamed_and_staged_runs_agree(tmp_path, fake) -> None: + """With the network's baseline (N1), streamed and staged runs agree. + + The streamed run, one job and three jobs give the same results and + summaries; the summaries record the baseline; the baseline changes the + results. + """ root = tmp_path / "streamed" table = make_session(root) bdir = write_baselines(root, tmp_path / "baselines") @@ -310,9 +325,11 @@ def test_network_streamed_and_staged_runs_agree(tmp_path, fake): assert "baseline_source" not in f.attrs # as MATLAB writes it -def test_baseline_file_change_redoes_its_containers(tmp_path, fake): - """The settings hash of a container covers its baseline file; MATLAB's - algorithm keeps the hash it had before the network was wired in.""" +def test_baseline_file_change_redoes_its_containers(tmp_path, fake) -> None: + """The settings hash of a container covers its baseline file. + + MATLAB's algorithm keeps the hash it had before the network was wired in. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines( @@ -356,7 +373,7 @@ def test_baseline_file_change_redoes_its_containers(tmp_path, fake): assert silo._prepare_hash(s, NET, ph, 0, 0, f) != old -def test_stages_refuse_another_baseline(tmp_path, fake): +def test_stages_refuse_another_baseline(tmp_path, fake) -> None: """Each stage checks that the stage before it used the same baseline.""" root = tmp_path / "s" s = SiloSession.open(make_session(root)) @@ -386,13 +403,15 @@ def test_stages_refuse_another_baseline(tmp_path, fake): def _args(*argv): - """Parsed arguments of a ``giant`` command line.""" + """Parse the arguments of a ``giant`` command line.""" return build_parser().parse_args(list(argv)) -def test_cli_baseline_default(): - """--baseline-dir or --f0-ckpt make the network the default; --baseline - chooses; otherwise MATLAB's moving median.""" +def test_cli_baseline_default() -> None: + """--baseline-dir or --f0-ckpt make the network the default. + + --baseline chooses; otherwise MATLAB's moving median. + """ p = params_from_args(_args("silo", "t.h5")) assert p.baseline_source == "median" and p.peak_th == 3.0 p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b")) @@ -438,15 +457,17 @@ def test_cli_baseline_default(): assert a.f0_device == "cpu" and a.f0_command is None -def test_run_silo_default_source(tmp_path, fake, monkeypatch): - """run_silo: a dict or no params take the network with its baselines; - a SiloParams is used as it is (with a warning that they are unused).""" +def test_run_silo_default_source(tmp_path, fake, monkeypatch) -> None: + """run_silo: a dict or no params take the network with its baselines. + + A SiloParams is used as it is (with a warning that they are unused). + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") seen = [] - def stop(session, params, *args, **kw): + def stop(session, params, *args, **kw) -> NoReturn: """Record the params and stop the run.""" seen.append(params) raise RuntimeError("stop") @@ -463,9 +484,12 @@ def stop(session, params, *args, **kw): assert silo.default_baseline_source(None, False) is None -def test_predict_baselines(tmp_path, monkeypatch): - """--f0-ckpt runs slap2-f0 predict-registered once, for the trial-paths - without a baseline file, with the run's trial preparation settings.""" +def test_predict_baselines(tmp_path, monkeypatch) -> None: + """--f0-ckpt runs slap2-f0 predict-registered once. + + It runs for the trial-paths without a baseline file, with the run's trial + preparation settings. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = tmp_path / "b" @@ -613,10 +637,12 @@ def fail_after_one(args, **kw): silo_baseline.predict_baselines(s, params, bdir, tmp_path / "x.pt") -def test_source_alone_redoes_plan_and_containers(tmp_path, fake): - """baseline_source enters the plan and prepare hashes (when it is not - MATLAB's): changing it alone redoes those stages rather than reusing - files that the next stage would refuse.""" +def test_source_alone_redoes_plan_and_containers(tmp_path, fake) -> None: + """baseline_source enters the plan and prepare hashes (when it is not MATLAB's). + + Changing it alone redoes those stages rather than reusing files that the + next stage would refuse. + """ alt = SiloParams( baseline_source="median", localization_baseline="network", @@ -646,12 +672,15 @@ def test_source_alone_redoes_plan_and_containers(tmp_path, fake): silo.prepare(s, NET, EX, baseline_dir=bdir) -def test_earlier_network_defaults_are_localized_again(tmp_path, fake): - """Files made with the network's defaults before 2026-11-28 (peak_th 8, - no evidence test) are localized again with the current ones (peak_th - is also the per-trial peaks' threshold, and every later stage checks - the hash of the one before), so a run never mixes the two; the earlier - defaults given as options keep the files.""" +def test_earlier_network_defaults_are_localized_again(tmp_path, fake) -> None: + """Files made with the network's defaults before 2026-11-28 are localized again. + + Files made with those defaults (peak_th 8, no evidence test) are + localized again with the current ones (peak_th is also the per-trial + peaks' threshold, and every later stage checks the hash of the one + before), so a run never mixes the two; the earlier defaults given as + options keep the files. + """ old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) s = SiloSession.open(make_session(tmp_path / "s")) bdir = write_baselines(tmp_path / "s", tmp_path / "b") @@ -663,11 +692,14 @@ def test_earlier_network_defaults_are_localized_again(tmp_path, fake): assert old.stage_settings("solve") == NET.stage_settings("solve") -def test_collect_refuses_another_seed_threshold(tmp_path, fake): - """A standalone collect of a folder seeded with the network's earlier +def test_collect_refuses_another_seed_threshold(tmp_path, fake) -> None: + """Refuse a collect of a folder seeded with another peak_th. + + A standalone collect of a folder seeded with the network's earlier default (peak_th 8) is refused under today's (3), which would record peakth 3 and judge the sources' evidence against it; the earlier - settings collect it.""" + settings collect it. + """ old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) s = SiloSession.open(make_session(tmp_path / "s")) bdir = write_baselines(tmp_path / "s", tmp_path / "b") @@ -684,11 +716,12 @@ def test_collect_refuses_another_seed_threshold(tmp_path, fake): assert float(np.ravel(f["params/peakth"][()])[0]) == 8.0 -def test_collect_refuses_another_seed_acceptance(tmp_path, fake): - """A standalone collect of a plan seeded with the null threshold is - refused under the image threshold (whose evidence test would exempt - strong seeds that the null mode judges); its own settings collect - it.""" +def test_collect_refuses_another_seed_acceptance(tmp_path, fake) -> None: + """A standalone collect of a plan seeded with the null threshold is refused. + + It is refused under the image threshold (whose evidence test would exempt + strong seeds that the null mode judges); its own settings collect it. + """ null = replace(NET, seed_acceptance="null_sd", localization_keep_null=True) assert null.evidence_judge_below is None s = SiloSession.open(make_session(tmp_path / "s")) @@ -703,10 +736,13 @@ def test_collect_refuses_another_seed_acceptance(tmp_path, fake): assert silo_collect.collect(s, null, EX, baseline_dir=bdir) is not None -def test_unrecorded_network_localization_is_redone(tmp_path, fake): - """A localization file without the record of its baseline (made before - it was recorded) counts as the moving median's: with the network's - settings it is localized again, with MATLAB's it is kept.""" +def test_unrecorded_network_localization_is_redone(tmp_path, fake) -> None: + """A localization file without the record of its baseline counts as the median's. + + Such a file (made before the baseline was recorded) counts as the moving + median's: with the network's settings it is localized again, with MATLAB's + it is kept. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -723,9 +759,11 @@ def test_unrecorded_network_localization_is_redone(tmp_path, fake): assert silo.localize_jobs(m, MEDIAN) == [] -def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake): - """The summary's network_baseline comes from the results files that - are assembled, not from earlier runs' files left in the folder.""" +def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake) -> None: + """The summary's network_baseline comes from the results files that are assembled. + + It does not come from earlier runs' files left in the folder. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -750,9 +788,11 @@ def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake): assert json.loads(f.attrs["network_baseline"])[stem] == used -def test_baseline_from_another_movie_is_refused(tmp_path, fake): - """A baseline file predicted from another movie than SILo reads (its - 'source') is refused.""" +def test_baseline_from_another_movie_is_refused(tmp_path, fake) -> None: + """A baseline file predicted from another movie than SILo reads is refused. + + The movie it was predicted from is its 'source'. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -762,10 +802,12 @@ def test_baseline_from_another_movie_is_refused(tmp_path, fake): silo.localize(s, NET, EX, baseline_dir=bdir) -def test_collect_checks_baselines_without_movies(tmp_path, fake): - """A collect machine without the registered movies still checks the - results against the baseline files (named after the trial table's - movies): a replaced baseline leaves the results stale.""" +def test_collect_checks_baselines_without_movies(tmp_path, fake) -> None: + """A collect machine without the registered movies still checks the baselines. + + It checks the results against the baseline files (named after the trial + table's movies): a replaced baseline leaves the results stale. + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") @@ -784,9 +826,11 @@ def test_collect_checks_baselines_without_movies(tmp_path, fake): silo_collect.collect(s, NET, EX, baseline_dir=bdir) -def test_localize_predicts_for_extraction_too(tmp_path, fake, monkeypatch): - """silo-localize --f0-ckpt predicts whenever a stage uses the network's - baselines, also when localization alone uses the moving median.""" +def test_localize_predicts_for_extraction_too(tmp_path, fake, monkeypatch) -> None: + """silo-localize --f0-ckpt predicts whenever a stage uses the network's baselines. + + It also predicts when localization alone uses the moving median. + """ table = make_session(tmp_path / "s") calls = [] monkeypatch.setattr( @@ -802,9 +846,11 @@ def test_localize_predicts_for_extraction_too(tmp_path, fake, monkeypatch): assert len(calls) == 1 -def test_extraction_uses_the_localization_baseline(tmp_path, fake): - """Extraction refuses another baseline file than the trial was - localized with (stages given different folders).""" +def test_extraction_uses_the_localization_baseline(tmp_path, fake) -> None: + """Extraction refuses another baseline file than the trial was localized with. + + Here the stages are given different folders. + """ import shutil root = tmp_path / "s" @@ -820,7 +866,7 @@ def test_extraction_uses_the_localization_baseline(tmp_path, fake): assert len(silo.prepare(s, NET, EX, baseline_dir=a)) == 6 -def test_predict_units_may_be_a_generator(tmp_path, monkeypatch): +def test_predict_units_may_be_a_generator(tmp_path, monkeypatch) -> None: """The trial-paths to predict may be given as a generator.""" root = tmp_path / "s" s = SiloSession.open(make_session(root)) @@ -855,9 +901,12 @@ def fake_run(args, **kw): assert _args("silo", "t.h5", "--f0-out-frames", "256").f0_out_frames == 256 -def test_summary_records_the_localization_baseline(tmp_path, fake): - """Localized with the network's baseline and extracted with MATLAB's - fit: the summary records the baseline that decided the seeds.""" +def test_summary_records_the_localization_baseline(tmp_path, fake) -> None: + """The summary records the baseline that decided the seeds. + + Here the trials are localized with the network's baseline and extracted + with MATLAB's fit. + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") @@ -876,10 +925,13 @@ def test_summary_records_the_localization_baseline(tmp_path, fake): assert first["network"] == {"checkpoint": "ckpt/s6_test.pt", "step": 1700} -def test_localized_again_after_the_plan(tmp_path, fake): - """Trials localized again (here with other baseline files) after their - plan was made: prepare and collect refuse the stale plan and results - instead of reading the new localization's peaks and baselines.""" +def test_localized_again_after_the_plan(tmp_path, fake) -> None: + """Prepare and collect refuse a plan made before the trials were localized again. + + Trials localized again (here with other baseline files) after their plan + was made: prepare and collect refuse the stale plan and results instead + of reading the new localization's peaks and baselines. + """ import shutil root = tmp_path / "s" @@ -902,11 +954,13 @@ def test_localized_again_after_the_plan(tmp_path, fake): assert len(silo.prepare(s, NET, EX, baseline_dir=b)) == 6 -def test_one_baseline_mode_per_run(tmp_path, fake): - """Containers prepared with the network's baseline are not solved with - MATLAB's fit (their hash covers a baseline the fit does not use, so - collect would take the results for stale); results name the baseline - only when the solver used it.""" +def test_one_baseline_mode_per_run(tmp_path, fake) -> None: + """Containers prepared with the network's baseline are not solved with MATLAB's fit. + + Their hash covers a baseline the fit does not use, so collect would take + the results for stale; results name the baseline only when the solver + used it. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -934,9 +988,12 @@ def test_one_baseline_mode_per_run(tmp_path, fake): assert "network_baseline" not in attrs -def test_collect_checks_the_localization_baseline(tmp_path, fake): - """collect refuses settings whose localization baseline is not the one - the trials were localized with (the summary would mislabel them).""" +def test_collect_checks_the_localization_baseline(tmp_path, fake) -> None: + """Collect refuses settings with another localization baseline than the trials'. + + It refuses settings whose localization baseline is not the one the trials + were localized with (the summary would mislabel them). + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") @@ -955,9 +1012,12 @@ def test_collect_checks_the_localization_baseline(tmp_path, fake): silo_collect.collect(s, median_loc, EX, baseline_dir=bdir) -def test_one_checkpoint_per_run(tmp_path, monkeypatch): - """Baselines kept from an earlier prediction must have been made with - the given checkpoint (its SHA-256, not only its name).""" +def test_one_checkpoint_per_run(tmp_path, monkeypatch) -> None: + """Baselines kept from an earlier prediction must match the given checkpoint. + + They must have been made with the given checkpoint (its SHA-256, not only + its name). + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -988,8 +1048,11 @@ def fake_run(args, **kw): def _copy_tree(src: Path, dest: Path) -> Path: - """A copy whose files have new modification times (as a data asset's - files carry their upload times).""" + """Copy a tree, giving its files new modification times. + + The copies have new modification times as a data asset's files carry + their upload times. + """ import shutil shutil.copytree(src, dest, copy_function=shutil.copyfile) @@ -1000,11 +1063,13 @@ def _copy_tree(src: Path, dest: Path) -> Path: return dest -def test_records_with_digests_identify_copied_files(tmp_path, monkeypatch): - """Records written with digests=True still identify the baseline, - movie and alignment files after they are copied elsewhere (another - modification time), and refuse a copy whose content changed; records - without digests refuse any copy, as before.""" +def test_records_with_digests_identify_copied_files(tmp_path, monkeypatch) -> None: + """Records written with digests=True still identify copied files. + + They identify the baseline, movie and alignment files after they are + copied elsewhere (another modification time), and refuse a copy whose + content changed; records without digests refuse any copy, as before. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) for d in range(N_PATHS): # movies with content, so that digests differ diff --git a/tests/raster/test_raster_silo_noise_seeds.py b/tests/raster/test_raster_silo_noise_seeds.py index d96ea0f8..819f7492 100644 --- a/tests/raster/test_raster_silo_noise_seeds.py +++ b/tests/raster/test_raster_silo_noise_seeds.py @@ -12,14 +12,20 @@ from giant_python.pipeline.silo_session import SiloSession # the fixture is used by name -from .test_raster_silo_stages import fake # noqa: F401 -from .test_raster_silo_stages import EX, PARAMS, make_session +from .test_raster_silo_stages import ( + EX, + PARAMS, + fake, # noqa: F401 + make_session, +) @pytest.mark.filterwarnings("ignore::RuntimeWarning") -def test_own_seeding_in_noise_completes(tmp_path, fake): # noqa: F811 - """Without a seeds file the session seeds itself; the run finishes and - writes its summaries.""" +def test_own_seeding_in_noise_completes(tmp_path, fake) -> None: # noqa: F811 + """Without a seeds file the session seeds itself. + + The run finishes and writes its summaries. + """ table = make_session(tmp_path / "own") report = silo.run_silo(table, PARAMS, EX) s = SiloSession.open(table) diff --git a/tests/raster/test_raster_silo_params.py b/tests/raster/test_raster_silo_params.py index 1b4a4c5e..a5ddf8a5 100644 --- a/tests/raster/test_raster_silo_params.py +++ b/tests/raster/test_raster_silo_params.py @@ -123,7 +123,7 @@ } -def test_defaults_are_matlabs_slap2_silo(): +def test_defaults_are_matlabs_slap2_silo() -> None: """The derived stage parameters keep each stage's MATLAB defaults.""" p = SiloParams() assert p.plan_params() == PlanParams() @@ -139,7 +139,7 @@ def test_defaults_are_matlabs_slap2_silo(): assert p.sel_radius == 6 -def test_footprint_default_is_the_solvers(monkeypatch): +def test_footprint_default_is_the_solvers(monkeypatch) -> None: """The footprint fit's default comes from the solver, not from here.""" from dataclasses import fields @@ -161,7 +161,7 @@ def test_footprint_default_is_the_solvers(monkeypatch): ) -def test_one_setting_reaches_every_stage(): +def test_one_setting_reaches_every_stage() -> None: """A shared setting is passed to each stage that uses it.""" p = SiloParams(sigma_px=1.5, nan_thresh=0.2, peak_th=4.0) assert p.plan_params().sigma_px == 1.5 @@ -182,9 +182,8 @@ def test_one_setting_reaches_every_stage(): assert net.localization_params(80).variance_floor is False -def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path): - """Written as saveStructToH5 would, the struct of MATLAB's algorithm - has MATLAB's schema.""" +def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path) -> None: + """Written as saveStructToH5 would, the struct of MATLAB's algorithm has MATLAB's schema.""" m = SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0, 12, "a", "b") assert set(m) == set(MATLAB_FIELDS) path = tmp_path / "p.h5" @@ -211,10 +210,12 @@ def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path): np.testing.assert_array_equal(m["Bfilter"][:, :, 2], sp.bfilter[2]) -def test_python_only_settings_are_recorded_when_not_matlabs(): - """MATLAB's algorithm has MATLAB's fields only; other settings add one - each, the defaults (fixed-variance footprint fit, local seed fit with - merging, F0 images) too.""" +def test_python_only_settings_are_recorded_when_not_matlabs() -> None: + """MATLAB's algorithm has MATLAB's fields only. + + Other settings add one each, the defaults (fixed-variance footprint fit, + local seed fit with merging, F0 images) too. + """ assert set(SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0)) == set( MATLAB_FIELDS ) @@ -275,23 +276,25 @@ def test_python_only_settings_are_recorded_when_not_matlabs(): {"valid_kernel": True}, ], ) -def test_invalid_values_are_rejected(kwargs): +def test_invalid_values_are_rejected(kwargs) -> None: """Values no stage can run with raise ValueError.""" with pytest.raises(ValueError): SiloParams(**kwargs) -def test_modes_not_ported_raise(): +def test_modes_not_ported_raise() -> None: """WMF seeding is not ported yet.""" with pytest.raises(NotImplementedError): SiloParams(peak_method="wmf") -def test_alignment_modes(): - """The three across-trial alignments are accepted and reach the plan - stage; others are rejected. The patch size counts in the plan's - settings only when it is not the default (plans made before it was a - field stay current).""" +def test_alignment_modes() -> None: + """The three across-trial alignments are accepted and reach the plan stage. + + Others are rejected. The patch size counts in the plan's settings only + when it is not the default (plans made before it was a field stay + current). + """ for mode in ("rigid", "affine", "patchwise"): p = SiloParams(inter_trial_alignment=mode, align_patch_px=1200) assert p.plan_params().inter_trial_alignment == mode @@ -310,7 +313,7 @@ def test_alignment_modes(): ).stage_settings("localize") -def test_stage_settings_change_only_with_their_fields(): +def test_stage_settings_change_only_with_their_fields() -> None: """A solver setting changes the solve stage's settings only.""" a, b = SiloParams(), SiloParams(lam=0.5) for stage in ("localize", "plan", "prepare", "collect"): @@ -323,12 +326,14 @@ def test_stage_settings_change_only_with_their_fields(): a.stage_settings("other") -def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes(): - """The seed fit's defaults (local fits, merging within 1.5 px) are the - plan stage's; they reach the plan and the per-trial peaks' stage and - are in those stages' settings, so outputs made with MATLAB's fit (the - behaviour before the options existed) are not current. Asking for - MATLAB's fit leaves those stages' settings as they were then.""" +def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes() -> None: + """The seed fit's defaults (local fits, merging within 1.5 px) are the plan stage's. + + They reach the plan and the per-trial peaks' stage and are in those + stages' settings, so outputs made with MATLAB's fit (the behaviour before + the options existed) are not current. Asking for MATLAB's fit leaves those + stages' settings as they were then. + """ a = SiloParams() assert ( (a.seed_fit, a.seed_merge_px) @@ -355,13 +360,15 @@ def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes(): assert "seedFit" not in matlab.to_matlab(2, 80.0) -def test_valid_kernel_is_one_setting_for_plan_and_solver(): - """The footprint support reaches the plan's zones and the solver - together (default 5 x 5, one default for the three types); 3 (MATLAB's) +def test_valid_kernel_is_one_setting_for_plan_and_solver() -> None: + """The footprint support reaches the plan's zones and the solver together. + + The default is 5 x 5, one default for the three types; 3 (MATLAB's) leaves every stage's settings as before the setting existed, so outputs made then stay current with it; another value changes the plan's and the solve's only; the saved params struct records validKernel at its - size.""" + size. + """ a, b = SiloParams(valid_kernel=3), SiloParams() assert b.valid_kernel == PlanParams.valid_kernel == 5 assert b.valid_kernel == SolverParams.valid_kernel @@ -384,7 +391,7 @@ def test_valid_kernel_is_one_setting_for_plan_and_solver(): np.testing.assert_array_equal(mb["validKernel"], np.ones((5, 5), bool)) -def test_execution_options(): +def test_execution_options() -> None: """Execution options validate and give the solver's options.""" e = SiloExecution(device="cuda", dtype="float32", batch_bytes=1e8) assert e.solver_options() == SolverOptions( @@ -411,7 +418,7 @@ def test_execution_options(): def _trial(sel, n_frames=30, seed=0): - """A trial with random data at the selected pixels of ``sel``.""" + """Build a trial with random data at the selected pixels of ``sel``.""" rng = np.random.default_rng(seed) cols, rows = np.nonzero(sel.T) rc = np.stack([rows, cols], 1) @@ -431,7 +438,7 @@ def _trial(sel, n_frames=30, seed=0): ) -def test_plan_groups_container_and_solver_share_one_type(tmp_path): +def test_plan_groups_container_and_solver_share_one_type(tmp_path) -> None: """A plan group's subproblem equals the container's: the solver's type.""" shape = (20, 24) rows, cols = np.array([5, 6, 14]), np.array([5, 8, 17]) @@ -464,9 +471,12 @@ def test_plan_groups_container_and_solver_share_one_type(tmp_path): assert (got.row0, got.col0) == (sub.row0, sub.col0) -def test_loader_warp(): - """A shift reaches the loader as a RigidShift, an affine map as a - function of zero-based coordinates; an unaligned trial raises.""" +def test_loader_warp() -> None: + """A shift reaches the loader as a RigidShift. + + An affine map reaches it as a function of zero-based coordinates; an + unaligned trial raises. + """ warp = TrialWarp.from_shifts(np.array([[1.5, -2.0], [np.nan, np.nan]])) w = loader_warp(warp, 0) assert w == RigidShift(1.5, -2.0) diff --git a/tests/raster/test_raster_silo_stages.py b/tests/raster/test_raster_silo_stages.py index 8f983363..279b501e 100644 --- a/tests/raster/test_raster_silo_stages.py +++ b/tests/raster/test_raster_silo_stages.py @@ -90,7 +90,7 @@ def fake_load( device="cpu", dtype=np.float32, ): - """A trial at the selected pixels: baseline plus sources with events.""" + """Make a trial at the selected pixels: baseline plus sources with events.""" name = Path(dat_path).name t = int(name.split("TRIAL")[1][:6]) - 1 d = int(name.split("DMD")[1][0]) - 1 @@ -175,7 +175,7 @@ def make_session(root: Path) -> Path: @pytest.fixture -def fake(monkeypatch): +def fake(monkeypatch) -> None: """Synthetic localization and loading, in this process.""" monkeypatch.setattr(trial_mod, "localize_trial", fake_localize) monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) @@ -186,8 +186,10 @@ def fake(monkeypatch): def seeds_file(root: Path) -> Path: - """The sources as seeds of both paths (zero-based); the plan's own - seeding is tested with the plan stage.""" + """Write the sources as seeds of both paths (zero-based). + + The plan's own seeding is tested with the plan stage. + """ from giant_python.extraction.raster.stage_files import write_seeds seeds = np.column_stack( @@ -199,14 +201,14 @@ def seeds_file(root: Path) -> Path: def _seeds(session, root): - """The seeds of :func:`seeds_file` per path.""" + """Read the seeds of :func:`seeds_file` per path.""" from giant_python.extraction.raster.stage_files import read_seeds return read_seeds(seeds_file(root), session.n_paths) def _data(path): - """The solved arrays of a results file, by subproblem.""" + """Read the solved arrays of a results file, by subproblem.""" r = read_results(path) return { k: { @@ -228,13 +230,13 @@ def _all_results(session): def _summary(path): - """A summary file's datasets (params' times left out).""" + """Read a summary file's datasets (params' times left out).""" s = load_struct_h5(path) s.pop("params", None) return s -def _equal(a, b): +def _equal(a, b) -> None: """Nested dicts of arrays are equal (NaN equal).""" assert a.keys() == b.keys() for k in a: @@ -244,9 +246,11 @@ def _equal(a, b): np.testing.assert_array_equal(a[k], b[k]) -def test_streamed_and_staged_runs_agree(tmp_path, fake): - """The streaming driver, one job and three jobs give the same results - and summaries; reruns keep finished units.""" +def test_streamed_and_staged_runs_agree(tmp_path, fake) -> None: + """The streaming driver, one job and three jobs give the same results and summaries. + + Reruns keep finished units. + """ table = make_session(tmp_path / "streamed") seeds = seeds_file(tmp_path) report = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) @@ -325,10 +329,13 @@ def test_streamed_and_staged_runs_agree(tmp_path, fake): assert many, "three jobs split a container into ranges" -def test_valid_kernel_through_the_run(tmp_path, fake): - """One footprint support for the whole run: streamed and staged runs - at 5 agree, differ from 3, and record it; a changed support redoes the - plan; the stages after the plan refuse files made with another one.""" +def test_valid_kernel_through_the_run(tmp_path, fake) -> None: + """One footprint support for the whole run. + + Streamed and staged runs at 5 agree, differ from 3, and record it; a + changed support redoes the plan; the stages after the plan refuse files + made with another one. + """ import json from dataclasses import replace @@ -384,7 +391,7 @@ def test_valid_kernel_through_the_run(tmp_path, fake): ) -def test_settings_change_redoes_units(tmp_path, fake): +def test_settings_change_redoes_units(tmp_path, fake) -> None: """A changed solver setting redoes the solve stage only.""" s = SiloSession.open(make_session(tmp_path)) silo.localize(s, PARAMS, EX) @@ -401,10 +408,12 @@ def test_settings_change_redoes_units(tmp_path, fake): assert all(v is not None for v in done.values()) -def test_inputs_and_stale_results(tmp_path, fake, monkeypatch): - """A changed raw file redoes prepare; collect uses only results of the - current plan and solve settings; a trial found without data loses its - earlier container and results.""" +def test_inputs_and_stale_results(tmp_path, fake, monkeypatch) -> None: + """A changed raw file redoes prepare. + + Collect uses only results of the current plan and solve settings; a trial + found without data loses its earlier container and results. + """ import os from giant_python.pipeline.silo_session import NO_DATA @@ -462,9 +471,11 @@ def no_data(dat_path, *args, **kw): silo_collect.collect(s, other, EX) -def test_collect_and_dispatch_without_raw_data(tmp_path, fake): - """Dispatch and collect need neither the raw data nor the movies; a - short trial is one item of no work.""" +def test_collect_and_dispatch_without_raw_data(tmp_path, fake) -> None: + """Dispatch and collect need neither the raw data nor the movies. + + A short trial is one item of no work. + """ import json import shutil @@ -495,9 +506,11 @@ def test_collect_and_dispatch_without_raw_data(tmp_path, fake): assert frames.tolist() == [FRAMES[0], FRAMES[1], FRAMES[2]] -def test_localize_fits_missing_peaks(tmp_path, fake): - """Localization files without their peaks (a streaming run stopped - before its background fits) get them from silo-localize.""" +def test_localize_fits_missing_peaks(tmp_path, fake) -> None: + """Localization files without their peaks get them from silo-localize. + + Such files come from a streaming run stopped before its background fits. + """ from giant_python.extraction.raster.stage_files import localization_attrs s = SiloSession.open(make_session(tmp_path)) @@ -512,7 +525,7 @@ def test_localize_fits_missing_peaks(tmp_path, fake): assert silo.localize(s, PARAMS, EX) == [] -def test_job_needs_its_container(tmp_path, fake): +def test_job_needs_its_container(tmp_path, fake) -> None: """A job refuses a container other than the one it was made for.""" s = SiloSession.open(make_session(tmp_path)) silo.localize(s, PARAMS, EX) @@ -525,10 +538,12 @@ def test_job_needs_its_container(tmp_path, fake): silo_solve.solve_job(job, execution=EX) -def test_job_without_valid_kernel_is_matlabs(tmp_path, fake): - """A job file written before valid_kernel existed (its params lack the - field) solves its containers at MATLAB's 3 x 3, which they were - prepared for, not at today's default.""" +def test_job_without_valid_kernel_is_matlabs(tmp_path, fake) -> None: + """A job file written before valid_kernel existed solves at MATLAB's 3 x 3. + + Its params lack the field; its containers are solved at MATLAB's 3 x 3, + which they were prepared for, not at today's default. + """ import json from dataclasses import replace @@ -547,9 +562,11 @@ def test_job_without_valid_kernel_is_matlabs(tmp_path, fake): assert results.results -def test_trial_without_data_is_skipped(tmp_path, fake, monkeypatch): - """A trial whose selected pixels have no sample is marked and left out - of the summaries, streamed and staged alike.""" +def test_trial_without_data_is_skipped(tmp_path, fake, monkeypatch) -> None: + """A trial whose selected pixels have no sample is marked and left out of the summaries. + + Streamed and staged alike. + """ from giant_python.pipeline.silo_session import NO_DATA def no_data(dat_path, *args, **kw): @@ -580,9 +597,8 @@ def no_data(dat_path, *args, **kw): assert silo.prepare(s, PARAMS, EX, units=[(1, 1)]) == [] -def test_seeds_file_replaces_seeding(tmp_path, fake): - """Seeds from a file (one-based, MATLAB's thetaf) give the plan's - sources.""" +def test_seeds_file_replaces_seeding(tmp_path, fake) -> None: + """Seeds from a file (one-based, MATLAB's thetaf) give the plan's sources.""" from giant_python.extraction.raster.plan import read_plan from giant_python.extraction.raster.stage_files import ( read_seeds, @@ -602,7 +618,7 @@ def test_seeds_file_replaces_seeding(tmp_path, fake): np.testing.assert_array_equal(p.source_cols, [7, 20]) -def test_cli(tmp_path, fake, capsys): +def test_cli(tmp_path, fake, capsys) -> None: """The commands parse their options and run the stages.""" assert parse_numbers("1,3-4") == [1, 3, 4] assert parse_numbers(None) is None @@ -680,13 +696,15 @@ def test_cli(tmp_path, fake, capsys): class _FakePool: """A pool whose tasks finish at a set time on a controlled clock.""" - def __init__(self, now, finish_at): + def __init__(self, now, finish_at) -> None: """Take the clock and each task's finish time.""" self.now, self.finish_at, self.futures = now, list(finish_at), [] def submit(self, *args, **kwargs): - """A future; finished at once (before the next submit) when its - time is None.""" + """Return a future. + + It is finished at once (before the next submit) when its time is None. + """ import concurrent.futures as cf f = cf.Future() @@ -697,11 +715,13 @@ def submit(self, *args, **kwargs): return f -def test_solve_span_is_the_last_subproblem_solved(monkeypatch): - """A trial's solve span ends when its last subproblem is done: a - subproblem solved while the rest are still submitted keeps its own +def test_solve_span_is_the_last_subproblem_solved(monkeypatch) -> None: + """A trial's solve span ends when its last subproblem is done. + + A subproblem solved while the rest are still submitted keeps its own time, a trial collected later still ends then, and a trial solved here - ends when that solve returns. Controlled clock, set completion order.""" + ends when that solve returns. Controlled clock, set completion order. + """ import types from giant_python.extraction.raster import solver as solver_mod @@ -737,9 +757,11 @@ def test_solve_span_is_the_last_subproblem_solved(monkeypatch): assert silo._solve_span(q, 0.0) == (0.7, 0.9) -def test_pool_workers_are_spawned_with_their_thread_counts(): - """Pool workers start a fresh interpreter (not a fork of this one), so - the thread variables are set before numpy loads its BLAS.""" +def test_pool_workers_are_spawned_with_their_thread_counts() -> None: + """Pool workers start a fresh interpreter (not a fork of this one). + + So the thread variables are set before numpy loads its BLAS. + """ import os from giant_python.pipeline.silo_session import make_pool diff --git a/tests/raster/test_raster_solver.py b/tests/raster/test_raster_solver.py index 4dc55110..204b9646 100644 --- a/tests/raster/test_raster_solver.py +++ b/tests/raster/test_raster_solver.py @@ -1,5 +1,7 @@ -"""Tests of the subproblem solver end to end, of the assembly of a trial's -results and of the trial's activity traces.""" +"""Tests of the subproblem solver end to end. + +Also tests the assembly of a trial's results and the trial's activity traces. +""" from dataclasses import replace from pathlib import Path @@ -43,7 +45,7 @@ def _corr(a, b): @pytest.fixture(scope="module") def fixture(): - """A real two-source subproblem and MATLAB's outputs for it.""" + """Load a real two-source subproblem and MATLAB's outputs for it.""" with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( y=f["in/y"][()].astype(np.float64), @@ -57,23 +59,25 @@ def fixture(): @pytest.fixture(scope="module") def solved(fixture): - """The solver's result on the fixture, with its baseline.""" + """Return the solver's result on the fixture, with its baseline.""" sub, _ = fixture return solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) @pytest.fixture(scope="module") def solved_matlab_loss(fixture): - """The result with MATLAB's loss for the footprint fit.""" + """Return the result with MATLAB's loss for the footprint fit.""" sub, _ = fixture opt = SolverOptions(keep_baseline=True) return solve_subproblem(sub, MATLAB_LOSS, opt) -def test_agrees_with_matlab(fixture, solved_matlab_loss): - """With MATLAB's loss, the converged solver's outputs are close to - MATLAB's, whose fits stop early: same footprints and least squares, - similar activity.""" +def test_agrees_with_matlab(fixture, solved_matlab_loss) -> None: + """With MATLAB's loss, the converged solver's outputs are close to MATLAB's. + + MATLAB's fits stop early: same footprints and least squares, similar + activity. + """ sub, out = fixture r = solved_matlab_loss assert r.footprints.shape == (sub.n_pixels, 2) @@ -99,7 +103,7 @@ def test_agrees_with_matlab(fixture, solved_matlab_loss): assert _corr(r.ls[1, j], out["LS"][1, j]) > 0.97 -def test_fits_converge_and_are_recorded(solved): +def test_fits_converge_and_are_recorded(solved) -> None: """Every fit ends on its tolerance, and its record is kept.""" fits = {k: v for k, v in solved.info.items() if isinstance(v, dict)} assert set(fits) == { @@ -116,17 +120,21 @@ def test_fits_converge_and_are_recorded(solved): assert solved.info["baseline1_seconds"] > 0 -def test_events_below_the_floor_are_dropped(solved): - """The debias refit keeps the events of 0.1 or more only, and does not - move the others' places.""" +def test_events_below_the_floor_are_dropped(solved) -> None: + """The debias refit keeps the events of 0.1 or more only. + + It does not move the others' places. + """ ev = solved.events assert not np.any((ev > 0) & (ev < 1e-3)) assert 0.01 < (ev[0] > 0).mean() < 0.5 -def test_batch_matches_single_solves(fixture, solved): - """Subproblems of different sizes solved together get the results they - get alone, to the fits' tolerance.""" +def test_batch_matches_single_solves(fixture, solved) -> None: + """Subproblems of different sizes solved together get the results they get alone. + + They agree to the fits' tolerance. + """ sub, _ = fixture # a smaller subproblem: the first source and the pixels near it rows, cols = sel_coords(sub.sel) @@ -151,9 +159,11 @@ def test_batch_matches_single_solves(fixture, solved): assert got.baseline is None -def test_batches_count_the_footprint_filter(fixture, monkeypatch): - """The size of a batch counts each member's data and its dense - pixels x pixels filter arrays.""" +def test_batches_count_the_footprint_filter(fixture, monkeypatch) -> None: + """The size of a batch counts each member's data and its filter arrays. + + The filter arrays are dense, pixels x pixels. + """ import giant_python.extraction.raster.solver as solver sub, _ = fixture @@ -178,9 +188,11 @@ def test_batches_count_the_footprint_filter(fixture, monkeypatch): assert sizes == [1, 1, 1] -def test_trials_of_different_length_are_grouped(fixture, solved): - """Subproblems with other numbers of frames or channels are solved in - batches of their own, and returned in the order given.""" +def test_trials_of_different_length_are_grouped(fixture, solved) -> None: + """Subproblems with other numbers of frames or channels are solved in their own batches. + + They are returned in the order given. + """ sub, _ = fixture short = replace( sub, y=sub.y[:1, :, :600].copy(), finv=sub.finv[:, :600].copy() @@ -191,18 +203,23 @@ def test_trials_of_different_length_are_grouped(fixture, solved): np.testing.assert_allclose(out[1].footprints, solved.footprints, atol=1e-6) -def test_more_than_two_channels_are_refused(fixture): - """The solver fits the activity channel and one more, as MATLAB's; a - third channel is refused, not dropped.""" +def test_more_than_two_channels_are_refused(fixture) -> None: + """The solver fits the activity channel and one more, as MATLAB's. + + A third channel is refused, not dropped. + """ sub, _ = fixture three = replace(sub, y=np.concatenate([sub.y, sub.y[:1]])) with pytest.raises(ValueError, match="3 channels"): solve_subproblem(three, PARAMS) -def test_data_the_fits_cannot_weigh_are_refused(fixture): - """NaN samples and variance multipliers that are not positive and - finite are input errors, not NaN results.""" +def test_data_the_fits_cannot_weigh_are_refused(fixture) -> None: + """Samples and variance multipliers the fits cannot weigh are input errors, not NaN results. + + That is, NaN samples and variance multipliers that are not positive and + finite. + """ sub, _ = fixture y = sub.y[:1].copy() y[0, 3, 7] = np.nan @@ -219,7 +236,7 @@ def test_data_the_fits_cannot_weigh_are_refused(fixture): assert solve_subproblems([], PARAMS) == [] -def test_options_are_checked(): +def test_options_are_checked() -> None: """Options the fits cannot run with are refused when they are made.""" with pytest.raises(ValueError, match="dtype"): SolverOptions(dtype="float16") @@ -237,7 +254,7 @@ def test_options_are_checked(): assert opt.fit_options("activity1")["max_iter"] == 7 -def test_float32_fits_are_close(fixture, solved): +def test_float32_fits_are_close(fixture, solved) -> None: """Fits in float32 give nearly the float64 result.""" sub, _ = fixture r = solve_subproblem(sub, PARAMS, SolverOptions(dtype="float32")) @@ -249,9 +266,11 @@ def test_float32_fits_are_close(fixture, solved): np.testing.assert_allclose(r.f0, solved.f0, rtol=1e-2) -def test_iteration_cap_is_reported(fixture, solved): - """With one Newton iteration per fit, the fits are marked as not - converged and reach higher losses.""" +def test_iteration_cap_is_reported(fixture, solved) -> None: + """With one Newton iteration per fit, the fits are marked as not converged. + + They also reach higher losses. + """ sub, _ = fixture r = solve_subproblem(sub, PARAMS, SolverOptions(max_iter=1)) assert not r.info["activity1"]["converged"] @@ -259,9 +278,11 @@ def test_iteration_cap_is_reported(fixture, solved): assert r.info["activity1"]["loss"] > solved.info["activity1"]["loss"] -def test_single_fits_can_be_capped(fixture, solved): - """A cap on one fit leaves the others to converge; a cap of 0 on the - footprint fit keeps the starting footprints' shape.""" +def test_single_fits_can_be_capped(fixture, solved) -> None: + """A cap on one fit leaves the others to converge. + + A cap of 0 on the footprint fit keeps the starting footprints' shape. + """ sub, _ = fixture one = replace(sub, y=sub.y[:1]) opt = SolverOptions(fit_max_iter={"footprints1": 0}) @@ -281,11 +302,13 @@ def test_single_fits_can_be_capped(fixture, solved): assert np.abs(r.footprints - solved.footprints).max() > 1e-3 -def test_default_footprint_fit_holds_its_variance(solved, solved_matlab_loss): - """By default the variance of the footprint fit is held at its value - at the fit's start, so the fit does not gain from raising the model: - the footprints come out more compact than with MATLAB's loss, and F0, - which scales with their spread, lower. Both fits converge.""" +def test_default_footprint_fit_holds_its_variance(solved, solved_matlab_loss) -> None: + """By default the variance of the footprint fit is held at its value at the fit's start. + + So the fit does not gain from raising the model: the footprints come out + more compact than with MATLAB's loss, and F0, which scales with their + spread, lower. Both fits converge. + """ assert PARAMS.footprint_variance == "fixed" fixed, model = solved, solved_matlab_loss assert fixed.info["footprints1"]["converged"] @@ -304,9 +327,11 @@ def test_default_footprint_fit_holds_its_variance(solved, solved_matlab_loss): replace(PARAMS, footprint_variance="other") -def test_debias_variance_model_gives_larger_events(fixture, solved): - """The model-variance debias refit rewards larger activity (MATLAB's - behaviour before the fixed variance); the rest is unchanged.""" +def test_debias_variance_model_gives_larger_events(fixture, solved) -> None: + """The model-variance debias refit rewards larger activity. + + This is MATLAB's behaviour before the fixed variance; the rest is unchanged. + """ sub, _ = fixture one = replace(sub, y=sub.y[:1]) r = solve_subproblem(one, replace(PARAMS, debias_variance="model")) @@ -319,9 +344,11 @@ def test_debias_variance_model_gives_larger_events(fixture, solved): assert same.mean() > 0.99 -def test_one_outer_iteration(fixture): - """With nmf_iter 1 the footprints stay at their start and no baseline - or footprint fit runs.""" +def test_one_outer_iteration(fixture) -> None: + """With nmf_iter 1 the footprints stay at their start. + + No baseline or footprint fit runs. + """ sub, _ = fixture one = replace(sub, y=sub.y[:1]) r = solve_subproblem(one, replace(PARAMS, nmf_iter=1)) @@ -329,8 +356,8 @@ def test_one_outer_iteration(fixture): assert r.events.shape == (1, 2, 1000) -def test_photon_scale_matches_matlab(): - """extractTrial's photon scale estimate.""" +def test_photon_scale_matches_matlab() -> None: + """ExtractTrial's photon scale estimate.""" with h5py.File(HELPERS, "r") as f: finv = f["photon/Finv"][()] y = 3 * f["photon/counts"][()] * np.sqrt(finv) @@ -339,7 +366,7 @@ def test_photon_scale_matches_matlab(): def _result(n_px, n_src, n_t, value, n_ch=2): - """A subproblem result filled with a constant.""" + """Build a subproblem result filled with a constant.""" return SubproblemResult( footprints=np.full((n_px, n_src), value), events=np.full((n_ch, n_src, n_t), value), @@ -350,7 +377,7 @@ def _result(n_px, n_src, n_t, value, n_ch=2): def _placed(pixels, sources, n_t): - """A subproblem that only says where its results go.""" + """Build a subproblem that only says where its results go.""" n_px = len(pixels) return Subproblem( y=np.zeros((2, n_px, n_t), np.float32), @@ -362,9 +389,12 @@ def _placed(pixels, sources, n_t): ) -def test_assemble_results(): - """Results go to their pixels and sources; events, least squares and - F0 return to movie units; what no subproblem covers is NaN.""" +def test_assemble_results() -> None: + """Results go to their pixels and sources. + + Events, least squares and F0 return to movie units; what no subproblem + covers is NaN. + """ subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] results = [_result(3, 1, 6, 1.0), _result(2, 2, 6, 2.0)] t = assemble_results(subs, results, 6, 5, photon_scale=25.0) @@ -413,10 +443,12 @@ def test_assemble_results(): assemble_results(subs, [results[0], wrong_snr], 6, 5, 25.0) -def test_process_result(): - """The denoised activity is the events convolved with each channel's - kernel; discarded frames are NaN in the traces, as MATLAB leaves them - (channel 2's events keep their values).""" +def test_process_result() -> None: + """The denoised activity is the events convolved with each channel's kernel. + + Discarded frames are NaN in the traces, as MATLAB leaves them (channel 2's + events keep their values). + """ n_t = 40 rng = np.random.default_rng(0) subs = [_placed([0, 1], [0, 1], n_t)] @@ -448,7 +480,7 @@ def test_process_result(): assert not np.isnan(trial.events).any() -def test_conv_same_is_matlabs(): +def test_conv_same_is_matlabs() -> None: """'same' keeps the first argument's length, also below the kernel's.""" k = np.array([0.0, 0.0, 1.0, 0.5, 0.25]) x = np.array([[1.0, 0.0, 0.0, 2.0]]) @@ -463,10 +495,12 @@ def _rms_width(h, rows, cols): return float(np.sqrt((h @ ((rows - m[0]) ** 2 + (cols - m[1]) ** 2)) / 2)) -def test_valid_kernel_lets_a_wide_footprint_be_fit(): - """A sigma-1.8 source on its true baseline: with the 3 x 3 support the - fitted footprint stops near its ceiling (1.56 px), with 5 x 5 it gets - close to the truth (1.8 px).""" +def test_valid_kernel_lets_a_wide_footprint_be_fit() -> None: + """A sigma-1.8 source on its true baseline, fit with the 3 x 3 and 5 x 5 supports. + + With the 3 x 3 support the fitted footprint stops near its ceiling (1.56 px), + with 5 x 5 it gets close to the truth (1.8 px). + """ rng = np.random.default_rng(3) sel = np.ones((13, 13), dtype=bool) rows, cols = sel_coords(sel) diff --git a/tests/raster/test_raster_solver_baseline.py b/tests/raster/test_raster_solver_baseline.py index 00b35d8c..ebb5ac1e 100644 --- a/tests/raster/test_raster_solver_baseline.py +++ b/tests/raster/test_raster_solver_baseline.py @@ -1,6 +1,8 @@ -"""Tests of the deterministic parts of the subproblem solver: the baseline -(splitFreq, fitB and its helpers), the floor and the noise estimate, -against GIAnT-MATLAB's values.""" +"""Tests of the deterministic parts of the subproblem solver. + +The baseline (splitFreq, fitB and its helpers), the floor and the noise +estimate, against GIAnT-MATLAB's values. +""" import warnings from pathlib import Path @@ -34,7 +36,7 @@ ) -def _close(a, b, tol=1e-12): +def _close(a, b, tol=1e-12) -> None: """Equal NaN patterns, and differences below tol of the largest value.""" a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) assert a.shape == b.shape @@ -49,7 +51,7 @@ def _conv_same(x, k): def _read_tree(g): - """An HDF5 group as nested dicts of arrays.""" + """Read an HDF5 group as nested dicts of arrays.""" return { k: _read_tree(v) if isinstance(v, h5py.Group) else v[()] for k, v in g.items() @@ -65,7 +67,7 @@ def helpers(): @pytest.fixture(scope="module") def sub(): - """The subproblem fixture: inputs as float64, MATLAB's intermediates.""" + """Load the subproblem fixture: inputs as float64, MATLAB's intermediates.""" with h5py.File(SUBPROBLEM, "r") as f: d = _read_tree(f) d["every"] = int(f.attrs["baseline_every"]) @@ -76,25 +78,27 @@ def sub(): @pytest.mark.parametrize("window", [4, 7, 20, 50]) -def test_lowess_and_movmean_match_matlab(helpers, window): - """smoothdata's lowess and movmean, for even, odd and too long - windows.""" +def test_lowess_and_movmean_match_matlab(helpers, window) -> None: + """Smoothdata's lowess and movmean, for even, odd and too long windows.""" s = helpers["smooth"] _close(sb.smooth_lowess(s["A"], window), s[f"lowess_{window}"]) _close(movmean_nan(s["A"].T, window).T, s[f"movmean_{window}"]) @pytest.mark.parametrize("window", [7, 20]) -def test_lowess_omits_nan_as_matlab(helpers, window): +def test_lowess_omits_nan_as_matlab(helpers, window) -> None: """NaN samples are left out of the local fits.""" s = helpers["smooth"] assert np.isnan(s["An"]).sum() == 10 _close(sb.smooth_lowess(s["An"], window), s[f"lowess_nan_{window}"]) -def test_lowess_degenerate_windows(): - """A window of one sample returns the data; a window whose only - weighted sample is the centre returns it; all-NaN windows give NaN.""" +def test_lowess_degenerate_windows() -> None: + """A window of one sample returns the data. + + A window whose only weighted sample is the centre returns it; all-NaN + windows give NaN. + """ a = np.array([[1.0, 4.0, 2.0, np.nan, np.nan, np.nan, 7.0]]) assert np.array_equal(sb.smooth_lowess(a[:, :3], 1), a[:, :3]) out = sb.smooth_lowess(a, 3) @@ -116,14 +120,16 @@ def test_lowess_degenerate_windows(): ("med_9", 5, 9, "symmetric"), ], ) -def test_order_filters_match_matlab(helpers, name, order, n, pad): - """ordfilt2 and medfilt2 along rows, with both paddings; the window of - 46 is longer than the 41 samples.""" +def test_order_filters_match_matlab(helpers, name, order, n, pad) -> None: + """ordfilt2 and medfilt2 along rows, with both paddings. + + The window of 46 is longer than the 41 samples. + """ o = helpers["ord"] assert np.array_equal(sb.ordfilt_rows(o["a"], order, n, pad), o[name]) -def test_split_freq_matches_matlab(helpers): +def test_split_freq_matches_matlab(helpers) -> None: """splitFreq, also for a trial too short to interpolate.""" s = helpers["split"] lp, hp = sb.split_freq(s["A"], 10, 6) @@ -134,25 +140,30 @@ def test_split_freq_matches_matlab(helpers): _close(sb.split_freq(s["D"], 10, 6)[0], s["LP_nan"]) -def test_initial_baseline_takes_min_where_nan(monkeypatch): - """Where splitFreq's low-pass is NaN the baseline is min_baseline, as - MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below.""" +def test_initial_baseline_takes_min_where_nan(monkeypatch) -> None: + """Where splitFreq's low-pass is NaN the baseline is min_baseline. + + As MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below. + """ lp = np.array([[np.nan, 0.5, -1.0], [2.0, np.nan, 0.001]]) monkeypatch.setattr(sb, "split_freq", lambda *a: (lp, None)) b = sb.initial_baseline(np.zeros((2, 3)), PARAMS) assert np.array_equal(b, [[0.01, 0.5, 0.01], [2.0, 0.01, 0.01]]) -def test_compute_floor_matches_matlab(helpers): +def test_compute_floor_matches_matlab(helpers) -> None: """computeFloor, for integer and fractional windows.""" f = helpers["floor"] _close(sb.compute_floor(f["X"], 7, 45.5), f["out"]) _close(sb.compute_floor(f["X"], 6, 40), f["out_int"]) -def test_bspline_basis_matches_matlab(helpers): - """bsplineBasis: whole knot intervals tile the trial; one interval when - the spacing exceeds it. The products are those of the basis.""" +def test_bspline_basis_matches_matlab(helpers) -> None: + """bsplineBasis: whole knot intervals tile the trial. + + One interval when the spacing exceeds it. The products are those of the + basis. + """ s = helpers["spline"] b = sb.bspline_basis(101, 17.3) _close(b.toarray(), s["B"], 1e-14) @@ -166,9 +177,8 @@ def test_bspline_basis_matches_matlab(helpers): ) -def test_curvature_penalty(): - """Squared second differences per knot interval: constants and lines - cost nothing.""" +def test_curvature_penalty() -> None: + """Squared second differences per knot interval: constants and lines cost nothing.""" pc = sb.curvature_penalty(7) c = np.arange(7.0) assert np.allclose(pc @ np.ones(7), 0) and np.allclose(pc @ c, 0) @@ -176,8 +186,8 @@ def test_curvature_penalty(): assert quad @ pc @ quad == pytest.approx(5 * 2.0**2 / 4) -def test_surround_matches_matlab(helpers): - """getSurround on a map with a hole, dense and sparse operators.""" +def test_surround_matches_matlab(helpers) -> None: + """GetSurround on a map with a hole, dense and sparse operators.""" sel = helpers["foot"]["selPix"].astype(bool) s = helpers["surround"] _close(SMALL.bfilter, s["Bfilter"].transpose(2, 0, 1)) @@ -189,10 +199,12 @@ def test_surround_matches_matlab(helpers): _close(sb.get_surround(s["HP"], sparse_ops), ref) -def test_fit_baseline_matches_matlab(helpers): - """fitB on a small synthetic problem. MATLAB's quadprog stops at its - tolerance, so the baselines agree to about 1e-8; Python's programs are - solved to machine precision.""" +def test_fit_baseline_matches_matlab(helpers) -> None: + """FitB on a small synthetic problem. + + MATLAB's quadprog stops at its tolerance, so the baselines agree to about + 1e-8; Python's programs are solved to machine precision. + """ sel = helpers["foot"]["selPix"].astype(bool) f = helpers["fitB"] y = f["Finv"] * f["counts"] @@ -208,7 +220,7 @@ def test_fit_baseline_matches_matlab(helpers): def _random_qp(rng, m, n, rank=None): - """A stack of random bounded quadratic programs.""" + """Build a stack of random bounded quadratic programs.""" a = rng.standard_normal((m, rank or n + 3, n)) g = np.einsum("mki,mkj->mij", a, a) c = rng.standard_normal((m, n)) * 3 @@ -217,9 +229,11 @@ def _random_qp(rng, m, n, rank=None): return g, c, lb, ub -def test_box_qp_matches_scipy(): - """The batched solver finds the minimum that a bounded least-squares - solver finds, with many bounds active.""" +def test_box_qp_matches_scipy() -> None: + """The batched solver finds the minimum that a bounded least-squares solver finds. + + With many bounds active. + """ rng = np.random.default_rng(3) g, c, lb, ub = _random_qp(rng, 40, 6) x, info = sb.solve_box_qp(g, c, lb, ub) @@ -236,9 +250,8 @@ def test_box_qp_matches_scipy(): np.testing.assert_allclose(x[i], ref, atol=1e-8) -def test_box_qp_zero_curvature_follows_the_linear_term(): - """A variable without curvature goes to the bound that its linear - term favours.""" +def test_box_qp_zero_curvature_follows_the_linear_term() -> None: + """A variable without curvature goes to the bound that its linear term favours.""" g = np.zeros((3, 1, 1)) c = np.array([[1.0], [-1.0], [0.0]]) lb, ub = np.full((3, 1), -3.0), np.full((3, 1), 2.0) @@ -253,9 +266,11 @@ def test_box_qp_zero_curvature_follows_the_linear_term(): assert x.ravel().tolist() == [0.5, 3.0] -def test_box_qp_fixed_variables(): - """Bounds that coincide fix a variable, in the Newton iterations and in - the fallback; the others are solved around it.""" +def test_box_qp_fixed_variables() -> None: + """Bounds that coincide fix a variable, in the Newton iterations and in the fallback. + + The others are solved around it. + """ one = np.ones((1, 1)) for max_iter in (100, 0): x, _ = sb.solve_box_qp(one[None], 0 * one, one, one, max_iter=max_iter) @@ -280,10 +295,12 @@ def test_box_qp_fixed_variables(): np.testing.assert_allclose(x[:, keep], ref, atol=1e-9) -def test_box_qp_fallback_keeps_the_objective(): - """The fallback solves the program as given: a singular G whose linear - term acts along the null direction ends on the bounds, without a - warning, as the Newton iterations do.""" +def test_box_qp_fallback_keeps_the_objective() -> None: + """The fallback solves the program as given. + + A singular G whose linear term acts along the null direction ends on the + bounds, without a warning, as the Newton iterations do. + """ g = np.array([[[1.0, 1.0], [1.0, 1.0]]]) lb, ub = np.full((1, 2), -2.0), np.full((1, 2), 2.0) for c in ([[1e-16, -1e-16]], [[0.5, -0.5]]): @@ -307,9 +324,11 @@ def test_box_qp_fallback_keeps_the_objective(): assert x.sum() == pytest.approx(1.0, abs=1e-9) and info["kkt"].max() < 1e-9 -def test_box_qp_zero_rows_and_fallback(): - """A variable with a zero row is left at its bound nearest zero; a - problem the Newton iterations do not finish goes to the fallback.""" +def test_box_qp_zero_rows_and_fallback() -> None: + """A variable with a zero row is left at its bound nearest zero. + + A problem the Newton iterations do not finish goes to the fallback. + """ rng = np.random.default_rng(4) g, c, lb, ub = _random_qp(rng, 5, 4) g[:, 2, :] = g[:, :, 2] = 0 @@ -332,7 +351,7 @@ def test_box_qp_zero_rows_and_fallback(): np.testing.assert_allclose(x, good, atol=1e-7) -def test_subproblem_start_matches_matlab(sub): +def test_subproblem_start_matches_matlab(sub) -> None: """Starting baseline, least squares and events of a real subproblem.""" y, every = sub["y"][0], sub["every"] b = sb.initial_baseline(y, PARAMS) @@ -346,7 +365,7 @@ def test_subproblem_start_matches_matlab(sub): _close(b2[:, ::every], sub["ch2"]["B"]) -def test_subproblem_noise_and_floor_match_matlab(sub): +def test_subproblem_noise_and_floor_match_matlab(sub) -> None: """Noise, SNR and floor from MATLAB's first activity fit.""" y, it1 = sub["y"][0], sub["it1"] b = sb.initial_baseline(y, PARAMS) @@ -362,9 +381,11 @@ def test_subproblem_noise_and_floor_match_matlab(sub): _close(np.fmax(0, x - floor - noise[:, None]), it1["X_thr"]) -def test_subproblem_baseline_fit_matches_matlab(sub): - """fitB on a real subproblem (its trial is shorter than the lowess - window of the high-pass split), to quadprog's tolerance.""" +def test_subproblem_baseline_fit_matches_matlab(sub) -> None: + """FitB on a real subproblem, to quadprog's tolerance. + + Its trial is shorter than the lowess window of the high-pass split. + """ y, it1 = sub["y"][0], sub["it1"] b0 = sb.initial_baseline(y, PARAMS) b, info = sb.fit_baseline( @@ -381,9 +402,8 @@ def test_subproblem_baseline_fit_matches_matlab(sub): assert info["converged"].all() and info["kkt"].max() < 1e-9 -def test_subproblem_footprint_update_matches_matlab(sub): - """H from MATLAB's fitted Hs through the footprint filter, and the - normalization.""" +def test_subproblem_footprint_update_matches_matlab(sub) -> None: + """H from MATLAB's fitted Hs through the footprint filter, and the normalization.""" it1 = sub["it1"] h = conv_operator(sub["sel"], PARAMS.hfilter) @ it1["Hs_out"] norm = h.sum(0) @@ -395,7 +415,7 @@ def test_subproblem_footprint_update_matches_matlab(sub): assert h.shape == (rows.size, 2) -def test_subproblem_outputs_match_matlab(sub): +def test_subproblem_outputs_match_matlab(sub) -> None: """SNR, least squares and F0 from MATLAB's final activity.""" y, out, it1 = sub["y"], sub["out"], sub["it1"] h = out["H"] @@ -420,7 +440,7 @@ def test_subproblem_outputs_match_matlab(sub): _close(sb.source_f0(h, b2), out["F0"][1]) -def test_interp1_extrapolates(): +def test_interp1_extrapolates() -> None: """Linear interpolation of rows with linear extrapolation.""" x = np.array([1.0, 2.0, 4.0]) y = np.array([[0.0, 1.0, 5.0]]) @@ -428,10 +448,12 @@ def test_interp1_extrapolates(): np.testing.assert_allclose(out, [[-1.0, 0.5, 3.0, 7.0]]) -def test_activity_noise_with_a_zero_footprint_is_matlabs(): - """A source whose footprint is all zero makes the normal matrix - singular: noise Inf and SNR 0 for every source, with a warning, as - MATLAB's inv gives; other inputs give the plain inverse's result.""" +def test_activity_noise_with_a_zero_footprint_is_matlabs() -> None: + """A source whose footprint is all zero makes the normal matrix singular. + + Noise Inf and SNR 0 for every source, with a warning, as MATLAB's inv + gives; other inputs give the plain inverse's result. + """ rng = np.random.default_rng(5) n_px, n_t = 40, 300 h = np.abs(rng.standard_normal((n_px, 3))) diff --git a/tests/raster/test_raster_solver_baseline_modes.py b/tests/raster/test_raster_solver_baseline_modes.py index 05eab5b8..1eafea75 100644 --- a/tests/raster/test_raster_solver_baseline_modes.py +++ b/tests/raster/test_raster_solver_baseline_modes.py @@ -1,6 +1,9 @@ -"""Tests of the solver's baseline modes (the variants R0, N0-N3 of the -SILo port's baseline test): an external baseline held, scaled per pixel, -scaled by a shared time course, or corrected by ``fitB``.""" +"""Tests of the solver's baseline modes. + +These are the variants R0, N0-N3 of the SILo port's baseline test: an external +baseline held, scaled per pixel, scaled by a shared time course, or corrected +by ``fitB``. +""" from dataclasses import replace from pathlib import Path @@ -39,8 +42,10 @@ def _corr(a, b): @pytest.fixture(scope="module") def real(): - """A real two-source subproblem (activity channel only) and the - default solver's result on it, with its baseline.""" + """Load a real two-source subproblem (activity channel only) and solve it. + + Returns it with the default solver's result on it, with its baseline. + """ with h5py.File(SUBPROBLEM, "r") as f: sub = Subproblem( y=f["in/y"][()][:1].astype(np.float64), @@ -52,7 +57,7 @@ def real(): def _synthetic(seed=0, n_t=1600, shared=None, scale=1.0): - """A one-source subproblem drawn from a known baseline and events. + """Draw a one-source subproblem from a known baseline and events. The baseline is a bright stripe times a slow drift (and ``shared``, a time course common to all pixels, if given); the data are ``F`` @@ -89,7 +94,7 @@ def _synthetic(seed=0, n_t=1600, shared=None, scale=1.0): return sub, b_true, s -def test_params_and_subproblem_check_the_baseline(): +def test_params_and_subproblem_check_the_baseline() -> None: """Unknown modes, a misfitting or non-finite baseline are refused.""" with pytest.raises(ValueError, match="baseline_mode"): SolverParams(baseline_mode="network") @@ -105,7 +110,7 @@ def test_params_and_subproblem_check_the_baseline(): replace(sub, baseline=bad, _coords=None) -def test_modes_other_than_fit_need_a_baseline(real): +def test_modes_other_than_fit_need_a_baseline(real) -> None: """Without Subproblem.baseline only the default mode runs.""" sub, _ = real for mode in ("fixed", "gain", "gain_shared", "fit_from"): @@ -113,7 +118,7 @@ def test_modes_other_than_fit_need_a_baseline(real): solve_subproblem(sub, replace(PARAMS, baseline_mode=mode)) -def test_fit_mode_ignores_an_external_baseline(real): +def test_fit_mode_ignores_an_external_baseline(real) -> None: """R0 gives the same results with and without an external baseline.""" sub, r0 = real with_b = replace(sub, baseline=2 * r0.baseline[0], _coords=None) @@ -122,9 +127,11 @@ def test_fit_mode_ignores_an_external_baseline(real): np.testing.assert_array_equal(getattr(again, name), getattr(r0, name)) -def test_fixed_mode_holds_the_baseline(real): - """N0 keeps the given baseline (bounded below) and, given R0's final - baseline, finds R0's sources.""" +def test_fixed_mode_holds_the_baseline(real) -> None: + """N0 keeps the given baseline (bounded below). + + Given R0's final baseline, it finds R0's sources. + """ sub, r0 = real b = r0.baseline[0] given = replace(sub, baseline=b, _coords=None) @@ -145,12 +152,11 @@ def test_fixed_mode_holds_the_baseline(real): def _mean_error(b, truth): - """Mean absolute error of the pixels' time means, over the truth's - mean.""" + """Mean absolute error of the pixels' time means, over the truth's mean.""" return float(np.abs(b.mean(1) - truth.mean(1)).mean() / truth.mean()) -def test_fit_from_mode_corrects_little_from_the_right_baseline(): +def test_fit_from_mode_corrects_little_from_the_right_baseline() -> None: """N3 given the true baseline stays near it, as R0 comes near it.""" sub, b_true, _ = _synthetic(seed=7) n3 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fit_from"), KEEP) @@ -159,9 +165,11 @@ def test_fit_from_mode_corrects_little_from_the_right_baseline(): assert _mean_error(r0.baseline[0], b_true) < 0.01 -def test_gain_mode_undoes_a_scale_error(): - """N1 given the true baseline times 1.1 finds gains near 1 / 1.1; N0 - keeps the error.""" +def test_gain_mode_undoes_a_scale_error() -> None: + """N1 given the true baseline times 1.1 finds gains near 1 / 1.1. + + N0 keeps the error. + """ sub, b_true, _ = _synthetic(seed=7, scale=1.1) n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) gain = n1.info["baseline_step"]["gain"] @@ -176,9 +184,8 @@ def test_gain_mode_undoes_a_scale_error(): assert abs(_mean_error(n0.baseline[0], b_true) - 0.1) < 1e-9 -def test_gain_programs_without_sources_are_weighted_ratios(): - """With no activity the gain is the weighted ratio of data and - predictor.""" +def test_gain_programs_without_sources_are_weighted_ratios() -> None: + """With no activity the gain is the weighted ratio of data and predictor.""" rng = np.random.default_rng(3) y = rng.random((4, 50)) + 1 q = rng.random((4, 50)) + 0.5 @@ -195,7 +202,7 @@ def test_gain_programs_without_sources_are_weighted_ratios(): assert (prog["lb"] == 0).all() -def test_shared_time_course_shrinks_noise_to_its_mean(): +def test_shared_time_course_shrinks_noise_to_its_mean() -> None: """Without a shared change the factor is flat; with one it follows.""" rng = np.random.default_rng(4) n_px, n_t = 200, 2000 @@ -218,9 +225,11 @@ def test_shared_time_course_shrinks_noise_to_its_mean(): assert np.abs(c - true).mean() < raw_err -def test_gain_shared_mode_finds_a_shared_change(): - """N2 recovers a fast change shared by all pixels that the external - baseline lacks, and N1 does not.""" +def test_gain_shared_mode_finds_a_shared_change() -> None: + """N2 recovers a fast change shared by all pixels that the external baseline lacks. + + N1 does not. + """ n_t = 1600 shared = 1 + 0.08 * np.sign(np.sin(np.arange(n_t) / 3.0)) sub, b_true, _ = _synthetic(seed=5, n_t=n_t, shared=shared) @@ -236,7 +245,7 @@ def test_gain_shared_mode_finds_a_shared_change(): assert err2 < 0.7 * err1 -def test_gain_shared_without_outside_pixels_is_gain(): +def test_gain_shared_without_outside_pixels_is_gain() -> None: """With too few pixels outside the footprints the factor is 1.""" sub, _, _ = _synthetic(seed=6) params = replace(PARAMS, baseline_mode="gain_shared") @@ -258,9 +267,11 @@ def test_gain_shared_without_outside_pixels_is_gain(): assert rows.size == cols.size == sub.n_pixels -def test_fit_baseline_offset(): - """A zero offset changes nothing; with the true baseline as offset the - fitted correction is small.""" +def test_fit_baseline_offset() -> None: + """A zero offset changes nothing. + + With the true baseline as offset the fitted correction is small. + """ sub, b_true, s = _synthetic(seed=7) y = sub.y[0] x = conv_same(s[None], PARAMS.k) @@ -278,9 +289,11 @@ def test_fit_baseline_offset(): assert err_from < 0.03 -def test_shared_variance_ignores_filled_frames(): - """Filled-in frames (variance multiplier 1000 x) do not hide a shared - change: they are left out of the shared variance and shrunk alone.""" +def test_shared_variance_ignores_filled_frames() -> None: + """Filled-in frames (variance multiplier 1000 x) do not hide a shared change. + + They are left out of the shared variance and shrunk alone. + """ rng = np.random.default_rng(8) n_px, n_t = 200, 2000 q = np.full((n_px, n_t), 3.0) @@ -299,9 +312,8 @@ def test_shared_variance_ignores_filled_frames(): assert np.abs(c[filled] - rec["mean"]).max() < 0.01 -def test_outside_pixels_ignore_a_source_without_footprint(): - """A source whose footprint is all zero leaves the outside pixels to - the other sources.""" +def test_outside_pixels_ignore_a_source_without_footprint() -> None: + """A source whose footprint is all zero leaves the outside pixels to the other sources.""" sub, _, _ = _synthetic(seed=9) params = replace(PARAMS, baseline_mode="gain_shared") rows, cols = np.nonzero(sub.sel.T)[::-1] @@ -315,9 +327,11 @@ def test_outside_pixels_ignore_a_source_without_footprint(): assert info["n_outside"] > 100 -def test_filled_frames_do_not_fake_a_shared_change(): - """With a constant baseline, many filled-in frames leave the residual - scale unbiased, so no shared change is found.""" +def test_filled_frames_do_not_fake_a_shared_change() -> None: + """With a constant baseline, many filled-in frames leave the residual scale unbiased. + + So no shared change is found. + """ rng = np.random.default_rng(10) n_px, n_t = 200, 2000 q = np.full((n_px, n_t), 3.0) @@ -331,7 +345,7 @@ def test_filled_frames_do_not_fake_a_shared_change(): assert np.ptp(c) < 0.01 -def test_filled_samples_do_not_count_in_alpha(): +def test_filled_samples_do_not_count_in_alpha() -> None: """Pixels filled in at some frames do not bias the residual scale.""" rng = np.random.default_rng(13) n_px, n_t = 200, 2000 @@ -346,9 +360,11 @@ def test_filled_samples_do_not_count_in_alpha(): assert np.ptp(c) < 0.01 -def test_shared_change_found_when_most_frames_are_filled(): - """With 70% of the frames filled in, the shared change is still found - on the others.""" +def test_shared_change_found_when_most_frames_are_filled() -> None: + """With 70% of the frames filled in, the shared change is still found. + + It is found on the other frames. + """ rng = np.random.default_rng(12) n_px, n_t = 200, 3000 q = np.full((n_px, n_t), 3.0) @@ -364,17 +380,21 @@ def test_shared_change_found_when_most_frames_are_filled(): def _paired_noise(rng, q, true): - """Poisson data whose noise neighbouring pixel pairs share (as on - resampled frames): each pair's pixels are the mean of two draws.""" + """Poisson data whose noise neighbouring pixel pairs share (as on resampled frames). + + Each pair's pixels are the mean of two draws. + """ n_px, n_t = q.shape draws = rng.poisson(q * true[None]).astype(np.float64) pair = draws.reshape(n_px // 2, 2, n_t).mean(1) return np.repeat(pair, 2, axis=0) -def test_halves_ignore_noise_shared_by_neighbours(): - """Noise shared by neighbouring pixels is no shared change when the - halves are apart; the independent-noise estimate mistakes it for one.""" +def test_halves_ignore_noise_shared_by_neighbours() -> None: + """Noise shared by neighbouring pixels is no shared change when the halves are apart. + + The independent-noise estimate mistakes it for one. + """ rng = np.random.default_rng(14) n_px, n_t = 200, 2000 q = np.full((n_px, n_t), 3.0) @@ -399,9 +419,8 @@ def test_halves_ignore_noise_shared_by_neighbours(): assert r4["s2"] == 0 -def test_outside_halves_are_apart(): - """The halves split the outside pixels along their longer extent, - with a gap.""" +def test_outside_halves_are_apart() -> None: + """The halves split the outside pixels along their longer extent, with a gap.""" sel = np.ones((5, 12), bool) outside = np.ones(60, bool) a, b = outside_halves(sel, outside) @@ -410,9 +429,11 @@ def test_outside_halves_are_apart(): assert a.sum() > 15 and b.sum() > 15 -def test_halves_skip_frames_where_one_half_is_filled(): - """Frames where one half is filled in (and the whole is not) do not - enter the halves' covariance.""" +def test_halves_skip_frames_where_one_half_is_filled() -> None: + """Frames where one half is filled in do not enter the halves' covariance. + + This holds for frames where the whole is not filled in. + """ rng = np.random.default_rng(15) n_px, n_t = 200, 3000 q = np.full((n_px, n_t), 3.0) @@ -429,9 +450,8 @@ def test_halves_skip_frames_where_one_half_is_filled(): assert _corr(c, true) > 0.85 -def test_halves_do_not_shrink_noiseless_factors(): - """Identical noiseless factors in both halves are kept as they are, - also with few frames.""" +def test_halves_do_not_shrink_noiseless_factors() -> None: + """Identical noiseless factors in both halves are kept as they are, also with few frames.""" q = np.ones((20, 2)) y = q * np.array([0.8, 1.2])[None] halves = (np.arange(20) < 8, np.arange(20) >= 12) @@ -440,10 +460,13 @@ def test_halves_do_not_shrink_noiseless_factors(): np.testing.assert_allclose(c, [0.8, 1.2]) -def test_halves_use_the_same_frames_for_both_variances(): - """When one half is filled in during the quiet part of a shared - change, the shared variance does not exceed the factors' variance on - the same frames, and the change is followed.""" +def test_halves_use_the_same_frames_for_both_variances() -> None: + """The halves use the same frames for the shared and the factors' variance. + + When one half is filled in during the quiet part of a shared change, the + shared variance does not exceed the factors' variance on the same + frames, and the change is followed. + """ rng = np.random.default_rng(16) n_px, n_t = 200, 3000 q = np.full((n_px, n_t), 3.0) diff --git a/tests/raster/test_raster_solver_fits.py b/tests/raster/test_raster_solver_fits.py index af8b76c3..2e0b7703 100644 --- a/tests/raster/test_raster_solver_fits.py +++ b/tests/raster/test_raster_solver_fits.py @@ -1,6 +1,8 @@ -"""Tests of the iterative fits of the subproblem solver: the loss and its -derivatives, the kernel, the bounded Newton solver, and the fits against -GIAnT-MATLAB's from the same inputs.""" +"""Tests of the iterative fits of the subproblem solver. + +The loss and its derivatives, the kernel, the bounded Newton solver, and the +fits against GIAnT-MATLAB's from the same inputs. +""" from pathlib import Path @@ -24,7 +26,7 @@ def _t(a): - """A float64 tensor with a leading batch dimension of one.""" + """Make a float64 tensor with a leading batch dimension of one.""" return torch.as_tensor(np.ascontiguousarray(a), dtype=DT)[None] @@ -54,7 +56,7 @@ def _small_problem(seed=0, n_px=14, n_src=2, n_t=60, batch=1, tau=3.0): @pytest.mark.parametrize("fixed", [False, True]) -def test_loss_derivatives(fixed): +def test_loss_derivatives(fixed) -> None: """First and second derivative of the loss in the model, by autograd.""" rng = np.random.default_rng(0) z = torch.as_tensor(rng.random((2, 3, 5)) * 4) @@ -75,9 +77,11 @@ def test_loss_derivatives(fixed): @pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) @pytest.mark.parametrize("n_t", [5, 40, 400]) -def test_time_kernel_matches_convolution(tau, n_t): - """The exponential kernels by shifted additions equal a 'same' - convolution, for trials shorter and longer than the kernel.""" +def test_time_kernel_matches_convolution(tau, n_t) -> None: + """The exponential kernels by shifted additions equal a 'same' convolution. + + This holds for trials shorter and longer than the kernel. + """ rng = np.random.default_rng(1) k = temporal_kernel(tau) kern = sf.TimeKernel(torch.as_tensor(k)) @@ -89,7 +93,7 @@ def test_time_kernel_matches_convolution(tau, n_t): np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-13) -def test_time_kernel_general(): +def test_time_kernel_general() -> None: """Kernels that are not causal exponentials go through conv1d.""" rng = np.random.default_rng(2) x = rng.standard_normal((1, 2, 30)) @@ -108,7 +112,7 @@ def test_time_kernel_general(): sf.TimeKernel(torch.ones(4)) -def _check_derivatives(problem, x): +def _check_derivatives(problem, x) -> None: """Gradient, Hessian products and diagonal against autograd.""" x = x.clone().requires_grad_() f = problem.value(x) @@ -131,7 +135,7 @@ def _check_derivatives(problem, x): @pytest.mark.parametrize("fixed", [False, True]) -def test_activity_problem_derivatives(fixed): +def test_activity_problem_derivatives(fixed) -> None: """The activity fit's gradient and curvature, with either variance.""" z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None @@ -139,7 +143,7 @@ def test_activity_problem_derivatives(fixed): _check_derivatives(problem, s * 0.5 + 1) -def test_footprint_problem_derivatives(): +def test_footprint_problem_derivatives() -> None: """The footprint fit's gradient and curvature.""" z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) rng = np.random.default_rng(6) @@ -150,9 +154,11 @@ def test_footprint_problem_derivatives(): _check_derivatives(problem, h.clone()) -def test_preconditioner_inverts_one_source(): - """For one source the preconditioner is the inverse of the Hessian on - the free events, up to the kernel's truncation.""" +def test_preconditioner_inverts_one_source() -> None: + """For one source the preconditioner is the inverse of the Hessian on the free events. + + Up to the kernel's truncation. + """ z, h, b, w, s, k = _small_problem(n_px=8, n_src=1, n_t=200) problem = sf.ActivityProblem(z, h, b, k, w, 0.9) problem.value_grad(s) @@ -169,7 +175,7 @@ def test_preconditioner_inverts_one_source(): assert float((jacobi - v).norm() / v.norm()) > 0.3 -def test_preconditioner_falls_back_to_diagonal(): +def test_preconditioner_falls_back_to_diagonal() -> None: """Kernels that are not exponential get the Hessian's diagonal.""" z, h, b, w, s, _ = _small_problem(n_px=6, n_t=20) k = torch.as_tensor([0.0, 0.0, 0.6, 0.1, 0.3], dtype=DT) @@ -181,9 +187,11 @@ def test_preconditioner_falls_back_to_diagonal(): assert torch.equal(problem.preconditioner(free, diag)(r), r / diag) -def test_activity_fit_reaches_scipy_optimum(): - """The fit ends at the optimum that L-BFGS-B approaches, with many - events on their bound.""" +def test_activity_fit_reaches_scipy_optimum() -> None: + """The fit ends at the optimum that L-BFGS-B approaches. + + Many events are on their bound. + """ z, h, b, w, s_true, k = _small_problem(seed=3, n_px=20, n_t=120) start = torch.full_like(s_true, 5.0) s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, history=True) @@ -216,7 +224,7 @@ def fun(x): assert np.corrcoef(found.ravel(), truth.ravel())[0, 1] > 0.7 -def test_fit_does_not_depend_on_its_start(): +def test_fit_does_not_depend_on_its_start() -> None: """A convex fit has one optimum: two starts end at the same events.""" z, h, b, w, s_true, k = _small_problem(seed=4, n_px=16, n_t=80) a, _ = sf.fit_activity(z, h, b, k, w, 0.9, torch.zeros_like(s_true)) @@ -224,9 +232,11 @@ def test_fit_does_not_depend_on_its_start(): assert torch.allclose(a, c, atol=1e-4) -def test_batched_fit_equals_separate_fits(): - """Members of a batch, padded with weightless pixels and a source held - at zero, get the fits they get alone.""" +def test_batched_fit_equals_separate_fits() -> None: + """Members of a batch get the fits they get alone. + + They are padded with weightless pixels and a source held at zero. + """ z, h, b, w, s_true, k = _small_problem(seed=5, n_px=12, n_t=70, batch=2) # member 1: 9 pixels and one source; the rest is padding w[1, 9:] = 0 @@ -252,9 +262,11 @@ def test_batched_fit_equals_separate_fits(): assert float(info.loss[1]) == pytest.approx(float(i1.loss[0]), rel=1e-10) -def test_iteration_cap_and_free_entries(): - """A capped fit reports that it did not converge and still lowers the - loss; entries that are not free stay at zero.""" +def test_iteration_cap_and_free_entries() -> None: + """A capped fit reports that it did not converge and still lowers the loss. + + Entries that are not free stay at zero. + """ z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) start = torch.full_like(s_true, 5.0) problem = sf.ActivityProblem(z, h, b, k, w, 0.9) @@ -269,9 +281,11 @@ def test_iteration_cap_and_free_entries(): assert torch.all(s2[~free] == 0) and float(s2[free].min()) >= 0 -def test_fixed_variance_fit_is_weighted_least_squares(): - """With the variance held, the fit of the free events is the bounded - weighted least-squares solution.""" +def test_fixed_variance_fit_is_weighted_least_squares() -> None: + """With the variance held, the fit of the free events is weighted least squares. + + It is the bounded weighted least-squares solution. + """ z, h, b, w, s_true, k = _small_problem(seed=7, n_px=10, n_src=1, n_t=40) kern = sf.TimeKernel(k) s0 = h @ kern.conv(s_true) + b + 1 @@ -294,9 +308,11 @@ def test_fixed_variance_fit_is_weighted_least_squares(): np.testing.assert_allclose(s.numpy().ravel()[idx], ref, atol=1e-5) -def test_footprint_fit_stays_on_its_support(): - """Footprints are fitted within their support, not below zero, and - reach a lower loss than the start.""" +def test_footprint_fit_stays_on_its_support() -> None: + """Footprints are fitted within their support, not below zero. + + They reach a lower loss than the start. + """ z, h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) x = sf.TimeKernel(k).conv(s) g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 @@ -341,7 +357,7 @@ def matlab(): return d -def test_loss_is_matlabs(matlab): +def test_loss_is_matlabs(matlab) -> None: """MATLAB's reported losses are this loss at MATLAB's solutions.""" m = matlab lam = PARAMS.lam @@ -373,9 +389,11 @@ def test_loss_is_matlabs(matlab): ) -def test_fits_reach_matlabs_loss_or_lower(matlab): - """Each fit, started from MATLAB's inputs, ends at a loss no higher - than MATLAB's (whose fits stop at iteration caps or tolerances).""" +def test_fits_reach_matlabs_loss_or_lower(matlab) -> None: + """Each fit, started from MATLAB's inputs, ends at a loss no higher than MATLAB's. + + MATLAB's fits stop at iteration caps or tolerances. + """ m = matlab lam = PARAMS.lam s, info = sf.fit_activity( diff --git a/tests/raster/test_raster_solver_setup.py b/tests/raster/test_raster_solver_setup.py index 9d84a56a..9c036ab6 100644 --- a/tests/raster/test_raster_solver_setup.py +++ b/tests/raster/test_raster_solver_setup.py @@ -36,7 +36,7 @@ PARAMS_B = SolverParams() -def _close(a, b, tol=1e-13): +def _close(a, b, tol=1e-13) -> None: """Largest difference relative to the largest reference value.""" a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) assert a.shape == b.shape @@ -44,9 +44,8 @@ def _close(a, b, tol=1e-13): @pytest.mark.parametrize("name, params", [("a", PARAMS_A), ("b", PARAMS_B)]) -def test_filters_match_matlab(name, params): - """Footprint filter, surround filters and kernels of - setParamsExtractTrial.""" +def test_filters_match_matlab(name, params) -> None: + """Footprint filter, surround filters and kernels of setParamsExtractTrial.""" with h5py.File(HELPERS, "r") as f: g = f["params"][name] _close(params.hfilter, g["Hfilter"][()]) @@ -59,9 +58,11 @@ def test_filters_match_matlab(name, params): assert params.denoise_window == g["denoiseWindow_samps"][()] -def test_kernel_and_windows(): - """The kernel is causal, sums to 1 and peaks at its centre; the windows - follow MATLAB's rounding.""" +def test_kernel_and_windows() -> None: + """The kernel is causal, sums to 1 and peaks at its centre. + + The windows follow MATLAB's rounding. + """ k = temporal_kernel(4.8) n = int(np.ceil(6 * 4.8)) assert k.size == 2 * n + 1 @@ -76,7 +77,7 @@ def test_kernel_and_windows(): assert SolverParams(tau_full=7.0).tau_frames == 7.0 -def test_params_reject_bad_values(): +def test_params_reject_bad_values() -> None: """Values the solver cannot run with are refused.""" with pytest.raises(ValueError, match="debias_variance"): SolverParams(debias_variance="other") @@ -107,9 +108,8 @@ def test_params_reject_bad_values(): ) -def test_initial_footprints_match_matlab(): - """Starting footprints, also for sources at the map's edge and next - to an unselected pixel.""" +def test_initial_footprints_match_matlab() -> None: + """Starting footprints, also for sources at the map's edge and next to an unselected pixel.""" with h5py.File(HELPERS, "r") as f: g = f["foot"] sel = g["selPix"][()].astype(bool) @@ -120,7 +120,7 @@ def test_initial_footprints_match_matlab(): assert np.array_equal(valid, g["Hvalid"][()].astype(bool)) -def test_sel_coords_are_column_major(): +def test_sel_coords_are_column_major() -> None: """Pixels are listed as MATLAB's find(sel) lists them.""" sel = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool) rows, cols = sel_coords(sel) @@ -128,9 +128,11 @@ def test_sel_coords_are_column_major(): assert cols.tolist() == [0, 0, 1, 2] -def test_conv_operator_is_same_convolution(): - """The operator equals a 'same' convolution of the map, zero outside - the selected pixels, read at the selected pixels.""" +def test_conv_operator_is_same_convolution() -> None: + """The operator equals a 'same' convolution of the map, zero outside the selected pixels. + + It is read at the selected pixels. + """ rng = np.random.default_rng(0) sel = rng.random((9, 11)) < 0.7 rows, cols = sel_coords(sel) @@ -148,7 +150,7 @@ def test_conv_operator_is_same_convolution(): np.testing.assert_allclose(got, same[rows, cols], atol=1e-13) -def test_subproblem_checks_its_arrays(): +def test_subproblem_checks_its_arrays() -> None: """A subproblem whose arrays do not fit together is refused.""" sel = np.ones((3, 3), dtype=bool) y = np.zeros((1, 9, 20), np.float32) @@ -166,8 +168,8 @@ def test_subproblem_checks_its_arrays(): Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1], [1, 1]]) -def _write_matlab_params(g, params: SolverParams, **extra): - """A MATLAB params struct as a v7.3 file holds it.""" +def _write_matlab_params(g, params: SolverParams, **extra) -> None: + """Write a MATLAB params struct as a v7.3 file holds it.""" fields = dict( analyzeHz=params.analyze_hz, tau_s=params.tau_s, @@ -219,10 +221,12 @@ def _write_matlab_subproblem(folder, y, finv, sel, rc, params, row0, col0): return folder / "sub_001.mat" -def test_load_matlab_subproblem(tmp_path): - """A saved subproblem is read in the port's convention: channels x - pixels x frames, zero-based sources, pixel indices in the trial's - list, and its parameters.""" +def test_load_matlab_subproblem(tmp_path) -> None: + """A saved subproblem is read in the port's convention. + + Channels x pixels x frames, zero-based sources, pixel indices in the + trial's list, and its parameters. + """ rng = np.random.default_rng(1) sel = np.ones((4, 5), dtype=bool) sel[0, 0] = sel[3, 4] = False @@ -257,9 +261,11 @@ def test_load_matlab_subproblem(tmp_path): assert load_matlab_subproblem(path, np.float32)[0].y.dtype == np.float32 -def test_trial_file_of_another_trial_is_refused(tmp_path): - """A trial.mat that does not select every pixel of the subproblem - cannot give its pixel indices.""" +def test_trial_file_of_another_trial_is_refused(tmp_path) -> None: + """A trial.mat that does not select every pixel of the subproblem is refused. + + It cannot give the subproblem's pixel indices. + """ sel = np.ones((3, 3), dtype=bool) path = _write_matlab_subproblem( tmp_path, @@ -283,9 +289,11 @@ def test_trial_file_of_another_trial_is_refused(tmp_path): load_matlab_subproblem(path) -def test_single_channel_subproblem_without_trial_file(tmp_path): - """One channel is saved as a 2-D array; without trial.mat the pixel - indices are unknown.""" +def test_single_channel_subproblem_without_trial_file(tmp_path) -> None: + """One channel is saved as a 2-D array. + + Without trial.mat the pixel indices are unknown. + """ sel = np.ones((2, 3), dtype=bool) y = np.arange(6 * 7, dtype=np.float64).reshape(1, 6, 7) path = _write_matlab_subproblem( @@ -307,7 +315,7 @@ def test_single_channel_subproblem_without_trial_file(tmp_path): assert sub.pixels is None -def test_params_warn_when_saved_filters_differ(tmp_path): +def test_params_warn_when_saved_filters_differ(tmp_path) -> None: """A saved kernel that the scalar parameters do not give is reported.""" with h5py.File(tmp_path / "p.mat", "w") as f: g = f.create_group("params") @@ -319,7 +327,7 @@ def test_params_warn_when_saved_filters_differ(tmp_path): assert p == SolverParams(tau_full=4.8, photon_scale=None, valid_kernel=3) -def test_subproblem_fixture_starts_as_matlab(): +def test_subproblem_fixture_starts_as_matlab() -> None: """The fixture's starting footprints are MATLAB's.""" with h5py.File(SUBPROBLEM, "r") as f: sel = f["in/sel"][()].astype(bool) @@ -331,9 +339,11 @@ def test_subproblem_fixture_starts_as_matlab(): assert np.array_equal(valid, f["init/Hvalid"][()].astype(bool)) -def test_valid_kernel_widens_the_support_only(): - """A larger validKernel widens where Hs may go, nothing else; a source - at the crop's edge gets the part of the square inside it.""" +def test_valid_kernel_widens_the_support_only() -> None: + """A larger validKernel widens where Hs may go, nothing else. + + A source at the crop's edge gets the part of the square inside it. + """ sel = np.ones((15, 15), dtype=bool) rc = np.array([[7, 7], [0, 1]]) hs3, h3, v3 = initial_footprints(sel, rc, 1.33) @@ -349,13 +359,13 @@ def test_valid_kernel_widens_the_support_only(): @pytest.mark.parametrize("bad", [0, 2, 4, -3, 3.0, True]) -def test_valid_kernel_must_be_odd_and_positive(bad): +def test_valid_kernel_must_be_odd_and_positive(bad) -> None: """An even, non-positive or non-integer side is rejected.""" with pytest.raises(ValueError, match="valid_kernel"): SolverParams(valid_kernel=bad) -def test_valid_kernel_from_matlab(): +def test_valid_kernel_from_matlab() -> None: """params_from_matlab reads validKernel's side; 3 without one.""" with h5py.File("vk.h5", "w", driver="core", backing_store=False) as f: assert params_from_matlab(f.create_group("none")).valid_kernel == 3 diff --git a/tests/raster/test_raster_spots.py b/tests/raster/test_raster_spots.py index 7a917cc4..21eccff5 100644 --- a/tests/raster/test_raster_spots.py +++ b/tests/raster/test_raster_spots.py @@ -1,5 +1,8 @@ -"""The spot annotation (GIAnT-Python#51 follow-up): spots of linked -sources, their tests and labels, and the annotation collect writes.""" +"""The spot annotation (GIAnT-Python#51 follow-up). + +Spots of linked sources, their tests and labels, and the annotation collect +writes. +""" import json import warnings @@ -24,7 +27,7 @@ ) -def test_link_groups(): +def test_link_groups() -> None: """Single linkage within link_px; sources without a position alone.""" rc = np.array( [[0, 0], [0, 2], [0, 4.2], [10, 10], [np.nan, np.nan], [30, 30]] @@ -36,7 +39,7 @@ def test_link_groups(): assert sp.link_groups(np.zeros((0, 2)), 2.5).size == 0 -def test_event_train_corr(): +def test_event_train_corr() -> None: """Shared events correlate; independent ones do not; one train: NaN.""" rng = np.random.default_rng(0) a = (rng.random(5000) < 0.01).astype(float) @@ -47,9 +50,11 @@ def test_event_train_corr(): def _movie(pos, n=600, rate=0.03, amp=40.0, noise=2.0, seed=1): - """A 15 x 15 window: Gaussian events (sigma 1.4) at positions ``pos`` - (one drawn per event), white noise; returns x (frames, pixels), rows, - cols and the event frames.""" + """Simulate a 15 x 15 window of Gaussian events and white noise. + + Gaussian events (sigma 1.4) at positions ``pos`` (one drawn per event), + white noise; returns x (frames, pixels), rows, cols and the event frames. + """ rng = np.random.default_rng(seed) rr, cc = np.meshgrid(np.arange(15.0), np.arange(15.0), indexing="ij") rr, cc = rr.ravel(), cc.ravel() @@ -65,9 +70,11 @@ def _movie(pos, n=600, rate=0.03, amp=40.0, noise=2.0, seed=1): return x, rr, cc, frames -def test_localize_events_finds_and_places_events(): - """Strong events are found at their frames and placed within a fraction - of a pixel; weak noise yields none.""" +def test_localize_events_finds_and_places_events() -> None: + """Strong events are found at their frames and placed within a fraction of a pixel. + + Weak noise yields none. + """ x, rr, cc, frames = _movie([(7.3, 6.6)]) ev = sp.localize_events(x, rr, cc, (7.0, 7.0), 4.0, sp.SpotSettings()) assert ev["frame"].size >= 0.9 * frames.size @@ -79,7 +86,7 @@ def test_localize_events_finds_and_places_events(): assert none["frame"].size <= 2 -def test_mixture_fit_counts_clusters(): +def test_mixture_fit_counts_clusters() -> None: """Two clusters 3 px apart give K = 2; one cluster K = 1.""" rng = np.random.default_rng(2) n = 80 @@ -96,7 +103,7 @@ def test_mixture_fit_counts_clusters(): assert np.sort(best.means[:, 1]) == pytest.approx([3.5, 6.5], abs=0.4) -def test_separation_power(): +def test_separation_power() -> None: """Points far apart are always resolved; one point never is.""" n = 60 S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) @@ -106,7 +113,7 @@ def test_separation_power(): assert np.isnan(sp.separation_power([[5, 5]], S, 0.0, (5, 5))) -def test_event_test_and_labels(): +def test_event_test_and_labels() -> None: """The event test on canvas positions, and the labels' precedence.""" st = sp.SpotSettings(n_sim=6) rng = np.random.default_rng(3) @@ -133,9 +140,12 @@ def test_event_test_and_labels(): assert sp.spot_label(2, 0.0, dict(wide, power=0.5), st) == "undecided" -def test_summary_warp_matches_the_plan(): - """The maps a summary records give the plan's warp: rigid, affine and - patchwise (its displacement field sampled on the canvas).""" +def test_summary_warp_matches_the_plan() -> None: + """The maps a summary records give the plan's warp. + + Rigid, affine and patchwise (its displacement field sampled on the + canvas). + """ a = np.array( [[[1.0, 0, 0.5], [0, 1, -1.0]], [[1.0, 0.02, 0], [0, 0.98, 2]]] ) @@ -152,10 +162,12 @@ def test_summary_warp_matches_the_plan(): np.testing.assert_allclose(got[1], [3.0 * 0.95, 12.25 * 0.95]) -def test_collect_writes_the_annotation(tmp_path, fake): # noqa: F811 - """Every run's summary gets each kept source's spot and each spot's - label; with empty movies the event test is skipped (a warning) and the - spots keep the correlation test; silo-spots writes it again.""" +def test_collect_writes_the_annotation(tmp_path, fake) -> None: # noqa: F811 + """Every run's summary gets each kept source's spot and each spot's label. + + With empty movies the event test is skipped (a warning) and the spots + keep the correlation test; silo-spots writes it again. + """ table = make_session(tmp_path / "s") params = SiloParams(min_kinetic_score=0.0, spot_link_px=4.0) with warnings.catch_warnings(record=True) as w: @@ -191,7 +203,7 @@ def test_collect_writes_the_annotation(tmp_path, fake): # noqa: F811 assert tuple(labels) == sp.LABELS -def test_spot_params(): +def test_spot_params() -> None: """Defaults and checks of the spot settings.""" p = SiloParams() assert (p.spot_link_px, p.spot_split_corr, p.spot_min_power) == ( @@ -213,9 +225,8 @@ def test_spot_params(): assert PARAMS.spot_event_test -def test_event_tests_in_a_pool_agree(): - """Event tests in spawned workers give the serial results (one seed - per spot).""" +def test_event_tests_in_a_pool_agree() -> None: + """Event tests in spawned workers give the serial results (one seed per spot).""" from giant_python.pipeline.silo_spots import _event_tests, _pool rng = np.random.default_rng(5) @@ -240,18 +251,19 @@ def test_event_tests_in_a_pool_agree(): assert _pool(1) is None -def test_few_events_are_not_fitted(): - """Fewer than MIN_FIT_EVENTS events give no cloud, whatever - min_events says.""" +def test_few_events_are_not_fitted() -> None: + """Fewer than MIN_FIT_EVENTS events give no cloud, whatever min_events says.""" st = sp.SpotSettings(min_events=1, n_sim=4) one = dict(r=[10.0], c=[10.0], se_r=[0.2], se_c=[0.2]) src = np.array([[10.0, 9.5], [10.0, 10.5]]) assert sp.event_test(one, src, st) == {"n_events": 1} -def test_tiff_and_hdf5_pixels_agree(tmp_path): - """A movie's pixels read from a TIFF (page by page) and from HDF5 are - the same, NaN outside the image.""" +def test_tiff_and_hdf5_pixels_agree(tmp_path) -> None: + """A movie's pixels read from a TIFF (page by page) and from HDF5 are the same. + + They are NaN outside the image. + """ import tifffile from giant_python.pipeline.silo_spots import _read_pixels @@ -273,7 +285,7 @@ def test_tiff_and_hdf5_pixels_agree(tmp_path): assert _read_pixels(tif, 2, 1, rows, cols, n_frames=2).shape == (2, 5) -def test_missing_movies_warn(): +def test_missing_movies_warn() -> None: """Trials to test without a movie are named in a warning.""" from giant_python.pipeline.silo_spots import _spot_events @@ -283,7 +295,7 @@ class _Session: n_trials = 2 keep = np.ones((1, 2), bool) - def movie(self, d, t): + def movie(self, d, t) -> None: """No movie.""" return None @@ -295,9 +307,11 @@ def movie(self, d, t): assert ev[0]["r"].size == 0 -def test_event_corr_uses_the_activity_channel(tmp_path): - """The summary keeps physical channels: the correlation is the - activity channel's.""" +def test_event_corr_uses_the_activity_channel(tmp_path) -> None: + """The summary keeps physical channels. + + The correlation is the activity channel's. + """ from giant_python.pipeline.silo_spots import _annotate_path rng = np.random.default_rng(7) @@ -321,9 +335,11 @@ def test_event_corr_uses_the_activity_channel(tmp_path): assert list(read_spots(summary, 1)["label"]) == [label] -def test_truncated_files_are_refused(tmp_path): - """A baseline (or movie) without every frame asked for is an error, - not frames left unfilled.""" +def test_truncated_files_are_refused(tmp_path) -> None: + """A baseline (or movie) without every frame asked for is an error. + + Frames are not left unfilled. + """ import tifffile from giant_python.pipeline.silo_spots import _read_pixels @@ -340,9 +356,11 @@ def test_truncated_files_are_refused(tmp_path): _read_pixels(path, 1, 0, [1], [1], n_frames=7) -def test_reannotation_uses_the_recorded_run(tmp_path): - """silo-spots reads the run's own activity channel and annotates the - paths the summary has (here only Path2).""" +def test_reannotation_uses_the_recorded_run(tmp_path) -> None: + """silo-spots reads the run's own activity channel. + + It annotates the paths the summary has (here only Path2). + """ from giant_python.pipeline.silo_spots import annotate_spots rng = np.random.default_rng(8) diff --git a/tests/raster/test_raster_stage_files.py b/tests/raster/test_raster_stage_files.py index 13af766a..f71b4383 100644 --- a/tests/raster/test_raster_stage_files.py +++ b/tests/raster/test_raster_stage_files.py @@ -1,5 +1,7 @@ -"""Tests of the files SILo's stages hand to each other: per-trial -localization files and seeds files.""" +"""Tests of the files SILo's stages hand to each other. + +These are per-trial localization files and seeds files. +""" import h5py import numpy as np @@ -15,7 +17,7 @@ ) -def test_localization_round_trip(tmp_path): +def test_localization_round_trip(tmp_path) -> None: """Images, discards and peaks come back; peaks can be added later.""" rng = np.random.default_rng(0) mean_im = rng.random((6, 7, 2)).astype(np.float32) @@ -52,7 +54,7 @@ def test_localization_round_trip(tmp_path): assert not side.exists() and read_localization(path).peaks is None -def test_localization_format_checks(tmp_path): +def test_localization_format_checks(tmp_path) -> None: """Other files are refused; a missing file has no attributes.""" with h5py.File(tmp_path / "other.h5", "w") as f: f.attrs["format"] = "other" @@ -76,7 +78,7 @@ def test_localization_format_checks(tmp_path): read_localization(path) -def test_seeds(tmp_path): +def test_seeds(tmp_path) -> None: """Seeds per path, one-based (MATLAB's thetaf) or zero-based.""" seeds = np.array([[2.0, 10.0, 20.0, 0.5], [1.0, 3.0, 4.0, 0.4]]) write_seeds(tmp_path / "s1.h5", {2: seeds}, index_base=1) @@ -90,7 +92,7 @@ def test_seeds(tmp_path): write_seeds(tmp_path / "bad.h5", {1: seeds}, index_base=2) -def test_recording_ids(tmp_path): +def test_recording_ids(tmp_path) -> None: """A recording's files: CYCLE segments and .meta; a missing one raises.""" from giant_python.pipeline.silo_session import recording_ids diff --git a/tests/raster/test_raster_summary.py b/tests/raster/test_raster_summary.py index 7ae15b11..a615af1c 100644 --- a/tests/raster/test_raster_summary.py +++ b/tests/raster/test_raster_summary.py @@ -1,5 +1,7 @@ -"""Tests of SILo's summaries in GIAnT-MATLAB's schema -(saveExperimentSummaryH5, savePerTrialSummaryH5).""" +"""Tests of SILo's summaries in GIAnT-MATLAB's schema. + +saveExperimentSummaryH5, savePerTrialSummaryH5. +""" import h5py import numpy as np @@ -31,7 +33,7 @@ def make_plan(): - """A plan of four sources on a 14 x 18 frame, three trials.""" + """Build a plan of four sources on a 14 x 18 frame, three trials.""" rng = np.random.default_rng(0) rows, cols = np.array([3, 4, 9, 10]), np.array([3, 5, 12, 15]) sel = np.zeros((H, W), bool) @@ -79,7 +81,7 @@ def make_plan(): def outcome(t, n_px, extracted=True): - """A trial's outcome with distinct values per source and channel.""" + """Build a trial's outcome with distinct values per source and channel.""" n = FRAMES[t] rng = np.random.default_rng(t) rec = TrialRecord( @@ -107,7 +109,7 @@ def outcome(t, n_px, extracted=True): def alignment(t): - """A registration record with 5 registered frames over the trial.""" + """Build a registration record with 5 registered frames over the trial.""" ds = np.linspace(100 * t + 1, 100 * t + 1 + FRAMES[t] * 8, 5) return AlignmentRecord( ds_frames=ds, @@ -160,7 +162,7 @@ def sizes(path): out = {} with h5py.File(path, "r") as f: - def visit(name, obj): + def visit(name, obj) -> None: """Record a dataset.""" if isinstance(obj, h5py.Dataset): out[name] = ( @@ -173,7 +175,7 @@ def visit(name, obj): return out -def test_experiment_summary_schema(written): +def test_experiment_summary_schema(written) -> None: """Names, MATLAB sizes and classes of saveExperimentSummaryH5.""" exp, _, _ = written s = sizes(exp) @@ -216,9 +218,11 @@ def test_experiment_summary_schema(written): assert {k: v for k, v in s.items() if k not in params} == want -def test_experiment_summary_values(written): - """Traces at their trials' frames in file channel order; kept sources - only; frame records; ROI traces reordered; profiles averaged.""" +def test_experiment_summary_values(written) -> None: + """Traces at their trials' frames in file channel order. + + Kept sources only; frame records; ROI traces reordered; profiles averaged. + """ exp, _, result = written e = load_struct_h5(exp)["Path1"] o1, o2 = result.trials[1], result.trials[2]() @@ -285,7 +289,7 @@ def test_experiment_summary_values(written): ) -def test_per_trial_summary(written): +def test_per_trial_summary(written) -> None: """Per-trial images, peaks in the consensus frame, footprints.""" _, per, result = written s = sizes(per) @@ -334,9 +338,11 @@ def test_per_trial_summary(written): assert (coords[:, :, 0] == 0).all() and np.isnan(coords[0, :, 1:]).all() -def test_short_trial_and_no_peaks(tmp_path): - """A trial loaded but not extracted adds frames, no sources; without - per-trial peaks the peak fields are left out.""" +def test_short_trial_and_no_peaks(tmp_path) -> None: + """A trial loaded but not extracted adds frames, no sources. + + Without per-trial peaks the peak fields are left out. + """ plan = make_plan() result = PathResult( plan=plan, @@ -361,9 +367,11 @@ def test_short_trial_and_no_peaks(tmp_path): assert "sources" not in p -def test_trial_without_sources_is_nan(tmp_path): - """Frames of a trial loaded but not extracted are NaN in the sources' - traces when other trials have sources.""" +def test_trial_without_sources_is_nan(tmp_path) -> None: + """Frames of a trial loaded but not extracted are NaN in the sources' traces. + + When other trials have sources. + """ plan = make_plan() result = PathResult( plan=plan, @@ -385,7 +393,7 @@ def test_trial_without_sources_is_nan(tmp_path): assert np.isnan(snr[1]).all() -def test_nearest_interpolation(): +def test_nearest_interpolation() -> None: """MATLAB's interp1 'nearest' with 'extrap': ties go right.""" ds = np.array([1.0, 5.0, 9.0]) v = np.array([10.0, 20.0, 30.0]) @@ -395,10 +403,12 @@ def test_nearest_interpolation(): np.testing.assert_array_equal(_nearest(ds[:1], v[:1], [0, 4]), [10, 10]) -def test_evidence_test_removes_weak_sources(tmp_path): - """With min_snr the sources whose SNR averaged over trials is below it - are removed with the kinetics test's, and marked in the summary; the - SNR of a source without one (NaN) does not judge it.""" +def test_evidence_test_removes_weak_sources(tmp_path) -> None: + """With min_snr the sources whose SNR averaged over trials is below it are removed. + + They are removed with the kinetics test's, and marked in the summary; the + SNR of a source without one (NaN) does not judge it. + """ plan = make_plan() result = PathResult( plan=plan, @@ -419,10 +429,12 @@ def test_evidence_test_removes_weak_sources(tmp_path): assert off.weak is None and off.keep.all() -def test_evidence_test_event_rate(tmp_path): - """min_event_rate compares each source's kinetics events per minute of - its frames with the rate, and the summary records the rejected - sources' rates.""" +def test_evidence_test_event_rate(tmp_path) -> None: + """min_event_rate compares each source's kinetics events per minute with the rate. + + Events per minute of its frames; the summary records the rejected + sources' rates. + """ plan = make_plan() result = PathResult( plan=plan, @@ -442,9 +454,11 @@ def test_evidence_test_event_rate(tmp_path): np.testing.assert_array_equal(kin.weak, kin.n_events == 0) -def test_evidence_test_judges_weak_seeds_only(): - """With judge_below the evidence test judges only the sources whose - seed height in the plan's combined image is below it.""" +def test_evidence_test_judges_weak_seeds_only() -> None: + """With judge_below the evidence test judges only the sources seeded below it. + + The sources whose seed height in the plan's combined image is below it. + """ from giant_python.extraction.raster.seeding import seed_heights plan = make_plan() @@ -466,9 +480,11 @@ def test_evidence_test_judges_weak_seeds_only(): assert every.weak.all() and every.seed_height is None -def test_evidence_events_skipped_without_counts(): - """The event criterion judges nothing when the kinetics test cannot - count events (decay under 3 frames); the SNR criterion still does.""" +def test_evidence_events_skipped_without_counts() -> None: + """The event criterion judges nothing when the kinetics test cannot count events. + + Decay under 3 frames; the SNR criterion still does. + """ plan = make_plan() result = PathResult( plan=plan, diff --git a/tests/raster/test_raster_summary_model.py b/tests/raster/test_raster_summary_model.py index dfab9500..b65123e4 100644 --- a/tests/raster/test_raster_summary_model.py +++ b/tests/raster/test_raster_summary_model.py @@ -1,5 +1,8 @@ -"""``ExperimentSummary.from_h5`` / ``to_h5`` on raster SILo's experiment -summary (column-major, GIAnT-MATLAB's layout) and on BandSILo's schema.""" +"""``ExperimentSummary.from_h5`` / ``to_h5`` on raster SILo's and BandSILo's summaries. + +Raster SILo's experiment summary is column-major (GIAnT-MATLAB's layout); +BandSILo's schema is also covered. +""" import dataclasses import json @@ -27,10 +30,10 @@ from giant_python.pipeline.silo_spots import _write as write_spots from .test_raster_summary import ( # noqa: F401 (fixture) - C, FRAMES, - H, N_TRIALS, + C, + H, W, alignment, make_plan, @@ -57,7 +60,7 @@ def _children(a, b, where): return [(x, y, f"{where}[{i}]") for i, (x, y) in enumerate(zip(a, b))] -def _equal(a, b, where="summary"): +def _equal(a, b, where="summary") -> None: """Two models hold the same values (NaN equal to NaN).""" if dataclasses.is_dataclass(a) or isinstance(a, (dict, list, tuple)): for x, y, w in _children(a, b, where): @@ -75,9 +78,12 @@ def _equal(a, b, where="summary"): assert np.array_equal(x, y), where -def test_from_h5_reads_a_raster_summary(written): # noqa: F811 - """A raster summary loads with the dimension order of the README, its - values, its kinetics and rejected sources, and no offlineZshifts.""" +def test_from_h5_reads_a_raster_summary(written) -> None: # noqa: F811 + """A raster summary loads with the dimension order of the README. + + It loads with its values, its kinetics and rejected sources, and no + offlineZshifts. + """ exp, _, result = written s = ExperimentSummary.from_h5(exp) raw = load_struct_h5(exp)["Path1"] @@ -121,9 +127,11 @@ def test_from_h5_reads_a_raster_summary(written): # noqa: F811 assert s.attrs == {} -def test_paths_without_sources_rois_or_depth(tmp_path): - """A path whose sources were all removed, without annotations and an - unknown depth, beside one with sources (in Path2).""" +def test_paths_without_sources_rois_or_depth(tmp_path) -> None: + """A path whose sources were all removed, without annotations and an unknown depth. + + It sits beside one with sources (in Path2). + """ plan = make_plan() n_px = plan.n_pixels @@ -174,9 +182,12 @@ def result(keep): _equal(back.paths[1], some) -def _annotated(exp): - """The written summary with a spot annotation, a baseline image, a - displacement field and root attributes, as raster SILo writes them.""" +def _annotated(exp) -> None: + """Add raster extras to the written summary, as raster SILo writes them. + + The extras are a spot annotation, a baseline image, a displacement field + and root attributes. + """ lab = np.array([0, 1, 0]) # sources 1 and 3 form a spot out = [ sp.SpotResult( @@ -206,9 +217,12 @@ def _annotated(exp): f.attrs["network_baseline"] = json.dumps({"path1_trial0002": {}}) -def test_spot_annotation_and_raster_extras(written): # noqa: F811 - """The spot annotation with its attributes, each source's spot, the - baseline image, the displacement field and the root attributes.""" +def test_spot_annotation_and_raster_extras(written) -> None: # noqa: F811 + """The spot annotation with its attributes, and the summary's raster extras. + + These are each source's spot, the baseline image, the displacement field + and the root attributes. + """ exp, _, _ = written _annotated(exp) s = ExperimentSummary.from_h5(exp) @@ -233,10 +247,12 @@ def test_spot_annotation_and_raster_extras(written): # noqa: F811 assert json.loads(s.attrs["network_baseline"]) == {"path1_trial0002": {}} -def test_raster_round_trip(written, tmp_path): # noqa: F811 - """A raster model written with to_h5 (BandSILo's row-major schema plus - the raster fields) reads back as the same model; to_h5 refuses to add - paths to the column-major file.""" +def test_raster_round_trip(written, tmp_path) -> None: # noqa: F811 + """A raster model written with to_h5 reads back as the same model. + + to_h5 writes BandSILo's row-major schema plus the raster fields, and + refuses to add paths to the column-major file. + """ exp, _, _ = written _annotated(exp) s = ExperimentSummary.from_h5(exp) @@ -252,7 +268,7 @@ def test_raster_round_trip(written, tmp_path): # noqa: F811 def _band_summary(): - """A BandSILo-like model: every band field, no raster field.""" + """Build a BandSILo-like model: every band field, no raster field.""" rng = np.random.default_rng(9) n, frames, ch = 2, 12, 2 sources = [ @@ -325,9 +341,11 @@ def _band_summary(): } -def test_band_schema_unchanged(tmp_path): - """A BandSILo model writes exactly the band datasets (no raster field, - no root attribute) and reads back unchanged.""" +def test_band_schema_unchanged(tmp_path) -> None: + """A BandSILo model writes exactly the band datasets and reads back unchanged. + + It writes no raster field and no root attribute. + """ s = _band_summary() out = tmp_path / "band.h5" s.to_h5(out) @@ -353,7 +371,7 @@ def test_band_schema_unchanged(tmp_path): np.testing.assert_array_equal(p.z_depths, [[12.5]]) -def test_partial_raster_scalars_are_refused(tmp_path): +def test_partial_raster_scalars_are_refused(tmp_path) -> None: """A raster field set for some sources only cannot be written.""" s = _band_summary() s.paths[0].sources[0].kinetic_score = 0.5 @@ -361,7 +379,7 @@ def test_partial_raster_scalars_are_refused(tmp_path): s.to_h5(tmp_path / "x.h5") -def test_raster_round_trip_without_snr(written, tmp_path): # noqa: F811 +def test_raster_round_trip_without_snr(written, tmp_path) -> None: # noqa: F811 """A raster file without SNR (no trial gave one) stays without it.""" exp, _, _ = written with h5py.File(exp, "a") as f: @@ -382,10 +400,11 @@ def test_raster_round_trip_without_snr(written, tmp_path): # noqa: F811 assert np.isnan(f["Path1/sources/temporal/SNR"][()]).all() -def test_raster_path_without_frames(tmp_path): - """A raster path without frames (no trial loaded) has no global trace, - no sources and ROI masks without traces; it is written back and reads - the same.""" +def test_raster_path_without_frames(tmp_path) -> None: + """A raster path without frames (no trial loaded) is written back and reads the same. + + It has no global trace, no sources and ROI masks without traces. + """ plan = make_plan() result = PathResult( plan=plan, @@ -414,9 +433,11 @@ def test_raster_path_without_frames(tmp_path): _equal(ExperimentSummary.from_h5(out), s) -def test_files_without_the_flag_are_refused(tmp_path): - """A nonempty file without /row_major reads as column-major: refused; - a new (empty) file is made row-major.""" +def test_files_without_the_flag_are_refused(tmp_path) -> None: + """A nonempty file without /row_major reads as column-major: refused. + + A new (empty) file is made row-major. + """ old = tmp_path / "old.h5" with h5py.File(old, "w") as f: f["Path1/Z_depths"] = np.zeros((1, 1)) @@ -429,7 +450,7 @@ def test_files_without_the_flag_are_refused(tmp_path): assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 -def test_partial_roi_traces_are_refused(tmp_path): +def test_partial_roi_traces_are_refused(tmp_path) -> None: """ROIs of which only some have a trace cannot be written.""" from giant_python.models.experiment_summary import UserRoi diff --git a/tests/raster/test_raster_trial.py b/tests/raster/test_raster_trial.py index bd4f466f..0273bcc7 100644 --- a/tests/raster/test_raster_trial.py +++ b/tests/raster/test_raster_trial.py @@ -16,9 +16,11 @@ PLAN_FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" -def test_discard_frames_around_a_motion_event(): - """A jump of recNegErr discards it and neighbours above half the - threshold (MATLAB: dilate by ~50 ms, keep above half, close).""" +def test_discard_frames_around_a_motion_event() -> None: + """A jump of recNegErr discards it and neighbours above half the threshold. + + MATLAB: dilate by ~50 ms, keep above half, close. + """ rne = -0.5 + 0.01 * np.random.default_rng(0).standard_normal(800) rne[400:402] += 0.2 # registration error jumps for two frames d = discard_frames(rne, 80.0, motion_thresh=2.0) @@ -29,11 +31,13 @@ def test_discard_frames_around_a_motion_event(): @pytest.mark.parametrize("layout", ["one_series", "page_by_page"]) -def test_load_registered_trial(tmp_path, layout): - """Channels are deinterleaved, pages transposed to MATLAB's rows and - columns, discards set to NaN, the variance factor read. The TIFF may - hold one series of all pages (MATLAB's Fast_BigTiff_Write) or one per - page (GIAnT-Python's registration writes each page on its own).""" +def test_load_registered_trial(tmp_path, layout) -> None: + """Channels are deinterleaved, pages transposed to MATLAB's rows and columns. + + Discards are set to NaN, the variance factor read. The TIFF may hold one + series of all pages (MATLAB's Fast_BigTiff_Write) or one per page + (GIAnT-Python's registration writes each page on its own). + """ tifffile = pytest.importorskip("tifffile") n, rows, cols = 400, 6, 9 # MATLAB rows x cols; n > the 4 s median rng = np.random.default_rng(0) @@ -72,9 +76,12 @@ def test_load_registered_trial(tmp_path, layout): @pytest.mark.parametrize("save_tif", [False, True]) -def test_load_registration_movie(tmp_path, save_tif): - """Movies written by GIAnT-Python's registration, HDF5 (the default) or - TIFF, load as the same frames in MATLAB's rows and columns.""" +def test_load_registration_movie(tmp_path, save_tif) -> None: + """Movies written by GIAnT-Python's registration, HDF5 or TIFF, load alike. + + HDF5 (the default) or TIFF load as the same frames in MATLAB's rows and + columns. + """ if save_tif: pytest.importorskip("tifffile") from giant_python.registration.outputs import MovieWriter @@ -102,9 +109,11 @@ def test_load_registration_movie(tmp_path, save_tif): np.testing.assert_allclose(tr.mean_im[..., 1], 100) -def test_localize_trial_retries_numerical_failures(monkeypatch): - """Any failure of the localization itself is retried with the outer - rows and columns NaN (MATLAB's catch); invalid inputs are not.""" +def test_localize_trial_retries_numerical_failures(monkeypatch) -> None: + """Any failure of the localization itself is retried with the outer rows and columns NaN. + + MATLAB's catch; invalid inputs are not. + """ import giant_python.extraction.raster.trial as trial_mod from giant_python.extraction.raster.localization import ( RasterLocalizationParams, @@ -117,7 +126,7 @@ def test_localize_trial_retries_numerical_failures(monkeypatch): monkeypatch.setattr(trial_mod, "load_registered_trial", lambda *a: fake) seen = [] - def flaky(mov, *args, **kwargs): + def flaky(mov, *args, **kwargs) -> str: """Fails like a numerical error unless the edges are NaN.""" seen.append(bool(np.isnan(mov[:, 0, :]).all())) if not seen[-1]: @@ -138,9 +147,11 @@ def flaky(mov, *args, **kwargs): "num_channels, activity_channel", [(2, 0), (2, 3), (0, 1), (2.0, 1), (2, True), (1, -1)], ) -def test_channel_arguments_checked(tmp_path, num_channels, activity_channel): - """Channel arguments outside 1..num_channels (0 would select the last - channel), or not integers, raise before anything is read.""" +def test_channel_arguments_checked(tmp_path, num_channels, activity_channel) -> None: + """Channel arguments outside 1..num_channels, or not integers, raise before anything is read. + + 0 would select the last channel. + """ with pytest.raises(ValueError, match="channel"): load_registered_trial( tmp_path, @@ -150,7 +161,7 @@ def test_channel_arguments_checked(tmp_path, num_channels, activity_channel): ) -def test_page_count_not_a_multiple_of_channels(tmp_path): +def test_page_count_not_a_multiple_of_channels(tmp_path) -> None: """An incomplete last frame is left out, with a warning.""" tifffile = pytest.importorskip("tifffile") n, rows, cols = 400, 4, 5 @@ -171,9 +182,12 @@ def test_page_count_not_a_multiple_of_channels(tmp_path): assert tr.movie.shape == (n, rows, cols) -def test_trial_halves_match_matlab(): - """trialHalves.m of GIAnT-MATLAB: alternating blocks, then the larger - half's last frames move over until the halves are equal to a frame.""" +def test_trial_halves_match_matlab() -> None: + """trialHalves.m of GIAnT-MATLAB: alternating blocks. + + Then the larger half's last frames move over until the halves are equal + to a frame. + """ cases = { (10, 3): [1, 1, 1, 2, 2, 2, 1, 1, 2, 2], (7, 2): [1, 1, 2, 2, 1, 1, 2], @@ -189,9 +203,11 @@ def test_trial_halves_match_matlab(): assert abs(int((half == 0).sum()) - int((half == 1).sum())) <= 1 -def test_half_mean_images_match_matlab(): - """The half-trial mean images of MATLAB's loadAndProcessTrialAsync on - a small movie with missing pixels (exactly: sums of whole counts).""" +def test_half_mean_images_match_matlab() -> None: + """The half-trial mean images of MATLAB's loadAndProcessTrialAsync. + + On a small movie with missing pixels (exactly: sums of whole counts). + """ with h5py.File(PLAN_FIXTURE, "r") as f: g = f["halves"] stack, half, ref = g["stack"][()], g["half"][()], g["half_ims"][()] @@ -202,9 +218,11 @@ def test_half_mean_images_match_matlab(): np.testing.assert_array_equal(out, ref) -def test_load_registered_trial_half_images(tmp_path): - """Half images are returned only when asked for; their mean is the - trial's mean image where nothing is missing.""" +def test_load_registered_trial_half_images(tmp_path) -> None: + """Half images are returned only when asked for. + + Their mean is the trial's mean image where nothing is missing. + """ n, rows, cols = 120, 5, 6 rng = np.random.default_rng(3) data = rng.poisson(20, (2 * n, cols, rows)).astype(np.float32) @@ -227,10 +245,12 @@ def test_load_registered_trial_half_images(tmp_path): ) -def test_channel_means_equal_the_joint_nanmean(): - """The mean image and the missing pixels, one channel at a time, are - those of ``nanmean`` and ``isnan(...).mean`` over all channels at once, - bit for bit (pixels without samples included).""" +def test_channel_means_equal_the_joint_nanmean() -> None: + """The mean image and the missing pixels, one channel at a time, match the joint ones. + + They are those of ``nanmean`` and ``isnan(...).mean`` over all channels + at once, bit for bit (pixels without samples included). + """ from giant_python.extraction.raster.trial import _channel_means rng = np.random.default_rng(3) diff --git a/tests/raster/test_raster_trial_data.py b/tests/raster/test_raster_trial_data.py index e7f9af13..bfd69cc6 100644 --- a/tests/raster/test_raster_trial_data.py +++ b/tests/raster/test_raster_trial_data.py @@ -70,7 +70,7 @@ def recording(tmp_path_factory): @pytest.fixture(scope="module") def online_recording(tmp_path_factory): - """A recording whose online offsets move the DMD pattern.""" + """Make a recording whose online offsets move the DMD pattern.""" path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" layout = make_layout(path, n_cycles=1400, seed=5) online = online_offsets(layout.total_lines) @@ -80,15 +80,17 @@ def online_recording(tmp_path_factory): class Noiseless: - """Stands in for the generator of ``write_recording``: samples are 20 - times their expected count instead of Poisson draws.""" + """Stands in for the generator of ``write_recording``. - def __init__(self, seed): + Samples are 20 times their expected count instead of Poisson draws. + """ + + def __init__(self, seed) -> None: """Keep a real generator for the other draws.""" self._rng = np.random.Generator(np.random.PCG64(seed)) def poisson(self, lam): - """The expected count, scaled to keep whole-number rounding small.""" + """Return the expected count, scaled to keep whole-number rounding small.""" return np.round(20 * lam) def random(self, n): @@ -98,9 +100,11 @@ def random(self, n): @pytest.fixture(scope="module") def quiet_online_recording(tmp_path_factory): - """A noise-free recording whose online offsets move the DMD pattern: - what varies in its motion-corrected samples is motion-correction - error (as GIAnT-MATLAB's TestCompensatedExtraction).""" + """Make a noise-free recording whose online offsets move the DMD pattern. + + What varies in its motion-corrected samples is motion-correction error + (as GIAnT-MATLAB's TestCompensatedExtraction). + """ from tests.registration import synthetic path = tmp_path_factory.mktemp("rec") / "quiet_DMD1-TRIAL000001.dat" @@ -115,7 +119,7 @@ def quiet_online_recording(tmp_path_factory): # ---------------------------------------------------------------- MATLAB -def test_movmean_matches_smoothdata(ref): +def test_movmean_matches_smoothdata(ref) -> None: """Even, odd and fractional windows are placed as smoothdata's.""" x = ref["mm_x"] for w, want in zip(ref["mm_w"].ravel(), ref["mm_y"]): @@ -129,7 +133,7 @@ def test_movmean_matches_smoothdata(ref): assert np.isnan(movmean(np.full((1, 5), np.nan), 3)).all() -def test_medfilt3_and_labeled_pixels(ref): +def test_medfilt3_and_labeled_pixels(ref) -> None: """medfilt2 is NaN wherever its window holds a NaN; zero padding.""" got = medfilt3(ref["med_in"]) np.testing.assert_array_equal(got, ref["med_out"]) @@ -139,9 +143,11 @@ def test_medfilt3_and_labeled_pixels(ref): assert not labeled_pixels(np.full((4, 4), np.nan)).any() -def test_upsample_motion_matches_interp1_pchip(ref): - """pchip with extrapolation, as interp1; frames without motion left - out; one frame's motion used throughout.""" +def test_upsample_motion_matches_interp1_pchip(ref) -> None: + """Pchip with extrapolation, as interp1. + + Frames without motion left out; one frame's motion used throughout. + """ x, y = ref["pchip_x"].ravel(), ref["pchip_y"].ravel() q = ref["pchip_q"].ravel() got = upsample_motion(x, y, q) @@ -158,7 +164,7 @@ def test_upsample_motion_matches_interp1_pchip(ref): upsample_motion(x, np.full(x.size, np.nan), q) -def test_upsample_discard_and_block_edges(ref): +def test_upsample_discard_and_block_edges(ref) -> None: """A frame is discarded if either registered frame around it is.""" d = ref["disc_in"].ravel() > 0 want = ref["disc_out"].ravel() > 0 @@ -171,7 +177,7 @@ def test_upsample_discard_and_block_edges(ref): np.testing.assert_array_equal(block_edges(10, 600), [0, 10]) -def test_frame_lines_are_ceil_of_matlab_colon(): +def test_frame_lines_are_ceil_of_matlab_colon() -> None: """``ceil(first:dt:last)``, with fractional line ranges.""" lines = frame_lines(1.0, 300974.0, 53.43333333333334) assert lines.size == 5633 and lines[0] == 1 @@ -179,8 +185,8 @@ def test_frame_lines_are_ceil_of_matlab_colon(): np.testing.assert_array_equal(frame_lines(2.5, 20.0, 4.0)[:3], [3, 7, 11]) -def test_roi_svd_trace_matches_matlab(ref): - """nansvd and the component choice of loadTrial.""" +def test_roi_svd_trace_matches_matlab(ref) -> None: + """Nansvd and the component choice of loadTrial.""" d = ref["svd_d"] u, s, v, bg = nansvd(d, 3, 10, 0.33) np.testing.assert_allclose(s, ref["svd_s"].ravel(), rtol=1e-8) @@ -205,10 +211,12 @@ def test_roi_svd_trace_matches_matlab(ref): assert np.isnan(roi_svd_trace(sparse, 0.33)).all() -def test_nansvd_selects_until_the_choice_is_stable(): - """Rows and columns are left out until the choice no longer changes: - leaving a column out can bring a row back, and the rows and columns - kept each miss less than the threshold among the other kept ones.""" +def test_nansvd_selects_until_the_choice_is_stable() -> None: + """Rows and columns are left out until the choice no longer changes. + + Leaving a column out can bring a row back, and the rows and columns + kept each miss less than the threshold among the other kept ones. + """ rng = np.random.default_rng(3) d = rng.standard_normal((8, 30)) + 5 d[0, :12] = np.nan # misses 40%: out, until ... @@ -227,10 +235,12 @@ def test_nansvd_selects_until_the_choice_is_stable(): "dtype, rtol", [(np.float64, 1e-12), (np.float32, 2e-6)] ) @pytest.mark.parametrize("rows", [2, 512]) -def test_finish_pixels_matches_matlab(ref, dtype, rtol, rows): - """Discards, outliers and gap filling as at the end of loadTrial: a - pixel without samples, gaps longer than the window (15 passes over - everything), and the variance multiplier of filled samples.""" +def test_finish_pixels_matches_matlab(ref, dtype, rtol, rows) -> None: + """Discards, outliers and gap filling as at the end of loadTrial. + + A pixel without samples, gaps longer than the window (15 passes over + everything), and the variance multiplier of filled samples. + """ y = ref["fin_y_in"].transpose(1, 0, 2).astype(dtype) # channels first finv = ref["fin_finv_in"].astype(dtype) discard = upsample_discard(ref["fin_discard_in"].ravel() > 0, y.shape[2]) @@ -244,7 +254,7 @@ def test_finish_pixels_matches_matlab(ref, dtype, rtol, rows): assert not np.isnan(y).any() and not np.isnan(finv).any() -def test_finish_pixels_without_gaps_changes_nothing(): +def test_finish_pixels_without_gaps_changes_nothing() -> None: """No discards and no missing samples: data and multiplier are kept.""" rng = np.random.default_rng(0) y = 5 + rng.random((2, 7, 40)) @@ -255,11 +265,12 @@ def test_finish_pixels_without_gaps_changes_nothing(): np.testing.assert_array_equal(finv, f0) -def test_finish_pixels_rejects_what_it_cannot_fill(): - """A window that reaches no frame ahead never fills a gap at the start - (MATLAB's loop would not end), and without any sample there is no - variance multiplier to give: both are errors. No pixels: nothing to - do.""" +def test_finish_pixels_rejects_what_it_cannot_fill() -> None: + """A window that reaches no frame ahead never fills a gap at the start. + + MATLAB's loop would not end; and without any sample there is no variance + multiplier to give: both are errors. No pixels: nothing to do. + """ rng = np.random.default_rng(0) y = 5 + rng.random((2, 4, 30)) finv = 1 + rng.random((4, 30)) @@ -371,9 +382,11 @@ def raster_window(layout): ) -def test_exclusive_boundary_and_pixel_sums(recording): - """The exclusive kernel leaves out the lines exactly max(3 dt, P) from - a frame; PixelFormer's sums are FrameFormer's, pixel by pixel.""" +def test_exclusive_boundary_and_pixel_sums(recording) -> None: + """The exclusive kernel leaves out the lines exactly max(3 dt, P) from a frame. + + PixelFormer's sums are FrameFormer's, pixel by pixel. + """ layout, samples, _ = recording times, dt = np.array([30, 500, 1777, 3480]), 8 num, den = raw_reference(layout, samples, times, dt, [1, 0]) @@ -397,7 +410,7 @@ def test_exclusive_boundary_and_pixel_sums(recording): assert (samples == -32768).any() # some sums leave samples out -def test_pixel_sums_with_shifts_match_shifted_sums(online_recording): +def test_pixel_sums_with_shifts_match_shifted_sums(online_recording) -> None: """Grouped by displacement, as FrameFormer.shifted_sums.""" layout, samples, _, _ = online_recording offsets = line_offsets(layout, (1, layout.total_lines)) @@ -440,9 +453,11 @@ def view_points(layout, step=1): ) -def test_frames_at_matches_definition(recording): - """Frames at whole-pixel and at fractional points, with motion that - crosses whole pixels and takes points off the image.""" +def test_frames_at_matches_definition(recording) -> None: + """Frames at whole-pixel and at fractional points. + + With motion that crosses whole pixels and takes points off the image. + """ layout, samples, _ = recording trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) times, dt = np.arange(200, 3300, 61), 8 @@ -468,9 +483,11 @@ def test_frames_at_matches_definition(recording): assert np.isnan(want[0]).any() and not np.isnan(want[0]).all() -def test_frames_at_points_off_the_raster(recording): - """Points whose neighbours are all outside the image need no sample: - every value is missing.""" +def test_frames_at_points_off_the_raster(recording) -> None: + """Points whose neighbours are all outside the image need no sample. + + Every value is missing. + """ layout, _, _ = recording trim_rows, trim_cols = raster_window(layout) r_d = np.array([-40.0, -41.0, trim_rows.size + 30.0]) @@ -513,9 +530,12 @@ def test_frames_at_points_off_the_raster(recording): assert y.shape == (2, 0, times.size) and fq.shape == (0, times.size) -def test_frames_at_compensated_matches_definition(online_recording): - """With compensation, each line's samples move by its online offset - relative to the block's reference, also past the trimmed raster.""" +def test_frames_at_compensated_matches_definition(online_recording) -> None: + """With compensation, each line's samples move by its online offset. + + The offset is relative to the block's reference; samples move also past + the trimmed raster. + """ layout, samples, _, _ = online_recording offsets = line_offsets(layout, (1, layout.total_lines)) comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) @@ -529,7 +549,7 @@ def test_frames_at_compensated_matches_definition(online_recording): assert pad >= 1 and compensation_pad(None, layout, times, dt) == 0 def shift(line): - """A line's displacement around the block's reference.""" + """Return a line's displacement around the block's reference.""" return ( int(offsets.y_eff[line - 1] - comp_b.ref_offset[1]), int(offsets.x[line - 1] - comp_b.ref_offset[0]), @@ -583,9 +603,12 @@ def shift(line): np.testing.assert_allclose(got[0][inner], other[0][inner], rtol=1e-9) -def test_compensation_helpers(online_recording): - """onlineCompensation: the motion to interpolate is the saved motion - plus each registered frame's offset; blocks take their median.""" +def test_compensation_helpers(online_recording) -> None: + """The helpers of onlineCompensation. + + The motion to interpolate is the saved motion plus each registered + frame's offset; blocks take their median. + """ layout, _, _, (x, y, y_dmd) = online_recording ds = np.arange(100.0, 9000.0, 20.0) ref = np.array([2.0, 0.0]) @@ -691,10 +714,12 @@ def loader_inputs(layout, truth, shift=(0.0, 0.0), ds_step=20): return alignment, sel, mean, [roi_a, roi_b, roi_c], discard, image -def test_load_trial_follows_the_scene(recording, monkeypatch): - """Motion-corrected samples of a static scene are steady and equal the - scene at each pixel's position; traces, discards and filled samples - are as loadTrial makes them.""" +def test_load_trial_follows_the_scene(recording, monkeypatch) -> None: + """Motion-corrected samples of a static scene are steady and equal the scene. + + The scene is taken at each pixel's position; traces, discards and filled + samples are as loadTrial makes them. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) shift = (0.3, -0.4) @@ -810,10 +835,12 @@ def test_load_trial_follows_the_scene(recording, monkeypatch): ) -def test_load_trial_with_a_general_warp(recording, monkeypatch): - """A callable warp is evaluated at every pixel: the same shift given as - a function gives the same data, and an affine map samples the scene at - the mapped positions.""" +def test_load_trial_with_a_general_warp(recording, monkeypatch) -> None: + """A callable warp is evaluated at every pixel. + + The same shift given as a function gives the same data, and an affine + map samples the scene at the mapped positions. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth) @@ -825,7 +852,7 @@ def test_load_trial_with_a_general_warp(recording, monkeypatch): rigid = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) def as_function(r, c): - """The shift as a general coordinate map.""" + """Apply the shift as a general coordinate map.""" return r + shift[0], c + shift[1] general = load_trial(*args, as_function, *rest, dtype=np.float64) @@ -838,7 +865,7 @@ def as_function(r, c): x0 = np.array([12.0, 17.0]) def affine(r, c): - """A stretch and shear about the field's centre, plus a shift.""" + """Apply a stretch and shear about the field's centre, plus a shift.""" p = a @ (np.stack([r, c]) - x0[:, None]) + x0[:, None] return p[0] + 0.25, p[1] - 0.15 @@ -858,11 +885,13 @@ def affine(r, c): def test_load_trial_reads_selected_pixels_beyond_the_frame( recording, monkeypatch -): - """The consensus frame may be larger than a trial's registered frame. A - selected pixel beyond the frame is read where the warp puts it: with a +) -> None: + """The consensus frame may be larger than a trial's registered frame. + + A selected pixel beyond the frame is read where the warp puts it: with a shift of nine rows up it stays on the raster under the motion, and has - data.""" + data. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) shift = (-9.3, 0.2) @@ -883,7 +912,7 @@ def test_load_trial_reads_selected_pixels_beyond_the_frame( ) def as_function(r, c): - """The shift as a general coordinate map.""" + """Apply the shift as a general coordinate map.""" return r + shift[0], c + shift[1] general = load_trial(*args, as_function, *rest, dtype=np.float64) @@ -893,11 +922,13 @@ def as_function(r, c): def test_recording_layout_is_read_once_per_file( recording, monkeypatch, tmp_path -): - """Trials of one recording file (a continuous recording's line - ranges) read its layout once, also when loaded at the same time; a - changed file, another file or a missing one is read again; the loads - are the same as with a layout read every time.""" +) -> None: + """Trials of one recording file read its layout once, also when loaded at the same time. + + The trials are a continuous recording's line ranges. A changed file, + another file or a missing one is read again; the loads are the same as + with a layout read every time. + """ import os import threading from concurrent.futures import ThreadPoolExecutor @@ -907,7 +938,7 @@ def test_recording_layout_is_read_once_per_file( lock = threading.Lock() def counted(path): - """The fake layout, counting reads.""" + """Return the fake layout, counting reads.""" with lock: calls.append(str(path)) return layout @@ -968,10 +999,13 @@ def load(first, last): def test_recording_layout_follows_segments_and_metadata( recording, monkeypatch, tmp_path -): - """A CYCLE-split recording's layout is read again when a segment is - added or removed or its metadata changes, and the path as given is - part of the key (its name decides how the reader opens it).""" +) -> None: + """A CYCLE-split recording's layout is read again when its segments change. + + That is, when a segment is added or removed or its metadata changes. The + path as given is part of the key (its name decides how the reader opens + it). + """ import os layout = recording[0] @@ -1034,9 +1068,11 @@ def test_recording_layout_follows_segments_and_metadata( assert len(calls) == 8 # not the cached layout of folder/first -def test_load_trial_without_selected_pixels(recording, monkeypatch): - """No selected pixel, no ROI and no labeled pixel: empty data, and the - traces are missing. A selection that is never sampled is an error.""" +def test_load_trial_without_selected_pixels(recording, monkeypatch) -> None: + """No selected pixel, no ROI and no labeled pixel: empty data, and the traces are missing. + + A selection that is never sampled is an error. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, _, discard, _ = loader_inputs(layout, truth) @@ -1053,7 +1089,7 @@ def test_load_trial_without_selected_pixels(recording, monkeypatch): load_trial(*args, margin, RigidShift(), discard, mean) -def test_load_trial_rejects_bad_inputs(recording, monkeypatch): +def test_load_trial_rejects_bad_inputs(recording, monkeypatch) -> None: """The activity channel and the mean image must fit the recording.""" layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) @@ -1073,9 +1109,11 @@ def test_load_trial_rejects_bad_inputs(recording, monkeypatch): ) == [1, 0] -def test_load_trial_second_activity_channel(recording, monkeypatch): - """With activityChannel 2, channel 0 of the data is the file's second - channel; the global trace stays in the file's order.""" +def test_load_trial_second_activity_channel(recording, monkeypatch) -> None: + """With activityChannel 2, channel 0 of the data is the file's second channel. + + The global trace stays in the file's order. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) @@ -1107,11 +1145,13 @@ def test_load_trial_second_activity_channel(recording, monkeypatch): def test_load_trial_after_compensated_registration( quiet_online_recording, tmp_path, monkeypatch -): - """Registered with compensateOnline, the loader undoes the online - correction too: samples of the static, noise-free scene vary less than - after an uncompensated registration, none is filled in, and the block - size does not show.""" +) -> None: + """Registered with compensateOnline, the loader undoes the online correction too. + + Samples of the static, noise-free scene vary less than after an + uncompensated registration, none is filled in, and the block size does + not show. + """ layout = quiet_online_recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) @@ -1153,9 +1193,12 @@ def test_load_trial_after_compensated_registration( np.testing.assert_allclose(td.finv, other.finv, rtol=1e-5) -def test_read_alignment_orientation(tmp_path): - """viewR and viewC are read in MATLAB's orientation from files written - column-major (MATLAB, GIAnT-Python) or row-major.""" +def test_read_alignment_orientation(tmp_path) -> None: + """ViewR and viewC are read in MATLAB's orientation. + + This holds for files written column-major (MATLAB, GIAnT-Python) or + row-major. + """ import h5py view_r = np.repeat(np.arange(-2.0, 5.0)[:, None], 4, 1) # 7 x 4 @@ -1181,7 +1224,7 @@ def test_read_alignment_orientation(tmp_path): assert a.align_hz == 80.0 and a.motion_c.shape == (5,) -def test_cuda_matches_cpu(recording): +def test_cuda_matches_cpu(recording) -> None: """Frames agree on CUDA and CPU (skipped without a GPU).""" if not torch.cuda.is_available(): pytest.skip("no CUDA device") diff --git a/tests/registration/test_cli.py b/tests/registration/test_cli.py index 2e7baf91..3d69de98 100644 --- a/tests/registration/test_cli.py +++ b/tests/registration/test_cli.py @@ -17,9 +17,12 @@ ) def test_register_reports_failed_trials( monkeypatch, capsys, failed, names, recorded, code -): - """Flagged trials are listed; a trial that raised makes the exit code - nonzero; a cell without a recording is listed as skipped.""" +) -> None: + """Flagged trials are listed. + + A trial that raised makes the exit code nonzero; a cell without a + recording is listed as skipped. + """ from types import SimpleNamespace from giant_python.io import trial_table @@ -48,7 +51,7 @@ def test_register_reports_failed_trials( @pytest.mark.parametrize( "flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)] ) -def test_register_movie_format(monkeypatch, flags, save_tif): +def test_register_movie_format(monkeypatch, flags, save_tif) -> None: """Registered movies are HDF5 unless ``--tif`` asks for TIFF.""" from types import SimpleNamespace @@ -58,7 +61,7 @@ def test_register_movie_format(monkeypatch, flags, save_tif): seen = {} def fake(table, params, **kwargs): - """A registration that records its parameters and writes nothing.""" + """Fake a registration that records its parameters and writes nothing.""" seen["params"] = params return { "registration_failed": np.array([[False]]), @@ -74,7 +77,7 @@ def fake(table, params, **kwargs): assert seen["params"].save_tif is save_tif -def test_register_movie_formats_exclusive(): +def test_register_movie_formats_exclusive() -> None: """``--tif`` and ``--h5`` cannot be combined.""" with pytest.raises(SystemExit): cli.main(["register", "trial_table.h5", "--tif", "--h5"]) diff --git a/tests/registration/test_compensation.py b/tests/registration/test_compensation.py index 58575815..fc01b398 100644 --- a/tests/registration/test_compensation.py +++ b/tests/registration/test_compensation.py @@ -15,8 +15,8 @@ from .synthetic import make_layout, online_offsets, write_recording -def test_dmd_y_leads_header_switches(): - """y switches 2 lines early, 6 with x, never before the last switch.""" +def test_dmd_y_leads_header_switches() -> None: + """Y switches 2 lines early, 6 with x, never before the last switch.""" x = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 7, 7]) sw = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 @@ -45,7 +45,7 @@ def online_recording(tmp_path_factory): return layout, online, truth -def test_line_offsets_reproduce_dmd_timing(online_recording): +def test_line_offsets_reproduce_dmd_timing(online_recording) -> None: """Headers decode, y_eff equals the generator's DMD y.""" layout, (x, y, y_dmd), _ = online_recording off = line_offsets(layout, (1, layout.total_lines)) @@ -85,7 +85,7 @@ def frames_reference(layout, former_samples, offsets, times, dt, box): return num, den -def test_compensated_frames_match_definition(online_recording): +def test_compensated_frames_match_definition(online_recording) -> None: """Each sample moves by its line's offset minus the frame's.""" from giant_python.io.slap2_raster import read_raster_samples from giant_python.registration.frames import FrameFormer @@ -149,7 +149,7 @@ def total_motion_error(res, adata, truth, header): def test_compensated_registration_recovers_motion( online_recording, tmp_path, monkeypatch -): +) -> None: """Total motion follows the truth with compensation, not without.""" from giant_python.io.hdf5 import load_struct_h5 @@ -178,7 +178,7 @@ def test_compensated_registration_recovers_motion( assert errors[True] < errors[False] / 3 -def test_compensation_on_cuda_matches_cpu(online_recording): +def test_compensation_on_cuda_matches_cpu(online_recording) -> None: """Compensated frames agree on CUDA and CPU (skipped without a GPU).""" if not torch.cuda.is_available(): pytest.skip("no CUDA device") diff --git a/tests/registration/test_curtain.py b/tests/registration/test_curtain.py index 8176cc9f..d8329404 100644 --- a/tests/registration/test_curtain.py +++ b/tests/registration/test_curtain.py @@ -50,14 +50,16 @@ def curtain_recording(tmp_path_factory): def plain(layout): - """The same layout without a curtain.""" + """Return the same layout without a curtain.""" return dataclasses.replace(layout, dmd_curtain=None, line_shear=None) def unlit_by_definition(layout, online, dmd_y=True): - """``(slots, cycles)``: True where the line's offsets (header x, DMD y; - the header's y with ``dmd_y=False``) put the slot's mirror behind the - curtain.""" + """``(slots, cycles)``: True where the slot's mirror is behind the curtain. + + The line's offsets (header x, DMD y; the header's y with ``dmd_y=False``) + put the slot's mirror there. + """ x, y = online[0], online[2] if dmd_y else online[1] p = layout.lines_per_cycle lines = ( @@ -70,7 +72,7 @@ def unlit_by_definition(layout, online, dmd_y=True): ) -def test_curtain_from_metadata(): +def test_curtain_from_metadata() -> None: """The acquisition path's curtain and its DMD's line shear.""" shear = np.arange(4.0) meta = types.SimpleNamespace( @@ -101,9 +103,11 @@ def test_curtain_from_metadata(): assert _dmd_curtain(types.SimpleNamespace(), 4) == (None, None) -def test_lit_mirrors_is_the_softwares_mask(curtain_recording): - """The acquisition software's curtain mask (``makeDmdCurtainMask``), - written out mirror by mirror.""" +def test_lit_mirrors_is_the_softwares_mask(curtain_recording) -> None: + """The acquisition software's curtain mask (``makeDmdCurtainMask``). + + Written out mirror by mirror. + """ layout = curtain_recording[0] n = layout.n_cols want = np.zeros((layout.n_rows, n), dtype=bool) @@ -119,9 +123,11 @@ def test_lit_mirrors_is_the_softwares_mask(curtain_recording): assert last[8] == 41 and last[27] == 39 -def test_unlit_samples_follow_the_offsets(curtain_recording): - """Exactly the samples behind the curtain are found, they hold no light, - and only they are marked invalid.""" +def test_unlit_samples_follow_the_offsets(curtain_recording) -> None: + """Exactly the samples behind the curtain are found. + + They hold no light, and only they are marked invalid. + """ layout, online, _ = curtain_recording n_c = layout.num_cycles want = unlit_by_definition(layout, online) @@ -153,8 +159,11 @@ def test_unlit_samples_follow_the_offsets(curtain_recording): def kernel_hits(layout, unlit, times, reach, pixels): - """``(frames, pixels)``: True where a frame's kernel, ``reach`` lines to - each side, holds an unlit sample of the pixel.""" + """``(frames, pixels)``: True where a frame's kernel holds an unlit sample. + + The kernel reaches ``reach`` lines to each side; True where it holds an + unlit sample of the pixel. + """ p = layout.lines_per_cycle s, c = np.nonzero(unlit) lines = c * p + layout.slot_line[s] @@ -166,10 +175,12 @@ def kernel_hits(layout, unlit, times, reach, pixels): return hit -def test_frames_give_unlit_samples_no_weight(curtain_recording): - """Pixels whose samples in a frame are all behind the curtain are NaN, - pixels with some are the mean of the lit ones, and every other value is - unchanged bit for bit.""" +def test_frames_give_unlit_samples_no_weight(curtain_recording) -> None: + """Pixels whose samples in a frame are all behind the curtain are NaN. + + Pixels with some are the mean of the lit ones, and every other value is + unchanged bit for bit. + """ layout, online, _ = curtain_recording n_c = layout.num_cycles raw = read_raster_samples(layout, (0, n_c)) @@ -201,7 +212,7 @@ def test_frames_give_unlit_samples_no_weight(curtain_recording): assert np.mean(v_mask[:, some] > v_raw[:, some]) > 0.5 -def test_extraction_frames_give_unlit_samples_no_weight(curtain_recording): +def test_extraction_frames_give_unlit_samples_no_weight(curtain_recording) -> None: """SILo's raw frames (``rawFramesAt``) leave out the same samples.""" layout, online, _ = curtain_recording ids = np.unique(layout.slot_pixel) @@ -228,10 +239,12 @@ def test_extraction_frames_give_unlit_samples_no_weight(curtain_recording): assert not np.isnan(before).any() -def test_registration_window_ignores_the_curtain(curtain_recording): - """The registration window is the bounding box of the pixels the first - frame samples, lit or not: a column behind the curtain in that frame - stays in the window.""" +def test_registration_window_ignores_the_curtain(curtain_recording) -> None: + """The registration window is the bounding box of the first frame's pixels. + + Those are the pixels the first frame samples, lit or not: a column behind + the curtain in that frame stays in the window. + """ from giant_python.registration.sources import _window_pixels layout, online, _ = curtain_recording @@ -261,11 +274,13 @@ def test_registration_window_ignores_the_curtain(curtain_recording): def test_registration_leaves_out_the_strip( curtain_recording, tmp_path, monkeypatch -): - """Registration forms its frames without the unlit samples: the strip - is missing from the registered movie, and the motion follows the true - motion (with the dark samples, which move with the offsets, it is off by - 0.2-0.5 px rms in this recording).""" +) -> None: + """Registration forms its frames without the unlit samples. + + The strip is missing from the registered movie, and the motion follows the + true motion (with the dark samples, which move with the offsets, it is off + by 0.2-0.5 px rms in this recording). + """ layout, _, seen = curtain_recording params = multiroi.MultiRoiRegistrationParams(maxshift=6) out = {} @@ -308,12 +323,14 @@ def test_registration_leaves_out_the_strip( def test_reg_stats_follow_the_alignment_file( curtain_recording, tmp_path, monkeypatch -): - """``giant reg-stats`` forms the frames as the registration did: - without the samples behind the curtain where the alignment file records - ``slap2/unlitMasked``, with them in files registered before.""" - from giant_python.registration.stats.io import read_stats, stats_path +) -> None: + """``giant reg-stats`` forms the frames as the registration did. + + Without the samples behind the curtain where the alignment file records + ``slap2/unlitMasked``, with them in files registered before. + """ from giant_python.pipeline.reg_stats import trial_stats + from giant_python.registration.stats.io import read_stats, stats_path layout = curtain_recording[0] monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) diff --git a/tests/registration/test_growth.py b/tests/registration/test_growth.py index d889a8e2..542af8e2 100644 --- a/tests/registration/test_growth.py +++ b/tests/registration/test_growth.py @@ -26,7 +26,7 @@ from .synthetic import make_layout, write_recording -def test_wide_correlation_equals_matrix_form(): +def test_wide_correlation_equals_matrix_form() -> None: """FFT correlation over the padded template equals the GEMM form.""" rng = np.random.default_rng(0) h, w, m = 14, 19, 4 @@ -61,7 +61,7 @@ def test_wide_correlation_equals_matrix_form(): assert (r - m, c - m) == (1, -2) -def test_peak_margin_and_runs(): +def test_peak_margin_and_runs() -> None: """Margin excludes the peak's neighbourhood; runs of True.""" corr = torch.zeros(1, 9, 9, dtype=torch.float64) corr[0, 4, 4] = 1.0 @@ -72,7 +72,7 @@ def test_peak_margin_and_runs(): assert _runs(mask) == [(1, 3), (5, 6), (7, 10)] -def test_template_update_adds_and_removes(): +def test_template_update_adds_and_removes() -> None: """Batch add then remove restores the sums.""" total = torch.ones(3, 3, dtype=torch.float64) * 4 count = torch.ones(3, 3, dtype=torch.float64) @@ -86,7 +86,7 @@ def test_template_update_adds_and_removes(): torch.testing.assert_close(state.count, count) -def test_seeds_from_consensus(): +def test_seeds_from_consensus() -> None: """Seeds are the nearest DS frames, with MATLAB's motion sign.""" init = np.array([105, 300, 501, 700]) ds = np.arange(1, 800, 20) @@ -110,7 +110,7 @@ def plain_recording(tmp_path_factory): return layout, truth -def test_grow_matches_sequential(plain_recording, tmp_path, monkeypatch): +def test_grow_matches_sequential(plain_recording, tmp_path, monkeypatch) -> None: """Growth aligns every frame, like sequential, and saves its record.""" layout, _ = plain_recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) @@ -140,7 +140,7 @@ def test_grow_matches_sequential(plain_recording, tmp_path, monkeypatch): assert qc["seedsAccepted"].item() == g.seeds_accepted -def test_junction_regrows_a_wrong_island(plain_recording, monkeypatch): +def test_junction_regrows_a_wrong_island(plain_recording, monkeypatch) -> None: """An island shifted by 2 px is realigned from its neighbour.""" from giant_python.registration.growth import FrameCache, Grower from giant_python.registration.multiroi import build_template, open_trial @@ -179,14 +179,14 @@ def test_junction_regrows_a_wrong_island(plain_recording, monkeypatch): assert err.max() < 0.2 -def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch): +def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch) -> None: """Seeds that align the last unaligned frame end the sub-round.""" from giant_python.registration.growth import Grower class Frames: """Stands in for a frame cache; only its length is used.""" - def __len__(self): + def __len__(self) -> int: """Five frames.""" return 5 @@ -196,7 +196,7 @@ def __len__(self): grower.motion[:4] = 0.0 grower.root[:4] = 0 - def seed(ks): + def seed(ks) -> None: """Align the candidates, as an accepted wide search would.""" grower.aligned[ks] = True grower.motion[ks] = 0.0 @@ -209,9 +209,10 @@ def seed(ks): def test_growth_handles_a_frame_without_valid_samples( plain_recording, monkeypatch -): - """Inside the grower, a frame whose correlation is undefined keeps its - anchor's motion and does not stop a realignment chain. +) -> None: + """Inside the grower, a frame whose correlation is undefined keeps its anchor's motion. + + It does not stop a realignment chain. (``register_grow`` leaves frames without samples out beforehand; this covers frames whose correlation is undefined for other reasons.) @@ -244,9 +245,11 @@ def test_growth_handles_a_frame_without_valid_samples( assert np.isnan(peak[0]) -def test_consensus_seeds_stay_within_maxshift(plain_recording, monkeypatch): - """Seeds start inside the padded template even when the consensus - motion (up to ``init_search``) exceeds ``maxshift``.""" +def test_consensus_seeds_stay_within_maxshift(plain_recording, monkeypatch) -> None: + """Seeds start inside the padded template even when the consensus motion exceeds ``maxshift``. + + The consensus motion goes up to ``init_search``. + """ from giant_python.registration.growth import FrameCache, Grower from giant_python.registration.multiroi import build_template, open_trial from giant_python.registration.sources import make_source @@ -267,7 +270,7 @@ def test_consensus_seeds_stay_within_maxshift(plain_recording, monkeypatch): assert grower.aligned[10] and np.all(np.isfinite(grower.motion[10])) -def test_seed_candidates_are_listed_once(): +def test_seed_candidates_are_listed_once() -> None: """Initial frames nearest the same DS frame give one candidate.""" init = np.array([2, 4, 6, 105]) ds = np.arange(1, 200, 20) @@ -278,9 +281,8 @@ def test_seed_candidates_are_listed_once(): assert seeds == [(5, 0, 0)] and cands == [0] -def test_a_seed_tried_twice_is_added_once(plain_recording, monkeypatch): - """A frame passed twice to the wide search adds one contribution to - the template, not two.""" +def test_a_seed_tried_twice_is_added_once(plain_recording, monkeypatch) -> None: + """A frame passed twice to the wide search adds one contribution to the template, not two.""" from giant_python.registration.growth import FrameCache, Grower from giant_python.registration.multiroi import build_template, open_trial from giant_python.registration.sources import make_source diff --git a/tests/registration/test_kernels.py b/tests/registration/test_kernels.py index 0f813e7e..964b27c6 100644 --- a/tests/registration/test_kernels.py +++ b/tests/registration/test_kernels.py @@ -96,7 +96,7 @@ def random_frame(rng, h=18, w=23, frac=0.4): @pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) -def test_correlation_map_matches_matlab_loop(dtype): +def test_correlation_map_matches_matlab_loop(dtype) -> None: """Weighted NCC equals the MATLAB loop at every shift.""" rng = np.random.default_rng(0) frame, fresh, template = random_frame(rng) @@ -117,7 +117,7 @@ def test_correlation_map_matches_matlab_loop(dtype): np.testing.assert_allclose(got, want, atol=tol) -def test_match_recovers_shift_with_subpixel_sign(): +def test_match_recovers_shift_with_subpixel_sign() -> None: """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" rng = np.random.default_rng(1) frame, fresh, template = random_frame(rng, frac=0.0) @@ -137,7 +137,7 @@ def test_match_recovers_shift_with_subpixel_sign(): assert peak[0] > 0.9 -def test_frame_without_valid_samples_has_nan_motion(): +def test_frame_without_valid_samples_has_nan_motion() -> None: """An undefined correlation map gives NaN motion, not a search edge. The other frame of the batch is unaffected, and ``match`` raises. @@ -168,9 +168,12 @@ def test_frame_without_valid_samples_has_nan_motion(): match(frames, weights, *args) -def test_motion_failed_needs_two_frames_with_motion(): - """Missing frames are left out of the SD; a trial of several frames - with fewer than two with motion fails (SILo cannot interpolate it).""" +def test_motion_failed_needs_two_frames_with_motion() -> None: + """Missing frames are left out of the SD. + + A trial of several frames with fewer than two with motion fails (SILo + cannot interpolate it). + """ from giant_python.registration.multiroi import motion_failed nan = np.nan @@ -188,7 +191,7 @@ def test_motion_failed_needs_two_frames_with_motion(): @pytest.mark.parametrize( "mr,mc", [(0.0, 0.0), (0.3, -0.7), (-1.25, 2.5), (3.0, -0.4), (30, 2)] ) -def test_interp_frame_matches_matlab(mr, mc): +def test_interp_frame_matches_matlab(mr, mc) -> None: """Resampling equals interpFrame, including NaN and edge behaviour.""" rng = np.random.default_rng(2) frame, fresh, _ = random_frame(rng) @@ -207,7 +210,7 @@ def test_interp_frame_matches_matlab(mr, mc): np.testing.assert_allclose(v.numpy(), want_v, rtol=1e-5) -def test_matlab_helpers(): +def test_matlab_helpers() -> None: """MATLAB rounding, colon and 2 x 2 downsampling semantics.""" np.testing.assert_array_equal( matlab_round([-2.5, -0.5, 0.5, 1.5, 2.4]), [-3, -1, 1, 2, 2] @@ -221,7 +224,7 @@ def test_matlab_helpers(): assert y[1, 2] == x[2, 4] + x[2, 5] + x[3, 4] + x[3, 5] -def test_rec_neg_err_matches_definition(): +def test_rec_neg_err_matches_definition() -> None: """Template excess over frames, with MATLAB's NaN handling.""" rng = np.random.default_rng(3) movie = rng.random((30, 6, 7)).astype(np.float32) * 20 @@ -241,8 +244,8 @@ def test_rec_neg_err_matches_definition(): np.testing.assert_allclose(err[k], np.sqrt(num / den), rtol=1e-5) -def test_template_state_matches_matlab_rules(): - """sqrt of the mean, NaN below min_samples, and the T0 average.""" +def test_template_state_matches_matlab_rules() -> None: + """Sqrt of the mean, NaN below min_samples, and the T0 average.""" total = torch.tensor([[4.0, 9.0], [0.0, 1.0]], dtype=torch.float64) count = torch.tensor([[1.0, 1.0], [0.0, 1.0]], dtype=torch.float64) t0 = torch.tensor([[1.0, float("nan")], [3.0, float("nan")]]) diff --git a/tests/registration/test_reg_stats.py b/tests/registration/test_reg_stats.py index 22fced68..e5bf2fb6 100644 --- a/tests/registration/test_reg_stats.py +++ b/tests/registration/test_reg_stats.py @@ -1,6 +1,7 @@ """Registration summary statistics (``registration.stats``).""" from pathlib import Path +from typing import NoReturn import h5py import numpy as np @@ -8,7 +9,7 @@ import torch from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import read_raster_samples +from giant_python.io.slap2_raster import RasterLayout, read_raster_samples from giant_python.registration import multiroi from giant_python.registration.frames import FrameFormer from giant_python.registration.interpolation import interp_frame @@ -21,7 +22,6 @@ read_stats, stats_path, ) -from giant_python.io.slap2_raster import RasterLayout from giant_python.registration.stats.gain import ( curve_from_sums, next_slots, @@ -35,8 +35,7 @@ ) from giant_python.registration.stats.session import combine_trials -from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout -from .synthetic import write_recording +from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout, write_recording MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" ADATA = "E1T1DMD1_ALIGNMENTDATA.h5" @@ -53,7 +52,7 @@ def recording(tmp_path_factory): @pytest.fixture def patched(recording, monkeypatch): - """The recording's layout, read by registration.""" + """Patch registration to read the recording's layout.""" monkeypatch.setattr(multiroi, "raster_layout", lambda path: recording) return recording @@ -84,7 +83,7 @@ def _motion(n, seed=0, jump=None): def _registered(source, ds, motion, margin): - """Registered frames and variance factors (``interp_frame``).""" + """Yield registered frames and variance factors (``interp_frame``).""" vals, fresh = source.frames(ds) win = source.window for k in range(ds.size): @@ -102,8 +101,10 @@ def _registered(source, ds, motion, margin): def _coefficients(layout, source, ds, motion, margin, t, p): - """Sample coefficients of registered frame ``t`` at output pixel ``p`` - by the definition (slow loops).""" + """Sample coefficients of registered frame ``t`` at output pixel ``p`` by the definition. + + This uses slow loops. + """ win = source.window w_out = win.shape[1] + 2 * margin ids = source.former.pixels[source.pixels.numpy()] @@ -134,7 +135,7 @@ def _coefficients(layout, source, ds, motion, margin, t, p): return out -def test_geometry_matches_definition(recording): +def test_geometry_matches_definition(recording) -> None: """Photon-noise sums equal sums over the samples' coefficients.""" layout = recording samples = read_raster_samples(layout, (0, layout.num_cycles)) @@ -172,7 +173,7 @@ def test_geometry_matches_definition(recording): def _compound_poisson(rate, rng, k=5.0, theta=22.0): - """Samples: sums of Poisson(rate) integer gamma pulses (int16).""" + """Draw samples: sums of Poisson(rate) integer gamma pulses (int16).""" n = rng.poisson(rate) out = np.zeros(rate.shape) for j in range(int(n.max())): @@ -182,9 +183,12 @@ def _compound_poisson(rate, rng, k=5.0, theta=22.0): def scan_layout(path: Path, n_cycles: int) -> RasterLayout: - """A raster scanned row by row: line ``r + 2`` samples row ``8 + r``, - columns 10-39 from left to right (so consecutive samples on a line are - horizontal neighbours); line 1 has no samples.""" + """Build a raster scanned row by row. + + Line ``r + 2`` samples row ``8 + r``, columns 10-39 from left to right + (so consecutive samples on a line are horizontal neighbours); line 1 has + no samples. + """ n_rows, n_cols, n_ch, rows = 36, 50, 2, 20 p = rows + 1 slot_line, slot_pos, slot_pixel = [], [], [] @@ -220,9 +224,11 @@ def scan_layout(path: Path, n_cycles: int) -> RasterLayout: def _shared_pulses(rate, nxt, rng, p_split=0.35, k=5.0, theta=22.0): - """Compound-Poisson samples whose pulses are sometimes shared with the - next sample on the line: with probability ``p_split`` a fraction - ``U(0, 0.5)`` of a pulse goes to the next sample.""" + """Draw compound-Poisson samples whose pulses are sometimes shared with the next sample. + + With probability ``p_split`` a fraction ``U(0, 0.5)`` of a pulse goes to + the next sample on the line. + """ n = rng.poisson(rate) out = np.zeros(rate.shape) has = nxt >= 0 @@ -237,9 +243,11 @@ def _shared_pulses(rate, nxt, rng, p_split=0.35, k=5.0, theta=22.0): return out.astype(np.int16) -def test_gain_groups_without_zeros_keep_their_gains(): - """Bright groups that have no zero sample keep their gains; the - non-zero rate comes from the groups that have zeros.""" +def test_gain_groups_without_zeros_keep_their_gains() -> None: + """Bright groups that have no zero sample keep their gains. + + The non-zero rate comes from the groups that have zeros. + """ rng = np.random.default_rng(4) rate = np.repeat(np.geomspace(0.05, 60, 320)[:, None], 2000, 1) x = (100 * rng.poisson(rate)).astype(np.int16) @@ -258,10 +266,11 @@ def test_gain_groups_without_zeros_keep_their_gains(): assert np.isnan(curve.at(np.nan)["g2"]) -def test_gain_sums_do_not_overflow(): - """Cubes of extreme second differences over a long trial would - overflow int64; those sums are float64 then (and exact int64 for - ordinary trials).""" +def test_gain_sums_do_not_overflow() -> None: + """Cubes of extreme second differences over a long trial would overflow int64. + + Those sums are float64 then (and exact int64 for ordinary trials). + """ x = np.zeros((2, 150_000), dtype=np.int16) x[:, ::3] = 32767 # d = 65534, -32767, -32767: cubes sum to > 2^63 got = slot_sums(torch.from_numpy(x[None]), 0) @@ -277,9 +286,11 @@ def test_gain_sums_do_not_overflow(): np.testing.assert_allclose(curve.g3, 3e18 / (6 * 980), rtol=1e-12) -def test_components_of_tall_and_wide_inputs(): - """The top components equal numpy's SVD whichever Gram matrix is - smaller (more time bins than spatial bins, or fewer).""" +def test_components_of_tall_and_wide_inputs() -> None: + """The top components equal numpy's SVD whichever Gram matrix is smaller. + + That is, with more time bins than spatial bins, or fewer. + """ from giant_python.registration.stats.svd import _components rng = np.random.default_rng(9) @@ -304,9 +315,11 @@ def test_components_of_tall_and_wide_inputs(): np.testing.assert_allclose(s, [np.linalg.norm(a) * np.linalg.norm(b)]) -def test_regression_weights_of_undetermined_pixels(): - """A pixel whose valid bins leave a time course flat gets NaN weights - (not an error); the others are fitted.""" +def test_regression_weights_of_undetermined_pixels() -> None: + """A pixel whose valid bins leave a time course flat gets NaN weights (not an error). + + The others are fitted. + """ from giant_python.registration.stats.svd import regression_weights rng = np.random.default_rng(8) @@ -322,7 +335,7 @@ def test_regression_weights_of_undetermined_pixels(): assert np.isnan(w[1]).all() -def test_gain_curve_of_compound_poisson(): +def test_gain_curve_of_compound_poisson() -> None: """Gains equal E[A^2]/E[A] and E[A^3]/E[A] of the pulse heights.""" rng = np.random.default_rng(3) rate = np.repeat(np.geomspace(0.03, 3, 1600)[:, None], 3000, 1) @@ -362,8 +375,10 @@ def _interior(maps): @pytest.fixture(scope="module") def uniform(tmp_path_factory): - """A uniform scene of compound-Poisson samples (0.05 and 2 photons - per sample in the two channels; no file needed).""" + """Simulate a uniform scene of compound-Poisson samples. + + 0.05 and 2 photons per sample in the two channels; no file needed. + """ path = tmp_path_factory.mktemp("uni") / "uniform_DMD1-TRIAL000001.dat" layout = make_layout(path, n_cycles=1600) rng = np.random.default_rng(5) @@ -372,10 +387,12 @@ def uniform(tmp_path_factory): return layout, _compound_poisson(rate, rng), rate -def test_photon_noise_maps_read_zero(uniform): - """Under photon noise alone the normalised maps are 0 at any - brightness (means over pixels: a variance from few blocks is unbiased - but its median is low, as for chi-square).""" +def test_photon_noise_maps_read_zero(uniform) -> None: + """Under photon noise alone the normalised maps are 0 at any brightness. + + Means over pixels: a variance from few blocks is unbiased but its median + is low, as for chi-square. + """ layout, samples, _ = uniform res = _stats(layout, samples, last=11000.0) maps = res["maps"] @@ -396,7 +413,7 @@ def test_photon_noise_maps_read_zero(uniform): assert res["svd"]["var_share"].shape == (2, 3) -def test_events_raise_fast_skewness(uniform): +def test_events_raise_fast_skewness(uniform) -> None: """Positive transients raise the fast maps where they are.""" layout, _, rate = uniform rate = rate.copy() @@ -435,11 +452,13 @@ def test_events_raise_fast_skewness(uniform): ), ], ) -def test_registration_and_command_agree(patched, tmp_path, device): - """``giant reg-stats`` on registration's outputs gives the same maps - (on a GPU registration's run on a thread and stream of their own, the - command's in line); the mean equals ``meanIM``; statistics do not - change the movie.""" +def test_registration_and_command_agree(patched, tmp_path, device) -> None: + """``giant reg-stats`` on registration's outputs gives the same maps. + + On a GPU registration's run on a thread and stream of their own, the + command's in line. The mean equals ``meanIM``; statistics do not change + the movie. + """ from giant_python.pipeline.reg_stats import trial_stats layout = patched @@ -473,9 +492,11 @@ def test_registration_and_command_agree(patched, tmp_path, device): @pytest.mark.parametrize("last", [2.0, 60.0]) -def test_short_trials_get_statistics(patched, tmp_path, last): - """A one-frame (or three-frame) trial gets a statistics file (maps - NaN where too few frames), equal to the command's.""" +def test_short_trials_get_statistics(patched, tmp_path, last) -> None: + """A one-frame (or three-frame) trial gets a statistics file equal to the command's. + + Its maps are NaN where there are too few frames. + """ from giant_python.pipeline.reg_stats import trial_stats layout = patched @@ -491,9 +512,12 @@ def test_short_trials_get_statistics(patched, tmp_path, last): np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) -def test_command_treats_empty_frames_as_missing(patched, tmp_path): - """A frame without data counts as missing in the command even where - the alignment file gives it a motion (as GIAnT-MATLAB's may).""" +def test_command_treats_empty_frames_as_missing(patched, tmp_path) -> None: + """A frame without data counts as missing in the command. + + This holds even where the alignment file gives it a motion (as + GIAnT-MATLAB's may). + """ from giant_python.pipeline.reg_stats import trial_stats layout = patched @@ -518,7 +542,7 @@ def test_command_treats_empty_frames_as_missing(patched, tmp_path): assert finite["attrs"][k] == missing["attrs"][k] -def test_rerun_without_stats_removes_old_file(patched, tmp_path): +def test_rerun_without_stats_removes_old_file(patched, tmp_path) -> None: """A registration without statistics leaves none from an earlier one.""" layout = patched params = multiroi.MultiRoiRegistrationParams(maxshift=6) @@ -532,11 +556,13 @@ def test_rerun_without_stats_removes_old_file(patched, tmp_path): @pytest.mark.parametrize("step", ["start", "setup", "add", "finish", "write"]) def test_failed_statistics_leave_registration( patched, tmp_path, step, monkeypatch, caplog -): - """A statistics step that fails (on the worker thread, or writing the - file, with its cleanup failing too) is logged; registration publishes - the same movie and alignment file, without statistics (and removes an - earlier statistics file).""" +) -> None: + """A statistics step that fails is logged. + + The step fails on the worker thread, or writing the file, with its + cleanup failing too. Registration publishes the same movie and alignment + file, without statistics (and removes an earlier statistics file). + """ import pathlib from giant_python.registration.stats import accumulate, io @@ -549,8 +575,8 @@ def test_failed_statistics_leave_registration( layout.files[0], 1, 3000, ref / MOVIE, ref / ADATA, params, stats=False ) - def fail(*args, **kwargs): - """A broken step.""" + def fail(*args, **kwargs) -> NoReturn: + """Fail as a broken step.""" raise RuntimeError("broken statistics") if step == "start": @@ -589,10 +615,11 @@ def locked(path, *args, **kwargs): np.testing.assert_array_equal(f[k][()], g[k][()]) -def test_command_checks_online_compensation(tmp_path, monkeypatch): - """For an online-compensated trial the command rebuilds the - compensation registration saved (same maps) and refuses a trial whose - saved record differs.""" +def test_command_checks_online_compensation(tmp_path, monkeypatch) -> None: + """For an online-compensated trial the command rebuilds the compensation registration saved. + + It gets the same maps and refuses a trial whose saved record differs. + """ from giant_python.pipeline.reg_stats import trial_stats from .synthetic import online_offsets @@ -624,10 +651,12 @@ def test_command_checks_online_compensation(tmp_path, monkeypatch): def test_statistics_file_that_cannot_be_moved( patched, tmp_path, monkeypatch, caplog -): - """If the statistics file cannot be moved into place, the movie and the - alignment file are published all the same, without statistics (an - earlier statistics file is removed).""" +) -> None: + """If the statistics file cannot be moved into place, the other outputs are published. + + The movie and the alignment file are published all the same, without + statistics (an earlier statistics file is removed). + """ import os layout = patched @@ -650,7 +679,7 @@ def refuse_stats(src, dst): assert sorted(p.name for p in tmp_path.iterdir()) == [ADATA, MOVIE] -def test_reg_stats_command(patched, tmp_path): +def test_reg_stats_command(patched, tmp_path) -> None: """The CLI writes the statistics of a table's trials once.""" from giant_python.cli import main from giant_python.pipeline.reg_stats import reg_stats @@ -695,9 +724,8 @@ def test_reg_stats_command(patched, tmp_path): "--device", "cpu"]) == 1 # fmt: skip -def test_validity_mismatch_counts_channels(): - """Samples whose validity differs from the first channel's are counted - per channel.""" +def test_validity_mismatch_counts_channels() -> None: + """Samples whose validity differs from the first channel's are counted per channel.""" from giant_python.io.slap2_raster import INVALID_SAMPLE from giant_python.registration.stats.gain import validity_mismatch @@ -709,7 +737,7 @@ def test_validity_mismatch_counts_channels(): assert validity_mismatch(torch.from_numpy(x)) == [0, 9, 5] -def test_stats_path_names(): +def test_stats_path_names() -> None: """Statistics files sit next to the movie, named after it.""" assert stats_path(Path("d") / MOVIE).name == "E1T1DMD1_REGSTATS-80Hz.h5" tif = Path("E2T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif") @@ -720,9 +748,11 @@ def test_stats_path_names(): # ----------------------------------------------------------------- session -def test_combine_trials_weights_by_frames(): - """Session maps: shifted, frame-weighted means; normalised maps from - the averages.""" +def test_combine_trials_weights_by_frames() -> None: + """Session maps: shifted, frame-weighted means. + + Normalised maps are formed from the averages. + """ shape = (1, 20, 30) trials = [] for t, (n, var) in enumerate(((100.0, 2.0), (300.0, 4.0))): @@ -749,9 +779,8 @@ def test_combine_trials_weights_by_frames(): assert out["n_trials"][0, 5, -1] == 1 -def test_combine_trials_of_different_sizes(): - """Trials of different registered sizes share the largest canvas - (top left, as SILo's).""" +def test_combine_trials_of_different_sizes() -> None: + """Trials of different registered sizes share the largest canvas (top left, as SILo's).""" trials = [] for shape in ((1, 20, 30), (1, 18, 32)): maps = {k: np.full(shape, 50.0) for k in ("n_valid", "n_blocks", @@ -780,7 +809,7 @@ def test_combine_trials_of_different_sizes(): assert (out["n_trials"][0, 2:-2, 2:-2] == 2).all() -def test_pair_sums_match_definition(tmp_path): +def test_pair_sums_match_definition(tmp_path) -> None: """Sums over pairs of consecutive samples equal their definition.""" layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 600) samples = np.ones((2, layout.slot_line.size, 600), dtype=np.int16) @@ -817,10 +846,12 @@ def test_pair_sums_match_definition(tmp_path): assert abs(res[name][t - f0, j] - ref) <= 1e-5 * g0 -def test_shared_pulses_read_zero(tmp_path): - """Pulses shared by consecutive samples correlate neighbouring pixels; - with the pair terms, photon noise still reads 0 after registration's - bilinear resampling mixes them.""" +def test_shared_pulses_read_zero(tmp_path) -> None: + """Pulses shared by consecutive samples correlate neighbouring pixels. + + With the pair terms, photon noise still reads 0 after registration's + bilinear resampling mixes them. + """ layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 1600) nxt = next_slots(layout.slot_line, layout.slot_pos) rng = np.random.default_rng(7) diff --git a/tests/registration/test_synthetic.py b/tests/registration/test_synthetic.py index 4cff98e2..189cff4a 100644 --- a/tests/registration/test_synthetic.py +++ b/tests/registration/test_synthetic.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path +from typing import NoReturn import h5py import numpy as np @@ -52,7 +53,7 @@ def frames_reference(layout, samples, times, dt): return num, den -def test_reader_and_line_headers(recording): +def test_reader_and_line_headers(recording) -> None: """Samples land at their slots; header offsets decode.""" layout, _ = recording s = read_raster_samples(layout, (10, 20), chunk_cycles=3) @@ -67,7 +68,7 @@ def test_reader_and_line_headers(recording): np.testing.assert_allclose(z, 0.25 * cyc) -def test_frame_former_matches_definition(recording): +def test_frame_former_matches_definition(recording) -> None: """Exp-kernel sums equal the definition, invalid samples masked.""" layout, _ = recording samples = read_raster_samples(layout, (0, layout.num_cycles)) @@ -85,7 +86,7 @@ def test_frame_former_matches_definition(recording): part.sums([20], 20) -def test_register_trial_recovers_motion(recording, tmp_path, monkeypatch): +def test_register_trial_recovers_motion(recording, tmp_path, monkeypatch) -> None: """Recovered motion follows the known motion (up to a constant).""" layout, truth = recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) @@ -130,7 +131,7 @@ def digests(*paths): @pytest.mark.parametrize("save_tif", [True, False]) def test_failed_rerun_keeps_the_previous_outputs( recording, tmp_path, monkeypatch, save_tif -): +) -> None: """A run that fails while writing leaves an existing pair as it was.""" layout, _ = recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) @@ -149,7 +150,7 @@ def fail_midway(self, k, regs, var_factor, *rest): raise OSError("disk full") return add(self, k, regs, var_factor, *rest) - def fail_at_the_end(*args, **kwargs): + def fail_at_the_end(*args, **kwargs) -> NoReturn: """Fail after the movie is complete.""" raise OSError("disk full") @@ -167,7 +168,7 @@ def fail_at_the_end(*args, **kwargs): def test_interrupted_publish_leaves_no_alignment_file( recording, tmp_path, monkeypatch -): +) -> None: """A pair that cannot be moved into place leaves no alignment file. The movie may then be new, but without an alignment file the trial is @@ -181,7 +182,7 @@ def test_interrupted_publish_leaves_no_alignment_file( multiroi.register_trial(*args) replace = os.replace - def refuse_alignment_file(src, dst): + def refuse_alignment_file(src, dst) -> None: """Fail to move the alignment file into place.""" if Path(dst) == adata: raise PermissionError("in use") @@ -195,15 +196,17 @@ def refuse_alignment_file(src, dst): assert sorted(tmp_path.iterdir()) == sorted([movie, stats]) -def blank_frames(monkeypatch, blank, half=None): - """Frames formed at times where ``blank(times)`` holds have no samples; - where ``half(times)`` holds, the lower half of the raster has none.""" +def blank_frames(monkeypatch, blank, half=None) -> None: + """Frames formed at times where ``blank(times)`` holds have no samples. + + Where ``half(times)`` holds, the lower half of the raster has none. + """ from giant_python.registration.frames import FrameFormer frames = FrameFormer.frames def blanked(self, times, dt, channels=None): - """The frames, with the selected ones emptied.""" + """Form the frames, with the selected ones emptied.""" vals, fresh = frames(self, times, dt, channels) t = np.asarray(times).ravel() lower = self.rows > np.median(self.rows) @@ -221,10 +224,12 @@ def blanked(self, times, dt, channels=None): @pytest.mark.parametrize("schedule", ["sequential", "grow"]) def test_frame_without_samples_is_missing( recording, tmp_path, monkeypatch, schedule -): - """A frame without valid samples in mid-trial gets NaN motion and an - all-NaN movie frame; the other frames are registered exactly as in a - run without that frame, and the trial does not fail.""" +) -> None: + """A frame without valid samples in mid-trial gets NaN motion and an all-NaN movie frame. + + The other frames are registered exactly as in a run without that frame, + and the trial does not fail. + """ from giant_python.registration.growth import MISSING layout, _ = recording @@ -286,11 +291,12 @@ def test_frame_without_samples_is_missing( @pytest.mark.parametrize("schedule", ["sequential", "grow"]) def test_trial_without_samples_at_its_start_or_at_all( recording, tmp_path, monkeypatch, schedule -): - """A recording that starts late is registered from its first frames - with samples, in the usual window even if the first of them covers - only part of the raster; a trial without any samples completes and is - flagged.""" +) -> None: + """A recording that starts late is registered from its first frames with samples. + + It is registered in the usual window even if the first of them covers only + part of the raster; a trial without any samples completes and is flagged. + """ from giant_python.registration.sources import make_source layout, _ = recording @@ -329,7 +335,7 @@ def test_trial_without_samples_at_its_start_or_at_all( def test_register_trial_keeps_fractional_lines( recording, tmp_path, monkeypatch -): +) -> None: """Fractional trial edges set the frame times, as in MATLAB. Trial tables of continuous recordings cut trials at ``linspace`` edges; @@ -357,7 +363,7 @@ def test_register_trial_keeps_fractional_lines( def test_register_multiroi_updates_trial_table( recording, tmp_path, monkeypatch -): +) -> None: """The pipeline writes MATLAB-named outputs and motion_correction.""" from giant_python.pipeline.register import register_multiroi @@ -400,7 +406,7 @@ def test_register_multiroi_updates_trial_table( def one_trial_table(layout, tmp_path): - """A MATLAB-style trial table with one 3000-line trial.""" + """Write a MATLAB-style trial table with one 3000-line trial.""" dat = Path(layout.files[0]) table = tmp_path / "trial_table.h5" save_struct_h5( @@ -420,7 +426,7 @@ def one_trial_table(layout, tmp_path): return table -def test_rerun_keeps_the_saved_failure_flag(recording, tmp_path, monkeypatch): +def test_rerun_keeps_the_saved_failure_flag(recording, tmp_path, monkeypatch) -> None: """Reused outputs report the registrationFailed they were saved with.""" from giant_python.pipeline.register import register_multiroi @@ -445,7 +451,7 @@ def test_rerun_keeps_the_saved_failure_flag(recording, tmp_path, monkeypatch): def test_rerun_with_other_settings_registers_again( recording, tmp_path, monkeypatch -): +) -> None: """Outputs are reused only if made with the requested settings.""" from giant_python.pipeline.register import register_multiroi from giant_python.registration.outputs import SETTINGS_ATTR @@ -484,9 +490,11 @@ def test_rerun_with_other_settings_registers_again( def test_failed_rerun_does_not_name_the_old_outputs( recording, tmp_path, monkeypatch -): - """A re-registration that raises leaves the old files on disk but - clears their names, so the table never pairs them with new settings.""" +) -> None: + """A re-registration that raises leaves the old files on disk but clears their names. + + So the table never pairs them with new settings. + """ from giant_python.pipeline.register import register_multiroi layout, _ = recording @@ -499,7 +507,7 @@ def test_failed_rerun_does_not_name_the_old_outputs( files = [moco / fields["fn_reg_ds"][0, 0], moco / fields["fn_adata"][0, 0]] before = digests(*files) - def fail(*args, **kwargs): + def fail(*args, **kwargs) -> NoReturn: """Fail before anything is published.""" raise OSError("disk full") @@ -519,9 +527,12 @@ def fail(*args, **kwargs): @pytest.mark.parametrize("case", ["row_major", "channels", "device"]) def test_rejected_request_writes_nothing( recording, tmp_path, monkeypatch, case -): - """A request that fails validation (a row-major table, an unsupported - recording, an unavailable device) leaves outputs and table untouched.""" +) -> None: + """A request that fails validation leaves outputs and table untouched. + + Such requests are a row-major table, an unsupported recording, an + unavailable device. + """ from giant_python.pipeline.register import register_multiroi layout, _ = recording @@ -555,9 +566,11 @@ def test_rejected_request_writes_nothing( assert sorted(moco.iterdir()) == sorted(old) -def test_ragged_table_skips_empty_cells(recording, tmp_path, monkeypatch): - """A cell without a recording (one path has fewer trials) is skipped - and flagged, with empty output names; the other cells register.""" +def test_ragged_table_skips_empty_cells(recording, tmp_path, monkeypatch) -> None: + """A cell without a recording (one path has fewer trials) is skipped and flagged. + + It gets empty output names; the other cells register. + """ from giant_python.pipeline.register import register_multiroi layout, _ = recording @@ -607,7 +620,7 @@ def test_ragged_table_skips_empty_cells(recording, tmp_path, monkeypatch): assert mc["registration_failed"][1, 1] == 1 -def test_trial_table_update_keeps_other_entries(tmp_path, monkeypatch): +def test_trial_table_update_keeps_other_entries(tmp_path, monkeypatch) -> None: """Only the registration fields are replaced, once all are written. Other entries of the group and their attributes are left untouched. @@ -640,7 +653,7 @@ def test_trial_table_update_keeps_other_entries(tmp_path, monkeypatch): } write = register.write_matlab_value - def fail_on_align_params(grp, key, value): + def fail_on_align_params(grp, key, value) -> None: """Fail while writing the last field.""" if key.startswith("align_params"): raise OSError("disk full") @@ -681,7 +694,7 @@ def entries(): def test_register_multiroi_keeps_fractional_lines( recording, tmp_path, monkeypatch -): +) -> None: """The pipeline passes the table's fractional trial edges on unrounded.""" from giant_python.io.hdf5 import load_struct_h5 from giant_python.pipeline.register import register_multiroi @@ -721,7 +734,7 @@ def test_register_multiroi_keeps_fractional_lines( ) -def test_unsupported_options_raise(): +def test_unsupported_options_raise() -> None: """MATLAB options that are not ported are rejected.""" with pytest.raises(NotImplementedError): multiroi.MultiRoiRegistrationParams(ref_stack_template=True) @@ -731,7 +744,7 @@ def test_unsupported_options_raise(): resolve_registration_options({"compensateOnline": True}) -def test_save_struct_h5_is_column_major(tmp_path): +def test_save_struct_h5_is_column_major(tmp_path) -> None: """Values come back in MATLAB orientation and MATLAB classes.""" path = tmp_path / "s.h5" save_struct_h5( @@ -758,7 +771,7 @@ def test_save_struct_h5_is_column_major(tmp_path): assert back["g"]["single"].dtype == np.float32 -def test_registration_runs_on_cuda_like_cpu(recording, tmp_path, monkeypatch): +def test_registration_runs_on_cuda_like_cpu(recording, tmp_path, monkeypatch) -> None: """CUDA and CPU give the same motion (skipped without a GPU).""" if not torch.cuda.is_available(): pytest.skip("no CUDA device") @@ -784,7 +797,7 @@ def test_registration_runs_on_cuda_like_cpu(recording, tmp_path, monkeypatch): assert np.median(diff) < 1e-3 and diff.max() < 0.1 -def test_var_factor_deflate_keeps_values(recording, tmp_path, monkeypatch): +def test_var_factor_deflate_keeps_values(recording, tmp_path, monkeypatch) -> None: """Deflated varFacDS (default) holds the same values as uncompressed.""" layout, _ = recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) @@ -814,7 +827,7 @@ def test_var_factor_deflate_keeps_values(recording, tmp_path, monkeypatch): assert m["data"].compression_opts == 1 -def test_cycle_split_names(): +def test_cycle_split_names() -> None: """Files of CYCLE-split recordings are recognised by name only.""" assert is_cycle_split("acq_DMD1-TRIAL000001-CYCLE-000000.dat") assert is_cycle_split("d/acq_DMD2-CYCLE-318000.dat") @@ -824,7 +837,7 @@ def test_cycle_split_names(): def split_recording(layout, k, tmp_path): - """The recording written as two files, split before cycle ``k``.""" + """Write the recording as two files, split before cycle ``k``.""" raw = np.fromfile(layout.files[0], dtype=np.int16) head = raw[:HEADER_WORDS] body = raw[HEADER_WORDS:].reshape(layout.num_cycles, -1) @@ -845,7 +858,7 @@ def split_recording(layout, k, tmp_path): def test_split_recording_reads_and_registers_alike( recording, tmp_path, monkeypatch -): +) -> None: """Reads and registration across two files equal those of one file.""" layout, _ = recording k = 500 diff --git a/tests/simulation/test_injection.py b/tests/simulation/test_injection.py index 70b58f03..20c7902b 100644 --- a/tests/simulation/test_injection.py +++ b/tests/simulation/test_injection.py @@ -35,7 +35,7 @@ def sha(path) -> str: # --------------------------------------------------------- pure functions -def test_time_course_peaks_at_one(): +def test_time_course_peaks_at_one() -> None: """Instant rise: exp decay from 1; short rise: peak 1 at its delay.""" t = np.array([-0.01, 0.0, 0.024, 0.048]) np.testing.assert_allclose( @@ -50,7 +50,7 @@ def test_time_course_peaks_at_one(): assert inj.time_course(-1e-9, 0.024, 0.003) == 0 -def test_event_traces_sum_events(): +def test_event_traces_sum_events() -> None: """Traces are sums of size x time course at the line times.""" s = inj.InjectionSettings(tau_s=0.01) ev = inj.Events( @@ -70,7 +70,7 @@ def test_event_traces_sum_events(): assert np.all(tr[1, : 12 - 5] == 0) -def test_draw_events_respect_edges_dead_time_and_classes(): +def test_draw_events_respect_edges_dead_time_and_classes() -> None: """Onsets stay inside the edges, apart by the dead time; classes mix.""" s = inj.InjectionSettings(rate_hz=4.0, min_interval_s=0.1, edge_s=0.5) period = 1e-4 @@ -102,9 +102,11 @@ def test_draw_events_respect_edges_dead_time_and_classes(): def _draw_events_before_sync(n_sources, first, last, period, s, rng): - """The event draws as they were before ``sync_share`` existed (the - loop of ``draw_events`` at GIAnT-Python a673714, kept here as the - reference): source, onset line and size class of every event.""" + """Draw the events as they were drawn before ``sync_share`` existed. + + This is the loop of ``draw_events`` at GIAnT-Python a673714, kept here as + the reference: source, onset line and size class of every event. + """ edge = s.edge_s / period lo, hi = float(first) + edge, float(last) - edge mean_gap = 1.0 / s.rate_hz / period @@ -127,10 +129,12 @@ def _draw_events_before_sync(n_sources, first, last, period, s, rng): return np.concatenate(src), np.concatenate(onset), np.concatenate(classes) -def test_draw_events_with_common_onsets(): - """``sync_share`` gives every source the onsets of one common train - beside its own: the common ones are in every source, the dead time - holds, the rate is about kept, and a share of 0 changes no draw.""" +def test_draw_events_with_common_onsets() -> None: + """``sync_share`` gives every source the onsets of one common train beside its own. + + The common ones are in every source, the dead time holds, the rate is + about kept, and a share of 0 changes no draw. + """ period = 1e-4 s = inj.InjectionSettings(rate_hz=2.0, min_interval_s=0.1, edge_s=0.5) args = (60, 1.0, 600001.0, period) # a minute @@ -196,7 +200,7 @@ def common_onsets(ev, n): assert gap.min() >= 0.1 / period - 1e-6 -def test_settings_reject_bad_values(): +def test_settings_reject_bad_values() -> None: """Invalid settings raise.""" with pytest.raises(ValueError): inj.InjectionSettings(rise_s=0.03) @@ -208,7 +212,7 @@ def test_settings_reject_bad_values(): inj.InjectionSettings(rate_hz=-1) -def test_footprints(): +def test_footprints() -> None: """Gaussian peak 1 and cut at its radius; image footprints interpolate.""" g = inj.GaussianFootprint(1.33, 4.0) assert g(0.0, 0.0) == 1.0 @@ -225,9 +229,8 @@ def test_footprints(): assert patch[3, 3] == pytest.approx(np.exp(-0.5 * (0.4 / 1.33) ** 2)) -def test_place_sources_follow_the_rules(): - """Sources sit on labeled pixels, away from edges, others and each - other.""" +def test_place_sources_follow_the_rules() -> None: + """Sources sit on labeled pixels, away from edges, others and each other.""" rng = np.random.default_rng(0) img = np.full((60, 80), 1.0) img[20:24, 5:75] = 10.0 # a horizontal "dendrite" @@ -246,10 +249,13 @@ def test_place_sources_follow_the_rules(): assert np.hypot(*(pos - exclude).T).min() >= 8 -def test_place_sources_keep_apart_from_placed_ones(): - """Candidates within the minimum distance of sources placed already - are dropped before any is chosen: one that is too near cannot stand in - the way of a free one behind it.""" +def test_place_sources_keep_apart_from_placed_ones() -> None: + """Candidates near sources placed already are dropped before any is chosen. + + Candidates within the minimum distance of sources placed already are + dropped first: one that is too near cannot stand in the way of a free + one behind it. + """ img = np.full((40, 60), 1.0) img[19:22, 20:41] = 10.0 # a short "dendrite" s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) @@ -283,7 +289,7 @@ def test_place_sources_keep_apart_from_placed_ones(): assert np.hypot(*(pos[0] - placed[0])) >= 6 -def test_align_images_recovers_subpixel_shift(): +def test_align_images_recovers_subpixel_shift() -> None: """A smooth random image moved by a known shift is found again.""" from scipy.ndimage import gaussian_filter @@ -299,8 +305,8 @@ def test_align_images_recovers_subpixel_shift(): # ------------------------------------------------------ synthetic recordings -def write_static(layout, gain: float, rate: float, seed: int = 0): - """Samples ``gain * Poisson(rate * brightness)`` of a static scene.""" +def write_static(layout, gain: float, rate: float, seed: int = 0) -> None: + """Write samples ``gain * Poisson(rate * brightness)`` of a static scene.""" rng = np.random.default_rng(seed) words = np.zeros((layout.num_cycles, layout.words_per_cycle), np.int16) bright = 1 + 9 * ((layout.slot_pixel * 7919) % 97) / 97.0 @@ -317,7 +323,7 @@ def write_static(layout, gain: float, rate: float, seed: int = 0): f.write(words.tobytes()) -def test_measure_raw_per_photon(tmp_path): +def test_measure_raw_per_photon(tmp_path) -> None: """The variance-to-mean ratio of scaled Poisson samples is the gain.""" layout = make_layout(tmp_path / "g_DMD1-TRIAL000001.dat", 400, seed=2) write_static(layout, gain=110.0, rate=0.05) @@ -339,8 +345,11 @@ def online(tmp_path_factory): def truth_geometry(layout, offs, truth, lines): - """Geometry in the scene frame: sample of DMD (r, c) on line l shows - the scene at (r + y_dmd - m_r, c + x - m_c).""" + """Geometry in the scene frame. + + The sample of DMD (r, c) on line l shows the scene at + (r + y_dmd - m_r, c + x - m_c). + """ x, _, y_dmd = offs ln = np.arange(lines[0], lines[1] + 1) shift = np.stack( @@ -349,9 +358,12 @@ def truth_geometry(layout, offs, truth, lines): return inj.TrialGeometry(lines[0], shift.astype(np.float64), True) -def test_sample_model_follows_the_tissue(online): - """Expected counts are photon_scale x footprint at the sample's tissue - position x the trace at its line, for every chunk of cycles.""" +def test_sample_model_follows_the_tissue(online) -> None: + """Expected counts follow the tissue, for every chunk of cycles. + + They are photon_scale x footprint at the sample's tissue position x the + trace at its line. + """ layout, offs, truth = online lines = (8, layout.total_lines - 3) geo = truth_geometry(layout, offs, truth, lines) @@ -423,7 +435,7 @@ def registered_table(layout, tmp_path, compensate: bool, trials): @pytest.fixture(scope="module") def registered(online, tmp_path_factory): - """The online recording registered as two trials, both ways.""" + """Register the online recording as two trials, both ways.""" layout, _, _ = online out = {} with pytest.MonkeyPatch.context() as mp: @@ -439,9 +451,11 @@ def registered(online, tmp_path_factory): @pytest.mark.parametrize("compensate", [True, False]) def test_geometry_from_registration_tracks_true_motion( online, registered, compensate -): - """The registered position of each line's samples follows the tissue: - shift(l) equals the true scene shift up to a constant.""" +) -> None: + """The registered position of each line's samples follows the tissue. + + shift(l) equals the true scene shift up to a constant. + """ layout, offs, truth = online table = Path(registered[compensate]) al = inj.read_alignment( @@ -477,9 +491,11 @@ def run_injection(online, table, out, monkeypatch, **kw): def test_no_events_leave_the_copy_identical( online, registered, tmp_path, monkeypatch -): - """Without events the copy equals the original byte for byte, and the - .meta file is copied.""" +) -> None: + """Without events the copy equals the original byte for byte. + + The .meta file is copied. + """ layout, _, _ = online s = inj.InjectionSettings(rate_hz=0.0, raw_per_photon=1.0) summary = run_injection( @@ -524,12 +540,15 @@ def injected(online, registered, tmp_path_factory): return out, summary, BRIGHT -def test_placed_sources_without_data_are_moved(online, registered, tmp_path): - """A source that the tool itself puts on a pixel without data in the +def test_placed_sources_without_data_are_moved(online, registered, tmp_path) -> None: + """A source the tool put on a pixel without data where its peaks are calibrated is moved. + + A source that the tool itself puts on a pixel without data in the stretch its frame peaks are calibrated on is placed anew: at the minimum distance from the sources that stay and from every place tried before; the others stay. A position that was given is not moved (an - error, as before), and so is a move with no place left.""" + error, as before), and so is a move with no place left. + """ first = np.array([[16.0, 20.0], [16.0, 200.0], [12.0, 27.0]]) asked = [] # the free candidates of the move, in the order they are drawn: the @@ -546,8 +565,11 @@ def place( exclude_rc=None, keep_apart_rc=None, ): - """Stand-in for place_sources: a first placement with a source - where no data is, then the candidates of a move.""" + """Stand-in for place_sources. + + A first placement with a source where no data is, then the + candidates of a move. + """ asked.append((n, exclude_rc, keep_apart_rc)) if len(asked) == 1: # the path's placement: one where no data is return first.copy(), 3 @@ -666,9 +688,11 @@ def place( assert len(asked) == 1 + inj.REPLACE_ROUNDS -def test_injection_changes_only_injected_samples(online, injected): - """Only channel-0 raster samples change, never invalid ones, and the - added counts are the recorded ones.""" +def test_injection_changes_only_injected_samples(online, injected) -> None: + """Only channel-0 raster samples change, never invalid ones. + + The added counts are the recorded ones. + """ layout, _, _ = online out, summary, s = injected src = Path(layout.files[0]) @@ -691,9 +715,8 @@ def test_injection_changes_only_injected_samples(online, injected): assert total == pytest.approx(drawn * s.raw_per_photon, rel=1e-3) -def test_truth_file_describes_the_injection(online, injected): - """The truth has positions per trial, events and traces at frame - lines.""" +def test_truth_file_describes_the_injection(online, injected) -> None: + """The truth has positions per trial, events and traces at frame lines.""" layout, _, _ = online out, summary, s = injected truth = inj.read_truth(out / inj.TRUTH_NAME) @@ -733,11 +756,14 @@ def test_truth_file_describes_the_injection(online, injected): def test_injected_signal_is_still_and_as_expected( online, registered, injected -): - """In registered frames made with the original's motion, the copy minus - the original matches the expected counts within Poisson noise, and a - static source's centroid stays put (drift < 0.1 px) across the online - offsets' switches.""" +) -> None: + """In frames registered with the original's motion, the copy matches the expected counts. + + In registered frames made with the original's motion, the copy minus the + original matches the expected counts within Poisson noise, and a static + source's centroid stays put (drift < 0.1 px) across the online offsets' + switches. + """ layout, _, _ = online out, _, s = injected table = Path(registered[True]) @@ -806,9 +832,11 @@ def test_injected_signal_is_still_and_as_expected( def test_registered_copy_keeps_the_motion( online, registered, tmp_path, monkeypatch -): - """Registering the injected copy gives the original's motion up to the - grid's anchoring; the truth then records both.""" +) -> None: + """Registering the injected copy gives the original's motion up to the grid's anchoring. + + The truth then records both. + """ layout, _, _ = online out = tmp_path / "inj" run_injection( @@ -842,9 +870,11 @@ def test_registered_copy_keeps_the_motion( np.testing.assert_allclose(off["shift_rc"], d["copy_shift_rc"]) -def test_saturation_invalid_samples_and_chunking(online, tmp_path): - """Huge events saturate at 32767; invalid samples stay; results do not - depend on the chunk size.""" +def test_saturation_invalid_samples_and_chunking(online, tmp_path) -> None: + """Huge events saturate at 32767; invalid samples stay. + + Results do not depend on the chunk size. + """ layout, offs, truth = online src = Path(layout.files[0]) data = np.fromfile(src, np.int16) @@ -875,7 +905,7 @@ def test_saturation_invalid_samples_and_chunking(online, tmp_path): assert outs[0].max() == inj.SAMPLE_MAX -def test_command_line(online, registered, tmp_path, monkeypatch, capsys): +def test_command_line(online, registered, tmp_path, monkeypatch, capsys) -> None: """``python -m giant_python.simulation.injection`` runs a session.""" layout, _, _ = online monkeypatch.setattr(inj, "raster_layout", lambda path: layout) @@ -915,7 +945,7 @@ def test_command_line(online, registered, tmp_path, monkeypatch, capsys): assert "trace_frames" not in p["trials_detail"][2] -def test_cuda_render_matches_cpu(online, registered): +def test_cuda_render_matches_cpu(online, registered) -> None: """Rendering on CUDA equals the CPU.""" if not torch.cuda.is_available(): pytest.skip("no CUDA device") @@ -935,9 +965,11 @@ def test_cuda_render_matches_cpu(online, registered): def test_ragged_table_keeps_copy_columns( online, registered, tmp_path, monkeypatch -): - """A trial without a recording is skipped; the others keep their - column of the copy's trial table.""" +) -> None: + """A trial without a recording is skipped. + + The others keep their column of the copy's trial table. + """ from giant_python.io.hdf5 import load_struct_h5 table = load_struct_h5(registered[False]) @@ -960,9 +992,12 @@ def test_ragged_table_keeps_copy_columns( np.testing.assert_array_equal(np.unique(truth["events"]["trial"]), [2]) -def test_sizes_are_peaks_in_frames(online, injected): - """With sizes in frame units, an isolated event's noiseless peak in the - 200 Hz frames at its source's peak pixel is its size, on average.""" +def test_sizes_are_peaks_in_frames(online, injected) -> None: + """With sizes in frame units, an isolated event's noiseless peak is its size. + + The peak is taken in the 200 Hz frames at its source's peak pixel, and + equals the size on average. + """ out, _, s = injected truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] fp = truth["frame_peak"] @@ -998,7 +1033,7 @@ def test_sizes_are_peaks_in_frames(online, injected): assert np.mean(ratios) == pytest.approx(1.0, abs=0.06) -def test_refuses_to_write_into_the_original(online, registered, monkeypatch): +def test_refuses_to_write_into_the_original(online, registered, monkeypatch) -> None: """The copy's folder cannot be the original's data folder.""" layout, _, _ = online src = Path(layout.files[0]) @@ -1013,9 +1048,11 @@ def test_refuses_to_write_into_the_original(online, registered, monkeypatch): ) -def test_registration_offset_includes_the_grid(registered): - """Different padding, window and reference offset move the copy's - positions; mixed compensation is refused.""" +def test_registration_offset_includes_the_grid(registered) -> None: + """Different padding, window and reference offset move the copy's positions. + + Mixed compensation is refused. + """ from dataclasses import replace as dc_replace moco = Path(registered[True]).parent / "motion_correction" @@ -1045,9 +1082,12 @@ def test_registration_offset_includes_the_grid(registered): inj.registration_offset(a, plain) -def test_frame_motion_uses_each_frames_own_reference(registered): - """A frame at a registered frame's time but with another reference - offset is moved by its own reference, not the recorded motion.""" +def test_frame_motion_uses_each_frames_own_reference(registered) -> None: + """A frame with another reference offset is moved by its own reference. + + The frame is at a registered frame's time but with another reference + offset, and is moved by its own reference, not the recorded motion. + """ from giant_python.simulation.render import frame_motion moco = Path(registered[True]).parent / "motion_correction" @@ -1064,9 +1104,11 @@ def test_frame_motion_uses_each_frames_own_reference(registered): np.testing.assert_allclose(other[ok, 0], al.motion_r[ok], atol=1e-9) -def test_calibration_keeps_overlapping_sources_apart(online, registered): - """Overlapping sources are calibrated in turns: a close neighbour does - not change a source's frame peak.""" +def test_calibration_keeps_overlapping_sources_apart(online, registered) -> None: + """Overlapping sources are calibrated in turns. + + A close neighbour does not change a source's frame peak. + """ layout, _, _ = online moco = Path(registered[True]).parent / "motion_correction" al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") @@ -1102,9 +1144,12 @@ def test_calibration_keeps_overlapping_sources_apart(online, registered): def test_inputs_that_would_corrupt_a_dataset_are_refused( online, registered, tmp_path, monkeypatch -): - """Repeated trials or paths, and an output folder that already holds a - dataset, are refused before anything is written.""" +) -> None: + """Repeated trials or paths and an existing dataset are refused before writing. + + Repeated trials or paths, and an output folder that already holds a + dataset, are refused before anything is written. + """ s = inj.InjectionSettings( raw_per_photon=4.0, frame_traces=False, size_reference="tissue" ) @@ -1141,9 +1186,8 @@ def test_inputs_that_would_corrupt_a_dataset_are_refused( ) -def test_copy_table_paths_and_absolute_folders(tmp_path, monkeypatch): - """The copy's table has absolute folders and no files for paths that - were not copied.""" +def test_copy_table_paths_and_absolute_folders(tmp_path, monkeypatch) -> None: + """The copy's table has absolute folders and no files for paths not copied.""" from giant_python.io.hdf5 import load_struct_h5 table = { @@ -1168,7 +1212,7 @@ def test_copy_table_paths_and_absolute_folders(tmp_path, monkeypatch): assert "motion_correction" not in t -def test_image_footprint_peak_and_calibration(online, registered): +def test_image_footprint_peak_and_calibration(online, registered) -> None: """An off-centre image footprint is calibrated at its maximum.""" layout, _, _ = online img = np.zeros((5, 5)) @@ -1187,10 +1231,12 @@ def test_image_footprint_peak_and_calibration(online, registered): assert 0.05 < peak[0] < 1.0 -def test_expected_frames_follow_the_trial_grid(online, registered): - """A path-frame pixel outside the trial grid's size is still rendered - where its trial position has data; channel 1 renders with channel 0's - freshness.""" +def test_expected_frames_follow_the_trial_grid(online, registered) -> None: + """A path-frame pixel outside the trial grid's size is still rendered. + + It is rendered where its trial position has data; channel 1 renders + with channel 0's freshness. + """ layout, _, _ = online moco = Path(registered[True]).parent / "motion_correction" al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") @@ -1214,9 +1260,12 @@ def test_expected_frames_follow_the_trial_grid(online, registered): np.testing.assert_allclose(ch1, here, rtol=1e-6) # no invalid samples -def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected): - """Two trials of one file: frames whose kernel reads the other trial's - injected samples are NaN in the truth's frame traces.""" +def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected) -> None: + """Two trials of one file: frames reading the other trial's injections are NaN. + + Frames whose kernel reads the other trial's injected samples are NaN in + the truth's frame traces. + """ out, _, _ = injected truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] reach = 24 @@ -1231,7 +1280,7 @@ def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected): def test_relative_registration_folder_is_stored_absolute( online, registered, tmp_path, monkeypatch -): +) -> None: """A relative registration folder is recorded as an absolute path.""" import os @@ -1256,10 +1305,12 @@ def test_relative_registration_folder_is_stored_absolute( assert os.path.isabs(truth["origin"]["moco_dir"]) -def test_more_inputs_are_checked(online, registered, tmp_path): - """Non-finite gains are refused; sources without data cannot be - calibrated; copies' filenames are their basenames; larger trial grids - keep their data when shifted into the path frame.""" +def test_more_inputs_are_checked(online, registered, tmp_path) -> None: + """Non-finite gains are refused; sources without data cannot be calibrated. + + Copies' filenames are their basenames; larger trial grids keep their + data when shifted into the path frame. + """ from giant_python.io.hdf5 import load_struct_h5 for bad in (float("inf"), float("nan")): @@ -1296,9 +1347,12 @@ def test_more_inputs_are_checked(online, registered, tmp_path): def test_bad_chunks_and_name_collisions_are_refused( online, registered, tmp_path, monkeypatch -): - """A nonpositive chunk size, and two recordings that would be copied - under one name, are refused before anything is written.""" +) -> None: + """A nonpositive chunk size and copies sharing a name are refused before writing. + + A nonpositive chunk size, and two recordings that would be copied under + one name, are refused before anything is written. + """ import shutil from giant_python.io.hdf5 import load_struct_h5 @@ -1338,9 +1392,11 @@ def test_bad_chunks_and_name_collisions_are_refused( assert not (tmp_path / "t").exists() -def test_neighbours_share_recording_files(): - """Trials are neighbours when their recordings share a file, whatever - file each trial names.""" +def test_neighbours_share_recording_files() -> None: + """Trials are neighbours when their recordings share a file. + + This holds whatever file each trial names. + """ ctx = { "names": ["c0.dat", "c1.dat", "other.dat"], "files": { @@ -1359,9 +1415,11 @@ def test_neighbours_share_recording_files(): def test_no_events_need_no_calibration( online, registered, tmp_path, monkeypatch -): - """Without events nothing is calibrated, even in a trial too short to - calibrate, and the copy stays identical.""" +) -> None: + """Without events nothing is calibrated, and the copy stays identical. + + This holds even in a trial too short to calibrate. + """ layout, _, _ = online s = inj.InjectionSettings(rate_hz=0.0, edge_s=1.6, raw_per_photon=1.0) run_injection( @@ -1373,9 +1431,11 @@ def test_no_events_need_no_calibration( np.testing.assert_array_equal(truth["frame_peak"], 1.0) -def test_silo_frames_leave_out_the_kernels_edge(online, registered): - """Frame traces and calibration use SILo's extraction frames, which - leave out the samples exactly at the kernel's reach.""" +def test_silo_frames_leave_out_the_kernels_edge(online, registered) -> None: + """Frame traces and calibration use SILo's extraction frames. + + These leave out the samples exactly at the kernel's reach. + """ layout, _, _ = online moco = Path(registered[True]).parent / "motion_correction" al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") diff --git a/tests/spine/synthetic.py b/tests/spine/synthetic.py index ca701a39..e2dde57e 100644 --- a/tests/spine/synthetic.py +++ b/tests/spine/synthetic.py @@ -33,7 +33,7 @@ def scene(path: int) -> np.ndarray: - """The consensus F0 scene of a path: smooth and positive.""" + """Build the consensus F0 scene of a path: smooth and positive.""" rr, cc = np.mgrid[0:H, 0:W].astype(float) return 50 + 10 * path + 2 * rr + 0.5 * cc @@ -44,7 +44,7 @@ def trial_scale(t: int) -> float: def footprints() -> np.ndarray: - """The sources' footprints ``(sources, rows, cols)``.""" + """Build the sources' footprints ``(sources, rows, cols)``.""" rr, cc = np.mgrid[0:H, 0:W].astype(float) out = np.zeros((len(SOURCES), H, W)) for k, (r0, c0) in enumerate(SOURCES): @@ -55,8 +55,7 @@ def footprints() -> np.ndarray: def trial_image(path: int, t: int) -> np.ndarray: - """A trial's registered F0 image (NaN where the shift leaves no - data).""" + """Build a trial's registered F0 image (NaN where the shift leaves no data).""" s = scene(path) * trial_scale(t) dr, dc = SHIFTS[t] out = np.full((H, W), np.nan) @@ -70,7 +69,7 @@ def trial_image(path: int, t: int) -> np.ndarray: def consensus_trial(path: int, t: int) -> np.ndarray: - """What a trial's image looks like in the consensus frame.""" + """Show what a trial's image looks like in the consensus frame.""" out = scene(path) * trial_scale(t) dr, dc = SHIFTS[t] rr, cc = np.mgrid[0:H, 0:W] @@ -79,9 +78,11 @@ def consensus_trial(path: int, t: int) -> np.ndarray: def _trial_maps(affine, displacement: bool) -> dict: - """The ``frame_info`` trial maps: ``affine`` (default: the shifts - ``SHIFTS``), or with ``displacement`` the shifts as a displacement field - beside identity affine maps.""" + """Build the ``frame_info`` trial maps. + + ``affine`` (default: the shifts ``SHIFTS``), or with ``displacement`` the + shifts as a displacement field beside identity affine maps. + """ if displacement: disp = np.broadcast_to( np.asarray(SHIFTS, float)[:, :, None, None], (N_TRIALS, 2, H, W) @@ -100,8 +101,10 @@ def _trial_maps(affine, displacement: bool) -> dict: def _in_box(images: np.ndarray, box) -> np.ndarray: - """``images`` (``(..., H, W)``) with NaN outside ``box`` (rows, cols - slices; None keeps every pixel).""" + """``images`` (``(..., H, W)``) with NaN outside ``box``. + + ``box`` is rows, cols slices; None keeps every pixel. + """ if box is None: return images keep = np.zeros((H, W), bool) @@ -250,7 +253,7 @@ def make_session( def write_results(path: Path, subproblems: dict, **attrs) -> None: - """A results file with ``subproblems`` (index -> (pixels, info)).""" + """Write a results file with ``subproblems`` (index -> (pixels, info)).""" with h5py.File(path, "w") as f: for k, v in {**RESULT_ATTRS, "container_hash": "c", **attrs}.items(): f.attrs[k] = v @@ -262,8 +265,10 @@ def write_results(path: Path, subproblems: dict, **attrs) -> None: def baseline_record(path: Path) -> str: - """The ``network_baseline`` attribute SILo's results record for a - baseline file (its identity and network).""" + """Build the ``network_baseline`` attribute SILo's results record for a baseline file. + + The attribute holds the file's identity and network. + """ st = Path(path).stat() return json.dumps( { @@ -279,9 +284,11 @@ def baseline_record(path: Path) -> str: def make_gain_work(root: Path, gain_of_trial, baselines=None) -> Path: - """A minimal 'gain'-mode work folder: a plan per path with the selected - pixels, and per trial-path one results file with two overlapping - subproblems whose gains are ``gain_of_trial(t)`` and twice that. + """Write a minimal 'gain'-mode work folder. + + A plan per path with the selected pixels, and per trial-path one results + file with two overlapping subproblems whose gains are ``gain_of_trial(t)`` + and twice that. With ``baselines`` (the session's folder) the results record its files as the baselines the gains were fitted against. diff --git a/tests/spine/test_spine_coverage.py b/tests/spine/test_spine_coverage.py index 6e869633..f7e34269 100644 --- a/tests/spine/test_spine_coverage.py +++ b/tests/spine/test_spine_coverage.py @@ -1,6 +1,7 @@ -"""Tests of the pixels a trial did not image -(:mod:`giant_python.spine.coverage`) and of their place in ``giant spine -readout``.""" +"""Tests of the pixels a trial did not image and of their place in ``giant spine readout``. + +See :mod:`giant_python.spine.coverage`. +""" import numpy as np import pytest @@ -21,9 +22,12 @@ def _stack(T=6, H=12, W=16, level=10.0): return a -def test_band_at_the_scan_edge_is_found(): - """A near-zero band touching the missing pixels, in the later trials and - in every channel, is not imaged; one pixel around it too.""" +def test_band_at_the_scan_edge_is_found() -> None: + """A near-zero band touching the missing pixels is not imaged. + + The band is in the later trials and in every channel; one pixel around it + is not imaged too. + """ ch1, ch2 = _stack(), _stack(level=1.0) for c, lvl in ((ch1, 0.2), (ch2, 0.02)): c[3:, :, 11:14] = lvl @@ -37,9 +41,8 @@ def test_band_at_the_scan_edge_is_found(): ].any() -def test_dimming_inside_the_field_or_in_one_channel_is_kept(): - """Dark pixels away from the scan's edge, or dark in one channel only, - are imaged.""" +def test_dimming_inside_the_field_or_in_one_channel_is_kept() -> None: + """Dark pixels away from the scan's edge, or dark in one channel only, are imaged.""" ch1, ch2 = _stack(), _stack(level=1.0) ch1[3:, 5:7, 5:7] = 0.1 # interior, both channels ch2[3:, 5:7, 5:7] = 0.01 @@ -49,7 +52,7 @@ def test_dimming_inside_the_field_or_in_one_channel_is_kept(): assert not unimaged_pixels([ch1, ch2], frac=0.0).any() -def test_the_frame_border_counts_as_the_edge(): +def test_the_frame_border_counts_as_the_edge() -> None: """A band at the frame's border is found without missing pixels.""" ch = np.full((4, 8, 8), 5.0) ch[2:, :, 6:] = 0.0 @@ -57,7 +60,7 @@ def test_the_frame_border_counts_as_the_edge(): assert un[2:, :, 6:].all() and un.sum() == 2 * 8 * 2 -def test_unimaged_pixels_checks_its_input(): +def test_unimaged_pixels_checks_its_input() -> None: """Channels must share a shape, and there must be one.""" with pytest.raises(ValueError, match="shape"): unimaged_pixels([np.ones((2, 3, 3)), np.ones((2, 3, 4))]) @@ -65,7 +68,7 @@ def test_unimaged_pixels_checks_its_input(): unimaged_pixels([]) -def test_window_weight_kept(): +def test_window_weight_kept() -> None: """The share of each window's weight on the valid pixels.""" masks = np.zeros((2, 4, 4), bool) masks[0, :, :2] = True @@ -78,14 +81,16 @@ def test_window_weight_kept(): @pytest.fixture def banded(tmp_path, monkeypatch): - """The synthetic session with a near-zero band at the right edge of - trials 3 and 4 (as left by a step of online motion correction) in every - per-trial image.""" + """Build the synthetic session with a near-zero band at the right edge of trials 3 and 4. + + The band is as left by a step of online motion correction, in every + per-trial image. + """ s = syn.make_session(tmp_path) real = RunSummary.per_trial_images def with_band(self, path, name, channel): - """The run's per-trial images with the band.""" + """Return the run's per-trial images with the band.""" a = np.array(real(self, path, name, channel), dtype=np.float32) band = a[2:, :, 17:] a[2:, :, 17:] = np.where(np.isfinite(band), 0.02, band) @@ -95,10 +100,12 @@ def with_band(self, path, name, channel): return s -def test_readout_leaves_out_the_band(banded, tmp_path): - """The band is left out of every image, a source mostly in it gets NaN - sizes, and a source partly in it keeps the same window in every trial - (no dip).""" +def test_readout_leaves_out_the_band(banded, tmp_path) -> None: + """The band is left out of every image. + + A source mostly in it gets NaN sizes, and a source partly in it keeps the + same window in every trial (no dip). + """ notes = [] rep = make_spine_summary( banded["run"], @@ -130,9 +137,11 @@ def test_readout_leaves_out_the_band(banded, tmp_path): assert p["image_attrs"]["mean_ch1"]["covers"] == "field" -def test_without_the_mask_the_band_makes_a_dip(banded, tmp_path): - """With the mask off, the partly covered source dips in the banded - trials (what the mask removes).""" +def test_without_the_mask_the_band_makes_a_dip(banded, tmp_path) -> None: + """With the mask off, the partly covered source dips in the banded trials. + + This is what the mask removes. + """ rep = make_spine_summary( banded["run"], banded["table"], @@ -161,15 +170,17 @@ def test_without_the_mask_the_band_makes_a_dip(banded, tmp_path): (dict(min_window=1.5), "min_window"), ], ) -def test_coverage_settings_are_checked(tmp_path, kw, match): +def test_coverage_settings_are_checked(tmp_path, kw, match) -> None: """Settings that cannot work are refused before anything is read.""" with pytest.raises(ValueError, match=match): make_spine_summary(tmp_path, tmp_path / "t.h5", tmp_path / "o", **kw) -def test_a_dimmer_trial_is_not_a_band(): - """A trial whose whole field is dimmer (bleaching, laser power) is not - taken for a band, while a band in such a trial still is.""" +def test_a_dimmer_trial_is_not_a_band() -> None: + """A trial whose whole field is dimmer (bleaching, laser power) is not taken for a band. + + A band in such a trial still is. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[4:] *= 0.2 ch2[4:] *= 0.2 @@ -180,9 +191,11 @@ def test_a_dimmer_trial_is_not_a_band(): assert un[5, :, 12:14].all() and un.sum() == 12 * 2 -def test_missing_pixels_of_any_channel_set_the_edge(): - """The scan's edge is where any channel lacks a value, whatever the - channels' order, and no missing pixel is marked.""" +def test_missing_pixels_of_any_channel_set_the_edge() -> None: + """The scan's edge is where any channel lacks a value, whatever the channels' order. + + No missing pixel is marked. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[:, :, 13] = np.nan # channel 1 misses one more column ch1[3:, :, 11:13] = 0.1 @@ -193,9 +206,11 @@ def test_missing_pixels_of_any_channel_set_the_edge(): assert a[3:, :, 11:13].all() and not a[:, :, 13:].any() -def test_no_source_left_is_not_a_reference(): - """When every source's sizes are NaN (all windows rejected), none is in - the normalization's reference set.""" +def test_no_source_left_is_not_a_reference() -> None: + """When every source's sizes are NaN, none is in the normalization's reference set. + + Every source's sizes are NaN when all windows are rejected. + """ from giant_python.spine.pipeline import _normalize nan = np.full((4, 3), np.nan) @@ -205,9 +220,11 @@ def test_no_source_left_is_not_a_reference(): assert np.isnan(norm["mean_ch1"]).all() -def test_a_trial_without_values_does_not_stop_the_search(): - """A trial with no value at all (not extracted) neither empties the - pixels every trial has nor gets marked.""" +def test_a_trial_without_values_does_not_stop_the_search() -> None: + """A trial with no value at all (not extracted) does not stop the search. + + It neither empties the pixels every trial has nor gets marked. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[1] = np.nan ch2[1] = np.nan @@ -218,20 +235,25 @@ def test_a_trial_without_values_does_not_stop_the_search(): assert un.sum() == 3 * 12 * 3 -def test_a_wide_band_does_not_set_the_brightness_scale(): - """Without the share limit, a band covering most of the field in two - trials is found, and the rest of the field is not marked in the other - trials; with it (default), such trials are skipped.""" +def test_a_wide_band_does_not_set_the_brightness_scale() -> None: + """Without the share limit, a band covering most of the field in two trials is found. + + The rest of the field is not marked in the other trials; with the limit + (default), such trials are skipped. + """ ch = np.full((6, 10, 10), 10.0) ch[4:, :, 4:] = 0.2 # 60% of the pixels un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) assert un[4:, :, 4:].all() and un.sum() == 2 * 10 * 6 -def test_a_band_too_large_to_tell_from_the_scene_is_not_marked(): - """A brightness change together with a band over most of the field - cannot be told from a change of the scene: such trials get nothing - marked and are reported, rather than losing their windows.""" +def test_a_band_too_large_to_tell_from_the_scene_is_not_marked() -> None: + """A brightness change with a band over most of the field cannot be told from a scene change. + + A brightness change together with a band over most of the field cannot be + told from a change of the scene: such trials get nothing marked and are + reported, rather than losing their windows. + """ ch = np.full((6, 10, 10), 2.0) ch[4:] = 10.0 ch[4:, :, 4:] = 0.2 @@ -246,9 +268,8 @@ def test_a_band_too_large_to_tell_from_the_scene_is_not_marked(): assert un[4:, :, 9:].all() and un.sum() == 2 * 10 and skipped.size == 0 -def test_wide_band_skipped_by_default(): - """With the default share limit, a band over 60% of the field is - reported, not marked.""" +def test_wide_band_skipped_by_default() -> None: + """With the default share limit, a band over 60% of the field is reported, not marked.""" ch = np.full((6, 10, 10), 10.0) ch[4:, :, 4:] = 0.2 un, skipped = unimaged_pixels([ch], frac=0.5, with_skipped=True) diff --git a/tests/spine/test_spine_gains.py b/tests/spine/test_spine_gains.py index ffff5d5b..e79630aa 100644 --- a/tests/spine/test_spine_gains.py +++ b/tests/spine/test_spine_gains.py @@ -19,9 +19,11 @@ from . import synthetic as syn -def test_gain_maps_average_overlapping_subproblems(tmp_path): - """A pixel in two subproblems gets the mean of its gains, and their - spread is reported.""" +def test_gain_maps_average_overlapping_subproblems(tmp_path) -> None: + """A pixel in two subproblems gets the mean of its gains. + + Their spread is reported. + """ work = syn.make_gain_work(tmp_path, lambda t: 1.0 + 0.1 * t) rows, cols, shape = selected_pixels(work / "plan" / "path1.h5") gain, spread, n_files = gain_maps(work, 1, syn.N_TRIALS) @@ -42,7 +44,7 @@ def test_gain_maps_average_overlapping_subproblems(tmp_path): assert np.isnan(gain[1, 0, 0]) -def test_trial_gains_needs_a_gain_record(tmp_path): +def test_trial_gains_needs_a_gain_record(tmp_path) -> None: """Results of a mode without gains are refused.""" path = tmp_path / "r.h5" with h5py.File(path, "w") as f: @@ -54,9 +56,8 @@ def test_trial_gains_needs_a_gain_record(tmp_path): trial_gains([path]) -def test_readout_adds_the_gain_image(tmp_path): - """``f0_gain`` is the gain times the network's image, at the selected - pixels.""" +def test_readout_adds_the_gain_image(tmp_path) -> None: + """``f0_gain`` is the gain times the network's image, at the selected pixels.""" s = syn.make_session(tmp_path) work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) rep = make_spine_summary( @@ -108,9 +109,12 @@ def test_readout_adds_the_gain_image(tmp_path): make_spine_summary(s["run"], s["table"], tmp_path, gain_work_dir=work) -def test_results_files_select_the_plan_and_the_exact_trial(tmp_path): - """Results of another plan are left out, a longer trial number with the - same prefix is not this trial, and two solves of the plan are refused.""" +def test_results_files_select_the_plan_and_the_exact_trial(tmp_path) -> None: + """Results of another plan are left out. + + A longer trial number with the same prefix is not this trial, and two + solves of the plan are refused. + """ work = syn.make_gain_work(tmp_path, lambda t: 1.0) res = work / "results" info = {"baseline_step": {"gain": [9.0]}} @@ -144,9 +148,11 @@ def test_results_files_select_the_plan_and_the_exact_trial(tmp_path): results_files(work, 1, 2) -def test_trial_gains_counts_a_copied_subproblem_once(tmp_path): - """A subproblem in two files (identical copies) is one subproblem; two - different copies are refused.""" +def test_trial_gains_counts_a_copied_subproblem_once(tmp_path) -> None: + """A subproblem in two files (identical copies) is one subproblem. + + Two different copies are refused. + """ work = syn.make_gain_work(tmp_path, lambda t: 1.0) rows, cols, _ = selected_pixels(work / "plan" / "path1.h5") n = rows.size @@ -168,9 +174,11 @@ def test_trial_gains_counts_a_copied_subproblem_once(tmp_path): gain_maps(work, 1, syn.N_TRIALS) -def test_trial_gains_refuses_a_shared_time_course(tmp_path): - """'gain_shared' subproblems are read only while their shared time - course is 1 (then the baseline is still gain x network baseline).""" +def test_trial_gains_refuses_a_shared_time_course(tmp_path) -> None: + """'gain_shared' subproblems are read only while their shared time course is 1. + + Then the baseline is still gain x network baseline. + """ path = tmp_path / "r.h5" step = {"gain": [2.0, 2.0], "shared": [1.0, 1.0, 1.0]} syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) @@ -182,7 +190,7 @@ def test_trial_gains_refuses_a_shared_time_course(tmp_path): trial_gains([path]) -def test_summary_key_follows_the_gain_plan(tmp_path): +def test_summary_key_follows_the_gain_plan(tmp_path) -> None: """A changed plan gives a new summary, not the old one reused.""" s = syn.make_session(tmp_path) work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) @@ -199,10 +207,12 @@ def test_summary_key_follows_the_gain_plan(tmp_path): assert rep2["key"] != rep["key"] and not rep2["reused"] -def test_gains_need_the_images_baseline_files(tmp_path): - """Gains are used only with the baseline files they were fitted - against: a baseline predicted again after the solve, or results that - record no network baseline, are refused.""" +def test_gains_need_the_images_baseline_files(tmp_path) -> None: + """Gains are used only with the baseline files they were fitted against. + + A baseline predicted again after the solve, or results that record no + network baseline, are refused. + """ import os s = syn.make_session(tmp_path) @@ -226,10 +236,12 @@ def test_gains_need_the_images_baseline_files(tmp_path): make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) -def test_trial_gains_needs_every_subproblem(tmp_path): - """As in the collect stage, a trial's results must hold all of its - subproblems: a missing shard, or files that disagree on the number of - subproblems, are refused; a trial too short to extract is not.""" +def test_trial_gains_needs_every_subproblem(tmp_path) -> None: + """As in the collect stage, a trial's results must hold all of its subproblems. + + A missing shard, or files that disagree on the number of subproblems, + are refused; a trial too short to extract is not. + """ info = {"baseline_step": {"gain": [1.0, 1.0]}} a, b = tmp_path / "a.h5", tmp_path / "b.h5" syn.write_results(a, {0: ([0, 1], info)}, n_subproblems=2) diff --git a/tests/spine/test_spine_images.py b/tests/spine/test_spine_images.py index b055e7d9..dc115d0e 100644 --- a/tests/spine/test_spine_images.py +++ b/tests/spine/test_spine_images.py @@ -19,20 +19,20 @@ from . import synthetic as syn -def test_kept_frames_trims_both_ends(): +def test_kept_frames_trims_both_ends() -> None: """The first and last round(trim_s * align_hz) frames are left out.""" keep = kept_frames(np.zeros(100), align_hz=10.0, trim_s=0.5) assert not keep[:5].any() and not keep[-5:].any() assert keep[5:95].all() -def test_kept_frames_falls_back_when_too_short(): +def test_kept_frames_falls_back_when_too_short() -> None: """A trial too short to trim keeps its frames that are not discarded.""" keep = kept_frames(np.zeros(10), align_hz=10.0, trim_s=1.0) assert keep.all() -def test_kept_frames_drops_motion_discards(): +def test_kept_frames_drops_motion_discards() -> None: """Frames SiLo discards for motion do not enter.""" rne = np.zeros(400) rne[200:204] = 1.0 # a sharp rise of the registration error @@ -41,13 +41,13 @@ def test_kept_frames_drops_motion_discards(): assert keep[:150].all() -def _baseline_file(path, frames): +def _baseline_file(path, frames) -> None: """Write ``frames`` ``(frame, rows, cols)`` as a baseline file.""" with h5py.File(path, "w") as f: f["baseline"] = np.transpose(frames, (0, 2, 1)).astype(np.float32) -def test_baseline_trial_mean_matches_numpy(tmp_path): +def test_baseline_trial_mean_matches_numpy(tmp_path) -> None: """The blockwise mean over kept frames equals numpy's, NaN kept out.""" rng = np.random.default_rng(1) frames = rng.random((70, 6, 9)) @@ -65,7 +65,7 @@ def test_baseline_trial_mean_matches_numpy(tmp_path): assert np.isnan(mean[0, 0]) -def test_baseline_trial_mean_checks_frame_count(tmp_path): +def test_baseline_trial_mean_checks_frame_count(tmp_path) -> None: """A frame mask of the wrong length is refused.""" path = tmp_path / "b.h5" _baseline_file(path, np.ones((10, 3, 3))) @@ -73,7 +73,7 @@ def test_baseline_trial_mean_checks_frame_count(tmp_path): baseline_trial_mean(path, np.ones(9, bool)) -def test_to_consensus_undoes_a_shift(): +def test_to_consensus_undoes_a_shift() -> None: """A shifted trial image lands back on the consensus scene.""" tmap = TrialMap( np.array([[[1, 0, 0], [0, 1, 0]], [[1, 0, 2], [0, 1, -1]]], float) @@ -87,7 +87,7 @@ def test_to_consensus_undoes_a_shift(): np.testing.assert_allclose(out[ok], scene[ok]) -def test_to_consensus_places_small_trials_top_left(): +def test_to_consensus_places_small_trials_top_left() -> None: """A trial smaller than the frame is padded at the bottom right.""" tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]]], float)) img = np.arange(12.0).reshape(3, 4) @@ -96,9 +96,11 @@ def test_to_consensus_places_small_trials_top_left(): assert np.isnan(out[3:]).all() and np.isnan(out[:, 4:]).all() -def test_network_f0_stack_recovers_the_scene(tmp_path): - """Per-trial F0 images equal the scaled scene where the trial covers - it, and the trimmed frames do not enter.""" +def test_network_f0_stack_recovers_the_scene(tmp_path) -> None: + """Per-trial F0 images equal the scaled scene where the trial covers it. + + The trimmed frames do not enter. + """ s = syn.make_session(tmp_path) tmap = TrialMap( np.stack([[[1, 0, dr], [0, 1, dc]] for dr, dc in syn.SHIFTS]).astype( @@ -121,7 +123,7 @@ def test_network_f0_stack_recovers_the_scene(tmp_path): assert st.inputs[0]["baseline"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" -def test_network_f0_stack_skips_missing_trials(tmp_path): +def test_network_f0_stack_skips_missing_trials(tmp_path) -> None: """Trials without a stem, a baseline file or a map stay NaN.""" s = syn.make_session(tmp_path) affine = np.zeros((syn.N_TRIALS, 2, 3)) @@ -136,7 +138,7 @@ def test_network_f0_stack_skips_missing_trials(tmp_path): assert list(st.n_frames[1:]) == [0, 0, 0] -def test_stack_key_changes_with_inputs(): +def test_stack_key_changes_with_inputs() -> None: """The cache key depends on every part.""" a = stack_key("x", {"trim_s": 1.0}, np.zeros(3)) assert a == stack_key("x", {"trim_s": 1.0}, np.zeros(3)) @@ -144,9 +146,11 @@ def test_stack_key_changes_with_inputs(): assert a != stack_key("x", {"trim_s": 1.0}, np.ones(3)) -def test_file_identity_keeps_folders_apart(tmp_path): - """Two files with the same name, size and modification time in - different folders have different identities.""" +def test_file_identity_keeps_folders_apart(tmp_path) -> None: + """Two files with the same name, size and modification time have different identities. + + The files are in different folders. + """ import os a = tmp_path / "a" / "x.h5" @@ -162,9 +166,11 @@ def test_file_identity_keeps_folders_apart(tmp_path): assert ia != ib -def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path): - """The aligned flags (a scan of every trial's map) are read once, not - per trial.""" +def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path) -> None: + """The aligned flags are read once, not per trial. + + Reading them is a scan of every trial's map. + """ s = syn.make_session(tmp_path) calls = [] @@ -186,7 +192,7 @@ def aligned(self): assert len(calls) == 1 -def test_trim_dropped_flags_untrimmed_trials(): +def test_trim_dropped_flags_untrimmed_trials() -> None: """trim_dropped says whether kept_frames had to drop the trim.""" from giant_python.spine.images import trim_dropped diff --git a/tests/spine/test_spine_pipeline.py b/tests/spine/test_spine_pipeline.py index 1f77ac40..ea98eed6 100644 --- a/tests/spine/test_spine_pipeline.py +++ b/tests/spine/test_spine_pipeline.py @@ -1,6 +1,7 @@ """End-to-end tests of ``giant spine`` on a synthetic session.""" import json +from typing import NoReturn import numpy as np import pytest @@ -21,11 +22,11 @@ @pytest.fixture def session(tmp_path): - """The synthetic session's folders.""" + """Make the synthetic session's folders.""" return syn.make_session(tmp_path) -def test_run_summary_reads_matlab_orientation(session): +def test_run_summary_reads_matlab_orientation(session) -> None: """Arrays come back in MATLAB's dimension order and orientation.""" run = RunSummary(session["run"]) assert run.paths == [1, 2] @@ -41,7 +42,7 @@ def test_run_summary_reads_matlab_orientation(session): np.testing.assert_allclose(act["mean_dF"][:, 0], 10 * np.arange(4) + 4.5) -def test_trial_map_needs_a_base_only_for_affine_maps(session): +def test_trial_map_needs_a_base_only_for_affine_maps(session) -> None: """Shift maps need no index base; true affine ones do.""" run = RunSummary(session["run"]) tm = run.trial_map(1) @@ -50,16 +51,18 @@ def test_trial_map_needs_a_base_only_for_affine_maps(session): np.testing.assert_allclose(r, [[1, 1], [2, 2]]) -def test_table_trials(session): +def test_table_trials(session) -> None: """Stems from the registered movies, numbers from the raw files.""" stems, acq = table_trials(session["table"], 2) assert stems[0] == "E1T1DMD2" np.testing.assert_array_equal(acq, [2, 3, 4, 5]) -def test_readout_writes_a_product(session, tmp_path): - """The readout's images, windows and normalized sizes are consistent, - and a rerun reuses the cache and the output.""" +def test_readout_writes_a_product(session, tmp_path) -> None: + """The readout's images, windows and normalized sizes are consistent. + + A rerun reuses the cache and the output. + """ out = tmp_path / "out" rep = make_spine_summary( session["run"], @@ -122,7 +125,7 @@ def test_readout_writes_a_product(session, tmp_path): assert not rep3["paths"][1]["f0_reused"] -def test_cli_readout_and_images(session, tmp_path, capsys): +def test_cli_readout_and_images(session, tmp_path, capsys) -> None: """``giant spine images`` fills the cache that ``readout`` reuses.""" out = tmp_path / "cli" common = [ @@ -147,7 +150,7 @@ def test_cli_readout_and_images(session, tmp_path, capsys): assert rep["paths"]["1"]["f0_reused"] and list(rep["paths"]) == ["1"] -def test_readout_without_baselines(tmp_path): +def test_readout_without_baselines(tmp_path) -> None: """Without baselines the run's own images are read out.""" s = syn.make_session(tmp_path, with_f0_silo=False) rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") @@ -155,7 +158,7 @@ def test_readout_without_baselines(tmp_path): assert set(p["images"]) == {"mean_ch1", "mean_ch2"} -def test_baselines_need_the_moco_folder(session, tmp_path): +def test_baselines_need_the_moco_folder(session, tmp_path) -> None: """A baseline folder without the motion-correction folder is refused.""" with pytest.raises(ValueError, match="both"): make_spine_summary( @@ -166,9 +169,11 @@ def test_baselines_need_the_moco_folder(session, tmp_path): ) -def test_activity_uses_the_activity_channel(tmp_path): - """Activity comes from ``params/activityChannel``; a trial without - traces is NaN, not inactive.""" +def test_activity_uses_the_activity_channel(tmp_path) -> None: + """Activity comes from ``params/activityChannel``. + + A trial without traces is NaN, not inactive. + """ s = syn.make_session(tmp_path, activity_channel=2, missing_trial=1) run = RunSummary(s["run"]) assert run.activity_channel() == 2 @@ -181,7 +186,7 @@ def test_activity_uses_the_activity_channel(tmp_path): assert np.isnan(act["event_frames"][1]).all() -def test_summary_key_follows_the_paths(tmp_path): +def test_summary_key_follows_the_paths(tmp_path) -> None: """Different path selections give different summaries.""" s = syn.make_session(tmp_path) keys = { @@ -193,7 +198,7 @@ def test_summary_key_follows_the_paths(tmp_path): assert len(set(keys.values())) == 3 -def test_network_images_take_a_trial_warp(session, tmp_path): +def test_network_images_take_a_trial_warp(session, tmp_path) -> None: """The extraction plan's TrialWarp works as the trial map.""" from giant_python.extraction.raster.alignment import TrialWarp from giant_python.spine.images import network_f0_stack @@ -210,15 +215,17 @@ def test_network_images_take_a_trial_warp(session, tmp_path): assert np.isfinite(a.images).any() -def test_write_atomic_gives_each_writer_its_own_file(tmp_path): - """A writer that starts while another is writing the same file does not - share its temporary file; both finish, and nothing is left behind. A - failed write leaves no file.""" +def test_write_atomic_gives_each_writer_its_own_file(tmp_path) -> None: + """A writer that starts while another is writing the same file has its own temporary file. + + It does not share the other's temporary file; both finish, and nothing is + left behind. A failed write leaves no file. + """ from giant_python.spine.pipeline import _write_atomic dest = tmp_path / "out" / "x.txt" - def outer(tmp): + def outer(tmp) -> None: """Write, with a second writer of the same file in between.""" tmp.write_text("outer") _write_atomic(dest, lambda t: t.write_text("inner")) @@ -228,8 +235,8 @@ def outer(tmp): assert dest.read_text() == "outer" assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] - def fail(tmp): - """A write that fails.""" + def fail(tmp) -> NoReturn: + """Write partially, then fail.""" tmp.write_text("partial") raise RuntimeError("stop") @@ -239,7 +246,7 @@ def fail(tmp): assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] -def test_stem_strips_windows_folders(): +def test_stem_strips_windows_folders() -> None: """A table written on Windows gives the bare stem on any system.""" name = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" assert _stem("C:\\moco\\" + name) == "E1T1DMD1" @@ -247,9 +254,11 @@ def test_stem_strips_windows_folders(): assert _stem("E1T1DMD1.tif") is None -def test_network_images_follow_the_runs_discards(tmp_path): - """Without overrides the network images leave out the frames the run - discarded (``params/discardInitial_s``); an explicit value wins.""" +def test_network_images_follow_the_runs_discards(tmp_path) -> None: + """Without overrides the network images leave out the frames the run discarded. + + These are ``params/discardInitial_s``; an explicit value wins. + """ s = syn.make_session(tmp_path, discard_initial_s=0.5) kw = dict(baseline_dir=s["baselines"], moco_dir=s["moco"], trim_s=0.1) rep = make_spine_summary(s["run"], s["table"], tmp_path / "a", **kw) @@ -265,9 +274,12 @@ def test_network_images_follow_the_runs_discards(tmp_path): assert (n0["n_frames"] == syn.N_FRAMES - 16).all() -def test_affine_maps_convert_from_one_based(tmp_path): - """A true affine map written one-based (GIAnT-MATLAB) gives the same - zero-based positions as the zero-based map (GIAnT-Python).""" +def test_affine_maps_convert_from_one_based(tmp_path) -> None: + """A true affine map written one-based gives the same positions as the zero-based map. + + The one-based map is GIAnT-MATLAB's, the zero-based one GIAnT-Python's; + both give the same zero-based positions. + """ lin = np.array([[1.01, 0.02], [-0.015, 0.99]]) b0 = np.array([1.5, -2.25]) a0 = np.zeros((syn.N_TRIALS, 2, 3)) @@ -290,7 +302,7 @@ def test_affine_maps_convert_from_one_based(tmp_path): np.testing.assert_allclose(c, expect_c, atol=1e-12) -def test_product_records_the_activity_channel(tmp_path): +def test_product_records_the_activity_channel(tmp_path) -> None: """The product says which file channel is the run's activity.""" s = syn.make_session(tmp_path, activity_channel=2) rep = make_spine_summary(s["run"], s["table"], tmp_path / "out") @@ -299,9 +311,11 @@ def test_product_records_the_activity_channel(tmp_path): assert {"mean_ch1", "mean_ch2"} <= set(prod["paths"][1]["images"]) -def test_displacement_maps_end_to_end(tmp_path): - """A run with a displacement field (patchwise alignment) puts the - network's trials in place through the field, not the affine maps.""" +def test_displacement_maps_end_to_end(tmp_path) -> None: + """A run with a displacement field puts the network's trials in place through the field. + + The field comes from the patchwise alignment; the affine maps are not used. + """ kw = dict(trim_s=0.1) s = syn.make_session(tmp_path / "d", displacement=True) run = RunSummary(s["run"]) @@ -343,12 +357,14 @@ def test_displacement_maps_end_to_end(tmp_path): assert np.abs(net / p0["images"]["f0_silo_ch1"][1:, ok0] - 1).max() > 1e-2 -def test_fitted_images_do_not_shrink_the_windows(tmp_path): - """SILo's own F0 images, with values only at the pixels it fitted, are - read out in the windows of the field images: the sources (inside the - fitted pixels) read as before, a user ROI partly outside keeps its +def test_fitted_images_do_not_shrink_the_windows(tmp_path) -> None: + """SILo's own F0 images are read out in the windows of the field images. + + The images have values only at the pixels SILo fitted. The sources (inside + the fitted pixels) read as before, a user ROI partly outside keeps its readouts of the other images and gets NaN in f0_silo, and the report - counts it.""" + counts it. + """ kw = dict(trim_s=0.1) full = syn.make_session(tmp_path / "full") box = syn.make_session( @@ -405,9 +421,11 @@ def test_fitted_images_do_not_shrink_the_windows(tmp_path): assert sum("does not cover" in m for m in notes) == 4 # 2 images x 2 paths -def test_no_shared_trial_reads_nothing(): - """Field images without a trial in common leave no trial and no valid - pixel, with a note, rather than windows over the whole frame.""" +def test_no_shared_trial_reads_nothing() -> None: + """Field images without a trial in common leave no trial and no valid pixel. + + They leave a note, rather than windows over the whole frame. + """ from giant_python.spine.readout import common_valid a = np.ones((4, 3, 3)) @@ -425,10 +443,12 @@ def test_no_shared_trial_reads_nothing(): assert not common_valid([a, b], used).any() -def test_acquisition_numbers_from_the_file_name(tmp_path): - """The acquisition number is read from the raw file's own name (not a - folder that also says TRIAL, with either separator), and a table whose - raw and registered lists differ in length is refused.""" +def test_acquisition_numbers_from_the_file_name(tmp_path) -> None: + """The acquisition number is read from the raw file's own name. + + Not from a folder that also says TRIAL, with either separator; and a table + whose raw and registered lists differ in length is refused. + """ from giant_python.io.hdf5 import save_struct_h5 reg = np.array( @@ -470,9 +490,11 @@ def test_acquisition_numbers_from_the_file_name(tmp_path): table_trials(table, 1) -def test_untrimmed_trials_are_reported(session, tmp_path): - """A trial too short for the trim is averaged whole, as GIAnT-MATLAB - does, and the product, the report and a note say so.""" +def test_untrimmed_trials_are_reported(session, tmp_path) -> None: + """A trial too short for the trim is averaged whole, as GIAnT-MATLAB does. + + The product, the report and a note say so. + """ notes = [] kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"]) # 160 frames: a 1 s trim at 80 Hz leaves nothing @@ -498,10 +520,12 @@ def test_untrimmed_trials_are_reported(session, tmp_path): assert "f0_untrimmed" not in rep["paths"][1] -def test_readout_runs_the_trend_tests(session, tmp_path): - """Every normalized image gets the trend tests over its trials, with - trial positions as trial-table indices; the test settings change the - output's key but not the network images' cache.""" +def test_readout_runs_the_trend_tests(session, tmp_path) -> None: + """Every normalized image gets the trend tests over its trials. + + Trial positions are trial-table indices; the test settings change the + output's key but not the network images' cache. + """ from giant_python.spine.trends import trend_tests kw = dict( @@ -556,9 +580,8 @@ def test_readout_runs_the_trend_tests(session, tmp_path): assert np.isnan(p2["trends"]["sources"]["f0_net"]["step_p"]).all() -def test_readout_refuses_bad_trend_settings(session, tmp_path): - """Invalid trend settings are refused before anything is read or - reused.""" +def test_readout_refuses_bad_trend_settings(session, tmp_path) -> None: + """Invalid trend settings are refused before anything is read or reused.""" with pytest.raises(ValueError, match="fdr_q"): make_spine_summary( session["run"], session["table"], tmp_path / "o", fdr_q=2.0 @@ -570,15 +593,17 @@ def test_readout_refuses_bad_trend_settings(session, tmp_path): assert not (tmp_path / "o").exists() -def test_trials_without_numbers_are_noted(session, tmp_path, monkeypatch): - """A trial whose raw file has no acquisition number is left out of the - brief test's runs, and the summary's notes say so.""" +def test_trials_without_numbers_are_noted(session, tmp_path, monkeypatch) -> None: + """A trial whose raw file has no acquisition number is left out of the brief test's runs. + + The summary's notes say so. + """ import giant_python.spine.pipeline as pl real = pl.table_trials def no_number(table, path): - """The table's trials with trial 2 unnumbered.""" + """Return the table's trials with trial 2 unnumbered.""" stems, acq = real(table, path) acq = acq.copy() acq[1] = -1 @@ -599,10 +624,12 @@ def no_number(table, path): assert blocks[1] != blocks[0] and blocks[1] != blocks[2] -def test_unnumbered_trials_follow_the_path_not_the_image(): - """With some numbered trials on the path, unnumbered trials stay - blocks of their own even in an image that covers only them; with no - numbers on the path, the table's order stands in (gaps split).""" +def test_unnumbered_trials_follow_the_path_not_the_image() -> None: + """With some numbered trials on the path, unnumbered trials stay blocks of their own. + + This holds even in an image that covers only them; with no numbers on the + path, the table's order stands in (gaps split). + """ from giant_python.spine.pipeline import _trends vals = np.random.default_rng(0).normal(size=(6, 4)) * 0.1 @@ -623,11 +650,13 @@ def test_unnumbered_trials_follow_the_path_not_the_image(): ) -def test_readout_calls_and_quality_columns(session, tmp_path, capsys): - """The default image and its calls go into the summary and the report; - every image but the structural one gets the structural channel's change - at its own split; the windows' motion beyond the trials' shifts is 0 - for shifts.""" +def test_readout_calls_and_quality_columns(session, tmp_path, capsys) -> None: + """The default image and its calls go into the summary and the report. + + Every image but the structural one gets the structural channel's change + at its own split; the windows' motion beyond the trials' shifts is 0 for + shifts. + """ from giant_python.spine.qc import structural_change kw = dict( @@ -693,9 +722,11 @@ def test_readout_calls_and_quality_columns(session, tmp_path, capsys): assert pr["paths"][1]["primary_image"] == "f0_silo_ch1" -def test_window_motion_needs_no_affine_base(tmp_path): - """Affine maps without a given index base still get the column (the - base moves only the translation).""" +def test_window_motion_needs_no_affine_base(tmp_path) -> None: + """Affine maps without a given index base still get the column. + + The base moves only the translation. + """ a = np.zeros((syn.N_TRIALS, 2, 3)) for t, ang in enumerate((0.0, 0.01, -0.01, 0.02)): c, s_ = np.cos(ang), np.sin(ang) @@ -708,10 +739,12 @@ def test_window_motion_needs_no_affine_base(tmp_path): assert np.isfinite(m).all() and (m > 0).all() -def test_default_image_without_trend_tests(tmp_path, monkeypatch): - """With too few trials for the trend tests, the default image still - comes from the images with sizes (here the run's F0 of activity - channel 2), and no calls are reported.""" +def test_default_image_without_trend_tests(tmp_path, monkeypatch) -> None: + """With too few trials for the trend tests, the default image still comes from sizes. + + It comes from the images with sizes (here the run's F0 of activity + channel 2), and no calls are reported. + """ import giant_python.spine.pipeline as pl monkeypatch.setattr(pl, "_trends", lambda *a, **k: ({}, {})) @@ -723,10 +756,12 @@ def test_default_image_without_trend_tests(tmp_path, monkeypatch): assert "calls" not in rep["paths"][1] -def test_default_image_needs_finite_sizes(tmp_path): - """An image that covers no window keeps its key with only NaN sizes; - it is not the default (here the run's F0 limited to a corner, so the - activity channel's mean takes its place).""" +def test_default_image_needs_finite_sizes(tmp_path) -> None: + """An image that covers no window keeps its key with only NaN sizes. + + It is not the default (here the run's F0 limited to a corner, so the + activity channel's mean takes its place). + """ s = syn.make_session(tmp_path, f0_silo_box=(slice(0, 2), slice(0, 2))) rep = make_spine_summary(s["run"], s["table"], tmp_path / "o", n_perm=50) p = read_product(rep["output"])["paths"][1] diff --git a/tests/spine/test_spine_qc.py b/tests/spine/test_spine_qc.py index a65fd859..580d344b 100644 --- a/tests/spine/test_spine_qc.py +++ b/tests/spine/test_spine_qc.py @@ -1,5 +1,7 @@ -"""Tests of the readout's quality columns and default image -(:mod:`giant_python.spine.qc`).""" +"""Tests of the readout's quality columns and default image. + +The module under test is :mod:`giant_python.spine.qc`. +""" import numpy as np import pytest @@ -18,9 +20,11 @@ def _shift_field(shifts, bump=None): - """A displacement field per trial: the shifts everywhere, plus - ``bump`` = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) - of extra row displacement.""" + """Build a displacement field per trial: the shifts everywhere, plus a bump. + + ``bump`` = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) of + extra row displacement. + """ T = len(shifts) disp = np.broadcast_to( np.asarray(shifts, float)[:, :, None, None], (T, 2, syn.H, syn.W) @@ -34,10 +38,13 @@ def _shift_field(shifts, bump=None): return TrialMap(eye, disp) -def test_primary_and_structural_images(): - """The default image is f0_gain, then f0_net, then the run's own F0 - and the mean of the activity channel; the structural image is the - first mean image of another channel.""" +def test_primary_and_structural_images() -> None: + """The default image and the structural image are chosen in order. + + The default image is f0_gain, then f0_net, then the run's own F0 and the + mean of the activity channel; the structural image is the first mean image + of another channel. + """ names = ["mean_ch1", "mean_ch2", "f0_net", "f0_gain", "f0_silo_ch1"] assert primary_image(names, 1) == "f0_gain" assert primary_image(names[:3], 1) == "f0_net" @@ -54,9 +61,11 @@ def test_primary_and_structural_images(): assert structural_image(["mean_ch1", "f0_net"], 1) is None -def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp(): - """Shifts move every window alike (0); a local warp in one trial moves - the window it covers and hardly the others.""" +def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp() -> None: + """Shifts move every window alike (0). + + A local warp in one trial moves the window it covers and hardly the others. + """ rs = sources_roiset(syn.footprints()) valid = np.ones((syn.H, syn.W), bool) trials = np.arange(syn.N_TRIALS) @@ -76,9 +85,11 @@ def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp(): assert m[0] == pytest.approx(np.std([0, 0, a, 0], ddof=1), rel=0.05) -def test_window_motion_of_affine_maps_ignores_the_index_base(): - """A rotation moves windows away from the centre; the index base only - moves the translation, which the column removes.""" +def test_window_motion_of_affine_maps_ignores_the_index_base() -> None: + """A rotation moves windows away from the centre. + + The index base only moves the translation, which the column removes. + """ rs = sources_roiset(syn.footprints()) valid = np.ones((syn.H, syn.W), bool) T = 3 @@ -95,7 +106,7 @@ def test_window_motion_of_affine_maps_ignores_the_index_base(): np.testing.assert_allclose(m, m1, atol=1e-9) -def test_window_motion_without_trials_or_pixels_is_nan(): +def test_window_motion_without_trials_or_pixels_is_nan() -> None: """Fewer than two aligned trials, or no valid pixel, give NaN.""" rs = sources_roiset(syn.footprints()) valid = np.ones((syn.H, syn.W), bool) @@ -110,9 +121,12 @@ def test_window_motion_without_trials_or_pixels_is_nan(): np.testing.assert_allclose(m, 0, atol=1e-12) -def test_structural_change_is_the_step_beyond_the_trend_at_the_split(): - """The structural channel's change at given splits: its own shared - trend removed, the mean after minus the mean before.""" +def test_structural_change_is_the_step_beyond_the_trend_at_the_split() -> None: + """The structural channel's change at given splits. + + With its own shared trend removed, it is the mean after minus the mean + before. + """ rng = np.random.default_rng(5) T, n = 12, 20 # a shared drift orthogonal to the planted step @@ -139,9 +153,11 @@ def test_structural_change_is_the_step_beyond_the_trend_at_the_split(): assert np.isnan(structural_change(L[:2], ok, np.ones(n, int))).all() -def test_structural_change_centres_a_subset_of_trials(): - """Over a subset of the trials the series are not centred; an offset - per source must not take the place of the shared trend.""" +def test_structural_change_centres_a_subset_of_trials() -> None: + """Over a subset of the trials the series are not centred. + + An offset per source must not take the place of the shared trend. + """ rng = np.random.default_rng(8) T, n = 12, 20 step = (np.arange(T) >= 6) - 0.5 diff --git a/tests/spine/test_spine_readout.py b/tests/spine/test_spine_readout.py index 23d2cfa9..09e25cb6 100644 --- a/tests/spine/test_spine_readout.py +++ b/tests/spine/test_spine_readout.py @@ -1,5 +1,8 @@ -"""Tests of the spine-size windows and readout (:mod:`giant_python.spine.rois` -and :mod:`giant_python.spine.readout`).""" +"""Tests of the spine-size windows and readout. + +The modules tested are :mod:`giant_python.spine.rois` and +:mod:`giant_python.spine.readout`. +""" import numpy as np import pytest @@ -22,7 +25,7 @@ from . import synthetic as syn -def test_sources_roiset_is_sparse_and_centred(): +def test_sources_roiset_is_sparse_and_centred() -> None: """Footprints are stored as their positive pixels, centroids weighted.""" fp = syn.footprints() rs = sources_roiset(fp) @@ -34,13 +37,13 @@ def test_sources_roiset_is_sparse_and_centred(): assert (w > 0).all() and idx.size == (fp[k] > 0).sum() -def test_masks_roiset_needs_one_label_per_mask(): +def test_masks_roiset_needs_one_label_per_mask() -> None: """Labels and masks must agree in number.""" with pytest.raises(ValueError, match="labels"): masks_roiset(np.zeros((2, 4, 4), bool), ["a"]) -def test_project_is_the_matlab_formula(): +def test_project_is_the_matlab_formula() -> None: """``F = (h . x) / (h . h)`` with h normalized over the valid pixels.""" rng = np.random.default_rng(2) fp = syn.footprints() @@ -57,9 +60,11 @@ def test_project_is_the_matlab_formula(): assert n_pix[0] == (fp[0] > 0).sum() - 1 -def test_project_is_scale_equivariant(): - """A uniform brightness change scales every readout by the same - factor, so it cancels in the normalization.""" +def test_project_is_scale_equivariant() -> None: + """A uniform brightness change scales every readout by the same factor. + + So it cancels in the normalization. + """ fp = syn.footprints() img = syn.scene(1)[None] rs = sources_roiset(fp) @@ -69,7 +74,7 @@ def test_project_is_scale_equivariant(): np.testing.assert_allclose(b, 0.8 * a) -def test_common_valid_requires_every_trial_and_stack(): +def test_common_valid_requires_every_trial_and_stack() -> None: """A pixel missing in one trial of one stack is not valid.""" a = np.ones((3, 4, 5)) b = np.ones((3, 4, 5)) @@ -82,7 +87,7 @@ def test_common_valid_requires_every_trial_and_stack(): assert not common_valid([a, b], []).any() -def test_mask_mean_and_coverage(): +def test_mask_mean_and_coverage() -> None: """Mean over the mask's pixels with a value; coverage is their share.""" masks = np.zeros((1, 4, 4), bool) masks[0, :2, :2] = True @@ -94,9 +99,11 @@ def test_mask_mean_and_coverage(): np.testing.assert_allclose(cov[:, 0], [1.0, 0.75]) -def test_norm_log_matches_spinetrends(): - """log F, minus each trial's median over the ok ROIs, minus each ROI's - mean (``normLog`` of ``spineTrends.m``).""" +def test_norm_log_matches_spinetrends() -> None: + """Log F, minus each trial's median over the ok ROIs, minus each ROI's mean. + + This is ``normLog`` of ``spineTrends.m``. + """ rng = np.random.default_rng(3) f = np.exp(rng.normal(size=(7, 9))) ok = np.ones(9, bool) @@ -107,7 +114,7 @@ def test_norm_log_matches_spinetrends(): np.testing.assert_allclose(norm_log(f, ok), expect) -def test_norm_log_removes_a_shared_trend(): +def test_norm_log_removes_a_shared_trend() -> None: """A brightness factor shared by all ROIs (bleaching) leaves zeros.""" sizes = np.array([1.0, 2.0, 3.0]) trend = np.array([1.0, 0.9, 0.8, 0.7]) @@ -115,7 +122,7 @@ def test_norm_log_removes_a_shared_trend(): np.testing.assert_allclose(out, 0, atol=1e-12) -def test_nearest_and_disks(): +def test_nearest_and_disks() -> None: """Points find the nearest ROI within a distance.""" rs = disks_roiset([5.0, 10.0], [5.0, 20.0], 2.0, (20, 30)) assert rs.meta["radius"] == 2.0 @@ -124,7 +131,7 @@ def test_nearest_and_disks(): ) -def test_marks_round_trip(tmp_path): +def test_marks_round_trip(tmp_path) -> None: """Marks keep GIAnT-MATLAB's spine_marks.csv columns.""" marks = [ { diff --git a/tests/spine/test_spine_trends.py b/tests/spine/test_spine_trends.py index 4115953b..aa1f6d43 100644 --- a/tests/spine/test_spine_trends.py +++ b/tests/spine/test_spine_trends.py @@ -1,6 +1,8 @@ -"""Tests of the trend tests (:mod:`giant_python.spine.trends`), against -direct transcriptions of GIAnT-MATLAB's ``spineTrends.m`` and -``spineTrendsResid.m``.""" +"""Tests of the trend tests (:mod:`giant_python.spine.trends`). + +They test against direct transcriptions of GIAnT-MATLAB's ``spineTrends.m`` and +``spineTrendsResid.m``. +""" import math @@ -70,18 +72,22 @@ def _brief_loop(x, blk, max_w): return tb, sb, wb, db -def test_trial_blocks_split_at_gaps(): - """A new block starts where the acquisition number jumps by more than 1 - (a repeat or a decrease does not start one, as in MATLAB).""" +def test_trial_blocks_split_at_gaps() -> None: + """A new block starts where the acquisition number jumps by more than 1. + + A repeat or a decrease does not start one, as in MATLAB. + """ np.testing.assert_array_equal( trial_blocks([2, 3, 4, 7, 8, 8, 6, 10]), [0, 0, 0, 1, 1, 1, 1, 2] ) assert trial_blocks([]).size == 0 -def test_trials_without_numbers_are_blocks_of_their_own(): - """A trial without an acquisition number is neither in a brief run nor - a neighbour of one; with no numbers at all, trials are consecutive.""" +def test_trials_without_numbers_are_blocks_of_their_own() -> None: + """A trial without an acquisition number is neither in a brief run nor a neighbour of one. + + With no numbers at all, trials are consecutive. + """ np.testing.assert_array_equal( trial_blocks([10, 11, -1, -1, 14, 15]), [0, 0, 1, 2, 3, 3] ) @@ -98,10 +104,12 @@ def test_trials_without_numbers_are_blocks_of_their_own(): assert start[0] == 3 -def test_image_blocks_keep_the_paths_boundaries(): - """A subset of a path's trials keeps the path's block boundaries, also - with acquisition numbers out of order, and splits where it skips a - trial.""" +def test_image_blocks_keep_the_paths_boundaries() -> None: + """A subset of a path's trials keeps the path's block boundaries. + + This holds also with acquisition numbers out of order, and the subset + splits where it skips a trial. + """ from giant_python.spine.trends import image_blocks pb = trial_blocks([1, 5, 2, 3]) # 1 | 5, 2, 3 (a decrease joins) @@ -137,13 +145,13 @@ def test_image_blocks_keep_the_paths_boundaries(): (dict(min_change=float("nan")), "min_change"), ], ) -def test_trend_settings_are_checked(kw, match): +def test_trend_settings_are_checked(kw, match) -> None: """Settings the tests cannot use are refused.""" with pytest.raises(ValueError, match=match): trend_tests(np.zeros((5, 2)), np.ones(2, bool), np.arange(5), **kw) -def test_step_stat_is_the_matlab_loop(): +def test_step_stat_is_the_matlab_loop() -> None: """Cumulative sums give MATLAB's statistic, split and size.""" rng = np.random.default_rng(3) x = rng.normal(size=(200, 17)) * 0.1 @@ -158,10 +166,11 @@ def test_step_stat_is_the_matlab_loop(): np.testing.assert_allclose(d, got[2], rtol=1e-10, atol=1e-15) -def test_no_step_or_run_keeps_a_missing_position(): - """A series without a non-zero statistic reports no split and no run - (not the first trial), and so does the summary through the pipeline's - mapping.""" +def test_no_step_or_run_keeps_a_missing_position() -> None: + """A series without a non-zero statistic reports no split and no run (not the first trial). + + So does the summary through the pipeline's mapping. + """ x = np.zeros((2, 8)) x[1] = np.arange(8) * 0.01 t, k, d = step_stat(x) @@ -184,15 +193,17 @@ def test_no_step_or_run_keeps_a_missing_position(): assert r["brief_start"][0] == -1 and r["brief_len"][0] == 0 -def test_step_at_out_of_range_is_nan(): +def test_step_at_out_of_range_is_nan() -> None: """A split outside 1..T-1 gives NaN.""" t, d = step_at(np.zeros((2, 5)) + [[0, 1, 2, 3, 4]], [0, 2]) assert np.isnan(t[0]) and np.isnan(d[0]) and d[1] == 2.5 -def test_median_without_matches_numpy(): - """The median once some ranks are taken out equals np.median of what - is left, ties included.""" +def test_median_without_matches_numpy() -> None: + """The median once some ranks are taken out equals np.median of what is left. + + Ties included. + """ rng = np.random.default_rng(5) for m_all, k in ((9, 2), (10, 3), (12, 4), (5, 4)): vals = rng.integers(0, 4, size=(300, m_all)).astype(float) @@ -211,7 +222,7 @@ def test_median_without_matches_numpy(): np.testing.assert_array_equal(got, np.median(vals[:, keep], 1)) -def test_brief_stat_is_the_matlab_loop(): +def test_brief_stat_is_the_matlab_loop() -> None: """The brief statistic, run and size equal MATLAB's, with blocks.""" rng = np.random.default_rng(4) T = 15 @@ -231,7 +242,7 @@ def test_brief_stat_is_the_matlab_loop(): assert np.median(start) == 6 and np.median(length) == 2 -def test_brief_stat_keeps_runs_inside_blocks(): +def test_brief_stat_keeps_runs_inside_blocks() -> None: """No run (or its neighbours) crosses a block boundary.""" x = np.zeros((1, 8)) x[0, 3] = 1.0 # trial 3 starts block 1: no neighbours before it there @@ -241,8 +252,8 @@ def test_brief_stat_keeps_runs_inside_blocks(): assert start[0] != 3 -def test_bh_adjust_is_the_step_up_rule(): - """q <= level exactly where the step-up rule rejects; NaN stays NaN.""" +def test_bh_adjust_is_the_step_up_rule() -> None: + """Q <= level exactly where the step-up rule rejects; NaN stays NaN.""" rng = np.random.default_rng(6) p = np.concatenate([rng.uniform(size=80), rng.uniform(0, 0.002, 20)]) p[5] = np.nan @@ -261,9 +272,8 @@ def test_bh_adjust_is_the_step_up_rule(): ) -def test_shared_mode_sign_and_share(): - """A rank-one pattern is recovered with all the variance, signed - positive at the end.""" +def test_shared_mode_sign_and_share() -> None: + """A rank-one pattern is recovered with all the variance, signed positive at the end.""" v0 = np.linspace(1, -1, 10) v0 /= np.linalg.norm(v0) x = np.outer([1.0, -2.0, 0.5], v0) @@ -275,9 +285,11 @@ def test_shared_mode_sign_and_share(): def _session(rng, n_src=40, T=20, step=0.25): - """Normalized-like sizes (trials, sources): noise, a shared drift (most - of the variance, as in real sessions) and one source with a step after - trial 9.""" + """Normalized-like sizes (trials, sources) with a shared drift and one step. + + Noise, a shared drift (most of the variance, as in real sessions) and + one source with a step after trial 9. + """ drift = np.linspace(-0.2, 0.2, T) x = rng.normal(size=(T, n_src)) * 0.05 + drift[:, None] * rng.normal( size=n_src @@ -286,9 +298,11 @@ def _session(rng, n_src=40, T=20, step=0.25): return x - x.mean(0) -def test_trend_tests_find_a_planted_step(): - """A planted step has small p and q; beyond the shared drift, the other - sources do not pile up at small p.""" +def test_trend_tests_find_a_planted_step() -> None: + """A planted step has small p and q. + + Beyond the shared drift, the other sources do not pile up at small p. + """ rng = np.random.default_rng(7) x = _session(rng) ok = np.ones(x.shape[1], bool) @@ -317,11 +331,13 @@ def test_trend_tests_find_a_planted_step(): assert r["shared_v"].shape == (20,) and 0 < r["var_share"] < 1 -def test_trend_tests_p_does_not_depend_on_the_others_or_threads(): - """Each source has its own trial orders: the step and brief p are the - same whichever other sources are tested, and no p depends on the - threads; the beyond-trend test depends on the tested set through the - shared trend.""" +def test_trend_tests_p_does_not_depend_on_the_others_or_threads() -> None: + """Each source has its own trial orders. + + The step and brief p are the same whichever other sources are tested, + and no p depends on the threads; the beyond-trend test depends on the + tested set through the shared trend. + """ rng = np.random.default_rng(8) x = _session(rng, n_src=6, T=12) acq = np.arange(12) @@ -337,9 +353,11 @@ def test_trend_tests_p_does_not_depend_on_the_others_or_threads(): assert not np.allclose(c["shared_v"], a["shared_v"]) -def test_ties_at_the_edge_split_count(): - """One outlying first trial: every order that puts it first or last - gives the same statistic, so p is about 2/T, not tiny.""" +def test_ties_at_the_edge_split_count() -> None: + """One outlying first trial gives p about 2/T, not tiny. + + Every order that puts it first or last gives the same statistic. + """ rng = np.random.default_rng(9) T = 20 x = rng.normal(size=(T, 1)) * 0.01 @@ -349,10 +367,12 @@ def test_ties_at_the_edge_split_count(): assert r["step_p"][0] == pytest.approx(2 / T, abs=0.02) -def test_noise_free_edge_outlier_ties_with_its_mirror(): - """A series without spread apart from one end trial has an infinite - step statistic, equal for the series and its mirror image, so every - order that puts the trial at either end ties (p about 2/T).""" +def test_noise_free_edge_outlier_ties_with_its_mirror() -> None: + """A series without spread apart from one end trial has an infinite step statistic. + + The statistic is equal for the series and its mirror image, so every + order that puts the trial at either end ties (p about 2/T). + """ x = np.zeros((2, 10)) x[0, -1] = 1.0 x[1, 0] = 1.0 @@ -371,7 +391,7 @@ def test_noise_free_edge_outlier_ties_with_its_mirror(): np.testing.assert_array_equal(step_at(x, [9, 1])[0], step_stat(x)[0]) -def test_trend_tests_without_permutations(): +def test_trend_tests_without_permutations() -> None: """n_perm 0 gives the statistics without p or q.""" rng = np.random.default_rng(10) x = _session(rng, n_src=5, T=10) @@ -381,15 +401,17 @@ def test_trend_tests_without_permutations(): assert r["counts"]["step"]["fdr_up"] == 0 -def test_trend_tests_need_three_trials(): +def test_trend_tests_need_three_trials() -> None: """Fewer than three trials: nothing is tested.""" r = trend_tests(np.zeros((2, 3)), np.ones(3, bool), [1, 2], n_perm=10) assert not r["tested"].any() and np.isnan(r["step_t"]).all() -def test_permutations_in_chunks_give_the_same_p(): - """The orders are drawn in chunks to bound memory; the p-values do not - depend on the chunk size.""" +def test_permutations_in_chunks_give_the_same_p() -> None: + """The orders are drawn in chunks to bound memory. + + The p-values do not depend on the chunk size. + """ from giant_python.spine.trends import _perm_p rng = np.random.default_rng(11) @@ -406,7 +428,7 @@ def test_permutations_in_chunks_give_the_same_p(): assert _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3, rows) == one -def test_trial_orders_are_seeded_permutations(): +def test_trial_orders_are_seeded_permutations() -> None: """Each row is a permutation; the same seed and source repeat.""" o = trial_orders(1, 7, 50, 9) assert (np.sort(o, axis=1) == np.arange(9)).all() @@ -415,10 +437,13 @@ def test_trial_orders_are_seeded_permutations(): assert trial_orders(1, 7, 0, 9).shape == (0, 9) -def test_calls_need_q_and_the_minimum_change(): - """A call is a change beyond the shared trend with q <= fdr_q and a - relative size of at least min_change, in either direction; a small - change that the test finds is not called, an untested source never.""" +def test_calls_need_q_and_the_minimum_change() -> None: + """A call is a change beyond the shared trend with q <= fdr_q and enough size. + + The relative size must be at least min_change, in either direction; a + small change that the test finds is not called, an untested source + never. + """ rng = np.random.default_rng(3) T, n_src = 20, 40 # a shared drift orthogonal to the planted steps' shape, so that diff --git a/tests/spine/test_spine_view.py b/tests/spine/test_spine_view.py index 0cccf85e..b1db47ab 100644 --- a/tests/spine/test_spine_view.py +++ b/tests/spine/test_spine_view.py @@ -1,5 +1,8 @@ -"""Tests of the spine viewer's data, API and HTML export -(:mod:`giant_python.spine.view`), on a synthetic session.""" +"""Tests of the spine viewer's data, API and HTML export. + +The viewer is :mod:`giant_python.spine.view`; the tests run on a synthetic +session. +""" import base64 import gzip @@ -29,7 +32,7 @@ @pytest.fixture def product(tmp_path): - """A synthetic session's spine summary (with network images).""" + """Make a synthetic session's spine summary (with network images).""" s = syn.make_session(tmp_path) rep = make_spine_summary( s["run"], @@ -43,7 +46,7 @@ def product(tmp_path): return rep["output"] -def test_blur_nan_ignores_nan(): +def test_blur_nan_ignores_nan() -> None: """NaN stays NaN and does not pull its neighbours down.""" img = np.ones((9, 9), np.float32) img[4, 4] = np.nan @@ -52,9 +55,11 @@ def test_blur_nan_ignores_nan(): np.testing.assert_allclose(out[np.isfinite(out)], 1.0, rtol=1e-6) -def test_robust_z_and_late_trials(): - """Median and MAD z-scores; late trials are the last block, or the - second half of one block.""" +def test_robust_z_and_late_trials() -> None: + """Median and MAD z-scores. + + Late trials are the last block, or the second half of one block. + """ z = robust_z(np.array([[0.0, 1.0, 2.0, np.nan]])) assert z[0, 1] == 0 and np.isnan(z[0, 3]) np.testing.assert_array_equal( @@ -63,9 +68,11 @@ def test_robust_z_and_late_trials(): np.testing.assert_array_equal(late_trials([0, 0, 0, 0]), [0, 0, 1, 1]) -def test_normalized_field_and_change(product): - """Each trial is divided by its median over the common pixels; the - change view compares blurred trials, with a brightness in [0, 1].""" +def test_normalized_field_and_change(product) -> None: + """Each trial is divided by its median over the common pixels. + + The change view compares blurred trials, with a brightness in [0, 1]. + """ store = SpineStore([(None, product)]) pr = store.products[0] stack = read_product(product)["paths"][1]["images"]["mean_ch1"] @@ -99,9 +106,11 @@ def test_normalized_field_and_change(product): assert act.shape == (1,) + stack.shape[1:] -def test_store_sources_roi_and_crops(product): - """Sources carry sizes and trends; a window and its crops sit on the - same grid around the source.""" +def test_store_sources_roi_and_crops(product) -> None: + """Sources carry sizes and trends. + + A window and its crops sit on the same grid around the source. + """ store = SpineStore([("syn", product)], crop_half=4) meta = store.meta() p1 = meta["products"][0]["paths"][1] @@ -132,9 +141,11 @@ def test_store_sources_roi_and_crops(product): assert ch.shape == (2, n_t + 1, 9, 9) -def test_marks_attach_by_position(product, tmp_path): - """A mark is stored with its source's position and attaches to the - nearest source within 2.5 px; clearing removes it.""" +def test_marks_attach_by_position(product, tmp_path) -> None: + """A mark is stored with its source's position. + + It attaches to the nearest source within 2.5 px; clearing removes it. + """ marks = tmp_path / "marks.csv" store = SpineStore([(None, product)], marks) got = store.set_mark(0, 1, 1, "Growing", "a note") @@ -161,7 +172,7 @@ def test_marks_attach_by_position(product, tmp_path): store.set_mark(0, 1, 1, "Big", "") -def test_product_is_read_again_when_it_changes(product, tmp_path): +def test_product_is_read_again_when_it_changes(product, tmp_path) -> None: """A rewritten product shows on the next request.""" import os import shutil @@ -192,7 +203,7 @@ def _get(url): return np.frombuffer(body, np.float32).reshape(shape) -def test_server_answers_the_api(product, tmp_path): +def test_server_answers_the_api(product, tmp_path) -> None: """The page and every API route answer; a mark is written by POST.""" marks = tmp_path / "marks.csv" store = SpineStore([(None, product)], marks) @@ -234,7 +245,7 @@ def test_server_answers_the_api(product, tmp_path): def _static(page: str) -> dict: - """The data embedded in an exported page.""" + """Extract the data embedded in an exported page.""" m = re.search( r'", @@ -244,7 +255,7 @@ def _static(page: str) -> dict: def _unpack(e) -> np.ndarray: - """An embedded array (as the page's ``unpack``).""" + """Decode an embedded array (as the page's ``unpack``).""" parts = [] for layer in e["layers"]: q = np.frombuffer(base64.b64decode(layer["b64"]), np.uint8) @@ -253,7 +264,7 @@ def _unpack(e) -> np.ndarray: return np.concatenate(parts).reshape(e["shape"]) -def test_pack_round_trips_within_a_code(): +def test_pack_round_trips_within_a_code() -> None: """uint8 codes keep values within half a step and NaN as NaN.""" rng = np.random.default_rng(0) a = rng.normal(1, 0.1, (1, 20, 30)).astype(np.float32) @@ -270,9 +281,12 @@ def test_pack_round_trips_within_a_code(): np.testing.assert_allclose(back, ch, atol=0.003) -def test_export_html_embeds_the_viewer_data(product, tmp_path): - """The page holds the meta, the sources, the mean fields and the crops - of the chosen sources, and nothing that needs the server.""" +def test_export_html_embeds_the_viewer_data(product, tmp_path) -> None: + """The page holds the meta, the sources, the mean fields and some crops. + + The crops are those of the chosen sources; the page holds nothing that + needs the server. + """ out = tmp_path / "page.html" rep = export_html(product, out, sources=[2], name="syn") page = out.read_text(encoding="utf-8") @@ -298,8 +312,8 @@ def test_export_html_embeds_the_viewer_data(product, tmp_path): np.testing.assert_allclose(back[inside], mean[inside], atol=step) -def test_cli_export(product, tmp_path, capsys): - """giant spine export-html writes the page and reports it.""" +def test_cli_export(product, tmp_path, capsys) -> None: + """Giant spine export-html writes the page and reports it.""" out = tmp_path / "e.html" assert ( main( @@ -311,9 +325,11 @@ def test_cli_export(product, tmp_path, capsys): assert rep["output"] == str(out) and out.is_file() -def test_pick_sources_marked_first_then_by_q_and_size(): - """The export's crops go to the marked sources, then by q, with ties at - the permutation floor going to the larger statistic.""" +def test_pick_sources_marked_first_then_by_q_and_size() -> None: + """The export's crops go to the marked sources, then by q. + + Ties at the permutation floor go to the larger statistic. + """ from giant_python.spine.view.export import pick_sources nan = float("nan") @@ -330,10 +346,12 @@ def test_pick_sources_marked_first_then_by_q_and_size(): assert pick_sources(src, "f0", 0) == [0] -def test_marks_need_json_from_this_server(product, tmp_path): - """The mark endpoint refuses bodies that are not JSON (a cross-origin - page could send those without a preflight) and requests whose Origin - is another site.""" +def test_marks_need_json_from_this_server(product, tmp_path) -> None: + """The mark endpoint refuses bodies that are not JSON and foreign origins. + + Bodies that are not JSON could be sent by a cross-origin page without a + preflight; requests whose Origin is another site are refused too. + """ marks = tmp_path / "marks.csv" store = SpineStore([(None, product)], marks) srv = make_server(store, port=0) @@ -372,7 +390,7 @@ def test_marks_need_json_from_this_server(product, tmp_path): srv.server_close() -def test_sources_without_sources_keep_the_fields(product, tmp_path): +def test_sources_without_sources_keep_the_fields(product, tmp_path) -> None: """A path without sources answers with the same, empty, fields.""" store = SpineStore([(None, product)]) pr = store.products[0] @@ -382,9 +400,11 @@ def test_sources_without_sources_keep_the_fields(product, tmp_path): assert src["marks"] == {"by_source": {}, "unattached": 0} -def test_cache_keys_follow_the_file(product, tmp_path): - """A result made from the old file is not served after the file - changes, even if it lands in the cache after the reload.""" +def test_cache_keys_follow_the_file(product, tmp_path) -> None: + """A result made from the old file is not served after the file changes. + + Even if it lands in the cache after the reload. + """ import os import shutil @@ -404,9 +424,11 @@ def test_cache_keys_follow_the_file(product, tmp_path): assert new is not old and not isinstance(new, str) -def test_server_refuses_untrusted_hosts(product, tmp_path): - """Requests naming another host (DNS rebinding) get nothing, and marks - from an origin that is not this server's trusted names are refused.""" +def test_server_refuses_untrusted_hosts(product, tmp_path) -> None: + """Requests naming another host (DNS rebinding) get nothing. + + Marks from an origin that is not this server's trusted names are refused. + """ store = SpineStore([(None, product)], tmp_path / "marks.csv") srv = make_server(store, port=0) th = threading.Thread(target=srv.serve_forever, daemon=True) @@ -447,17 +469,21 @@ def test_server_refuses_untrusted_hosts(product, tmp_path): srv.server_close() -def test_export_refuses_unknown_paths(product, tmp_path): - """Asking for a path the summary does not have is an error, not an - empty page.""" +def test_export_refuses_unknown_paths(product, tmp_path) -> None: + """Asking for a path the summary does not have is an error. + + Not an empty page. + """ with pytest.raises(ValueError, match="no path"): export_html(product, tmp_path / "p.html", paths=[7]) assert not (tmp_path / "p.html").exists() -def test_pick_sources_uses_the_strongest_test_at_the_smallest_q(): - """Among tests tied at a source's smallest q, the largest statistic - breaks ties between sources.""" +def test_pick_sources_uses_the_strongest_test_at_the_smallest_q() -> None: + """Among tests tied at a source's smallest q, the largest statistic wins. + + It breaks ties between sources. + """ from giant_python.spine.view.export import pick_sources tr = { @@ -472,9 +498,11 @@ def test_pick_sources_uses_the_strongest_test_at_the_smallest_q(): assert pick_sources(src, "f0", 1) == [0] -def test_marks_keep_their_order_within_a_path(product, tmp_path): - """Two marks with the same time that land on one source: the one - written later wins, whatever their rows.""" +def test_marks_keep_their_order_within_a_path(product, tmp_path) -> None: + """Two marks with the same time that land on one source. + + The one written later wins, whatever their rows. + """ from giant_python.spine.rois import write_marks store = SpineStore([(None, product)], tmp_path / "marks.csv") @@ -502,9 +530,11 @@ def test_marks_keep_their_order_within_a_path(product, tmp_path): assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" -def test_pick_sources_keeps_infinite_statistics_first(): - """An infinite statistic (a change without noise) ranks first among - equal q-values.""" +def test_pick_sources_keeps_infinite_statistics_first() -> None: + """An infinite statistic (a change without noise) ranks first. + + Among equal q-values. + """ from giant_python.spine.view.export import pick_sources inf = float("inf") @@ -518,7 +548,7 @@ def test_pick_sources_keeps_infinite_statistics_first(): assert pick_sources(src, "f0", 1) == [1] -def test_summary_without_rois_loads(product, tmp_path): +def test_summary_without_rois_loads(product, tmp_path) -> None: """A summary with no sources and no user ROIs (no rois group) loads.""" import shutil @@ -535,14 +565,14 @@ def test_summary_without_rois_loads(product, tmp_path): assert store.meta()["products"][0]["paths"][1]["n_sources"] == 0 -def test_server_on_ipv6_loopback_and_port_80_names(product): - """The server binds an IPv6 literal, and at port 80 trusts the names - without a port, as browsers send them.""" - import socket as so +def test_server_on_ipv6_loopback_and_port_80_names(product) -> None: + """The server binds an IPv6 literal, and at port 80 trusts portless names. - from giant_python.spine.view.server import _bracket + Those are the names without a port, as browsers send them. + """ + import socket as so - from giant_python.spine.view.server import allowed_hosts + from giant_python.spine.view.server import _bracket, allowed_hosts assert _bracket("::1") == "[::1]" and _bracket("localhost") == "localhost" at80 = allowed_hosts("127.0.0.1", 80) @@ -568,9 +598,11 @@ def test_server_on_ipv6_loopback_and_port_80_names(product): srv.server_close() -def test_a_note_alone_keeps_the_label(product, tmp_path): - """A note saved on its own keeps the label the source has at that - moment (Unsure without one).""" +def test_a_note_alone_keeps_the_label(product, tmp_path) -> None: + """A note saved on its own keeps the label the source has at that moment. + + Unsure without one. + """ store = SpineStore([(None, product)], tmp_path / "marks.csv") got = store.set_mark(0, 1, 0, None, "first note") assert got["by_source"][0]["label"] == "Unsure" @@ -584,7 +616,7 @@ def test_a_note_alone_keeps_the_label(product, tmp_path): assert len(read_marks(tmp_path / "marks.csv")) == 1 -def test_export_refuses_unknown_sources_and_images(product, tmp_path): +def test_export_refuses_unknown_sources_and_images(product, tmp_path) -> None: """Source numbers and crop images the summary lacks are errors.""" with pytest.raises(ValueError, match="no source"): export_html(product, tmp_path / "p.html", sources=[99]) @@ -593,9 +625,11 @@ def test_export_refuses_unknown_sources_and_images(product, tmp_path): assert not (tmp_path / "p.html").exists() -def test_export_crops_only_the_images_asked_for(product, tmp_path): - """With --crop-images, a path that lacks them gets no crops rather - than every image.""" +def test_export_crops_only_the_images_asked_for(product, tmp_path) -> None: + """With --crop-images, a path that lacks them gets no crops. + + Rather than every image. + """ import h5py out = tmp_path / "p.html" @@ -611,9 +645,11 @@ def test_export_crops_only_the_images_asked_for(product, tmp_path): assert not [k for k in data["crops"] if k.startswith("2|")] -def test_cache_makes_a_value_once_for_concurrent_requests(): - """Concurrent requests for a value being made wait for it instead of - making it again.""" +def test_cache_makes_a_value_once_for_concurrent_requests() -> None: + """Concurrent requests for a value being made wait for it. + + Instead of making it again. + """ import time as _t from giant_python.spine.view.data import _Lru @@ -621,8 +657,8 @@ def test_cache_makes_a_value_once_for_concurrent_requests(): cache = _Lru(4) calls = [] - def make(): - """A slow value.""" + def make() -> str: + """Make a slow value.""" calls.append(1) _t.sleep(0.2) return "v" @@ -640,9 +676,11 @@ def make(): assert cache.making == {} -def test_cache_is_bounded_by_bytes(): - """Values are evicted, oldest first, once their arrays exceed the - budget; the newest stays even when it alone is larger.""" +def test_cache_is_bounded_by_bytes() -> None: + """Values are evicted, oldest first, once their arrays exceed the budget. + + The newest stays even when it alone is larger. + """ from giant_python.spine.view.data import _Lru cache = _Lru(3000) @@ -653,10 +691,12 @@ def test_cache_is_bounded_by_bytes(): assert list(cache.d) == ["big"] -def test_cache_lock_stays_while_requests_wait(): - """The lock of a key being made stays while any request still uses it, - even if the value is evicted meanwhile: a later request for the key - waits on the same lock instead of computing in parallel.""" +def test_cache_lock_stays_while_requests_wait() -> None: + """The lock of a key being made stays while any request still uses it. + + Even if the value is evicted meanwhile: a later request for the key waits + on the same lock instead of computing in parallel. + """ import time as _t from giant_python.spine.view.data import _Lru @@ -666,14 +706,14 @@ def test_cache_lock_stays_while_requests_wait(): peak = [] def make(): - """A slow value that records how many are being made at once.""" + """Make a slow value that records how many are being made at once.""" running.append(1) peak.append(len(running)) _t.sleep(0.05) running.pop() return np.zeros(10) - def worker(): + def worker() -> None: """Ask for the key, then for another (evicting it).""" cache.get("k", make) cache.get(object(), lambda: np.zeros(10)) @@ -687,9 +727,11 @@ def worker(): assert cache.making == {} -def test_mark_refused_when_the_source_moved(product, tmp_path): - """A mark that names a position other than the source's (the summary - changed under an open page) is refused and writes nothing.""" +def test_mark_refused_when_the_source_moved(product, tmp_path) -> None: + """A mark that names a position other than the source's is refused. + + The summary changed under an open page; the mark writes nothing. + """ store = SpineStore([(None, product)], tmp_path / "marks.csv") rs = read_product(product)["paths"][1]["rois"]["sources"] with pytest.raises(ValueError, match="changed"): @@ -701,10 +743,12 @@ def test_mark_refused_when_the_source_moved(product, tmp_path): assert got["by_source"][1]["label"] == "Growing" -def test_change_needs_only_its_own_cache_entry(product): - """change() reads everything it needs from the change record, so it - does not reload the normalized stack (no thrashing when the two do not - fit together in the cache).""" +def test_change_needs_only_its_own_cache_entry(product) -> None: + """change() reads everything it needs from the change record. + + So it does not reload the normalized stack (no thrashing when the two do + not fit together in the cache). + """ store = SpineStore([(None, product)]) pr = store.products[0] pr.change_prep(1, "mean_ch1") @@ -716,9 +760,12 @@ def test_change_needs_only_its_own_cache_entry(product): assert calls == [] -def test_default_image_calls_and_window_motion_reach_the_page(product): - """The page gets the summary's default image, the calls and structural - change of each image's tests, and the windows' motion.""" +def test_default_image_calls_and_window_motion_reach_the_page(product) -> None: + """The page gets the default image, the calls and the windows' motion. + + That is, the summary's default image, the calls and structural change of + each image's tests, and the windows' motion. + """ store = SpineStore([(None, product)]) p1 = store.meta()["products"][0]["paths"][1] assert p1["primary_image"] == "f0_net" @@ -738,9 +785,12 @@ def test_default_image_calls_and_window_motion_reach_the_page(product): assert key in page -def test_summaries_before_format_4_still_load(product, tmp_path): - """Without the default image, the calls or the window motion (format - 3), the page gets None for the image and NaN (null) motion.""" +def test_summaries_before_format_4_still_load(product, tmp_path) -> None: + """Summaries before format 4 still load. + + Without the default image, the calls or the window motion (format 3), the + page gets None for the image and NaN (null) motion. + """ import shutil import h5py @@ -765,9 +815,11 @@ def test_summaries_before_format_4_still_load(product, tmp_path): assert read_product(copy)["paths"][1]["primary_image"] is None -def test_pick_sources_takes_the_calls_first(): - """The export's crops go to the marked sources, then to the calls (by - q), then to the smallest q.""" +def test_pick_sources_takes_the_calls_first() -> None: + """The export's crops go to the marked sources, then to the calls. + + The calls are taken by q, then the rest by the smallest q. + """ from giant_python.spine.view.export import pick_sources, primary_image tr = { diff --git a/tests/trial_table/test_build_slap2.py b/tests/trial_table/test_build_slap2.py index d78f791d..839eb4bd 100644 --- a/tests/trial_table/test_build_slap2.py +++ b/tests/trial_table/test_build_slap2.py @@ -43,7 +43,7 @@ def datenum(t: datetime.datetime) -> float: class FakeSession: """A data folder whose .dat files are empty, with a fake reader.""" - def __init__(self, root: Path, monkeypatch): + def __init__(self, root: Path, monkeypatch) -> None: """Create the data folder and put the fake reader in place.""" self.dir = root / "data" self.dir.mkdir() @@ -51,13 +51,12 @@ def __init__(self, root: Path, monkeypatch): monkeypatch.setattr(tt, "read_dat_info", self.read) def read(self, path): - """The fake reader: a file's line count and first-line time.""" + """Read a file's line count and first-line time (the fake reader).""" lines, first = self.info[Path(path).name] return DatInfo(lines, first, LINE_PERIOD_S) - def dat(self, name, lines, mtime, first_line=None): - """Add an empty .dat file with its line count, file time and first-line - time.""" + def dat(self, name, lines, mtime, first_line=None) -> None: + """Add an empty .dat file with its line count, file time and first-line time.""" p = self.dir / name p.write_bytes(b"") stamp = mtime.timestamp() @@ -66,8 +65,7 @@ def dat(self, name, lines, mtime, first_line=None): self.info[name] = (lines, first) def triggered(self, lines1, lines2): - """Add triggered recordings of both paths with the given line - counts.""" + """Add triggered recordings of both paths with the given line counts.""" dmd1 = [ f"acq_DMD1-TRIAL{k:06d}.dat" for k in range(1, len(lines1) + 1) ] @@ -80,7 +78,7 @@ def triggered(self, lines1, lines2): self.dat(name, n, START + datetime.timedelta(minutes=k)) return dmd1, dmd2 - def references(self): + def references(self) -> None: """Write a small reference stack per path, described as SLAP2 does.""" import tifffile @@ -104,7 +102,7 @@ def references(self): ) def mtimes(self, names): - """The files' modification times as MATLAB datenums.""" + """Return the files' modification times as MATLAB datenums.""" return np.array([tt._mtime_datenum(self.dir / n) for n in names]) def build(self, save_dir, **kw): @@ -114,11 +112,11 @@ def build(self, save_dir, **kw): @pytest.fixture def session(tmp_path, monkeypatch): - """A fake session in a temporary folder.""" + """Provide a fake session in a temporary folder.""" return FakeSession(tmp_path, monkeypatch) -def test_triggered_trials(session, tmp_path): +def test_triggered_trials(session, tmp_path) -> None: """Triggered recordings of both paths give one trial per file pair.""" lines = [100000, 120000, 110000] dmd1, dmd2 = session.triggered(lines, lines) @@ -144,9 +142,8 @@ def test_triggered_trials(session, tmp_path): ) -def test_triggered_trial_line_mismatch(session, tmp_path): - """A file holding two trials back to back is lined up with the other - path.""" +def test_triggered_trial_line_mismatch(session, tmp_path) -> None: + """A file holding two trials back to back is lined up with the other path.""" # DMD1's trial number failed to increment: its second file holds DMD2's # second and third trials back to back dmd1, dmd2 = session.triggered([100000, 220000], [100000, 100000, 120000]) @@ -169,9 +166,8 @@ def test_triggered_trial_line_mismatch(session, tmp_path): ) -def test_order_from_file_names_not_mod_times(session, tmp_path): - """Acquisitions are ordered by the time in their names, not by file - times.""" +def test_order_from_file_names_not_mod_times(session, tmp_path) -> None: + """Acquisitions are ordered by the time in their names, not by file times.""" # copies carry upload times: DMD1's are scrambled within a few seconds, # DMD2's identical; the earlier acquisition sorts last alphabetically acqs = [("spont_20250314_101500", 2), ("activity_20250314_111223", 12)] @@ -206,7 +202,7 @@ def test_order_from_file_names_not_mod_times(session, tmp_path): ) -def test_file_order_falls_back_to_mod_time(session, tmp_path): +def test_file_order_falls_back_to_mod_time(session, tmp_path) -> None: """Without a time in the names, files are ordered by modification time.""" names = ["b_DMD1.dat", "a_DMD1.dat"] for k, n in enumerate(names, start=1): @@ -222,9 +218,8 @@ def test_file_order_falls_back_to_mod_time(session, tmp_path): ] -def test_trial_times_from_line_clock(session, tmp_path): - """Trial times come from the line clock, which shows gaps the line counts - hide.""" +def test_trial_times_from_line_clock(session, tmp_path) -> None: + """Trial times come from the line clock, which shows gaps the line counts hide.""" # DMD1's second file holds trials 2 and 3, with a 0.5 s gap that the line # count alone doesn't show; mtimes are identical upload times starts = [ @@ -259,9 +254,8 @@ def test_trial_times_from_line_clock(session, tmp_path): ) -def test_multicycle_trials_and_times(session, tmp_path): - """A continuous recording is cut into trials with times from the line - clock.""" +def test_multicycle_trials_and_times(session, tmp_path) -> None: + """A continuous recording is cut into trials with times from the line clock.""" lines = 450000 t0 = datetime.datetime(2025, 3, 14, 11, 12, 55) names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] @@ -286,9 +280,8 @@ def test_multicycle_trials_and_times(session, tmp_path): ) -def test_multicycle_times_from_mtime(session, tmp_path): - """Without the line clock, a continuous recording's times come from file - times.""" +def test_multicycle_times_from_mtime(session, tmp_path) -> None: + """Without the line clock, a continuous recording's times come from file times.""" lines = 450000 names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] for n in names: @@ -312,9 +305,11 @@ def test_multicycle_times_from_mtime(session, tmp_path): ) -def test_multicycle_times_from_last_file_mtime(session, tmp_path): - """Without the line clock, a CYCLE-split recording ends at its last - file's modification time (MATLAB takes the first file's).""" +def test_multicycle_times_from_last_file_mtime(session, tmp_path) -> None: + """Without the line clock, a CYCLE-split recording ends at its last file's modification time. + + MATLAB takes the first file's. + """ lines = 450000 names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] for n in names: @@ -342,9 +337,8 @@ def test_multicycle_times_from_last_file_mtime(session, tmp_path): ) -def test_multicycle_edges_are_matlab_linspace(session, tmp_path): - """The trial edges of a continuous recording are MATLAB's linspace - values.""" +def test_multicycle_edges_are_matlab_linspace(session, tmp_path) -> None: + """The trial edges of a continuous recording are MATLAB's linspace values.""" # 3 trials of 599838 lines: the edges are fractional, as MATLAB's lines = 599837 names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] @@ -358,7 +352,7 @@ def test_multicycle_edges_are_matlab_linspace(session, tmp_path): np.testing.assert_array_equal(s2["last_line"][0], edges[1:]) -def test_matlab_linspace_values(): +def test_matlab_linspace_values() -> None: """matlab_linspace reproduces values computed in MATLAB.""" # values from MATLAB R2023b: linspace(1, 599838, 4) y = matlab_linspace(1, 599838, 4) @@ -367,7 +361,7 @@ def test_matlab_linspace_values(): assert y[2] == 1 + (2 * (599838 - 1)) / 3 -def test_reference_stack(session, tmp_path): +def test_reference_stack(session, tmp_path) -> None: """Each path's reference stack is found and stored.""" session.triggered([100000], [100000]) session.references() @@ -387,9 +381,8 @@ def test_reference_stack(session, tmp_path): assert ref["IM"].dtype == np.float32 -def test_write_trial_table_h5(session, tmp_path): - """The written trial_table.h5 holds the table in MATLAB's column-major - layout.""" +def test_write_trial_table_h5(session, tmp_path) -> None: + """The written trial_table.h5 holds the table in MATLAB's column-major layout.""" dmd1, dmd2 = session.triggered([100000, 120000], [100000, 120000]) session.references() out = tmp_path / "out" @@ -414,7 +407,7 @@ def test_write_trial_table_h5(session, tmp_path): assert h["row_major"][()].item() == 0 -def test_max_duration_trims_and_keeps_untrimmed(session, tmp_path): +def test_max_duration_trims_and_keeps_untrimmed(session, tmp_path) -> None: """max_duration_s trims the table and also writes the untrimmed one.""" session.triggered([100000, 120000, 110000], [100000, 120000, 110000]) session.references() @@ -430,9 +423,8 @@ def test_max_duration_trims_and_keeps_untrimmed(session, tmp_path): assert full["filename"].shape == (2, 3) -def test_trim_keeps_whole_trials_before_the_limit(): - """Trimming keeps the trials that start before the limit and shortens the - last.""" +def test_trim_keeps_whole_trials_before_the_limit() -> None: + """Trimming keeps the trials that start before the limit and shortens the last.""" table = { "filename": np.array([["a", "b"], ["c", "d"]], dtype=object), "true_trial_ix": np.array([[1.0, 2.0], [1.0, 2.0]]), @@ -458,14 +450,14 @@ def test_trim_keeps_whole_trials_before_the_limit(): trim_trial_table(table, 0.0, 1e-4) -def test_no_reference_stack_error(session, tmp_path): +def test_no_reference_stack_error(session, tmp_path) -> None: """A session without a reference stack raises FileNotFoundError.""" session.triggered([100000], [100000]) with pytest.raises(FileNotFoundError): session.build(tmp_path / "out") -def test_unaligned_dmds_error(session, tmp_path): +def test_unaligned_dmds_error(session, tmp_path) -> None: """Paths whose recordings do not line up raise an error.""" session.triggered([100000], [150000]) session.references() @@ -473,9 +465,8 @@ def test_unaligned_dmds_error(session, tmp_path): session.build(tmp_path / "out") -def test_unmatched_trailing_recordings_warn(session, tmp_path): - """Data left after the last trial that lines up is left out, as in - MATLAB, with a warning.""" +def test_unmatched_trailing_recordings_warn(session, tmp_path) -> None: + """Data left after the last trial that lines up is left out, as in MATLAB, with a warning.""" session.triggered([100000, 100000], [100000]) session.references() with pytest.warns(TrialTableWarning, match="100000 lines of DMD1"): @@ -483,7 +474,7 @@ def test_unmatched_trailing_recordings_warn(session, tmp_path): assert t["filename"].shape == (2, 1) -def test_no_trials_error(session, tmp_path): +def test_no_trials_error(session, tmp_path) -> None: """A session in which no trial lines up warns and raises.""" session.triggered([100000], []) session.references() @@ -493,7 +484,7 @@ def test_no_trials_error(session, tmp_path): @pytest.mark.filterwarnings("ignore:Could not read acquisition times") -def test_mixed_continuous_and_triggered_error(session, tmp_path): +def test_mixed_continuous_and_triggered_error(session, tmp_path) -> None: """Continuous and triggered recordings in one folder raise an error.""" session.triggered([100000], [100000]) for n in ("acq2_DMD1-CYCLE-000000.dat", "acq2_DMD2-CYCLE-000000.dat"): @@ -503,9 +494,8 @@ def test_mixed_continuous_and_triggered_error(session, tmp_path): session.build(tmp_path / "out") -def test_acquisition_order(): - """Files sort by acquisition time and trial number; ambiguous names are - refused.""" +def test_acquisition_order() -> None: + """Files sort by acquisition time and trial number; ambiguous names are refused.""" names = [ "a_20250314_111223_DMD1-TRIAL000010.dat", "a_20250314_111223_DMD1-TRIAL000002.dat", @@ -523,8 +513,8 @@ def test_acquisition_order(): assert not ok # same position -def _write_mat_datetime(path: Path, ms: complex, tz: str = ""): - """A v7.3 MAT file holding ``fpgaTimeReference`` as MATLAB writes it. +def _write_mat_datetime(path: Path, ms: complex, tz: str = "") -> None: + """Write a v7.3 MAT file holding ``fpgaTimeReference`` as MATLAB writes it. The ``FileWrapper__`` blob lists strings, one class (datetime) and one object whose properties are ``data`` (cell 0) and, when given, ``tz`` @@ -575,7 +565,7 @@ def _write_mat_datetime(path: Path, ms: complex, tz: str = ""): ds.attrs["MATLAB_class"] = np.bytes_(b"datetime") -def test_read_mat_datetime(tmp_path): +def test_read_mat_datetime(tmp_path) -> None: """The .meta decoder reads an unzoned MATLAB datetime.""" # 2025-03-14 09:30:20.5 wall clock, unzoned ms = ( @@ -595,9 +585,12 @@ def test_read_mat_datetime(tmp_path): ) -def test_read_mat_datetime_offset_across_dst(tmp_path): - """The offset is elapsed time: 01:30 PST plus two hours on the day DST - starts is 04:30 PDT (MATLAB: datetime + seconds).""" +def test_read_mat_datetime_offset_across_dst(tmp_path) -> None: + """The offset is elapsed time. + + 01:30 PST plus two hours on the day DST starts is 04:30 PDT (MATLAB: + datetime + seconds). + """ utc = datetime.datetime(2025, 3, 9, 9, 30) # 01:30 in Los Angeles (PST) ms = (utc - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 p = tmp_path / "a.meta" @@ -610,9 +603,11 @@ def test_read_mat_datetime_offset_across_dst(tmp_path): @pytest.mark.parametrize("n", [0, 2]) -def test_read_mat_datetime_needs_one_value(tmp_path, n): - """An empty or multi-element reference gives None (file times are used - instead), not an error or the first value.""" +def test_read_mat_datetime_needs_one_value(tmp_path, n) -> None: + """An empty or multi-element reference gives None, not an error or the first value. + + File times are used instead. + """ p = tmp_path / "a.meta" _write_mat_datetime(p, complex(1.7e12, 0)) with h5py.File(p, "r+") as h: @@ -626,11 +621,11 @@ def test_read_mat_datetime_needs_one_value(tmp_path, n): assert read_mat_datetime_ms(p, "fpgaTimeReference") is None -def test_first_line_timestamp(tmp_path): - """The first line's timestamp is read from the .dat file, after a magic- - number check.""" +def test_first_line_timestamp(tmp_path) -> None: + """The first line's timestamp is read from the .dat file, after a magic-number check.""" class File: """A stand-in for the SLAP2 data-file object.""" + datFileName = str(tmp_path / "x.dat") header = {"firstCycleOffsetBytes": 16} diff --git a/tests/viewer/synthetic.py b/tests/viewer/synthetic.py index 2d7d84a3..dc1b037c 100644 --- a/tests/viewer/synthetic.py +++ b/tests/viewer/synthetic.py @@ -43,13 +43,15 @@ def make_warp(mode: str) -> TrialWarp: def gaussian(shape, centre, sigma=SIGMA, at=None): - """A Gaussian image summing to 1 on the canvas grid (zero beyond 3 - sigma); with ``at = (rows, cols)``, the same function evaluated at - those canvas positions instead of the grid.""" + """Build a Gaussian image summing to 1 on the canvas grid (zero beyond 3 sigma). + + With ``at = (rows, cols)``, the same function evaluated at those canvas + positions instead of the grid. + """ rr, cc = np.mgrid[: shape[0], : shape[1]] def f(r, c): - """The truncated, unnormalized Gaussian.""" + """Evaluate the truncated, unnormalized Gaussian.""" d2 = (r - centre[0]) ** 2 + (c - centre[1]) ** 2 return np.where( d2 > (3 * sigma) ** 2, 0.0, np.exp(-d2 / (2 * sigma**2)) @@ -80,13 +82,16 @@ def _put(g, name: str, a) -> None: def _strings(a) -> np.ndarray: - """A string array for the trial table.""" + """Convert to a string array for the trial table.""" return np.asarray(a, dtype=object).astype(h5py.string_dtype()) def write_session(root: Path, mode: str = "rigid", n80: int = 120): - """Write the synthetic session under ``root``; returns a dict of its - folders, the warp and the true trial-frame footprints and traces.""" + """Write the synthetic session under ``root``. + + Returns a dict of its folders, the warp and the true trial-frame + footprints and traces. + """ root = Path(root) moco, base, run = (root / x for x in ("moco", "base", "run")) for d in (moco, base, run / "source_extraction"): @@ -134,7 +139,7 @@ def write_session(root: Path, mode: str = "rigid", n80: int = 120): def _write_table(path: Path, savedr: Path, moco: Path) -> None: - """A one-path, two-trial trial table (row-major).""" + """Write a one-path, two-trial trial table (row-major).""" names = [f"E1T{t + 1}DMD1" for t in range(N_TRIALS)] with h5py.File(path, "w") as f: f["row_major"] = np.array([[1]], np.uint8) diff --git a/tests/viewer/test_viewer_render.py b/tests/viewer/test_viewer_render.py index 0e831ed6..e2e548d6 100644 --- a/tests/viewer/test_viewer_render.py +++ b/tests/viewer/test_viewer_render.py @@ -18,8 +18,8 @@ from .synthetic import ( CENTRES, - H, N_TRIALS, + H, W, gaussian, make_warp, @@ -28,7 +28,7 @@ def _exporter_weights(lines200, disc, ds, dt, half): - """The exporter's loop (exportF0TrainingData.m), as a dense matrix.""" + """Run the exporter's loop (exportF0TrainingData.m), as a dense matrix.""" wk = np.zeros((lines200.size, ds.size)) share = np.zeros(ds.size) for j in range(ds.size): @@ -42,7 +42,7 @@ def _exporter_weights(lines200, disc, ds, dt, half): return wk, share -def test_frame_weights_match_the_exporter(): +def test_frame_weights_match_the_exporter() -> None: """Weights and discard shares equal the exporter's loop.""" rng = np.random.default_rng(0) lines200 = np.ceil(1 + 53.4 * np.arange(400)) @@ -56,8 +56,8 @@ def test_frame_weights_match_the_exporter(): assert np.allclose(full[full > 0], 1.0) -def test_kernel_dt_and_matched_kernel(): - """dt from DSframes; the matched kernel removes the 200 Hz part.""" +def test_kernel_dt_and_matched_kernel() -> None: + """Dt from DSframes; the matched kernel removes the 200 Hz part.""" assert kernel_dt(1 + 134 * np.arange(10), None, 2.5) == 134 assert kernel_dt(np.array([5.0]), np.arange(0, 540, 54.0), 2.5) == 135 lines = np.ceil(1 + 53.4 * np.arange(100)) @@ -70,7 +70,7 @@ def test_kernel_dt_and_matched_kernel(): @pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_trial_map_inverse(mode): +def test_trial_map_inverse(mode) -> None: """The map's inverse undoes it (and agrees with TrialWarp's).""" warp = make_warp(mode) rng = np.random.default_rng(3) @@ -93,7 +93,7 @@ def test_trial_map_inverse(mode): np.testing.assert_allclose(ic, wc, atol=tol) -def test_affine_map_inverse_is_exact(): +def test_affine_map_inverse_is_exact() -> None: """An affine map's inverse is exact.""" a = np.array([[1.01, 0.02, 0.4], [-0.015, 0.99, -0.3]]) m = TrialMap(a) @@ -105,15 +105,18 @@ def test_affine_map_inverse_is_exact(): def _fp_tuple(img, s): - """A canvas footprint image as ``(rows, cols, sources, values)``.""" + """Convert a canvas footprint image to ``(rows, cols, sources, values)``.""" r, c = np.nonzero(img) return r, c, np.full(r.size, s), img[r, c] @pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_place_footprints_moves_them_through_the_map(mode): - """A placed footprint lands at the mapped centroid; its sum changes - only by the map's local area factor (a few percent for this bend).""" +def test_place_footprints_moves_them_through_the_map(mode) -> None: + """A placed footprint lands at the mapped centroid. + + Its sum changes only by the map's local area factor (a few percent for + this bend). + """ warp = make_warp(mode) parts = [_fp_tuple(gaussian((H, W), c), s) for s, c in enumerate(CENTRES)] fp = tuple(np.concatenate(x) for x in zip(*parts)) @@ -134,7 +137,7 @@ def test_place_footprints_moves_them_through_the_map(mode): np.testing.assert_allclose(cen, np.ravel(want), atol=0.02) -def test_place_footprints_blur_keeps_the_sum(): +def test_place_footprints_blur_keeps_the_sum() -> None: """A blurred footprint still sums to (about) 1.""" m = TrialMap(np.array([[1.0, 0, 0.2], [0, 1.0, -0.1]])) fp = _fp_tuple(gaussian((H, W), CENTRES[1]), 0) @@ -143,12 +146,15 @@ def test_place_footprints_blur_keeps_the_sum(): @pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_rendered_activity_reproduces_the_movie(tmp_path, mode): - """On a synthetic run whose movie is footprints x 80 Hz traces plus a +def test_rendered_activity_reproduces_the_movie(tmp_path, mode) -> None: + """The rendered activity of a synthetic run has the movie's flux and centroids. + + On a synthetic run whose movie is footprints x 80 Hz traces plus a baseline, the rendered activity has the movie's flux and centroids at every source (rigid and patchwise maps); pixel by pixel it differs by the bilinear interpolation of a 1.33 px footprint (up to ~12% at - a half-pixel shift).""" + a half-pixel shift). + """ syn = write_session(tmp_path, mode) run = SiloRun(syn["run"], "net") assert run.path(1).alignment == mode @@ -197,7 +203,7 @@ def test_rendered_activity_reproduces_the_movie(tmp_path, mode): assert fm.shape == (5, tr.N) and not np.array_equal(fm[1], fr[1]) -def test_run_reader(tmp_path): +def test_run_reader(tmp_path) -> None: """Sources, images, traces and per-trial footprints of a run.""" syn = write_session(tmp_path, "rigid") run = SiloRun(syn["run"], "r") @@ -216,7 +222,7 @@ def test_run_reader(tmp_path): assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 -def test_movie_found_by_stem(tmp_path): +def test_movie_found_by_stem(tmp_path) -> None: """A table naming a TIFF finds the HDF5 movie, as SILo does.""" import h5py @@ -235,7 +241,7 @@ def test_movie_found_by_stem(tmp_path): assert session.movie_file(0, 0).suffix == ".h5" -def test_kernels_follow_each_runs_frame_lines(tmp_path): +def test_kernels_follow_each_runs_frame_lines(tmp_path) -> None: """Each run's matched kernel comes from its own 200 Hz frame lines.""" syn = write_session(tmp_path, "rigid") session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) @@ -251,9 +257,11 @@ def test_kernels_follow_each_runs_frame_lines(tmp_path): def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float): - """Frames formed from a densely sampled signal (one sample per line, - line ``i + 1`` holds ``x[i]``) as weighted means with - ``exp(-|dline| / dt)`` within ``reach`` lines of each frame's line.""" + """Frames formed from a densely sampled signal as weighted means. + + One sample per line, line ``i + 1`` holds ``x[i]``; the weights are + ``exp(-|dline| / dt)`` within ``reach`` lines of each frame's line. + """ lines = np.arange(1, x.size + 1, dtype=float) out = np.empty(at.size) for j, a in enumerate(at): @@ -263,11 +271,12 @@ def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float): return out -def test_exact_kernel_undoes_the_double_smoothing(): - """On densely sampled data (kernels not truncated) the exact kernel - turns 200 Hz frames into the movie's 80 Hz frames to about 1%; the - exporter's kernel loses ~10% of a fast event's peak, the matched one - ~5%.""" +def test_exact_kernel_undoes_the_double_smoothing() -> None: + """The exact kernel turns 200 Hz frames into the movie's 80 Hz frames to about 1%. + + On densely sampled data (kernels not truncated); the exporter's kernel + loses ~10% of a fast event's peak, the matched one ~5%. + """ n = 60000 x = np.zeros(n) k = np.exp(-np.arange(1200) / 150.0) # ~14 ms decay at 10.7 kHz lines @@ -300,7 +309,7 @@ def test_exact_kernel_undoes_the_double_smoothing(): assert rms["exact"] < rms["matched"] < rms["exporter"] -def test_interp_weights_skip_discarded_frames(): +def test_interp_weights_skip_discarded_frames() -> None: """Interpolation uses kept neighbours only, holds at the ends.""" lines = np.array([10.0, 20, 30, 40, 50]) keep = np.array([True, True, False, True, True]) @@ -315,9 +324,12 @@ def test_interp_weights_skip_discarded_frames(): assert (one[3] == 1).all() -def test_exact_weights_with_discarded_frames(): - """Columns sum to 1; discarded frames get no weight; a frame with no - kept 200 Hz frame within reach stays empty, as the exporter's.""" +def test_exact_weights_with_discarded_frames() -> None: + """Columns sum to 1; discarded frames get no weight. + + A frame with no kept 200 Hz frame within reach stays empty, as the + exporter's. + """ rng = np.random.default_rng(4) lines200 = np.ceil(1 + 53.4 * np.arange(400)) disc = rng.random(400) < 0.1 @@ -335,10 +347,12 @@ def test_exact_weights_with_discarded_frames(): @pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_cubic_placement_keeps_the_shape(mode): - """Moved by a fraction of a pixel, a footprint keeps its flux with - either interpolation; the cubic spline also keeps its peak, where - bilinear interpolation blurs it.""" +def test_cubic_placement_keeps_the_shape(mode) -> None: + """Moved by a fraction of a pixel, a footprint keeps its flux with either interpolation. + + The cubic spline also keeps its peak, where bilinear interpolation blurs + it. + """ warp = make_warp(mode) for t in range(N_TRIALS): field = None @@ -366,9 +380,11 @@ def test_cubic_placement_keeps_the_shape(mode): assert max(err[3]) < max(err[1]) -def test_matched_kernel_with_one_frame(): - """With one 200 Hz frame the matched kernel keeps the movie's dt (as - render_dt) and still renders the frame.""" +def test_matched_kernel_with_one_frame() -> None: + """With one 200 Hz frame the matched kernel keeps the movie's dt. + + As render_dt does, and it still renders the frame. + """ w, _, info = kernel_weights( "matched", np.array([100.0]), np.zeros(1, bool), np.array([90.0]), 134 ) diff --git a/tests/viewer/test_viewer_server.py b/tests/viewer/test_viewer_server.py index 6cc9eb79..86f0c0a6 100644 --- a/tests/viewer/test_viewer_server.py +++ b/tests/viewer/test_viewer_server.py @@ -12,12 +12,12 @@ from giant_python.cli import build_parser from giant_python.viewer.server import make_server, make_store -from .synthetic import H, N_TRIALS, W, write_session +from .synthetic import N_TRIALS, H, W, write_session @pytest.fixture def server(tmp_path): - """A running server on a synthetic session with two runs.""" + """Start a running server on a synthetic session with two runs.""" syn = write_session(tmp_path, "patchwise") args = build_parser().parse_args( [ @@ -49,7 +49,7 @@ def _get(url): return r.read(), r.headers -def test_api(server): +def test_api(server) -> None: """Every endpoint answers with the expected shapes.""" base, store = server body, _ = _get(base + "/") @@ -86,7 +86,7 @@ def test_api(server): assert json.loads(_get(base + "/api/progress?key=1/0")[0]) == {"msg": ""} -def test_api_errors(server): +def test_api_errors(server) -> None: """Unknown paths and bad keys are errors, not crashes.""" base, _ = server with pytest.raises(urllib.error.HTTPError) as e: @@ -103,7 +103,7 @@ def test_api_errors(server): assert e.value.code == 400 -def test_runs_must_share_the_activity_channel(tmp_path): +def test_runs_must_share_the_activity_channel(tmp_path) -> None: """Runs read with different activity channels are not compared.""" from giant_python.viewer.run import SiloRun from giant_python.viewer.server import Store @@ -125,7 +125,7 @@ def test_runs_must_share_the_activity_channel(tmp_path): Store([a, b], session) -def test_large_valid_kernel_is_reported(tmp_path): +def test_large_valid_kernel_is_reported(tmp_path) -> None: """A 9 x 9 support (81 values) is still described.""" import h5py diff --git a/uv.lock b/uv.lock index 903cebb2..c904296e 100644 --- a/uv.lock +++ b/uv.lock @@ -1,21 +1,21 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version < '3.11'", ] @@ -82,8 +82,7 @@ name = "beautifulsoup4" version = "4.15.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "soupsieve", version = "2.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11.5'" }, - { name = "soupsieve", version = "4.1.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11.5'" }, + { name = "soupsieve" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } @@ -91,51 +90,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" }, ] -[[package]] -name = "black" -version = "26.10.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click" }, - { name = "mypy-extensions" }, - { name = "packaging" }, - { name = "pathspec" }, - { name = "platformdirs", version = "4.12.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "platformdirs", version = "4.14.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "pytokens" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f8/65/a9611a6ec0a8c88d86e59385da02d68d9533f7e86a05913d20c67be54029/black-26.10.1.tar.gz", hash = "sha256:5f9f83beae62437e060dafd53d7f1fc327e3d3494f74d72ee5c2b73eb90fc4e7", size = 741979, upload-time = "2026-10-10T04:13:40.776Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/03/35/46e9ee9a1b0b5f06d7702fb484e73a5b944acece76898a7ac4d75123514a/black-26.10.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:51d5e417e700fe6ec0b0ecdc408c6f6cb5def80328f31f724993d82c6486b746", size = 2140312, upload-time = "2026-10-10T04:18:26.873Z" }, - { url = "https://files.pythonhosted.org/packages/64/9d/a8f1fdff294ece6cac5d465b9c2349d6c0ca8173977c8b617ea2e12f673e/black-26.10.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:70ccbd175b7f6be29d2b727ee7ca6b4c54053df59da653a6df80b175d20a94fa", size = 1982094, upload-time = "2026-10-10T04:18:29.124Z" }, - { url = "https://files.pythonhosted.org/packages/8e/57/84c7274ecf3732d85a1533ce93d0eb25b318981a26e5c98a37c8f91274a8/black-26.10.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5bd3518d8e97138fef295230b1e9804076d69fa4e3594071494a8c68abe6266", size = 2038822, upload-time = "2026-10-10T04:18:30.829Z" }, - { url = "https://files.pythonhosted.org/packages/14/40/ca69d7af0b8da635fe16eabca737b1e414d44aad967e18ae59f9cd5d00bf/black-26.10.1-cp310-cp310-win_amd64.whl", hash = "sha256:0ce08b367307b0fd91c9dd1d4084e62b05b3055475f951f0f34a46b6e2393b64", size = 1606468, upload-time = "2026-10-10T04:18:33.142Z" }, - { url = "https://files.pythonhosted.org/packages/d8/21/71a49a1f337a89aae496ca864896e499440f36608cbc64054119d71c7cbe/black-26.10.1-cp310-cp310-win_arm64.whl", hash = "sha256:19fa8f5beb5e77c54c9c7e21d00cc93ed6c8b6228ee385616906d6befe081143", size = 1459642, upload-time = "2026-10-10T04:18:34.898Z" }, - { url = "https://files.pythonhosted.org/packages/6f/1e/c1d4f71299d45f4ff54c9c42ef9214d6b228223f196bc1bb2ee196aeaeee/black-26.10.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9a0219b29cd70e49f920acb7081e6ce5025c719008447c521d0200dcad93206a", size = 2121821, upload-time = "2026-10-10T04:18:36.793Z" }, - { url = "https://files.pythonhosted.org/packages/7f/e2/43944049c0945199bbd5c8b291b85306bfd0eeccbc908bf65538a69ff1b0/black-26.10.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7bdade400bfe24d78a7762896acc2f9a8e1a17fb0fd0536bf6b7c7097cf3eec7", size = 1961908, upload-time = "2026-10-10T04:18:38.942Z" }, - { url = "https://files.pythonhosted.org/packages/d5/e9/9616d58f69f0e4bfa89ebe8686b6ef50f4b4f0f91237ae4c76f34dabf8aa/black-26.10.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ff57f63029aa1353fa8b1b0c8971fd88a6c92dc766608d2eee33ad2deb23270e", size = 2019042, upload-time = "2026-10-10T04:18:40.612Z" }, - { url = "https://files.pythonhosted.org/packages/c5/de/0415cce69e2402a5c186cdb5462a0edd3fa44d69d1a1630e68e58daaa6a4/black-26.10.1-cp311-cp311-win_amd64.whl", hash = "sha256:3414a0c52901964dceabd98c7c56beac0f964115a116ecedcce7247359b14017", size = 1608383, upload-time = "2026-10-10T04:18:42.25Z" }, - { url = "https://files.pythonhosted.org/packages/a9/61/af18e716432e932f166ce9dfa419ce3f05fd5ef8c52c0510d27ae41aaa51/black-26.10.1-cp311-cp311-win_arm64.whl", hash = "sha256:1935b32f5326028019856e18cb42b4da63db23765dc84464cec723e0de478a9b", size = 1466048, upload-time = "2026-10-10T04:18:44.271Z" }, - { url = "https://files.pythonhosted.org/packages/f7/ca/357ccdd12e8f8429539f8f52edc153de58acba84f6670ac36c254a276691/black-26.10.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fe85fc4019bee59bc495c0f2a8ee76c5cd02c7015508d94a967ba2376f39a52c", size = 2167369, upload-time = "2026-10-10T04:18:45.948Z" }, - { url = "https://files.pythonhosted.org/packages/a5/a2/4709110a7ca326ba7b4f81a669fbebc20653c79a972b0f8de4ba5b5c5e68/black-26.10.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:182f6c32be38074b16d378498c498b32cb51928178ee611485344972c35ec9c6", size = 1990732, upload-time = "2026-10-10T04:18:48.252Z" }, - { url = "https://files.pythonhosted.org/packages/1e/96/9f8fa839c169d19c38ce6582d9449f2d7d70dabd313ac28f15a930260c1f/black-26.10.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b5347d760f0c02bb00dd249384cab71c3bf828b4f68d5b401eb116e0390f147d", size = 2065235, upload-time = "2026-10-10T04:18:50.064Z" }, - { url = "https://files.pythonhosted.org/packages/2b/ee/929eaf7de6f05a3141d6df72acf9248118f49a5e48f9375be3180e9babf7/black-26.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:4d9a90516db1d99c25dbb20cc0998e0e01531dd903466c7744e56d66f864220a", size = 1621579, upload-time = "2026-10-10T04:18:51.59Z" }, - { url = "https://files.pythonhosted.org/packages/90/3a/8b6a44abf9648b087311003b91298226c1763172cd8d223ece5b7cf8f795/black-26.10.1-cp312-cp312-win_arm64.whl", hash = "sha256:2ffbc023a12d0c729408823b8f10514490bd0baa301d0d4e21a7240249f9507f", size = 1469662, upload-time = "2026-10-10T04:18:53.245Z" }, - { url = "https://files.pythonhosted.org/packages/99/6b/bc0d39990bd7a71457d669639fa06acf6191bec28bafe8b8103f597cce76/black-26.10.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b6272cfd7e1e8e271f5b0e0207259fe2834687e5cb9b5f620b34a44db9754993", size = 2153812, upload-time = "2026-10-10T04:18:55.041Z" }, - { url = "https://files.pythonhosted.org/packages/85/0e/cc83b88a6b1a51fc051aa4e24663918f0bf4fa9fca98552ee93a125a6780/black-26.10.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:978113a40223a6aaefc17364176a809a320e6b288683841427fff04c6d7b4130", size = 1980352, upload-time = "2026-10-10T04:18:56.849Z" }, - { url = "https://files.pythonhosted.org/packages/7b/0f/4dd24ea0ebadbe05e293c3ea7fbebd4389f50508f714640c9b309a0849d2/black-26.10.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:03c0ddd93bb392e71209903a691767eb366fe1a76deb9509ccbaae9e1f14bb52", size = 2055268, upload-time = "2026-10-10T04:18:58.974Z" }, - { url = "https://files.pythonhosted.org/packages/a2/06/221f8e81891ecf5e4df9c258a11037997f1f218533ffe4fa1dc4db37f19c/black-26.10.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6dba8138cdc99061ef07b958ac082d2aa057b6961d1936f9717c350f02bab5f", size = 1625938, upload-time = "2026-10-10T04:19:00.65Z" }, - { url = "https://files.pythonhosted.org/packages/2b/3b/763d2dd073fc1e2cbf0fe5e584fe96913bf0d14cd725d1116f4b38453adf/black-26.10.1-cp313-cp313-win_arm64.whl", hash = "sha256:d42dd2fac7c342ae67e64ee99c9532e20b2a84e92c79ed3317fa2ef54c801d93", size = 1470752, upload-time = "2026-10-10T04:19:03.009Z" }, - { url = "https://files.pythonhosted.org/packages/76/7b/e8d275b23f3023881c0b0d8ce3bbda0d100c79bdef87fb6518bf9e0c5040/black-26.10.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:8375962579d537364cc0efa19b1474481915d3a793f9fc0774901814c5e5b5f4", size = 2147731, upload-time = "2026-10-10T04:19:04.643Z" }, - { url = "https://files.pythonhosted.org/packages/ee/62/e44f86ee5fc7b893ee0ee935a79c785932da7758d2c339749d90a20ef213/black-26.10.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d8b3a9074a680b3c5749633714e9ae3992a1e5a23343a97ad61cd9b119b444d2", size = 1981714, upload-time = "2026-10-10T04:19:06.287Z" }, - { url = "https://files.pythonhosted.org/packages/89/2f/e12ca76edfcd037fe9e7e7635d9468d1d51255cf25a01b2f8f97a38f147d/black-26.10.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:289282aa2e09d3162312a3be1788ff21b08e9ea9cc4a81e656024728b32428fb", size = 2047807, upload-time = "2026-10-10T04:19:08.193Z" }, - { url = "https://files.pythonhosted.org/packages/c3/af/676d3c5cbb2ab0f17c8459b3ae8ea15ebdcc5a2f1c1c586228ec85b8897f/black-26.10.1-cp314-cp314-win_amd64.whl", hash = "sha256:5cd88fd7b444ca51f3fc883b6f6657ea53a258b0b2eef6d9f2dfcfa17ce0e27b", size = 1652537, upload-time = "2026-10-10T04:19:09.817Z" }, - { url = "https://files.pythonhosted.org/packages/ad/7b/860022d369fdd5fe14280b1e7109f58753c371ff91ce2311d68a056e488a/black-26.10.1-cp314-cp314-win_arm64.whl", hash = "sha256:2520037aa62f8a1454d0811b8f5c88b444445b03a4bfba480d8d220893b64c34", size = 1504226, upload-time = "2026-10-10T04:19:11.367Z" }, - { url = "https://files.pythonhosted.org/packages/b1/28/9dd29175c1db777e6189e2a0bb5f37101adf19c3e509b236c8920f778d0b/black-26.10.1-py3-none-any.whl", hash = "sha256:28842f9a8207cc1df6eb983a35a14c5a0dfcd603d214fe82d84bef552afd2e3a", size = 239267, upload-time = "2026-10-10T04:13:38.808Z" }, -] - [[package]] name = "bottleneck" version = "1.6.0" @@ -208,16 +162,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -568,10 +522,10 @@ version = "1.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -661,10 +615,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -743,6 +697,285 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/bf/eb4ff492e1c3d027617b5a20e4e6d63a035b41b8cf77a95950159556a3a5/contourpy-1.4.0-cp315-cp315t-win_arm64.whl", hash = "sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184", size = 587064, upload-time = "2026-09-11T19:04:51.148Z" }, ] +[[package]] +name = "coverage" +version = "7.16.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/2f/55/d1eaf3e73781174340a00dc1ba2aee8a65f82fadb18e2797b192b6b3925b/coverage-7.16.2.tar.gz", hash = "sha256:ca64d9f1f384f151b9511bec01126072acd2f313439f8ed015a22d8790aab6fa", size = 971999, upload-time = "2026-09-27T12:29:01.118Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/72/db17bf5f87568ab524413693385be2eeb03e652ab56c54ea05fa85515675/coverage-7.16.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:23219888477edd736b6fcaec1272d47d93b926e999641ffea7e53a1738e70b2b", size = 223670, upload-time = "2026-09-27T12:25:34.675Z" }, + { url = "https://files.pythonhosted.org/packages/d1/e1/285727a8a74d48de256e8605413ee4cf82301228253ea58e5ab4270138b0/coverage-7.16.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:40c0f00899fe6181ae7f434ceb200e51f5ee4b8ed10e3b5f0b605f0cae15da87", size = 224191, upload-time = "2026-09-27T12:25:36.476Z" }, + { url = "https://files.pythonhosted.org/packages/50/c7/c737b73bac9bf5034f5ff45a4237b7a189d417a4e36751faf5d10c082cbe/coverage-7.16.2-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:a4624f80732f6b427ac58f1f59c577a0994a12e8174b5af6a027b4b58795d4c3", size = 250921, upload-time = "2026-09-27T12:25:37.857Z" }, + { url = "https://files.pythonhosted.org/packages/29/4e/e1d38d27817d91776ca543d01276a67eace3df675a673cac32b12c167d58/coverage-7.16.2-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:191803c4996b499fcd78c2ad5e5f767dcc53cb4dc6de6d6a741b443a1821ef02", size = 252751, upload-time = "2026-09-27T12:25:39.291Z" }, + { url = "https://files.pythonhosted.org/packages/0e/19/14a8e44cbb2ad36ae62aaa03c5eec4a06a7f7df220ea3776af26927acbe2/coverage-7.16.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fd670ac43b709c575aefc25bf52d8a598a3bc5017bddfd0a179152ab06a2deb", size = 254616, upload-time = "2026-09-27T12:25:40.506Z" }, + { url = "https://files.pythonhosted.org/packages/f9/72/f5bcad0d9a9b450080032344fbff7ec60c1b0e3d38019f7735dee2b69645/coverage-7.16.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:705e5af11d34647efdc170c7840b6857c81cf74be96419a553f237e68e62cb72", size = 256541, upload-time = "2026-09-27T12:25:41.785Z" }, + { url = "https://files.pythonhosted.org/packages/ae/9a/8c735234e8abb52bf5d063f98c780fa942e77c4c0225f9fcb9b33effc346/coverage-7.16.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8afd9bf35cc6a1f22eb3634808fa8e0b91902459c5721ef2e4461dfe771d7f08", size = 251589, upload-time = "2026-09-27T12:25:43.269Z" }, + { url = "https://files.pythonhosted.org/packages/35/6a/1bf6d32e55642d6972aa842640e0a8850e612d19ac7d05e2c32fa59dfd34/coverage-7.16.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3f43bac1856ba269b905302778d4df433d6006489a192174ad77ac528e395032", size = 252660, upload-time = "2026-09-27T12:25:45.051Z" }, + { url = "https://files.pythonhosted.org/packages/53/5b/05b1c0d0e9495cb056155a16066259adc1e935e7411a82a62779bf729975/coverage-7.16.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f8475460aa33ee28ac896ab1156d0bb3b6c639f7f8383c2677d3359eb35f8205", size = 250660, upload-time = "2026-09-27T12:25:46.51Z" }, + { url = "https://files.pythonhosted.org/packages/05/33/5bc3db57fc9c56b4ef055725c38c34faa818a27d17d65e251371f7f0e3a0/coverage-7.16.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:d6276d78f6fca7d0ac066d5da4165c5acd07829e8305c2cb900b738fb3a75a72", size = 254479, upload-time = "2026-09-27T12:25:47.819Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0f/4a5de66daef26eb919213f63b84f45d5065ab2df94cd767fc7c1174ac5e2/coverage-7.16.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:736fde09ea39646d11f8e3b76bd3425c075aa4dd45f24891970bb77c14ff20f5", size = 250940, upload-time = "2026-09-27T12:25:49.227Z" }, + { url = "https://files.pythonhosted.org/packages/57/d3/84cd6a11e707e422194739e9734d947746efa5e5b3358ff2d601f823ee45/coverage-7.16.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c85d54e7e8a2ca932fe8399301af9b8d5907ea2a455ffaff6e7d1208db83b943", size = 251543, upload-time = "2026-09-27T12:25:50.554Z" }, + { url = "https://files.pythonhosted.org/packages/ab/bc/3d84c2e2a95f38e346ce3730d9f0e53114f4e8aace72e6e51e014afb9992/coverage-7.16.2-cp310-cp310-win32.whl", hash = "sha256:5139009b5efd2194fc168ee9362f0e191ba612ef5d29242f9269c22f9b8f80c7", size = 225732, upload-time = "2026-09-27T12:25:51.945Z" }, + { url = "https://files.pythonhosted.org/packages/07/86/31f1f3170571a345ab9d8361a7b2f8e0c5698173fbecd1f7149b6e2089ee/coverage-7.16.2-cp310-cp310-win_amd64.whl", hash = "sha256:c3305c38a2fa21a4254f2ace7dd9ef5fc569c9a558b66e7017650b3d637fb95e", size = 226357, upload-time = "2026-09-27T12:25:53.272Z" }, + { url = "https://files.pythonhosted.org/packages/58/fa/ce3baf63d85b730398d92a7162f486f3a5e4e2cc3382a02488b3943725ba/coverage-7.16.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:732d950e51f3ba4fb6209c73250f3e8924fefca42953ee04a9e65d8c02414d7d", size = 223797, upload-time = "2026-09-27T12:25:54.756Z" }, + { url = "https://files.pythonhosted.org/packages/7a/57/9ba29c2aac7f756d479f03d45762120060f0f988788001001bf36e0e6fca/coverage-7.16.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5dca0bb66b4c3d624ba047887bf70270030c150692d543cb501293dc38a9f4b5", size = 224303, upload-time = "2026-09-27T12:25:56.214Z" }, + { url = "https://files.pythonhosted.org/packages/5d/7b/0d6d60906dca7d28cc1e3fce12a9861801c4fbb6cbf220ad78cd059c9467/coverage-7.16.2-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:af2a2a8c7c74de0559e0c368d94c8def9e16c58faaee33a0bf081057c4227e3b", size = 254715, upload-time = "2026-09-27T12:25:57.755Z" }, + { url = "https://files.pythonhosted.org/packages/cd/b8/9198b865679379fb165c689c64f6e11105ef380f6bd1c7673e83f73d9f5c/coverage-7.16.2-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:db5f8394e17f877a625b257f2ba0ce8e728a499c2c1579ad66220272cd3df510", size = 256627, upload-time = "2026-09-27T12:25:59.131Z" }, + { url = "https://files.pythonhosted.org/packages/98/79/9521462cb6072fe394701bc8974b74afd576c9c9355156c7844e1a86a42b/coverage-7.16.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b3146d2317c75f70df2509066d979dadd941f7021cdf9b5db4bcd8568258e25", size = 258724, upload-time = "2026-09-27T12:26:00.691Z" }, + { url = "https://files.pythonhosted.org/packages/a6/76/8d7d5d633db9fe0f3182fedc731bf09f9bcf2366055735152504ad614677/coverage-7.16.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e1d0ced76318bab499693ff25f64faa343415187cb2e4d7befdfdd391a1cf6a", size = 260692, upload-time = "2026-09-27T12:26:02.083Z" }, + { url = "https://files.pythonhosted.org/packages/4e/a7/76cb09c89ba46d74d37428bf93251fc14fb0bbe9e05cc2a5ef61773d318a/coverage-7.16.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:af98ad5ed9d6daaca956201e00bb429a7eb2b080426686f70a20353e0f9839f5", size = 254800, upload-time = "2026-09-27T12:26:03.369Z" }, + { url = "https://files.pythonhosted.org/packages/72/b6/2351c1979aaeb5b4a8091a75b90ca997ad60de36e181ddba267cf61dac97/coverage-7.16.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d56e4d21c56d2046447733f8b118409597db48c01efe898ee9ac24e858ec2d6", size = 256423, upload-time = "2026-09-27T12:26:04.751Z" }, + { url = "https://files.pythonhosted.org/packages/0f/f4/ad9a4f8b5cb2d494fa9452b546fe742ed2f9d3847cc14c05e36279a3e649/coverage-7.16.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1d5d0e3b660506fb84f995814e3118a21efdc0c8eb80127da1be627d90093c17", size = 254487, upload-time = "2026-09-27T12:26:06.082Z" }, + { url = "https://files.pythonhosted.org/packages/6c/1f/a520470472f3e8b01169bf42162b1470c9ba992230432f62ca36269bf3a0/coverage-7.16.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:17228fbca0f22976f797be94e975dcd237799c657d49551c7de1e0654d1202e9", size = 258259, upload-time = "2026-09-27T12:26:07.513Z" }, + { url = "https://files.pythonhosted.org/packages/09/d2/ff26d5938274745855fa61cfcba0245c88ccc10d98d2cbd96064f16cd5a7/coverage-7.16.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:bc0b0ac781d489304b741269857f1f8338b7a26b1b89c06c0344658001ec0035", size = 254216, upload-time = "2026-09-27T12:26:08.982Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1d/5d832d3b06785d9f53267e4f2724a9f60c312eee6ebed9063a461d0d3b45/coverage-7.16.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bf1bd822ec4e387ed245bed0d71151582cf7be9e5309bc4145eefe36083d5878", size = 255125, upload-time = "2026-09-27T12:26:10.35Z" }, + { url = "https://files.pythonhosted.org/packages/55/4d/1d33edbc2fcf7d99e384e393e712aa5a2ebbbd8409825357815982207976/coverage-7.16.2-cp311-cp311-win32.whl", hash = "sha256:7ed238d227e23cc300c3d464babdaf9f6ddc740aa1b15a77ae96136e6a7c4516", size = 225898, upload-time = "2026-09-27T12:26:11.7Z" }, + { url = "https://files.pythonhosted.org/packages/6f/7c/676df4882118756c4f8f560c954eddb93e166d84dda8c5f0b6a829689bde/coverage-7.16.2-cp311-cp311-win_amd64.whl", hash = "sha256:a90700f743e29aa3d75a6ff5f01953176a889c00e526194bc4d281731b88d99d", size = 226369, upload-time = "2026-09-27T12:26:13.375Z" }, + { url = "https://files.pythonhosted.org/packages/7a/0e/a457f4a461b3c5610d845137fdd45fa465e011a64c25af440518ab1f4e41/coverage-7.16.2-cp311-cp311-win_arm64.whl", hash = "sha256:a336eec40e3520d369b8a6cdabb4f596e69a8b42927ca074aa1452fed943238a", size = 226344, upload-time = "2026-09-27T12:26:15.127Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2c/f8296c63c5d542f3d21aed685e56b7031a419037d155bb3382fc0940d249/coverage-7.16.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:218d742afca2b5ad5ca759e93eddedfbcc6eadf8322f080dcefc40b7bd4e2d48", size = 223969, upload-time = "2026-09-27T12:26:16.753Z" }, + { url = "https://files.pythonhosted.org/packages/90/23/6f3dcb1423a0d43216e402ea1746e4a7c7c44f38896b97dd573790f56a40/coverage-7.16.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a9a638be322a8d76a41cdb17781c7f82aaee6a66493d8ffb7e2c09ee22423d99", size = 224328, upload-time = "2026-09-27T12:26:18.15Z" }, + { url = "https://files.pythonhosted.org/packages/ac/7d/8f3b6dc920e3fc6732f7678785a2091db439f186afbec30dbf2214d9b1f7/coverage-7.16.2-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:724bd0f1e81856b35e59fc98cf7b4e544a3cb662e4e0864dca73d4326ee9d808", size = 255832, upload-time = "2026-09-27T12:26:19.799Z" }, + { url = "https://files.pythonhosted.org/packages/d1/36/6c45f15be4eca4ac1062c6a55a323286494c99726a7e58951fe85967ac08/coverage-7.16.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5375ebd99038021b35e99dc88255022912c06565d316212f4a576e4b08d30f5d", size = 258571, upload-time = "2026-09-27T12:26:21.199Z" }, + { url = "https://files.pythonhosted.org/packages/34/fb/b54cbeba3ad89082c2e441278681859e538322cc34b84b2af7ebff00080f/coverage-7.16.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a076277ca9f5750cc230f0f578ebd2620cec60255b25707361699fef6fb465c", size = 259680, upload-time = "2026-09-27T12:26:22.822Z" }, + { url = "https://files.pythonhosted.org/packages/6e/a2/0dc65ec3d61930e1e4c2e371763b15eb4290896eb343a12d5d3091308116/coverage-7.16.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:58d4a54c6ea672afef66d49be922a2c69826c5ae1a42a9cd94f0c9c2bacdf800", size = 261945, upload-time = "2026-09-27T12:26:24.336Z" }, + { url = "https://files.pythonhosted.org/packages/d6/93/5fad7a61f2c14e08e98946fc31c1c7ffc1195061bf3fdc351db3be77a863/coverage-7.16.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0dcbcfcc059117284c603ff8cb61a65872512882f84a8cf0339241f7f7c2f148", size = 256191, upload-time = "2026-09-27T12:26:25.89Z" }, + { url = "https://files.pythonhosted.org/packages/2d/47/74e5de9227b939ece9f64e729645ddc4296bea10dbfa98721c1333c8be2e/coverage-7.16.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:afdf43b72ef3876c1fe66423b91466e37877c9e81e8cec70542b7e8525b9d1b7", size = 257610, upload-time = "2026-09-27T12:26:27.35Z" }, + { url = "https://files.pythonhosted.org/packages/13/fe/2cf28d40b43645d1b72388fe3ee7f7c747533a6a9557bb8c24a7ae74fe1a/coverage-7.16.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9acc7f7ec4a1b5f89bd929fde5b8a714f6fafdc6cc18725413d510aa082b47ad", size = 255757, upload-time = "2026-09-27T12:26:28.949Z" }, + { url = "https://files.pythonhosted.org/packages/d7/3d/7c149fd99fc8bbc39c80db5e688d1d39fd040be2ecb78b8335a51a55b9c0/coverage-7.16.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:80d3f7b48d43ee8fc5e8707a8adb43d743a5a1a85256c25a24f9d6d0e2238fa6", size = 259822, upload-time = "2026-09-27T12:26:30.515Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3f/b283fce09d5995e227bd8e513358dd7471bedc0f78abc85a925ebdb0a2f6/coverage-7.16.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:126d1af8804d7224421fe991ff65d3ce649081560df7a98b1a5ffff07f9923bd", size = 255325, upload-time = "2026-09-27T12:26:32.037Z" }, + { url = "https://files.pythonhosted.org/packages/bf/91/f3325edf0c4223fb1fe1532b8dbef2a1d2f729459a9a7d1a44d073bae534/coverage-7.16.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c19cd6d025c1673f22afcd22c7df8a662d779e05d8e3fa6820c22afb895b0206", size = 257191, upload-time = "2026-09-27T12:26:33.525Z" }, + { url = "https://files.pythonhosted.org/packages/c4/89/21eb5e83ecf2eed523c4eb3d65ae513cd082c8fd1b6deb34c4cb6c332f97/coverage-7.16.2-cp312-cp312-win32.whl", hash = "sha256:152877cdc8a07264882cfcd503ba56a3ef6cba56a70e8c70f6eb8ffd7384789a", size = 226034, upload-time = "2026-09-27T12:26:35.021Z" }, + { url = "https://files.pythonhosted.org/packages/db/de/e3ad6d864c0833624b4f1f9b53f9e58e116c945e5e965c3f1e172c5e84cd/coverage-7.16.2-cp312-cp312-win_amd64.whl", hash = "sha256:e6c52d3307824ff93b39efd99e4185d557db40bd841452abfb32e5d9151ca162", size = 226569, upload-time = "2026-09-27T12:26:36.604Z" }, + { url = "https://files.pythonhosted.org/packages/3e/c1/bccc58ebe5489cc70628f635c1932fd371f5d7da850dbcf960f95f4c4afc/coverage-7.16.2-cp312-cp312-win_arm64.whl", hash = "sha256:a678c0b6b22086ec2427359d22e37445d4a792f5fdbbc744112c7dade65cad02", size = 226372, upload-time = "2026-09-27T12:26:38.406Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f6/8eb4f220ef24f84fb27d852d4f9bf83e0c73ec1a4a08dd9a87e3f4529739/coverage-7.16.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1a37c6e478cf687e1aa30a593d19c92c02fad9d122b51ab73f51b8dc7a0c0fc9", size = 223993, upload-time = "2026-09-27T12:26:40.164Z" }, + { url = "https://files.pythonhosted.org/packages/40/23/d4bbaf0c154e0b0c2b5264890dbf6ef098dcb50ec8f2469be9490d191660/coverage-7.16.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0993d0e90858c03943d3cb152e068a20dd4707924deec84dd2230261baae3b1b", size = 224368, upload-time = "2026-09-27T12:26:41.762Z" }, + { url = "https://files.pythonhosted.org/packages/7f/48/fc1e88fd571ec5cb38150b7f89f7696ca1bdf9920e01432febb69774cc85/coverage-7.16.2-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bb2fc905bbf4e6b7f40806ea79e31515abf6349594cdf0adf27c4215f0463204", size = 255358, upload-time = "2026-09-27T12:26:43.442Z" }, + { url = "https://files.pythonhosted.org/packages/1d/56/6785397d07c29c8e70fbb9a07e97d062b43c21ffc5f12385917847f09f63/coverage-7.16.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4358b9c8c0125b460407f3017c6cce8156e904b32772c5630d27112f52bdbfe5", size = 257955, upload-time = "2026-09-27T12:26:45.725Z" }, + { url = "https://files.pythonhosted.org/packages/27/3b/c8cdd07721e5f99abd81cea970d971997f99bf158c0b85f51bd284179c8b/coverage-7.16.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1f15254427c9b33eedac4f198eaf9e356eb4f6214551afb43da6194a2c088ad7", size = 259183, upload-time = "2026-09-27T12:26:47.208Z" }, + { url = "https://files.pythonhosted.org/packages/9b/11/606b192fe43d32574ec6238549d48de588fdcc18485682a5ec0a8ac357f2/coverage-7.16.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9a75a4704ff640e46170042eec1f984385a121227c505d5a16ad8e495f452541", size = 261325, upload-time = "2026-09-27T12:26:49.084Z" }, + { url = "https://files.pythonhosted.org/packages/67/90/eea481f8b0305ceeb33f081a5f47e298391dbd1b589de0c4b3b3aa50d3f2/coverage-7.16.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:14253fc7bb15749b849795a06f5d3b6d8bc3fb8a4b5ddc341faf7a89dce205fc", size = 255531, upload-time = "2026-09-27T12:26:50.509Z" }, + { url = "https://files.pythonhosted.org/packages/6b/be/dedbf9aea1457b120c27ac10b8fc2a357f37fa2b54c3e7286d42980a0a2a/coverage-7.16.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:921415102a90637fcc2e3f169f61dad7699ecf690e8639fc21b813acbedc0967", size = 257329, upload-time = "2026-09-27T12:26:52.005Z" }, + { url = "https://files.pythonhosted.org/packages/fa/cb/b25c19d5bb2bd0f2e4e27fe8e2ffcae80c7a91ae181c0dc749ed60e9b1a4/coverage-7.16.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cce2bc991293f15cc4084ca116827b5900c5f34e1a54dfe83f10ab5c43162eb7", size = 255294, upload-time = "2026-09-27T12:26:53.634Z" }, + { url = "https://files.pythonhosted.org/packages/5f/a2/892c5c5f4ad44b7b2ca009aee705191f3f268f15052244f2f9e3539b2e35/coverage-7.16.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:e1fa594c887365b69745f25a416806e61085dd07b94c9eae68a6e20730629b23", size = 259444, upload-time = "2026-09-27T12:26:55.243Z" }, + { url = "https://files.pythonhosted.org/packages/ed/99/a562537deba0a3e370182ae71c149be796c39d8087365f17a09188f27145/coverage-7.16.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:11e597173af1dc33d5f8a7332ada544199269a223af1ee1770ddd5e245ad0fe8", size = 255111, upload-time = "2026-09-27T12:26:56.851Z" }, + { url = "https://files.pythonhosted.org/packages/2d/20/854ec68641a9b3362ff068a32dfa41637299761617ef253791dbade6fc76/coverage-7.16.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3e7f99698ba3a7d13988bdd984b7ebf13af4dbe2166dc8502eef90d77603b0a4", size = 256882, upload-time = "2026-09-27T12:26:58.41Z" }, + { url = "https://files.pythonhosted.org/packages/db/0d/748e4518b0ac0f9ff2687c248a6e5f8c0737306e709372632a2556f84443/coverage-7.16.2-cp313-cp313-win32.whl", hash = "sha256:f80bd9f9633eafc73d0a913ba2645c96ba58bba1befc30590f7c0fbfde59d865", size = 226045, upload-time = "2026-09-27T12:26:59.983Z" }, + { url = "https://files.pythonhosted.org/packages/31/fa/6e46edba66a183fe4d99d4bb52c173287e9b8dddabe0888d24cb8210e580/coverage-7.16.2-cp313-cp313-win_amd64.whl", hash = "sha256:8be099e979fc42559328a21828281b4578304191ae46ed4e80a407048a82eee6", size = 226581, upload-time = "2026-09-27T12:27:01.494Z" }, + { url = "https://files.pythonhosted.org/packages/1b/d9/9ef6845367600b336ff75d000444a0d32497d6972c833141bd39356abf68/coverage-7.16.2-cp313-cp313-win_arm64.whl", hash = "sha256:28ff850182a67d117990fa2ce5ea1032836d8c9630dae867e8bdd3bff4533b79", size = 226409, upload-time = "2026-09-27T12:27:03.116Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/577fc0803dab4155dcf808faffbdd7b159256781c0874a8586e17b81b149/coverage-7.16.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4ee546b9e4872ffa194bf07ac87bfa1202ebb824d0795dc1ef22f175545ca90a", size = 224138, upload-time = "2026-09-27T12:27:05.141Z" }, + { url = "https://files.pythonhosted.org/packages/75/9e/e3785ba3ecba2bd11efc74bfe2801ca4b78c4480b15a375648d809a59da3/coverage-7.16.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a2fac6895eb299a2e52d7bbb8fb3903502b9da8d3f5309ceb16ec40c646b58ee", size = 224445, upload-time = "2026-09-27T12:27:06.805Z" }, + { url = "https://files.pythonhosted.org/packages/f0/d0/963ff22d3fd27117da3b8cc442f5bdc91196f783321e1a8ff0ec43476772/coverage-7.16.2-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:57ff3783f99d75a1e81dd56a9737eb5665e6736a5d93258ba596b6dcad8fd05b", size = 256112, upload-time = "2026-09-27T12:27:08.43Z" }, + { url = "https://files.pythonhosted.org/packages/a8/d4/a306940c81c6ae759e82fff27d20b7fdc6896e422b821f51313cce212b6c/coverage-7.16.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:35f37886699cb9abd29958247d718628d5bc6f39e623dff66a09e546c42a7e03", size = 258727, upload-time = "2026-09-27T12:27:09.927Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a3/d3d99d93b02517087aa05bc0cf2d04d372956b849e5443e059079901429b/coverage-7.16.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0fd7a86fdda7cb6d616d178654bd0ad6bc0f3f33c2e478aa598500a1a9e34eda", size = 259909, upload-time = "2026-09-27T12:27:11.55Z" }, + { url = "https://files.pythonhosted.org/packages/08/44/39dd599181726758dd185ae4dc0c0ab3aeabf7ca70e68e145060feeaaa16/coverage-7.16.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ac0f3b379c94acc2f7dce5f5f0b24d44fa1cc6a509717ef83dfee07450c2117c", size = 262481, upload-time = "2026-09-27T12:27:13.17Z" }, + { url = "https://files.pythonhosted.org/packages/99/e8/91ee43f6ded411460c359d7e1aebde4d6fd8f00a2e5394182d9d212eb23c/coverage-7.16.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7d0732c83746bc24123c581a85d9dd96b70ddb538c9076020aa1a041790361e9", size = 256012, upload-time = "2026-09-27T12:27:14.91Z" }, + { url = "https://files.pythonhosted.org/packages/11/8c/e9499ddc33197bd7eabcb1118ca81756fc874457b324e2b479a4804b2ad2/coverage-7.16.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7b451c68218c150f616bc9649783ec8de76a59792c759b43aa0c9c0466a465e4", size = 257898, upload-time = "2026-09-27T12:27:16.588Z" }, + { url = "https://files.pythonhosted.org/packages/5f/6e/c081cb5991a0afba99f9c4ad6c74a5fce9513a38ddc64e3e6680c6fed9af/coverage-7.16.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:a56ac4fa5a75c7e182e8f62600cfb4aff43c5ed7356a034f3557659c3bec1d90", size = 255938, upload-time = "2026-09-27T12:27:18.19Z" }, + { url = "https://files.pythonhosted.org/packages/b2/42/1c3d819e8f9b6eb01c2fe90874d67a8882adb9507e0bbb09361ed131ea89/coverage-7.16.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4cc4f73aa3fabc36e32046d6cd2971405948d8a903636508a3d3b2f9128b3a95", size = 260368, upload-time = "2026-09-27T12:27:19.903Z" }, + { url = "https://files.pythonhosted.org/packages/19/4f/d70eac07901fd587b6ab05e659b52afe13959992aa5113bf6cce059cc572/coverage-7.16.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:723dcdab91357159b722935b500ee8abc0a66c8c432e1e9fabf4cc7598952de8", size = 255620, upload-time = "2026-09-27T12:27:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/34/5e/6d87af88317d3d9a9b18a9ca1bc1673eb516917f296e579d0d4a55cb3490/coverage-7.16.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5397e21a90dde0e9c6896b77ded8f0be26b66f8b22b33aed41f6043ed95d55e6", size = 257521, upload-time = "2026-09-27T12:27:23.358Z" }, + { url = "https://files.pythonhosted.org/packages/79/bb/90c2641170d2fa1a6757b3f8450ba2740197317b0ddd749e9604b914e886/coverage-7.16.2-cp314-cp314-win32.whl", hash = "sha256:848893e1d361448c113dc2f0913503522a6f7be231d0e38333d2a22d9698a011", size = 226248, upload-time = "2026-09-27T12:27:25.153Z" }, + { url = "https://files.pythonhosted.org/packages/30/08/d8d0478bb02c8eb0ae20a496fc80c40fcf4d3450bd184300d682ba2d28a6/coverage-7.16.2-cp314-cp314-win_amd64.whl", hash = "sha256:5a27b731c171e43dc8b5f32b76a5051dde2ec9b9366c87028f08a7088ebc2c7b", size = 226732, upload-time = "2026-09-27T12:27:26.907Z" }, + { url = "https://files.pythonhosted.org/packages/32/3f/0001da22155b0a8ce063ec0f7e64ecbe17b373f306e7a74435f6d6accb72/coverage-7.16.2-cp314-cp314-win_arm64.whl", hash = "sha256:1c569a9fd25505f1cd6bea90588818f90373ce90e2632e2cacf19ddbd6e14fdb", size = 226645, upload-time = "2026-09-27T12:27:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/d7/85/6d8813aff9b8b8586691a9d33c43c5604f7227622574da7cdc3d91a86861/coverage-7.16.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d93db87adb6b1c1b408dce4763314b55d76a9f589e96783a84ac9e7689e48bdf", size = 224871, upload-time = "2026-09-27T12:27:30.32Z" }, + { url = "https://files.pythonhosted.org/packages/5c/70/444f3a4981ac2cda40fdcf4cc9b56a4e1a33c222abeb33e51ed3e3eb2a6b/coverage-7.16.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:aa62c85046473959c13ba9edca9dc90a77d5c1095b1ba313556314d77fe5b036", size = 225123, upload-time = "2026-09-27T12:27:32.33Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c1/980681cd7b33eb66ac835044116ef0a92e11fcc7bdd866cc89d10b1130b9/coverage-7.16.2-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:db76506aa5416081f3e8974ae0f7965c58ada0bb0ef7339ac86099588dbb20d3", size = 265049, upload-time = "2026-09-27T12:27:34.085Z" }, + { url = "https://files.pythonhosted.org/packages/b2/e3/87679875c33bb2191f0f05544a1cc9adcc940fe0c35443a10f2df753dde5/coverage-7.16.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a0f2285329dac10ab08f79cb11f5692c497018e6c7c511f95e6fd63a70b8f831", size = 267717, upload-time = "2026-09-27T12:27:36.025Z" }, + { url = "https://files.pythonhosted.org/packages/76/64/5d372776d6eb523d4e93bafba2253f96984e3b18261c4cc56a50863c6d0d/coverage-7.16.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:382d3346d56b0eec1b793d53a4c88799c8053f516aa3a8d7c44315696954bacf", size = 270047, upload-time = "2026-09-27T12:27:37.96Z" }, + { url = "https://files.pythonhosted.org/packages/be/c1/44082ff0cbf9f97d0043f57970a71204097ec7ba606361a9fd2065393669/coverage-7.16.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:648352b94507179d82637292e7ae8802508d95f78e2f00a705a50b6c48011681", size = 271360, upload-time = "2026-09-27T12:27:39.766Z" }, + { url = "https://files.pythonhosted.org/packages/b8/17/9a215efe25b5e0ecc87c89dbe525c4a87d14d87c8c0c7316ef140a5f6f3e/coverage-7.16.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fb2bde05838fffae1a1bf75e5d411a6cac3e4e9bb97e6640fed8cd47888b33f0", size = 264736, upload-time = "2026-09-27T12:27:42.072Z" }, + { url = "https://files.pythonhosted.org/packages/a2/da/7f0a31af8e448107d4d32844bd684757f51ea907bc0c68c8fd537b2123ff/coverage-7.16.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:6a75180829efb8ae62b4aded25be6ddca1c888d138d2d82e21d93bfbd88f41cb", size = 267600, upload-time = "2026-09-27T12:27:43.85Z" }, + { url = "https://files.pythonhosted.org/packages/dd/a4/3bfecbd3366b775bacdcb3330394d356cf384b5d8f5b2146ac4b14b252b5/coverage-7.16.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:99704f73721e23859112072d522076e11c31744fc96b5652e5dd2018aa4359f7", size = 264767, upload-time = "2026-09-27T12:27:45.768Z" }, + { url = "https://files.pythonhosted.org/packages/b8/3f/5d62163732d87e4a0c4710a0eab30f0fd6a2d480112abe2029f014fe8c9d/coverage-7.16.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:29309ccc86b7f33df7db12813c299f215bbbc470ed6292d0bedd63ffae1ebf64", size = 269026, upload-time = "2026-09-27T12:27:47.787Z" }, + { url = "https://files.pythonhosted.org/packages/49/4d/8e4579f225426535085a9be371cc75e3b026d058d679b80affbdfb4c3ef0/coverage-7.16.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:30c1b65d529e46569899fadca59e4a87c1faf2886923f1307ba61e654d4f3c20", size = 264147, upload-time = "2026-09-27T12:27:49.681Z" }, + { url = "https://files.pythonhosted.org/packages/d1/36/ef1f77e2c3f7bb03c2b13b9a2006f88700fdd75535ef158d70049f425c1c/coverage-7.16.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dcf4bc2aab4e16b1c4c0c2005918f23a7dd5d7821ddae82caed9e3342dc2fcce", size = 266376, upload-time = "2026-09-27T12:27:51.551Z" }, + { url = "https://files.pythonhosted.org/packages/be/79/0cb2bf4428830dec971c718c2c841a039c084415c99e67281f5a72841aab/coverage-7.16.2-cp314-cp314t-win32.whl", hash = "sha256:a9cd3de0a5bfe7b0e21ee10e1a14e3d61bf52efc88217ab1d95d6ace6970bd46", size = 226585, upload-time = "2026-09-27T12:27:53.945Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f9/da17121c16667fd84998e972200ae226a41540f6ea4795776c6d99e8976f/coverage-7.16.2-cp314-cp314t-win_amd64.whl", hash = "sha256:611a44e5229a59d7483ce830160e1a0e85f700562c7a5651c7c63fb8f4eb528c", size = 227378, upload-time = "2026-09-27T12:27:55.778Z" }, + { url = "https://files.pythonhosted.org/packages/74/89/01179c62d1b7e6e33bd5001566b02d7f778cf33d3ec1e81e94ca170c517f/coverage-7.16.2-cp314-cp314t-win_arm64.whl", hash = "sha256:22957cef43ce038641de78ba995de7568d2d6a37c6ddbf7fa0fd7d1ae2344d91", size = 227064, upload-time = "2026-09-27T12:27:57.496Z" }, + { url = "https://files.pythonhosted.org/packages/4c/57/52935003c3f627ba6e5203d7179aad32448c10899663a30336aba8e81a2c/coverage-7.16.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:414c26dfdb96aac2d570a54e03008f001e32eb2d413705365503648c6bd361d8", size = 224140, upload-time = "2026-09-27T12:27:59.343Z" }, + { url = "https://files.pythonhosted.org/packages/31/38/df472520f3e626524d7e2fc9d6da0afe7895a2f1489d36b48af8ca40bb41/coverage-7.16.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00d3eb96e9988c45f50cccd1f1496571ac5c1f91386ac02c4d55516eeda19a24", size = 224449, upload-time = "2026-09-27T12:28:01.299Z" }, + { url = "https://files.pythonhosted.org/packages/0c/aa/3be084d5b82e63ccdad4ed751e4acbae294673573e30481d29f8b7402eec/coverage-7.16.2-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4dbbd1155ca46e6e0b6b89d204428c56ef6a459af21333f365d135a2820e5a09", size = 256060, upload-time = "2026-09-27T12:28:03.185Z" }, + { url = "https://files.pythonhosted.org/packages/de/29/48fca82a7ebf7ff7b2e35019cc9537e7f65e4d2aa1215cc5a8792c989251/coverage-7.16.2-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8fc15cc8d0d06e873c00ef18e1372d605f9aaf3de27d8c24e50782e75bc8b843", size = 259106, upload-time = "2026-09-27T12:28:05.15Z" }, + { url = "https://files.pythonhosted.org/packages/06/3d/b2d5986f2dd53fe201aa1be2e4ab204fa1aed5101e67c0dbbb419b850aee/coverage-7.16.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c6afdd69218202bc1758c9a14b86b8cf1084f37ed2ca143e567a103772b16d1", size = 260674, upload-time = "2026-09-27T12:28:06.868Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7e/b50160be3506ead12e6480d14279af7f0f17627694300a2d1fd2c42d2ff5/coverage-7.16.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:aba5c63b7afdc749cc9eae943d5b868cba2b261a176378fa1c5a30bc8bc89982", size = 263139, upload-time = "2026-09-27T12:28:08.771Z" }, + { url = "https://files.pythonhosted.org/packages/14/5e/7c805ac9a32606de1399bd7e9bd375aa2f973dc61b12680d9e6403c2e891/coverage-7.16.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9174f0af24e5eff248b9dbfe76ec5275a3d19d37edbc2810543f12cf97347a34", size = 256591, upload-time = "2026-09-27T12:28:10.842Z" }, + { url = "https://files.pythonhosted.org/packages/ab/9e/76f1ed129a2daf658a3ea17122824cf2e3b91fea0460d8d3664fc5a61018/coverage-7.16.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:80e9fdb4c3d926b6ba721d4bf7435bdb869c3527ae7803290361d0ab73db13b6", size = 258708, upload-time = "2026-09-27T12:28:12.962Z" }, + { url = "https://files.pythonhosted.org/packages/5a/b7/8d62e75f48b527619239a65294f842d4b7fd02a0839d43ae1de80184e2df/coverage-7.16.2-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:7b3bce4a0d05401d70b7d0d5ca783e686bc9d30e81dbd7d980d532609bf809e4", size = 256562, upload-time = "2026-09-27T12:28:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/b8/8d/0a15f95c3afb78e947c52644786ba4bc9de259905687dd720d5e6fae2e76/coverage-7.16.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:44f21e407b278efdfc1ee5e481e00518bd1d500310a30a5fbf2bcbedfef4aaf0", size = 261077, upload-time = "2026-09-27T12:28:17.215Z" }, + { url = "https://files.pythonhosted.org/packages/25/00/88389987305a47d732866c07c8a500000ab574df9505e3114ac69c8d027f/coverage-7.16.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:59c3926585e1cd1f2190f4b2ac9014de1bbeaf0d5d0587b0dc6b0aa90d17896a", size = 256034, upload-time = "2026-09-27T12:28:19.08Z" }, + { url = "https://files.pythonhosted.org/packages/92/02/34d079d4952ad461bde037d353f9a6e037a7edc45fe0f9ee8781ff73f028/coverage-7.16.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:066429634299e14dd2d511e1e85f8f9cecc500781f6b41907c0dd6f1baea7e63", size = 258034, upload-time = "2026-09-27T12:28:21.242Z" }, + { url = "https://files.pythonhosted.org/packages/f6/d8/3e59a62879285b464ec1b10fd824fbc1af9ce66e842cd39974f80a0becc4/coverage-7.16.2-cp315-cp315-win32.whl", hash = "sha256:893ea9cf86cb8d2546812ac93d973aaf2ee1fb45110a873b014214fd23e3725e", size = 226252, upload-time = "2026-09-27T12:28:23.102Z" }, + { url = "https://files.pythonhosted.org/packages/f4/e1/128026e1b2836e9ad6b219207ba9edf1c5e0088a7869e23088aee7fbbe7a/coverage-7.16.2-cp315-cp315-win_amd64.whl", hash = "sha256:01c6908bc613b420c26c818fe948e1b97dfd041a53c98b01c63bd8321f5c9aae", size = 226728, upload-time = "2026-09-27T12:28:25.21Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f4/c9fa8e7cf525ca7748ac52b0ee89331d13fe09808e45c679830708782e90/coverage-7.16.2-cp315-cp315-win_arm64.whl", hash = "sha256:967d72c835d7a8cf0af99ec813a2d06e3db6df706402f1fe85b31b437645f495", size = 226648, upload-time = "2026-09-27T12:28:27.136Z" }, + { url = "https://files.pythonhosted.org/packages/a2/13/e96b045447a856666f36f9c653e2a80bdaa732aaaf72412b19aa2c26a473/coverage-7.16.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:98d9c97f51b334b0adce7b964442a9af33c1a00c6ac856984cc5dc8d18f81c75", size = 224858, upload-time = "2026-09-27T12:28:29.169Z" }, + { url = "https://files.pythonhosted.org/packages/23/90/087f6ad1bd3df059632ca3407a4e6552ed1053ee35354de0a771acf35423/coverage-7.16.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e861f1071dcc2fec1e88bef0920f6b1eaa66a143555b4f8ab79ba2b0f30ef55", size = 225139, upload-time = "2026-09-27T12:28:31.131Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8e/285dcef0184358044e7cbcd810a1bdc9566bc620f54702d605477155df4a/coverage-7.16.2-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fb9d92ecfe2d5b494367c67f7446f8b75b68d8d0c8cf3bc3e6997478be25d9e2", size = 265090, upload-time = "2026-09-27T12:28:33.04Z" }, + { url = "https://files.pythonhosted.org/packages/06/b2/cc83f3a6e5789a4e89059c69555bc641c2efcde568405a1c06fc702951ab/coverage-7.16.2-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:eb57acff4a74246ae513c142d4b36e18c389c3aed8661914a53f7cd0071031b2", size = 268254, upload-time = "2026-09-27T12:28:35.135Z" }, + { url = "https://files.pythonhosted.org/packages/ac/41/f548c19530f5d66ac6e3c92bbcbc49da7261de3a458b9f3e54a3efb1a0b2/coverage-7.16.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:444889f7f66b74e4455c0a97e0e166dd41177f1dca8c0239a47cff25e05ba7e1", size = 270695, upload-time = "2026-09-27T12:28:36.959Z" }, + { url = "https://files.pythonhosted.org/packages/94/61/4dc27cf82ef96434d2874110ad0cc10ea4621025705dc5049862bd3bd181/coverage-7.16.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a740ea6f083c6db7b926534d159508f80ba275ab35e722522de0d18d0f56e55f", size = 271853, upload-time = "2026-09-27T12:28:38.821Z" }, + { url = "https://files.pythonhosted.org/packages/38/29/bf8072b1b8bd5f2de8b21460a404460b1a2b97e80a9464c78ec0271f6199/coverage-7.16.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8e209591f7c41ae4a9171335cf6156afda0b21de73b02f73f5aa95b2d5fbb08d", size = 265644, upload-time = "2026-09-27T12:28:40.815Z" }, + { url = "https://files.pythonhosted.org/packages/7c/2f/0aecb8721be5cdeb8afd9d6d9f6b463f074e4d8d37f00f4c42442522709f/coverage-7.16.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:396bb16e04ce04efbb3df91456ae4e3da918e69ecdf67fb711b0a0fdf35ccce0", size = 268530, upload-time = "2026-09-27T12:28:42.725Z" }, + { url = "https://files.pythonhosted.org/packages/ab/0b/92b4b7628268ee711249958e68fc0328779bd3d9a7ab4715379465aedb84/coverage-7.16.2-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9cdf19874e0d247f32f03609200370343c3c7aa260b191d8c2bb251d36198283", size = 265154, upload-time = "2026-09-27T12:28:44.684Z" }, + { url = "https://files.pythonhosted.org/packages/7b/d9/41c95c1ab29b3dcd357cd1227181d1c98185632aca41ce670ce671b23a43/coverage-7.16.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:fd3d72233eb8b48acc94fa57d44e2d32ce8e7abed02882ccb6d855ccc4ed33ec", size = 269799, upload-time = "2026-09-27T12:28:46.672Z" }, + { url = "https://files.pythonhosted.org/packages/80/07/ebeb259aa5362b033a137b86d7274ff4b109d59be8cc9913889b783bf75a/coverage-7.16.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:bb4ffe96aa663cee727659db5a2afeb38c95f8677b747d447b90d6d4874ea2c5", size = 265196, upload-time = "2026-09-27T12:28:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/b2/18/8437620f90d023680a072eee02f968055f3658bbfb7d386d0ea34cfb7f30/coverage-7.16.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:dba2edfb054f6d4a08df9d1637c39a5aa3865bca6617c13c86be21e45658a59c", size = 267266, upload-time = "2026-09-27T12:28:51.361Z" }, + { url = "https://files.pythonhosted.org/packages/28/6c/f08e8ee4293e6434035424180bef4d45e028e8ecc006c61bf9453e74405e/coverage-7.16.2-cp315-cp315t-win32.whl", hash = "sha256:251aed777c47c77aba047096d4542889db089227655711dfc2b9c54ef0e15e35", size = 226583, upload-time = "2026-09-27T12:28:53.33Z" }, + { url = "https://files.pythonhosted.org/packages/f7/fd/3f939c2847f4a72c20cff8b1ac33da78ea91a2d38d9b43336e60db719103/coverage-7.16.2-cp315-cp315t-win_amd64.whl", hash = "sha256:2aca0bdfa9e91621d5b09d815357bf63def4fc0e9cb66da67bf2cf93f3b1a6f5", size = 227374, upload-time = "2026-09-27T12:28:55.158Z" }, + { url = "https://files.pythonhosted.org/packages/5a/35/b98cdc354c952402132e675a87f2cc3227fb68f959c84aaa491fbe15933d/coverage-7.16.2-cp315-cp315t-win_arm64.whl", hash = "sha256:b88841e654f09732804809e435b3e005a929ffd9998b872b7b213957b8759cb8", size = 227064, upload-time = "2026-09-27T12:28:57.075Z" }, + { url = "https://files.pythonhosted.org/packages/3f/0c/7a64e1ac90541a8edf50daef0914848011fb057a5bf55284a4811e21939a/coverage-7.16.2-py3-none-any.whl", hash = "sha256:11d28e9123a9156cb405d8d27b44256c9a58fb5decc2073a8f17862057e3aa0f", size = 215754, upload-time = "2026-09-27T12:28:59.075Z" }, +] + +[package.optional-dependencies] +toml = [ + { name = "tomli" }, +] + +[[package]] +name = "coverage" +version = "7.18.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/50/6e/25ddd31de302ac7d4a19d10e1750ac13bbf0ca2a040298b9bb26ca0b2fba/coverage-7.18.0.tar.gz", hash = "sha256:dd7258fab7dbc3bedcc94d6e9d4431408e390f080687b3463dbee3147715867f", size = 1016051, upload-time = "2026-11-29T20:36:44.124Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8c/c1/090c723b0addce38716dfaef23e852d9bf57c2a23700454c3876e8bb7ca0/coverage-7.18.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:186da9badea00c533b5442eedd817f58dbd788ca1828209c8aece222f2184dc0", size = 230725, upload-time = "2026-11-29T20:34:10.977Z" }, + { url = "https://files.pythonhosted.org/packages/f6/a0/282d4ae3ee1e6868a6729a0f7864eb00db4612ba92748689f06ae2868ec3/coverage-7.18.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8369e55eaf84968595bf12257bfe577a10ddc52749d4ce885da14a0b0c70dfaa", size = 231156, upload-time = "2026-11-29T20:34:13.869Z" }, + { url = "https://files.pythonhosted.org/packages/fb/50/4dcfe3df7bcf7cb4409c931c1cc93849d5fa812810c53790294a7bd84d44/coverage-7.18.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7d25a73b2ae9f353f78dbb50295688a70c7c0b82b225d80210a99ea986c9d352", size = 263364, upload-time = "2026-11-29T20:34:15.08Z" }, + { url = "https://files.pythonhosted.org/packages/f2/79/3031e691cf6ff86afbcd35d5973b4d548c69f46355dea6a482e042556eab/coverage-7.18.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14574d625824113d0447912fe0b67ac98f89c2fbd53e4216d00f832b76b05bd6", size = 265332, upload-time = "2026-11-29T20:34:16.379Z" }, + { url = "https://files.pythonhosted.org/packages/6d/af/bdd3ed367726145ff2da7070f15c31caa5449062b3f49dccd0925104f537/coverage-7.18.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5fe7960d3b39675efea1272b10cc3988a7b307c5bf75367bf5d9ff9637a5f28a", size = 267624, upload-time = "2026-11-29T20:34:17.661Z" }, + { url = "https://files.pythonhosted.org/packages/2e/8d/dc205d85dd899c65a0b7fc3aac0a44dbbd553d7f363b8b239d009afa3a8e/coverage-7.18.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2da02772eae0d083f07d621e8206260138beefaddf3c85edf216abcd4342e455", size = 269612, upload-time = "2026-11-29T20:34:19.007Z" }, + { url = "https://files.pythonhosted.org/packages/8d/09/c1c7556156ec585752cae19a9984cbbc7833fb9cca42bde1d7e1b7de1c2f/coverage-7.18.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:80d6d63a0a8f0f19b6af7fcd6be4b086bb6fb945c35ecc8e89363f145cee01d2", size = 263238, upload-time = "2026-11-29T20:34:20.342Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3b/a84396e68bbcc510966a44ba2cc6306df67581da25309a1d9012906fbf62/coverage-7.18.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:53f00c1d9fee5218ae770fc003b8ae6233c2ca6962a4411312383cd6ccc01ea3", size = 265336, upload-time = "2026-11-29T20:34:21.551Z" }, + { url = "https://files.pythonhosted.org/packages/4d/1b/ad160526f6e55305506a1791d62f79b301a924dcd8e88d2ceb30950f3651/coverage-7.18.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5188bcd8c4bd257696d937f3b7926f644549fd49dba62bbf8c867b122162760a", size = 263147, upload-time = "2026-11-29T20:34:22.879Z" }, + { url = "https://files.pythonhosted.org/packages/b0/d9/f655af7633098eb77ab4140eb4f58bce6352a1470a18fbbaa7c5e0a7b8ad/coverage-7.18.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e36cbf67badda80444ed4ebb37cc3408ed9ea2841afe7673abb39eb99ca5955a", size = 267123, upload-time = "2026-11-29T20:34:24.035Z" }, + { url = "https://files.pythonhosted.org/packages/59/2f/da5b73716b1ddb5bbb280ce312cf4a3850627dee0291aab3ef42e46938a9/coverage-7.18.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:dc04ce588a8e277b5c10033ff870736424ae6ef84594efa6ee67116c1411e5a6", size = 262774, upload-time = "2026-11-29T20:34:25.234Z" }, + { url = "https://files.pythonhosted.org/packages/c2/e8/1eda0e89d054885886d1a39ccd9ee44af652495090e76fb9d28720fecf97/coverage-7.18.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:21df0391e721d8788466d83bf231850f4a4c49ddc9a6a77759667389937ffdf2", size = 263824, upload-time = "2026-11-29T20:34:26.728Z" }, + { url = "https://files.pythonhosted.org/packages/78/1e/00820ac19f5645897ee29154919cb3a72739d282faef357a9ec7c80acf2e/coverage-7.18.0-cp311-cp311-win32.whl", hash = "sha256:7d891f7e3b5f4f698cdcf9faba0c1a8aa546ab0c50cf0eecbe286cabe23e16f8", size = 232636, upload-time = "2026-11-29T20:34:29.104Z" }, + { url = "https://files.pythonhosted.org/packages/53/55/89fe24139520d7690ee5f6248f168ab4dadd5f2aa72e5661f0210b9b6cee/coverage-7.18.0-cp311-cp311-win_amd64.whl", hash = "sha256:7d07c2f9aa5dabe9220a78e50cfc6e38abc23c4273cfa5d0b40b9e3fc06f3451", size = 233357, upload-time = "2026-11-29T20:34:30.522Z" }, + { url = "https://files.pythonhosted.org/packages/9c/9c/54dbb3c36537b597cf1afc1d628d2e3176ee92b951b72b68eba8e0f0422c/coverage-7.18.0-cp311-cp311-win_arm64.whl", hash = "sha256:7577a67a99b049c75159de953661d939b94beb70eb4b2184523ce4919bb8a567", size = 233539, upload-time = "2026-11-29T20:34:31.789Z" }, + { url = "https://files.pythonhosted.org/packages/a2/7e/dd20c5cb95ec01c02a60bd1e8ae1d51d7b1a08b5083130e8b9b551d75cdf/coverage-7.18.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4552d064c6779d14705518193da97fc9b373d2ac1713ec463dfc38c95f4e81ad", size = 230814, upload-time = "2026-11-29T20:34:33.117Z" }, + { url = "https://files.pythonhosted.org/packages/c8/c8/4ecab406803fa05cbb6894b54239e9ede6f3e05d2a321e3c1174634a520e/coverage-7.18.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:511edacf9589f9df6dfe82bafa270bca89380da897bf4d431e27007b29b4c0dc", size = 231070, upload-time = "2026-11-29T20:34:34.364Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a2/66bbb42ef2f4469643f840087607d836f60c36a259a31b00b4dc92a366cb/coverage-7.18.0-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:85930db02b6a00aaf15cb5ba2ac4b58beeeb78a1a639ca98d11ae1cff071078e", size = 263392, upload-time = "2026-11-29T20:34:35.786Z" }, + { url = "https://files.pythonhosted.org/packages/38/06/14603f50a8424cbb276163059b1de82159e50843f487ce322fc65b2ceed9/coverage-7.18.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d1a1a25e4b1090df14e09d75f6d9d72540533861ddc1c42e496aa00a92a49155", size = 266678, upload-time = "2026-11-29T20:34:37.051Z" }, + { url = "https://files.pythonhosted.org/packages/1b/be/791339d9f82adf43ecfe0141f0bd4b509e5357d5ce5fb48d603c5735534f/coverage-7.18.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9a63d93b51d8c9b39c202a6a6efe783cbc44264191471e02a50f1a978fbe9cc4", size = 267457, upload-time = "2026-11-29T20:34:38.173Z" }, + { url = "https://files.pythonhosted.org/packages/cf/be/9d5b1de371ad05a9f204a5013413bee591d8def5e45f5d1882cb2144e885/coverage-7.18.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9df6c16283323cc1f141773bf89a3f2466156db1ccce19ff885a41b5a47037de", size = 269719, upload-time = "2026-11-29T20:34:39.371Z" }, + { url = "https://files.pythonhosted.org/packages/29/7b/9cef8c89862267e9e4b78375b49ca8bb1d4cb7261af509e7372f37cd6a98/coverage-7.18.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04551c389f9941280d58ca7b43fb81c9be68e50e91d6fe020ec0196a69b82b4e", size = 263722, upload-time = "2026-11-29T20:34:40.494Z" }, + { url = "https://files.pythonhosted.org/packages/6b/65/4e820768b5b493d69410b28dd48aace87c394b60267883a946033f96fa5d/coverage-7.18.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1b7aee404e53abeab4dd6985556d5f87a229e8c372dd4fd52704e9f70898317c", size = 265391, upload-time = "2026-11-29T20:34:41.736Z" }, + { url = "https://files.pythonhosted.org/packages/0d/c2/c3ed0dac64e39c0c6be4e118d69a2e79545f603b2c9365b52e533eb07a1c/coverage-7.18.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:906976f9915913302d207d6788c83bffcb05307806fc910e6c7eb4f842a225b4", size = 263286, upload-time = "2026-11-29T20:34:42.963Z" }, + { url = "https://files.pythonhosted.org/packages/78/03/6b2b4fbba631430944ff9af7542e6c9b0ad6d0ca61005c6bd5c4ed673fb1/coverage-7.18.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5731cd3bc436802fd8ebec2913eef852c90e2ed1556684cfbb3665ea932312b8", size = 267546, upload-time = "2026-11-29T20:34:44.077Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ea/69c10d6a06999951fde477a77730d5238209aa3df11c8ddf090341ac8e8c/coverage-7.18.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:901fe85f528b9054e6aa80e4d05662e9223a95f19406c4a53e56dd12849b57b2", size = 262874, upload-time = "2026-11-29T20:34:45.245Z" }, + { url = "https://files.pythonhosted.org/packages/b9/8f/f271c42c768c76769087330e8687e9e1f088a7cd16a16985f9b1bdd1dc27/coverage-7.18.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:290dd85ee7e43a99a110c8e7506eb8f6943b651fb56f02600ba67a4c2f96be53", size = 265253, upload-time = "2026-11-29T20:34:46.564Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fc/5159becd4cc1748708b91f43b34c59a4d6a9649f9cf7fb102fb48c8a9774/coverage-7.18.0-cp312-cp312-win32.whl", hash = "sha256:7252429bd59b0da6e7f4bb0d0a407eea9e526d358b72feb5a39e0d79ae5f29b3", size = 232753, upload-time = "2026-11-29T20:34:47.644Z" }, + { url = "https://files.pythonhosted.org/packages/27/3f/96c567cff3bb1b82220de4b5d4a4b25d39f3132acf5dcce57188d052efb5/coverage-7.18.0-cp312-cp312-win_amd64.whl", hash = "sha256:87d3f47400b417932abc384b4f9bc3de6e3f2850676efad14d9b634f25d1c5d1", size = 233422, upload-time = "2026-11-29T20:34:48.999Z" }, + { url = "https://files.pythonhosted.org/packages/5f/0f/0545d5ff6424b77795c617319fdc762d83f4c6c8bd81fc1c203b50f59074/coverage-7.18.0-cp312-cp312-win_arm64.whl", hash = "sha256:78acddd1aed34874013c9071384616f890c73a2c586d5fca738e94c49e2afb14", size = 233394, upload-time = "2026-11-29T20:34:50.41Z" }, + { url = "https://files.pythonhosted.org/packages/c3/0e/aead6d4bb1657a54ac2c12db19935f2c325ca6217ba69e42c9e9c2b4f6dd/coverage-7.18.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:e138c8bad1cb41e473616af1aec9f0af2c577eb5545c61c5316c3a7f8c16f7cc", size = 232079, upload-time = "2026-11-29T20:34:51.753Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7c/db6e89f4c939dfee0bc007356059b173df863c2416827ec371f73c123460/coverage-7.18.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:cfb497d3fa36b4e47a3a549d7e62caf617d7caded5c969058c6898c9e615c5f0", size = 232166, upload-time = "2026-11-29T20:34:53.056Z" }, + { url = "https://files.pythonhosted.org/packages/8f/ca/8e32577f7bcacb1e3de2ab0174b54fe16fa06ac3ea7eadb3e7cccca2a7e0/coverage-7.18.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:26af02eb583c0ad1156f9ae4165c83070ff6931530cec800a011be8270489c79", size = 230425, upload-time = "2026-11-29T20:34:54.252Z" }, + { url = "https://files.pythonhosted.org/packages/0f/19/0badc5b3bb37a651a544c0eb15126ed978452d867b72273bf89aa6afae61/coverage-7.18.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d17fd0c367201117165d1f8919b44be3830040da05f7b2ae8c8205514216a29e", size = 230719, upload-time = "2026-11-29T20:34:55.447Z" }, + { url = "https://files.pythonhosted.org/packages/20/c5/e6140082230a51c49c5e533693652d9886655708da3f88aca7adee07dc56/coverage-7.18.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:fc467f7c53eff1963f8cc42141786a4bbabcbe9c0cd7ebd1437e6002f15e9cda", size = 230798, upload-time = "2026-11-29T20:34:56.622Z" }, + { url = "https://files.pythonhosted.org/packages/ec/71/4503c40e0aa8757f244029c3b96673ae6391a87e36c10366b08ec38d1acb/coverage-7.18.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3b2ebbcaa57828ae51d08d3b07541a1eaee6b3538405dfd6e00566ba5fd305be", size = 231116, upload-time = "2026-11-29T20:34:57.879Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/5ae44c834fd3f99d3a4196bb99924b2cad04965c7748ee99cba7c60ac700/coverage-7.18.0-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f6643a015a3a78c6a0f8f46e2e5bab123587fd0f46273a74864dcf4168f52e07", size = 262371, upload-time = "2026-11-29T20:34:59.125Z" }, + { url = "https://files.pythonhosted.org/packages/42/ad/e6ec4102a4cf0848facdffed400b11e5e283008860d76116da16ee304eae/coverage-7.18.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c81ae6c62807cca4aa5df15912f77c2c35584ed5f2b0273953f99789a98d6247", size = 265344, upload-time = "2026-11-29T20:35:00.258Z" }, + { url = "https://files.pythonhosted.org/packages/74/e8/f0eecd880935ec0b766940d0d571196a090551d98f14a6905d58b196cd3f/coverage-7.18.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a90f20668cc0a1aedef26d366a0116fed09cb60efcfd4c48effb0f80637cff6", size = 266144, upload-time = "2026-11-29T20:35:01.502Z" }, + { url = "https://files.pythonhosted.org/packages/ff/f9/c92933943f019633943437da8a536632a5c2702564333605b8f11c1bad69/coverage-7.18.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2d8676820aeac97239e08227a284c6562dbd35db6dd7e982ef8bf9f4e32f9229", size = 268542, upload-time = "2026-11-29T20:35:02.946Z" }, + { url = "https://files.pythonhosted.org/packages/de/7f/dac332a28ee6e995391930563b60d0a3859b7d9751d5d52210c240b31371/coverage-7.18.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6b37f74ab85356ead041f036c1607f09cc00ef34ef3c21b0e4144476414a7c64", size = 262583, upload-time = "2026-11-29T20:35:04.138Z" }, + { url = "https://files.pythonhosted.org/packages/18/99/7cb9651d7bb6e63f6709bf7fccec708422dd0895a2b102b60c66d5227ffa/coverage-7.18.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:fef0517d326cc1010b5999af6d4940fc47b3d6e67fc8e4ff3b1430ba2f0cd312", size = 264359, upload-time = "2026-11-29T20:35:05.672Z" }, + { url = "https://files.pythonhosted.org/packages/6c/94/a206462ad0c0b31f56a22c702c99c5dce59171e2d3134592c4e1c9caabc5/coverage-7.18.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:c5db509ec59c974654c7e1e6491094074b307ec348e5ebf0848265bcc864756b", size = 262377, upload-time = "2026-11-29T20:35:06.898Z" }, + { url = "https://files.pythonhosted.org/packages/bc/b7/89b7f421834b9801b85d5de5a2b235bcf963d584b9be5987b29af244095f/coverage-7.18.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a7b56b62e0dcb0932e1c8935dd8ab8ea608d9c3e341c79ca42338b423cf2ba3f", size = 266673, upload-time = "2026-11-29T20:35:08.022Z" }, + { url = "https://files.pythonhosted.org/packages/c8/18/6be3db394f4c904ddeeb1450337ec4498dc021b955117e6ec52f943f6106/coverage-7.18.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a228e48ba4ae337846f321702939ea3e74025e3b3cbb20c8ef920f2f8a73cc71", size = 262296, upload-time = "2026-11-29T20:35:09.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/0e/4d92ca9a08deec29e50f43200ec7f7e495082c0e1b9374f71d5ac1c47228/coverage-7.18.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8fff70fbec357e1d392568772b4a242cc7dc54d76d30915090ebf8919e73a5fc", size = 264283, upload-time = "2026-11-29T20:35:10.457Z" }, + { url = "https://files.pythonhosted.org/packages/ec/df/d336a64b918faf91a0a85a196ee3a3fc8973dfffad48b293757b8301a99d/coverage-7.18.0-cp313-cp313-win32.whl", hash = "sha256:410a5327098c8c6a96c7af17cdc703df019de5c56855b7a45829dbbdf4b8f582", size = 232675, upload-time = "2026-11-29T20:35:12.074Z" }, + { url = "https://files.pythonhosted.org/packages/69/94/3bd5eb0ca657bf983c43021c9c9ca0ee93a3dbfa5805d6fb545b1efa66cb/coverage-7.18.0-cp313-cp313-win_amd64.whl", hash = "sha256:06a9051f33f4cf66f7ef1764ec080ab15b6ecbbfcaf02acadc92d92daac7d796", size = 233461, upload-time = "2026-11-29T20:35:13.271Z" }, + { url = "https://files.pythonhosted.org/packages/a9/e0/de3450e97554b96982b018d9df816299477aa2fb41b97900ff64d4ec9d7d/coverage-7.18.0-cp313-cp313-win_arm64.whl", hash = "sha256:df7e6a9aea715fe265c34a16215ca5687f4ea9be6f60ff0466e92dcba0b9d42b", size = 233331, upload-time = "2026-11-29T20:35:14.626Z" }, + { url = "https://files.pythonhosted.org/packages/87/58/ccbda3547d53431636319f5c4d86e28df1ca34068f5ef24a5c4b8359fbcd/coverage-7.18.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:58ddff21a6a4e9aef487c5cc72124b1a2c75452df9b23075934a02580f28e06c", size = 232203, upload-time = "2026-11-29T20:35:15.872Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/2bcbbd2086d11ae759dc7ceb03c49fa460610cb9eefe8de95e6097462679/coverage-7.18.0-cp314-cp314-android_24_x86_64.whl", hash = "sha256:37bf304bd3ff00d6f28156152b35e7285e4de3b6f163ada9be7bdee9f496aec6", size = 232280, upload-time = "2026-11-29T20:35:17.033Z" }, + { url = "https://files.pythonhosted.org/packages/c6/17/3ccdda27fb9a9f3e4ca3a0886966b8b4a6769439b907966be0d65f2d6428/coverage-7.18.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0b1a94f1d4015a3e566c815cb1bfd25be6a7a5a07ec7e3fc7dd97e1ab8bbac4a", size = 230512, upload-time = "2026-11-29T20:35:18.587Z" }, + { url = "https://files.pythonhosted.org/packages/c7/5a/645b148a814afda46c5e2f59ee45f2594dbb67c454eccd1c9a0a968e9a7f/coverage-7.18.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:950ecfce98dfece283e1477908911f10f91c8cfdb0e7d31d009d9f27ffe0f4ed", size = 230812, upload-time = "2026-11-29T20:35:19.728Z" }, + { url = "https://files.pythonhosted.org/packages/ad/fa/c7122df00ea4ea72e49cf6c6236811493ff2b402bed8131290f4c76cf678/coverage-7.18.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:bbbce08e600454d5f53bb3698711d764ca699fb715be548dac9f40ff3b2420ab", size = 231016, upload-time = "2026-11-29T20:35:20.869Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a9/71c1ba1d208816cc63175bb9b97b667e9e68cb8b6308c8e2242b01bba748/coverage-7.18.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7bb6963bdbe18d8d2786dac131c83a704b7c6a1768ff520d25b0bb5d3189918c", size = 231208, upload-time = "2026-11-29T20:35:22.071Z" }, + { url = "https://files.pythonhosted.org/packages/21/f6/a003acea0ed85dd5e599557541208d279fd6bd0317321f61910614b62be1/coverage-7.18.0-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4fcc541be778613d134caf9fabb2f6c7b39204e880f7b3d6d8a17461cb5d3849", size = 263274, upload-time = "2026-11-29T20:35:23.259Z" }, + { url = "https://files.pythonhosted.org/packages/78/16/07c10091a730c23358d837452f64766c7927dce346efe6460fbc3c219235/coverage-7.18.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:425f0b8fa746ecaf110ed3f831295feaf67d6ee539b9887d17c07504d0d464e8", size = 266155, upload-time = "2026-11-29T20:35:24.448Z" }, + { url = "https://files.pythonhosted.org/packages/04/05/b95a1710f617e2fbe2260fd2ccce69d1225d6931ab1a60be91483af55ae7/coverage-7.18.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57b9a3dbaf80c7d55ee42f56020bec896b2c7ce320bca5a27f339956bf2564a6", size = 266953, upload-time = "2026-11-29T20:35:25.733Z" }, + { url = "https://files.pythonhosted.org/packages/c9/20/ed099fe8bd916f3d03889754372bd307b943e5f8dde075e595986d8fa960/coverage-7.18.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5106a4dd74d92f94a99c61c86ff3f13eed6cd2fab7e112e9b5f3d38e430e91f7", size = 269933, upload-time = "2026-11-29T20:35:26.839Z" }, + { url = "https://files.pythonhosted.org/packages/65/f7/9b27387bc223c83414a33deff1889e62320cd7d2c67c3b6b5b82730dc5b7/coverage-7.18.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:73c9b20f8e4df974260f150c5e4aefad62f1fac9d78bed38592ed2681b885910", size = 263022, upload-time = "2026-11-29T20:35:28.035Z" }, + { url = "https://files.pythonhosted.org/packages/9b/c9/05d19dc321b79484236446f18b9287a900cb69ea87eaa734ed9c4de38712/coverage-7.18.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:041b7da73462294b32e63d85556a58f28465e3b5b368069553d3e4f5414852e6", size = 264990, upload-time = "2026-11-29T20:35:29.528Z" }, + { url = "https://files.pythonhosted.org/packages/7b/43/0859cf7a12c65393c9935dfdd64f3bb317732c406c6992b66329d0bd78a5/coverage-7.18.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9d6bcde38a2748b492df0592e87a15fa5e649a2366218740a43ac42ba4c4ac00", size = 263162, upload-time = "2026-11-29T20:35:30.85Z" }, + { url = "https://files.pythonhosted.org/packages/82/1b/59de18416ec85343b13e0c3708a632e59ff678ddd00bb31f3c81c721e2b0/coverage-7.18.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:2aee866f8a232d4378f533f5635251678b479b670994b48d61360842d9023cab", size = 267695, upload-time = "2026-11-29T20:35:32.005Z" }, + { url = "https://files.pythonhosted.org/packages/d6/9d/e5fff3d6a100996203c3ffe05a6b047a87ad706da262f4c47293525ff311/coverage-7.18.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:43689bb7c4d8ab3a54ba1d923bd9282e50604e8691be9dc0484b47af16e58686", size = 262838, upload-time = "2026-11-29T20:35:33.253Z" }, + { url = "https://files.pythonhosted.org/packages/58/8e/de97a99d35d4f5d7d4c9c8682a7c6f282ba040e12c3439a532e653166e44/coverage-7.18.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ee99c0421e1fd46082ea1331b0ac2953fc0503651b49f4c012623023ba046fe4", size = 264886, upload-time = "2026-11-29T20:35:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/34/a2/08ead821bb192f6d3f6d03cdfda48270ed2413c1725face04a37771bba4f/coverage-7.18.0-cp314-cp314-win32.whl", hash = "sha256:fad89bdc436ac0f9735d4c48e20955d66e24d1d5b059ef542d94ff639db657e3", size = 232929, upload-time = "2026-11-29T20:35:35.505Z" }, + { url = "https://files.pythonhosted.org/packages/79/7f/f4ed29e125566b3e3d1d1c962f88194071c1622420a79b178520ed61a562/coverage-7.18.0-cp314-cp314-win_amd64.whl", hash = "sha256:a989777145597f07f5db8c2e8768e3638f3a8049bcfeeb56f61fd70ccfdd8655", size = 233779, upload-time = "2026-11-29T20:35:36.655Z" }, + { url = "https://files.pythonhosted.org/packages/8d/20/e3ebf8ab3aeb0282ced39b35a60e58ace84cf4b75aeec799166b8dd54a7d/coverage-7.18.0-cp314-cp314-win_arm64.whl", hash = "sha256:a610b3c9680dd04afdcce900e76407c6ff876f3cdfb0e2fe20d946c28ff794dc", size = 233613, upload-time = "2026-11-29T20:35:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/4e/da/5427478892a6ff7f0e18428617edbd1ecd81ad031ebf70889bc5bd0031cf/coverage-7.18.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:971b8eea5046be5707d287977f3cff5c7d8143029a0e0e631af3075f0effa65f", size = 231547, upload-time = "2026-11-29T20:35:39.248Z" }, + { url = "https://files.pythonhosted.org/packages/f7/5a/8d15aa3462e2213b53aaf9d3cf96df8714356dcda6a5f8efd195a5fdd49b/coverage-7.18.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e9cf9e831e7d7245a6788889baa36b3480fd254adb434bb7ce1c40a419237c58", size = 231794, upload-time = "2026-11-29T20:35:40.63Z" }, + { url = "https://files.pythonhosted.org/packages/cb/de/df846b3a08bc1eb4979f062456b0bd2646fa9d40e91f019a8f86590aa95f/coverage-7.18.0-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:ed7bcaec8d49ac2a81fb38f007416a6eadb911b93132cd5bc3060c1aa4d6ee3b", size = 271744, upload-time = "2026-11-29T20:35:41.779Z" }, + { url = "https://files.pythonhosted.org/packages/2e/29/8a28f26a5ecb370be81bac3a1c8a60f5efc515523a1a0a89af1e95249253/coverage-7.18.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cb93ebd8505845ff3dccfc8f4224e92494bd66e4cb6630c49c29a0c4753d1a65", size = 274424, upload-time = "2026-11-29T20:35:43.45Z" }, + { url = "https://files.pythonhosted.org/packages/3f/a2/2b18e6fdf42048e23ee5045b9b59246fb86dd9df93d3b24d593a13870a4b/coverage-7.18.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61a01578d43e3bc88b9686cf736ea9127430db5a6060b3b45858c1eef3455128", size = 276959, upload-time = "2026-11-29T20:35:44.724Z" }, + { url = "https://files.pythonhosted.org/packages/0f/76/52e6e24739512b29f6bdfc38d538dc8ae7b6b0d529c12aebd41bcbfe3fca/coverage-7.18.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:738f79c92c5f49808d89983fd110c51d5ef14a0dee2530030550e073a41705c8", size = 278281, upload-time = "2026-11-29T20:35:45.906Z" }, + { url = "https://files.pythonhosted.org/packages/8b/32/30f65d6c01a3241c391c72b9b22b62e62a3e1b0538297d0eb20ad712c9d6/coverage-7.18.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:978156935e95ad1bd421925a8cbf8dd2f7ca3f960e27bf79fdcff8f27d55c655", size = 271764, upload-time = "2026-11-29T20:35:47.191Z" }, + { url = "https://files.pythonhosted.org/packages/43/af/bbd6621d59a462cef8ee506c78a25aaf0eb4291f71d2d445c16e90591ba3/coverage-7.18.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:345b0afbeb6ae1925422592e420c7288584f1cdddefa602527f856c421ecde04", size = 274324, upload-time = "2026-11-29T20:35:48.509Z" }, + { url = "https://files.pythonhosted.org/packages/e5/1a/129c6d87a1e7598085ec0f121d684fa52ba7a79dc12a94c4adf384a43c56/coverage-7.18.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ae11683de228222196da81936450c109e9575fec48ed5658ff0fd6f47a7bc40a", size = 271696, upload-time = "2026-11-29T20:35:49.674Z" }, + { url = "https://files.pythonhosted.org/packages/6b/fb/dcc5c8651e3db4dd1ebb5c6cfeb69bfa7557eedbf07adceb34d65f4bf9d4/coverage-7.18.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:47d1d451e107f836bae9d39bcf8e45cb0bf576d9a5cec8064518e48c6aeb3391", size = 275918, upload-time = "2026-11-29T20:35:51.248Z" }, + { url = "https://files.pythonhosted.org/packages/d3/1e/3f472f2e697a8222550cdfeb7c6803756e2bfa4d49595b3ee6c2144d5988/coverage-7.18.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a776021fbd363521ea5f74967e0f01f3af43b194d96f05eb1dd6c9b01eebf4dd", size = 271141, upload-time = "2026-11-29T20:35:52.4Z" }, + { url = "https://files.pythonhosted.org/packages/18/e5/81a9440edfdd240db9f7d076a296ef9e679810c72972e07b95e96fe07002/coverage-7.18.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a28e71a2bc34bef6ae8e0bb03425cc8be334fc47ca564c1818947299f806f1c3", size = 273139, upload-time = "2026-11-29T20:35:53.645Z" }, + { url = "https://files.pythonhosted.org/packages/29/2d/2a966fb675c7948645a213e14f8ebe08d37d7f7f8779e050e03f99598e6a/coverage-7.18.0-cp314-cp314t-win32.whl", hash = "sha256:941f02f81d96c5cc7bf501e682d1914b7d99edb07795534181dca89a6646d8c7", size = 233262, upload-time = "2026-11-29T20:35:54.839Z" }, + { url = "https://files.pythonhosted.org/packages/4c/9d/91094d02246f2353c81cba44122c61132ed7e176e1f4b2feb856276440cd/coverage-7.18.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d302b62af4b90a0242b705c6c8cb3fa6d56c16917efc8931942cd80ab7af9f42", size = 234310, upload-time = "2026-11-29T20:35:55.966Z" }, + { url = "https://files.pythonhosted.org/packages/64/f1/14c594f4649d75045495ad8d84bd4aac7da1c1633217dc3c68fb066d4b54/coverage-7.18.0-cp314-cp314t-win_arm64.whl", hash = "sha256:e8319b9c65a5a2b0f0f84c062d1181d9335d5cc62e7e3a0206c7540ec65dba8b", size = 233996, upload-time = "2026-11-29T20:35:57.124Z" }, + { url = "https://files.pythonhosted.org/packages/4c/89/e19b9e7557d5634143385c93142f9b08487828490ceb4639def9878c8ad0/coverage-7.18.0-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:798fe514dc1c7f5b4f1ae2de844fe9d67b302331ee32b47337de811a174715a3", size = 232211, upload-time = "2026-11-29T20:35:58.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/74/71bedc3814725583f8a9591ccf42403467bc5e473f7c600c560cb11a7073/coverage-7.18.0-cp315-cp315-android_24_x86_64.whl", hash = "sha256:019291ddc4e663c4e3c9ca2e93b4928333d117019c9760b827b287dd8f88e1c2", size = 232290, upload-time = "2026-11-29T20:35:59.545Z" }, + { url = "https://files.pythonhosted.org/packages/06/ec/9f3fdae6285f31d2aefabfc484ac086348d21c7f6373236c0df4fc1af354/coverage-7.18.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e7fc6ceb1d818c81246ef0885f5bf27b0eb9086a03ef1dfa709500a8311ebf2a", size = 230532, upload-time = "2026-11-29T20:36:00.729Z" }, + { url = "https://files.pythonhosted.org/packages/45/75/3ff7b4f4b97e556a283d79ee4cd8e887e265d8b456e52a592bdc83c520c0/coverage-7.18.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9d4881f069484ec0de1696ba4f1a66ea04faff948b8aa8a1172462a319111f37", size = 230823, upload-time = "2026-11-29T20:36:01.848Z" }, + { url = "https://files.pythonhosted.org/packages/6b/29/4a253ff9d544a4020873a22c9b5d6129a60110684483ec50b3651b2911fe/coverage-7.18.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:5e859cd08cbbcfca8a94a471a7ee52c238e2c497923e98ad6da816a615bff904", size = 231025, upload-time = "2026-11-29T20:36:03.029Z" }, + { url = "https://files.pythonhosted.org/packages/d5/63/5ee38671ffff454bb3b4b24905d4d62da431749cca225dac65d9f4857f3c/coverage-7.18.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:acaba0e9d5dae44236ec929d295137036ec6caa43d4dc805928b8d7e0995c9b6", size = 231218, upload-time = "2026-11-29T20:36:04.256Z" }, + { url = "https://files.pythonhosted.org/packages/c1/53/18ed7cca58ae4cb0b7b2471f592279c01659c6c12cc532d37ebe2e7eba3b/coverage-7.18.0-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:6f7cfb050bb23f64113178776918024c8d0a2f7f54cd9b700e9903bece84e898", size = 263230, upload-time = "2026-11-29T20:36:05.44Z" }, + { url = "https://files.pythonhosted.org/packages/4e/1e/7442997c30816465b4062bcb537b28841952fedb0c745079d0dc6f00bba1/coverage-7.18.0-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5e1b10461c0e9029b3c4d53abfc0794deda32500607f2238d798a0255be14444", size = 266799, upload-time = "2026-11-29T20:36:07.084Z" }, + { url = "https://files.pythonhosted.org/packages/ac/8e/07307f5698f8d4062c670d7e13edbfed1dbed4a4bf786734a58ffc32e8eb/coverage-7.18.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c057e15c980989c8602aff25dbf02f632fa60fae28cef3564e689d135dd2ebd", size = 267750, upload-time = "2026-11-29T20:36:08.508Z" }, + { url = "https://files.pythonhosted.org/packages/dc/63/70e6fa5a47e828e72222764cedff7b902b0e8deaf0326eb4740cc53edbf7/coverage-7.18.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:304971d13d32d460eae3a48e66de8f6bd087a887e7e3772ebf892c661825be6b", size = 270594, upload-time = "2026-11-29T20:36:09.783Z" }, + { url = "https://files.pythonhosted.org/packages/c3/60/aae5fb984615872012418ef3d6c3c79e75877dbcf2c5e06609b1c2c03eff/coverage-7.18.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cc7bbd5784fb9590958a51b0cd0a562209151514700d322294550a86753b6f68", size = 263550, upload-time = "2026-11-29T20:36:11.42Z" }, + { url = "https://files.pythonhosted.org/packages/98/4a/abea9be4265cd1344175f65a40d3d0c14686cabeb6293f4e71c90f0cfddc/coverage-7.18.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:bf7c3853c43eae22049fe5d5f49cc8613dfc763035afbf9aadcde7c32dc1c554", size = 265793, upload-time = "2026-11-29T20:36:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/6e/27/7913b19b6f8910238a147b2d78555534627a046d4588f61890f12df0a251/coverage-7.18.0-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:5cdaf8f88abeeb4675055aa33eba6e982b9f5a803556deb198e8e22a3dfb8087", size = 263833, upload-time = "2026-11-29T20:36:13.807Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b4/d493425cc62590085ecf679c1d9b298cde1c02ec775f77cd438bb0288da1/coverage-7.18.0-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:760fe2423a55d0307efbd990c978ea2e75a4777dca8217e9fa2f886265f29bdb", size = 268398, upload-time = "2026-11-29T20:36:14.931Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ed/6d1f213a771ca9d65aa095c525613e4a550f532f44270420b1d1c5be4359/coverage-7.18.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:23370fcef3c15189a7b5a972d7a6f71afd3395750ae19dd26ea4fe78ec53c61d", size = 263175, upload-time = "2026-11-29T20:36:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/83/d6/e8585873b5f7f81549878f90ad651ca995bbd5c4f29fd0dbfda4abce637d/coverage-7.18.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:fd52df836d1e645e5ec32739c95daa4bfae697d2b3e84dea10918023c8891a40", size = 265619, upload-time = "2026-11-29T20:36:17.509Z" }, + { url = "https://files.pythonhosted.org/packages/64/c7/6ba0f7389f69cba861c1752fc072133a73f1f5891e2684c752424e7fdd41/coverage-7.18.0-cp315-cp315-win32.whl", hash = "sha256:e6437adddfdf5a9661b3f841fb37d548fa0a65c4d31c58b1f642d2b5d05bd62d", size = 232928, upload-time = "2026-11-29T20:36:18.986Z" }, + { url = "https://files.pythonhosted.org/packages/de/61/0ee7f022b55a8b80f9b08a19b4f0751d9de3feab352651e5d431950b8c4b/coverage-7.18.0-cp315-cp315-win_amd64.whl", hash = "sha256:487033703c29cdaa3618e1e8d2442317c0045b8c8d18be34acc6d60106ca9268", size = 233772, upload-time = "2026-11-29T20:36:20.197Z" }, + { url = "https://files.pythonhosted.org/packages/9d/d7/0ec37eeb4b4b08966cbcbe8e4a3a4caa2f79d3febceb88a0528bc35390f8/coverage-7.18.0-cp315-cp315-win_arm64.whl", hash = "sha256:38297b0de0c445856bfc11a704ff240198585aaa03d8c7bfa9f0a69433abbe88", size = 233614, upload-time = "2026-11-29T20:36:21.395Z" }, + { url = "https://files.pythonhosted.org/packages/2f/2a/b386ca7e5de966bdd82fec7f9e4190165c8227a3e580cb74dc81620d8224/coverage-7.18.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:1db58dff2e82d1a9ad588570e7c57867d618a2ebb688241fea98d67fb59224f8", size = 231543, upload-time = "2026-11-29T20:36:22.596Z" }, + { url = "https://files.pythonhosted.org/packages/49/c7/7da05d7d78c16cb8c2324167bc496d0eaaddd701a4ab120c608004180cb8/coverage-7.18.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:efeadfafa2b6387035dd3b7f091cc92eef42ad1be9e3736c3c50e2189ea3661d", size = 231816, upload-time = "2026-11-29T20:36:24.258Z" }, + { url = "https://files.pythonhosted.org/packages/7a/6d/c236368399cbd40eb0f9bb00a81367c7c145b91cdaed4c51464b0bf3fa38/coverage-7.18.0-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3346e60d6230829db2e6b2a8c199d6aa6efd864a095d3717a740dc0f6a6fd6b1", size = 272158, upload-time = "2026-11-29T20:36:25.483Z" }, + { url = "https://files.pythonhosted.org/packages/ec/2c/e5dfc31828ab46814a537bf22a9735adbeb1f789ce33e6c483d2be983465/coverage-7.18.0-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2f35c2418de025bad5c2a1fdc9481198115bd10582e82f9ce2115e99291fb5a2", size = 275040, upload-time = "2026-11-29T20:36:26.65Z" }, + { url = "https://files.pythonhosted.org/packages/d0/55/d1b346d03b13cb9259dea07a6c649da2f44de307eb250c8c65281ef96105/coverage-7.18.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c584b32f9e7cffd87ce0939e1637f36a3bf0a30e3c8c52f665efdf1c0b34b1e", size = 277695, upload-time = "2026-11-29T20:36:28.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/69/93c1b744b039f5098d688adff376705e0a0f4a6ea21e6aa286145495d960/coverage-7.18.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:19aa1b39a7d428bc8cab0e5bb5a92bd6c016b924b56c9a85b01c8c2f45324db3", size = 278834, upload-time = "2026-11-29T20:36:29.433Z" }, + { url = "https://files.pythonhosted.org/packages/dc/6f/4e6ee5ccecd638878ad4f440519227ea1c3e856b8c05d65b4c015b09ba64/coverage-7.18.0-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a29b2a1141aa6a6c6bb373014d93680776afa718bcfb60247e5b36b4d4e5fb2e", size = 272773, upload-time = "2026-11-29T20:36:30.668Z" }, + { url = "https://files.pythonhosted.org/packages/b5/c7/93b42c4f8715a71f61130d0cc4839b91b64c3c7508b9b79bba71b7e2258e/coverage-7.18.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:2bb2c054130632f2688f8543d1e5d441735e59503bfde2b4161b368583f7702a", size = 275163, upload-time = "2026-11-29T20:36:32.242Z" }, + { url = "https://files.pythonhosted.org/packages/bc/b2/8cc3883ad1057951e9b9517fd245e9f4ca1f12167f4c9ffc5b2285c870ea/coverage-7.18.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:26996b004aa04573ed8c2db6e440860de319a9f6253498fbc5cc960fb6153853", size = 272104, upload-time = "2026-11-29T20:36:33.448Z" }, + { url = "https://files.pythonhosted.org/packages/7d/a8/9f174608a942e77b06ed26be74f5d341089fa36c435ddf3d5fd03b83680d/coverage-7.18.0-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:2fbaabe5efa61a5d44145d7b37764e9f073723d0645a374826458d1f795b3661", size = 276677, upload-time = "2026-11-29T20:36:34.959Z" }, + { url = "https://files.pythonhosted.org/packages/94/46/efe228fd75d74ef23399e68123c6e7062dae8376528d5da6aa7ad5ff9233/coverage-7.18.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:f3ceab01a6d5626aa305eb0c8237b62d6a6e42913105eb11edb57523c1f032c6", size = 272360, upload-time = "2026-11-29T20:36:36.371Z" }, + { url = "https://files.pythonhosted.org/packages/c5/fc/5e74c9fdf4d5b96639ae76dc5331054fbe30210c1924504611ff588fcde3/coverage-7.18.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:65e88bd482732ae640b324898afb82a28432859d2d1548fa2ebd2a8e6c0a4a30", size = 273964, upload-time = "2026-11-29T20:36:37.575Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a7/2215a6074f6a0ebeff3171dc69caffa0b0e26607d1ea0b3deecc747ae973/coverage-7.18.0-cp315-cp315t-win32.whl", hash = "sha256:97761b08a88c99365e7b8f4df487b1476c71c03f441a699009daeb42628ee5b2", size = 233256, upload-time = "2026-11-29T20:36:38.911Z" }, + { url = "https://files.pythonhosted.org/packages/f1/23/53c4a494ff5ee203ca6f0c4462ae48a16593fe0eae0dfdc21927e599fd94/coverage-7.18.0-cp315-cp315t-win_amd64.whl", hash = "sha256:b61fe81af35aad950288659937d23bcabe33800bb2a7da2b98d714bb24e244a9", size = 234304, upload-time = "2026-11-29T20:36:40.159Z" }, + { url = "https://files.pythonhosted.org/packages/2f/0a/6e1b1108e8f4a55f7d833a547d75a65a7c0a6facc4a0e4a396df18a65d3e/coverage-7.18.0-cp315-cp315t-win_arm64.whl", hash = "sha256:18f9e6d346c55eaff13c1ba0c1d0326dfc9db68d3311e8e34ce93ebb57e48d7c", size = 233991, upload-time = "2026-11-29T20:36:41.332Z" }, + { url = "https://files.pythonhosted.org/packages/17/f6/f3064179ce394e3013e95d0c04b9c479893b0ae59cba2a3da35e82618065/coverage-7.18.0-py3-none-any.whl", hash = "sha256:b4f867fe47373534b6caed43cbe3882a0f14766aa272e448a1cfc78595538185", size = 222287, upload-time = "2026-11-29T20:36:42.892Z" }, +] + [[package]] name = "cuda-bindings" version = "13.4.4" @@ -972,18 +1205,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/bb/03ad4489fe19a410fe0065bbfb5424d28455eac9115e9cee7a56b6b1ec37/decorator-5.3.2-py3-none-any.whl", hash = "sha256:d3fb2a434ac31e231d14175ecbda823d83f26b7e45270cd7cd4d0350264b79e2", size = 11830, upload-time = "2026-11-21T05:12:50.003Z" }, ] -[[package]] -name = "docutils" -version = "0.21.2" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -sdist = { url = "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", size = 2204444, upload-time = "2024-04-23T18:57:18.24Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", size = 587408, upload-time = "2024-04-23T18:57:14.835Z" }, -] - [[package]] name = "docutils" version = "0.22.4" @@ -992,12 +1213,6 @@ resolution-markers = [ "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/ae/b6/03bb70946330e88ffec97aefd3ea75ba575cb2e762061e0e62a213befee8/docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968", size = 2291750, upload-time = "2025-12-18T19:00:26.443Z" } wheels = [ @@ -1084,69 +1299,21 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", -] -sdist = { url = "https://files.pythonhosted.org/packages/b2/de/99f4266dc2b97503fe35af46d4bf54ea4d434bc322992103145c9de7da95/filelock-4.3.2.tar.gz", hash = "sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3", size = 744182, upload-time = "2026-11-27T22:58:32.45Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/4f/6429bb372197194e65bb33885cd112c7008c2b9cf7496285874aa274e506/filelock-4.3.2-py3-none-any.whl", hash = "sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b", size = 244905, upload-time = "2026-11-27T22:58:31.01Z" }, -] - -[[package]] -name = "flake8" -version = "7.4.1" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "mccabe" }, - { name = "pycodestyle" }, - { name = "pyflakes", version = "4.0.3", source = { registry = "https://pypi.org/simple" } }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c2/94/85870fc02dfe4ab0885c440e7e41f6a986b10e43eca6717e90f8ce1215cc/flake8-7.4.1.tar.gz", hash = "sha256:84ea5afcaf344487b0ea5baaebb8100f4cfaebc01f755998f75876664029f587", size = 47897, upload-time = "2026-09-23T12:21:59.283Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/d4/8e58a7221419bf8cb194f362ab26abf504c983135975e4c785fac0852886/flake8-7.4.1-py2.py3-none-any.whl", hash = "sha256:78480274a6d7289d9cb8eafeda241fac57d4ea687d26e32dfdca37b72cdeddad", size = 57449, upload-time = "2026-09-23T12:21:58.085Z" }, -] - -[[package]] -name = "flake8" -version = "7.5.0" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform == 'emscripten'", - "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] -dependencies = [ - { name = "mccabe" }, - { name = "pycodestyle" }, - { name = "pyflakes", version = "4.1.0", source = { registry = "https://pypi.org/simple" } }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9a/da/b0d00f8c4c676212284edd3cc3d371588ce0e36a349373c3a01e188b5639/flake8-7.5.0.tar.gz", hash = "sha256:0dab7566341aca0d80aa29b5812bdadf256caa6a63e6068e49ac2649918236a4", size = 47811, upload-time = "2026-10-28T20:17:22.128Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b2/de/99f4266dc2b97503fe35af46d4bf54ea4d434bc322992103145c9de7da95/filelock-4.3.2.tar.gz", hash = "sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3", size = 744182, upload-time = "2026-11-27T22:58:32.45Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5d/57/a3adc5f380f50ef3d01014cb9d3b8c17b25de9b89def20d559def4fc3c4e/flake8-7.5.0-py2.py3-none-any.whl", hash = "sha256:637ea1a443a78ed6ee461725cdf71ca93bc5cde0abf25436dbebdc3880b4e078", size = 57487, upload-time = "2026-10-28T20:17:21.061Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4f/6429bb372197194e65bb33885cd112c7008c2b9cf7496285874aa274e506/filelock-4.3.2-py3-none-any.whl", hash = "sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b", size = 244905, upload-time = "2026-11-27T22:58:31.01Z" }, ] [[package]] @@ -1234,16 +1401,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/06/7a/83dd380d74b56a57c3eafce90265035d8727469d05ca4d2942d14367a6c7/fonttools-4.69.1.tar.gz", hash = "sha256:d09a2ea8ed4c71ac52e789ba9313da3e26cee3f812400d7e8a8b3a38d0f98dfe", size = 3958958, upload-time = "2026-11-25T17:04:21.285Z" } @@ -1345,9 +1512,7 @@ dependencies = [ { name = "accessible-pygments" }, { name = "beautifulsoup4" }, { name = "pygments" }, - { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, - { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" }, { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, { name = "sphinx-basic-ng" }, ] @@ -1386,18 +1551,19 @@ dependencies = [ [package.dev-dependencies] dev = [ - { name = "black" }, - { name = "flake8", version = "7.4.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "flake8", version = "7.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "furo" }, { name = "interrogate" }, - { name = "isort" }, - { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "pytest-cov" }, + { name = "ruff" }, +] +docs = [ + { name = "furo", marker = "python_full_version >= '3.12'" }, { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, ] +[package.group-requires-python] +docs = ">=3.12" + [package.metadata] requires-dist = [ { name = "bottleneck" }, @@ -1416,12 +1582,13 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ - { name = "black" }, - { name = "flake8" }, - { name = "furo" }, - { name = "interrogate" }, - { name = "isort" }, - { name = "sphinx" }, + { name = "interrogate", specifier = ">=1.7.0,<2.0.0" }, + { name = "pytest-cov", specifier = ">=7.1.0,<8.0.0" }, + { name = "ruff", specifier = ">=0.15.20,<1.0.0" }, +] +docs = [ + { name = "furo", marker = "python_full_version >= '3.12'", specifier = "==2025.12.19" }, + { name = "sphinx", marker = "python_full_version >= '3.12'", specifier = ">=9.1.0,<10.0.0" }, ] [[package]] @@ -1543,16 +1710,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/c7/6f/139a4b35fa329a855d3a2af2f8e1351b133bca13a3fa2731bbd8a5273f95/hsluv-5.0.5.tar.gz", hash = "sha256:fe9891df52ff78ddc9fc9cdba0fd0de49a4378d41e30a3901a1d716ec0c14163", size = 541586, upload-time = "2026-10-21T23:50:05.347Z" } @@ -1594,16 +1761,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -1646,10 +1813,10 @@ version = "10.2.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -1721,16 +1888,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -1780,53 +1947,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c3/55/298e9b3b864a198234997e87a1471c1b17d7f3546ace6d18fb5cf1ce24b2/ipywidgets-8.1.9-py3-none-any.whl", hash = "sha256:f2b8cbcaae10252b809fbe4d7470db75c09b769a32cbf816d20e5ca6d3c5a79d", size = 140101, upload-time = "2026-08-18T08:54:22.339Z" }, ] -[[package]] -name = "isort" -version = "9.0.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mypy-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/da/cf/068066b8fdab91cd40bcd63e483137908710a3d25a4d3a01b538be45d9d6/isort-9.0.2.tar.gz", hash = "sha256:d2298980ce44350f11d9d24c8150eaef1883431ec203dddbb4e9b5c3ceb54c70", size = 685196, upload-time = "2026-09-28T19:21:58.07Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/16/02099475d03310b0a209ca4928bb0779fb273b97c8924a94a32c38cc1eeb/isort-9.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b3e81cae981a52f94d5b31a474e1cbb033ea9cc850bc4c922117c0534a1864dd", size = 1070114, upload-time = "2026-09-28T19:20:58.339Z" }, - { url = "https://files.pythonhosted.org/packages/f1/36/60423264e176965fc0002bbb0a0a8b4ac21d4ee32dfef9a490767d5a7eb4/isort-9.0.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cd67d39c3501d7227e8b229476da1d8679c03e0af97bd295876cf7070e5b709", size = 1625659, upload-time = "2026-09-28T19:21:00.076Z" }, - { url = "https://files.pythonhosted.org/packages/20/75/b008785e61ccd53f6964501ef26a65c17ccc1c5ed9676dec6ebd2662cdb1/isort-9.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:288a320e6d52ba2d3447345390c8a8400591e4033ffbe4ce6bc3e50e5b4818e1", size = 1611889, upload-time = "2026-09-28T19:21:01.732Z" }, - { url = "https://files.pythonhosted.org/packages/db/a1/da35cd0cf273d560c844f94e92f2b266e23b416edc8dd6b6db0934543863/isort-9.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:67b12d9504e5bc6359bb3bb4493f36cf1093d15477c61c349f52f7d04209fb5d", size = 872900, upload-time = "2026-09-28T19:21:03.597Z" }, - { url = "https://files.pythonhosted.org/packages/19/e2/73251e82fec4218d278c63be8de6d79de99dc04cd6219746d18502108079/isort-9.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4a54aed1bb731d7cf80ef5dfbae5b960f777cea70523b751ee6049bcb604371", size = 1057035, upload-time = "2026-09-28T19:21:05.383Z" }, - { url = "https://files.pythonhosted.org/packages/d1/04/dfa9686e44bb8e8a41ebbb77fae0b5bd7e3acbdd30c73c0dfef396ab54ca/isort-9.0.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b34a165cd4e25726930ed2eed8cf2fe46fb1a5ebacd9b28eaf566b343a6457ca", size = 1593851, upload-time = "2026-09-28T19:21:07.062Z" }, - { url = "https://files.pythonhosted.org/packages/99/af/347958db3d7705116f7cadb718a37fddb24b52cf854032585cfae340208a/isort-9.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5c929e8ec9d9fb83f034d5f50895503f40c624605f552b97ad090a37e62407ca", size = 1579176, upload-time = "2026-09-28T19:21:08.815Z" }, - { url = "https://files.pythonhosted.org/packages/d8/03/b323bf130ce480bd5ef9c90b874c03f1a10126b583b26b7be2b1dbebd5f3/isort-9.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:5f448510ef0a92fa626a975759d76bdbe3b721c3d615da6d1010cc451de5610d", size = 873698, upload-time = "2026-09-28T19:21:10.34Z" }, - { url = "https://files.pythonhosted.org/packages/41/c3/3cd3e0f66af21e1bf917f50b45d3389de3d9a25661f2e7f74e51c7fb37a8/isort-9.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a05dc63cb6ae2a8e62ec4184153f424b1650593e00a24e6138184c46193891e9", size = 1062138, upload-time = "2026-09-28T19:21:11.782Z" }, - { url = "https://files.pythonhosted.org/packages/ab/36/512c41f0d9f4c2a61d56d383db21d42a9b82b4f768827f7e852139d14123/isort-9.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:af8be0b5cac101202c8255360e5de832ebbb84b2e863dc0f65dbb1a3d63dd40a", size = 1680120, upload-time = "2026-09-28T19:21:13.474Z" }, - { url = "https://files.pythonhosted.org/packages/84/6f/44fa0de7eb71d576d08d0ad3a1d5d401d6cc0c4f908d76159c52b690e6de/isort-9.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3fe693c1e56781de387a6c206306e9e5e560cfeb4acdfd85f0c46122afd48792", size = 1669955, upload-time = "2026-09-28T19:21:15.095Z" }, - { url = "https://files.pythonhosted.org/packages/b1/cc/89e9a499612665321a1f05e3bb1f4ff6f99e170568cff5c0162bd5d82ae6/isort-9.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:f7a9efeb3689c7327a0d637eb4e12691e8d5ab1297caee997b144dc595ccb93f", size = 880360, upload-time = "2026-09-28T19:21:16.534Z" }, - { url = "https://files.pythonhosted.org/packages/99/44/b51a78a2aee3bc14b91d5f071aea2fe35d9acde5f65f0ac5cb77800616a3/isort-9.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f65ff614632ddc3306c40f619717b3b3ca69938ffee21d97110056d52472c79a", size = 1038192, upload-time = "2026-09-28T19:21:18.25Z" }, - { url = "https://files.pythonhosted.org/packages/28/54/0ac6f7cf254c29bde0832dc655b0327d84752c4511f9f56fbd0778251542/isort-9.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e5f11c7ccd5f079ac0431fe52c7b38ea5d9f4e31a1889746de81dac0e7b0a766", size = 1670286, upload-time = "2026-09-28T19:21:19.895Z" }, - { url = "https://files.pythonhosted.org/packages/65/0c/22a3f073415110f95a9fcfd9aaee72144545c66e5fd99a3ed15c8634e8f1/isort-9.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:810561edf6f1f5f3600f02aa709603a4360d5290c5fff2ae4b370090dd1a5445", size = 1660662, upload-time = "2026-09-28T19:21:21.599Z" }, - { url = "https://files.pythonhosted.org/packages/5f/da/c357996945d7fcd653281e2b53cf5f16ec7c540d86bac045581ecff5ed63/isort-9.0.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:e2636222848a48cadbd712280058b5da19fa147c501132e04a486a5bddcc9e28", size = 465149, upload-time = "2026-09-28T19:21:23.392Z" }, - { url = "https://files.pythonhosted.org/packages/99/fc/3f477cb8ac91b116773bd0682d072c0bcf2bcf5d77ee288c1e46a95b0c8a/isort-9.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:71870ac3b1afdf3c259b8404c05076d3ab874122fec6f78339f1c92d2c29b012", size = 884875, upload-time = "2026-09-28T19:21:25.403Z" }, - { url = "https://files.pythonhosted.org/packages/53/25/b0dae3025157f020d9010bc126120e703b50ed74ebfb5ca56be81e064d0c/isort-9.0.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bd8c4fb9829a5e7117d9f71f540ff1e8caafb471e574012057ce6dc35fda2d7b", size = 1039110, upload-time = "2026-09-28T19:21:27.024Z" }, - { url = "https://files.pythonhosted.org/packages/7e/da/f97a4905cf8212c31d584f0222ae8b1deed391e42db910e8e908eb89002e/isort-9.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6eb3e714d64de6eba78ee29051f7fc80613c74e90c6f54f84082f59c429c0a0b", size = 1674555, upload-time = "2026-09-28T19:21:28.645Z" }, - { url = "https://files.pythonhosted.org/packages/90/f4/df11f0de3a2796ef1a74071d1331158b67961770c8066850d60f362ba7cc/isort-9.0.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:bf3ef0a91974f29f406e25eef0e04781fd5c2254b8ab55e7655b20d8cd7c5514", size = 1666034, upload-time = "2026-09-28T19:21:30.35Z" }, - { url = "https://files.pythonhosted.org/packages/15/f0/0007f037135659de11f6ef29563b75c8080eeb51d67f37e82128d66613dc/isort-9.0.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:cd1e0e5e61497e95a4e5be269088e6a1013f530aeccf6ebd6134f403285ecd63", size = 464424, upload-time = "2026-09-28T19:21:31.98Z" }, - { url = "https://files.pythonhosted.org/packages/ae/5c/f64d0cc97abbdf6f7902b0e38171e5101842ba75ac22212fd6d254156bb3/isort-9.0.2-cp314-cp314-win_amd64.whl", hash = "sha256:11da67a30f5a88383c71db075488ca3d081f427f53368f90bb1d74e958a9b040", size = 903922, upload-time = "2026-09-28T19:21:33.412Z" }, - { url = "https://files.pythonhosted.org/packages/14/8a/c0bdd165c6cfcb7c87b3acdee5ebc03e10da5317482017084cdf92a2a076/isort-9.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f7c2fa33e1c9fbcf9fd639997e4550515c0b712b52ed70a059124a5247825480", size = 1106274, upload-time = "2026-09-28T19:21:35.13Z" }, - { url = "https://files.pythonhosted.org/packages/b9/ec/4ab29f699d58baa7c00840bc66328ce8f06be31cd36250aef8d4f71bd24e/isort-9.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:85e859fd72e50c27306d05185f9472ed97fae9e1cce91c0e891260d16f2ecece", size = 1887727, upload-time = "2026-09-28T19:21:37.015Z" }, - { url = "https://files.pythonhosted.org/packages/bc/ec/12f58041288e08c35dc9a719108482c2c599b157ce0913454d57d32c7b5c/isort-9.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2a960e4252ac5b00f78adc0f731529e122657ee642e650896b36e1ff83028023", size = 1905479, upload-time = "2026-09-28T19:21:38.789Z" }, - { url = "https://files.pythonhosted.org/packages/56/ea/69fd476d07e5dddea5b41d6b3adfad4d2f5d251362f2fb594f2cfd0f5308/isort-9.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:91b60ce3d96fcb0730d61fc5ab84ee5b56d676fbb92550f7ea333f58778f2f20", size = 928154, upload-time = "2026-09-28T19:21:40.745Z" }, - { url = "https://files.pythonhosted.org/packages/93/93/ed3f1894ec261381abbdc22a3216fa86ad8fb2ec5f5d1f414f1d56c94ffe/isort-9.0.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:aa810daf72ff5d8ade462b2190dad9c0e16d6d428a3f9aea210f14cca2487d58", size = 1038495, upload-time = "2026-09-28T19:21:42.41Z" }, - { url = "https://files.pythonhosted.org/packages/2c/fd/4a911a73beb68a746a2f827a842f71030c3118a056585400023e37b5c8ec/isort-9.0.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8dde4e2d9cfb35390437353f0861ec41378f91ff958d8cd3051fb95cae59315a", size = 1686028, upload-time = "2026-09-28T19:21:44.107Z" }, - { url = "https://files.pythonhosted.org/packages/7e/3e/6fb9ab0f5a89e174d45ae2809970fcb908f2b261e1b77993101e52a20869/isort-9.0.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:4315e23e701bb1fcdfd364da59da61d78c3332c554318b7eb635ea3924d24c5e", size = 1675313, upload-time = "2026-09-28T19:21:45.6Z" }, - { url = "https://files.pythonhosted.org/packages/74/a2/e73c430847408ae900bf0fb7627daa87e939c80c2f0713fb9a163ec48663/isort-9.0.2-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:1c134ef9d94943eae14bf31c634db1904dd875e6e7280a60baee10ca06132db6", size = 464361, upload-time = "2026-09-28T19:21:47.142Z" }, - { url = "https://files.pythonhosted.org/packages/08/29/236939344dc87499299f36469527fc01a516a51abcf0d82ba5b7644f5966/isort-9.0.2-cp315-cp315-win_amd64.whl", hash = "sha256:d4da51a99dfd00e5c51e507ed91ebad6aafd44dc65135c17e2ef37355cd9fa98", size = 904023, upload-time = "2026-09-28T19:21:48.583Z" }, - { url = "https://files.pythonhosted.org/packages/ff/ec/14dfd5e8e20a1500043d50053d899527c742dcebeaba2fb2633abfad2ec1/isort-9.0.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:16436aefeebe3aa2d5d7ae1ca895b2278f770fc4a41d95c22569a30f7413ec45", size = 1105456, upload-time = "2026-09-28T19:21:50.162Z" }, - { url = "https://files.pythonhosted.org/packages/5a/f7/c0e4d16a17f742b459397be8570af4edce4173e91d64ccf16c1ecd7826d8/isort-9.0.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a36f30b6b85d9726f79c7623d35f3e966d5d7d9d0a005af91ba19988fccd038b", size = 1874501, upload-time = "2026-09-28T19:21:51.786Z" }, - { url = "https://files.pythonhosted.org/packages/c3/98/226855cb96275e7df63167ed8fae3b65e0c94e38c9d63a6a80458da919b1/isort-9.0.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:d03c68e9d0a83b51ed381d04b0919f2d918fb66c1ca1766761157ff44149366f", size = 1890469, upload-time = "2026-09-28T19:21:53.42Z" }, - { url = "https://files.pythonhosted.org/packages/bb/e5/3a1c4748483a05533a065b49dcf64039a68162e84175e08d1d70db7e7413/isort-9.0.2-cp315-cp315t-win_amd64.whl", hash = "sha256:29669ea6c410528ffe3b632a41835757f08282257e4ddac892a5e6d01bd35201", size = 927256, upload-time = "2026-09-28T19:21:55.063Z" }, - { url = "https://files.pythonhosted.org/packages/8b/c9/0849e74b868ef10312eecfc24278710e97dd14bc49c1df629d7df142d318/isort-9.0.2-py3-none-any.whl", hash = "sha256:6c29deeb39698a8717823b7f75b2ac58c5e8ab8dcf6cf31205a72a6617fb454e", size = 105052, upload-time = "2026-09-28T19:21:56.512Z" }, -] - [[package]] name = "jedi" version = "0.20.1" @@ -2278,16 +2398,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -2384,15 +2504,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a8/c0/2dfab7b319dabe23f5a7b515a797c74b501d15c72e7a03837cf0cf779b9e/matplotlib_scalebar-0.9.0-py3-none-any.whl", hash = "sha256:5140525cd4e0c60bcade541b86571dabaf446fa69192530bd82d60b54601aa79", size = 16411, upload-time = "2025-01-17T22:10:57.319Z" }, ] -[[package]] -name = "mccabe" -version = "0.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e7/ff/0ffefdcac38932a54d2b5eed4e0ba8a408f215002cd178ad1df0f2806ff8/mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325", size = 9658, upload-time = "2022-01-24T01:14:51.113Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/27/1a/1f68f9ba0c207934b35b86a8ca3aad8395a3d6dd7921c0686e23853ff5a9/mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e", size = 7350, upload-time = "2022-01-24T01:14:49.62Z" }, -] - [[package]] name = "mpmath" version = "1.3.0" @@ -2491,15 +2602,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/d2/87bb8406c3d172af5ecd21fdce3eed558be3f6cce6692fc7d938e90c396a/msgspec-0.23.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8cb516c68f9b91fbe5c08de75394ec4629fbc78ba2e7da84ed3130f876234ddd", size = 210112, upload-time = "2026-11-28T19:29:06.882Z" }, ] -[[package]] -name = "mypy-extensions" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d0/6f/43edf3be2748d0e40974a5ee046a8bb4c9961a4bdd3e7d5c6dcbf32d1af6/mypy_extensions-1.2.0.tar.gz", hash = "sha256:c6e275a07f1c2fc096b62940452d0eaa3f3af7de45d704787866240a7c6d5a51", size = 6566, upload-time = "2026-11-03T16:26:33.692Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/99/7b1adac7e97ce7bbda34792dc6e9b2f5cc5cffd1875883f78a818b2a2687/mypy_extensions-1.2.0-py3-none-any.whl", hash = "sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768", size = 5114, upload-time = "2026-11-03T16:26:32.731Z" }, -] - [[package]] name = "networkx" version = "3.4.2" @@ -2518,10 +2620,10 @@ version = "3.6.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } @@ -2538,10 +2640,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" } @@ -2585,10 +2687,10 @@ version = "0.16.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -2628,10 +2730,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -2733,10 +2835,10 @@ version = "2.4.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } @@ -2823,10 +2925,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/4e/3a/8770c288c47f0b5c2a786d3c20e79f66fd245f2d42cd232d7cd5e00e83e5/numpy-2.5.5.tar.gz", hash = "sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf", size = 20873892, upload-time = "2026-11-15T21:32:28.607Z" } @@ -3392,16 +3494,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -3493,15 +3595,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/e7/40fb618334dcdf7c5a316c0e7343c5cd82d3d866edc100d98e29bc945ecd/partd-1.4.2-py3-none-any.whl", hash = "sha256:978e4ac767ec4ba5b86c6eaa52e5a2a3bc748a2ca839e8cc798f1cc6ce6efb0f", size = 18905, upload-time = "2024-05-06T19:51:39.271Z" }, ] -[[package]] -name = "pathspec" -version = "1.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, -] - [[package]] name = "pexpect" version = "4.9.0" @@ -3620,16 +3713,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } @@ -3718,44 +3811,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, ] -[[package]] -name = "platformdirs" -version = "4.12.4" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -sdist = { url = "https://files.pythonhosted.org/packages/90/a1/d5f9002a70298c64a789779077d8dd90c10aa1f47fe40c86802df874f2a6/platformdirs-4.12.4.tar.gz", hash = "sha256:63743c02414e755de4e31b8f68125c1407495b86c5a006e203c01ff8b9924250", size = 60010, upload-time = "2026-10-07T23:30:32.426Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/ba/223e00b885e960edd5d4b4d178c88acce019bd5b83786093681b8c393492/platformdirs-4.12.4-py3-none-any.whl", hash = "sha256:78bfb9db2a8471ed7eebe3c3c932da413911042994e699b384fbb4493fa872d7", size = 32596, upload-time = "2026-10-07T23:30:30.825Z" }, -] - -[[package]] -name = "platformdirs" -version = "4.14.9" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", - "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", -] -sdist = { url = "https://files.pythonhosted.org/packages/d6/96/549558270586699a271a18b1111482dc3fc39baa0ef61d183e230d2c961d/platformdirs-4.14.9.tar.gz", hash = "sha256:c6b188e03ffd4dfe1bf8c4bcb47cd94711af244a9852dbff60297bd753684d5d", size = 87729, upload-time = "2026-11-27T20:53:44.721Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/e7/fc53dfd2f9469cce9be9c58385bdcdb5087e790c135c9dadd4cc8401bb3d/platformdirs-4.14.9-py3-none-any.whl", hash = "sha256:d0d3a23e7ff282cfa94b77f5a22b81030dcb68ba0430f90c74f4bd8d090782ea", size = 94272, upload-time = "2026-11-27T20:53:43.511Z" }, -] - [[package]] name = "pluggy" version = "1.7.0" @@ -3832,53 +3887,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f6/f0/10642828a8dfb741e5f3fbaac830550a518a775c7fff6f04a007259b0548/py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378", size = 98708, upload-time = "2021-11-04T17:17:00.152Z" }, ] -[[package]] -name = "pycodestyle" -version = "2.15.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/86/df/178e41c9ed0ff33c23b3f3757e4e658c889f9abc5ad76ece6cd607b12e9c/pycodestyle-2.15.0.tar.gz", hash = "sha256:318f5db083869b4c4dad922d0b11124fb27ab181b6730b93371da671e31bd50e", size = 39765, upload-time = "2026-09-22T22:15:34.926Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/56/e2/480bcdb153feecde4d736b18c908c7eee4846f11d7547d2e0c71499af630/pycodestyle-2.15.0-py2.py3-none-any.whl", hash = "sha256:12fd2f73c7b8ee8845a0431111df8faf4c1a07d6e64e2ee7f0c74014dab14181", size = 31583, upload-time = "2026-09-22T22:15:34.007Z" }, -] - -[[package]] -name = "pyflakes" -version = "4.0.3" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -sdist = { url = "https://files.pythonhosted.org/packages/2c/1b/3ba8bd62723cfe1b651c4e4b89b33767fce7a08bb800491cf1d3dd3a7716/pyflakes-4.0.3.tar.gz", hash = "sha256:94762a3a5a343a79b28754f96c554bce057a592a4896907d73f0369fe824e053", size = 67126, upload-time = "2026-10-07T18:57:25.327Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/44/b0/554d720d71083ccd24ba2f376c048544c073570e7bb18b34d769cef77f66/pyflakes-4.0.3-py2.py3-none-any.whl", hash = "sha256:330ba92b8c1db2eb0b8f4068f6c58674e2649a99e334769aa50e3e9c5b11c23a", size = 66250, upload-time = "2026-10-07T18:57:24.403Z" }, -] - -[[package]] -name = "pyflakes" -version = "4.1.0" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", - "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", -] -sdist = { url = "https://files.pythonhosted.org/packages/9b/43/f4566b992ab97abd18426aeba516a83c7a833230614a2c3f4d3e9d8ff0f0/pyflakes-4.1.0.tar.gz", hash = "sha256:592beb57058eb82eb190fb7514f2081c555c51000b029ff71286a681e6cf2f83", size = 67243, upload-time = "2026-10-28T20:10:02.469Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/52/98c9a0e4718abe887121279457bc7140115df22d714b7183880eb61e359f/pyflakes-4.1.0-py2.py3-none-any.whl", hash = "sha256:b2e05e6bac8e49b67be2a6ffa63422c60f7193fc72e8180255907b41ec997dc1", size = 66258, upload-time = "2026-10-28T20:10:01.109Z" }, -] - [[package]] name = "pygments" version = "2.21.0" @@ -4067,6 +4075,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, ] +[[package]] +name = "pytest-cov" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "coverage", version = "7.16.2", source = { registry = "https://pypi.org/simple" }, extra = ["toml"], marker = "python_full_version < '3.11'" }, + { name = "coverage", version = "7.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "pluggy" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, +] + [[package]] name = "python-dateutil" version = "3.0.0" @@ -4092,16 +4115,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -4112,45 +4135,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, ] -[[package]] -name = "pytokens" -version = "0.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b6/34/b4e015b99031667a7b960f888889c5bd34ef585c85e1cb56a594b92836ac/pytokens-0.4.1.tar.gz", hash = "sha256:292052fe80923aae2260c073f822ceba21f3872ced9a68bb7953b348e561179a", size = 23015, upload-time = "2026-01-30T01:03:45.924Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/42/24/f206113e05cb8ef51b3850e7ef88f20da6f4bf932190ceb48bd3da103e10/pytokens-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2a44ed93ea23415c54f3face3b65ef2b844d96aeb3455b8a69b3df6beab6acc5", size = 161522, upload-time = "2026-01-30T01:02:50.393Z" }, - { url = "https://files.pythonhosted.org/packages/d4/e9/06a6bf1b90c2ed81a9c7d2544232fe5d2891d1cd480e8a1809ca354a8eb2/pytokens-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:add8bf86b71a5d9fb5b89f023a80b791e04fba57960aa790cc6125f7f1d39dfe", size = 246945, upload-time = "2026-01-30T01:02:52.399Z" }, - { url = "https://files.pythonhosted.org/packages/69/66/f6fb1007a4c3d8b682d5d65b7c1fb33257587a5f782647091e3408abe0b8/pytokens-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:670d286910b531c7b7e3c0b453fd8156f250adb140146d234a82219459b9640c", size = 259525, upload-time = "2026-01-30T01:02:53.737Z" }, - { url = "https://files.pythonhosted.org/packages/04/92/086f89b4d622a18418bac74ab5db7f68cf0c21cf7cc92de6c7b919d76c88/pytokens-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:4e691d7f5186bd2842c14813f79f8884bb03f5995f0575272009982c5ac6c0f7", size = 262693, upload-time = "2026-01-30T01:02:54.871Z" }, - { url = "https://files.pythonhosted.org/packages/b4/7b/8b31c347cf94a3f900bdde750b2e9131575a61fdb620d3d3c75832262137/pytokens-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:27b83ad28825978742beef057bfe406ad6ed524b2d28c252c5de7b4a6dd48fa2", size = 103567, upload-time = "2026-01-30T01:02:56.414Z" }, - { url = "https://files.pythonhosted.org/packages/3d/92/790ebe03f07b57e53b10884c329b9a1a308648fc083a6d4a39a10a28c8fc/pytokens-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d70e77c55ae8380c91c0c18dea05951482e263982911fc7410b1ffd1dadd3440", size = 160864, upload-time = "2026-01-30T01:02:57.882Z" }, - { url = "https://files.pythonhosted.org/packages/13/25/a4f555281d975bfdd1eba731450e2fe3a95870274da73fb12c40aeae7625/pytokens-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a58d057208cb9075c144950d789511220b07636dd2e4708d5645d24de666bdc", size = 248565, upload-time = "2026-01-30T01:02:59.912Z" }, - { url = "https://files.pythonhosted.org/packages/17/50/bc0394b4ad5b1601be22fa43652173d47e4c9efbf0044c62e9a59b747c56/pytokens-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b49750419d300e2b5a3813cf229d4e5a4c728dae470bcc89867a9ad6f25a722d", size = 260824, upload-time = "2026-01-30T01:03:01.471Z" }, - { url = "https://files.pythonhosted.org/packages/4e/54/3e04f9d92a4be4fc6c80016bc396b923d2a6933ae94b5f557c939c460ee0/pytokens-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d9907d61f15bf7261d7e775bd5d7ee4d2930e04424bab1972591918497623a16", size = 264075, upload-time = "2026-01-30T01:03:04.143Z" }, - { url = "https://files.pythonhosted.org/packages/d1/1b/44b0326cb5470a4375f37988aea5d61b5cc52407143303015ebee94abfd6/pytokens-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:ee44d0f85b803321710f9239f335aafe16553b39106384cef8e6de40cb4ef2f6", size = 103323, upload-time = "2026-01-30T01:03:05.412Z" }, - { url = "https://files.pythonhosted.org/packages/41/5d/e44573011401fb82e9d51e97f1290ceb377800fb4eed650b96f4753b499c/pytokens-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:140709331e846b728475786df8aeb27d24f48cbcf7bcd449f8de75cae7a45083", size = 160663, upload-time = "2026-01-30T01:03:06.473Z" }, - { url = "https://files.pythonhosted.org/packages/f0/e6/5bbc3019f8e6f21d09c41f8b8654536117e5e211a85d89212d59cbdab381/pytokens-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d6c4268598f762bc8e91f5dbf2ab2f61f7b95bdc07953b602db879b3c8c18e1", size = 255626, upload-time = "2026-01-30T01:03:08.177Z" }, - { url = "https://files.pythonhosted.org/packages/bf/3c/2d5297d82286f6f3d92770289fd439956b201c0a4fc7e72efb9b2293758e/pytokens-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:24afde1f53d95348b5a0eb19488661147285ca4dd7ed752bbc3e1c6242a304d1", size = 269779, upload-time = "2026-01-30T01:03:09.756Z" }, - { url = "https://files.pythonhosted.org/packages/20/01/7436e9ad693cebda0551203e0bf28f7669976c60ad07d6402098208476de/pytokens-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ad948d085ed6c16413eb5fec6b3e02fa00dc29a2534f088d3302c47eb59adf9", size = 268076, upload-time = "2026-01-30T01:03:10.957Z" }, - { url = "https://files.pythonhosted.org/packages/2e/df/533c82a3c752ba13ae7ef238b7f8cdd272cf1475f03c63ac6cf3fcfb00b6/pytokens-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:3f901fe783e06e48e8cbdc82d631fca8f118333798193e026a50ce1b3757ea68", size = 103552, upload-time = "2026-01-30T01:03:12.066Z" }, - { url = "https://files.pythonhosted.org/packages/cb/dc/08b1a080372afda3cceb4f3c0a7ba2bde9d6a5241f1edb02a22a019ee147/pytokens-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8bdb9d0ce90cbf99c525e75a2fa415144fd570a1ba987380190e8b786bc6ef9b", size = 160720, upload-time = "2026-01-30T01:03:13.843Z" }, - { url = "https://files.pythonhosted.org/packages/64/0c/41ea22205da480837a700e395507e6a24425151dfb7ead73343d6e2d7ffe/pytokens-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5502408cab1cb18e128570f8d598981c68a50d0cbd7c61312a90507cd3a1276f", size = 254204, upload-time = "2026-01-30T01:03:14.886Z" }, - { url = "https://files.pythonhosted.org/packages/e0/d2/afe5c7f8607018beb99971489dbb846508f1b8f351fcefc225fcf4b2adc0/pytokens-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29d1d8fb1030af4d231789959f21821ab6325e463f0503a61d204343c9b355d1", size = 268423, upload-time = "2026-01-30T01:03:15.936Z" }, - { url = "https://files.pythonhosted.org/packages/68/d4/00ffdbd370410c04e9591da9220a68dc1693ef7499173eb3e30d06e05ed1/pytokens-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:970b08dd6b86058b6dc07efe9e98414f5102974716232d10f32ff39701e841c4", size = 266859, upload-time = "2026-01-30T01:03:17.458Z" }, - { url = "https://files.pythonhosted.org/packages/a7/c9/c3161313b4ca0c601eeefabd3d3b576edaa9afdefd32da97210700e47652/pytokens-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:9bd7d7f544d362576be74f9d5901a22f317efc20046efe2034dced238cbbfe78", size = 103520, upload-time = "2026-01-30T01:03:18.652Z" }, - { url = "https://files.pythonhosted.org/packages/8f/a7/b470f672e6fc5fee0a01d9e75005a0e617e162381974213a945fcd274843/pytokens-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4a14d5f5fc78ce85e426aa159489e2d5961acf0e47575e08f35584009178e321", size = 160821, upload-time = "2026-01-30T01:03:19.684Z" }, - { url = "https://files.pythonhosted.org/packages/80/98/e83a36fe8d170c911f864bfded690d2542bfcfacb9c649d11a9e6eb9dc41/pytokens-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97f50fd18543be72da51dd505e2ed20d2228c74e0464e4262e4899797803d7fa", size = 254263, upload-time = "2026-01-30T01:03:20.834Z" }, - { url = "https://files.pythonhosted.org/packages/0f/95/70d7041273890f9f97a24234c00b746e8da86df462620194cef1d411ddeb/pytokens-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc74c035f9bfca0255c1af77ddd2d6ae8419012805453e4b0e7513e17904545d", size = 268071, upload-time = "2026-01-30T01:03:21.888Z" }, - { url = "https://files.pythonhosted.org/packages/da/79/76e6d09ae19c99404656d7db9c35dfd20f2086f3eb6ecb496b5b31163bad/pytokens-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f66a6bbe741bd431f6d741e617e0f39ec7257ca1f89089593479347cc4d13324", size = 271716, upload-time = "2026-01-30T01:03:23.633Z" }, - { url = "https://files.pythonhosted.org/packages/79/37/482e55fa1602e0a7ff012661d8c946bafdc05e480ea5a32f4f7e336d4aa9/pytokens-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:b35d7e5ad269804f6697727702da3c517bb8a5228afa450ab0fa787732055fc9", size = 104539, upload-time = "2026-01-30T01:03:24.788Z" }, - { url = "https://files.pythonhosted.org/packages/30/e8/20e7db907c23f3d63b0be3b8a4fd1927f6da2395f5bcc7f72242bb963dfe/pytokens-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8fcb9ba3709ff77e77f1c7022ff11d13553f3c30299a9fe246a166903e9091eb", size = 168474, upload-time = "2026-01-30T01:03:26.428Z" }, - { url = "https://files.pythonhosted.org/packages/d6/81/88a95ee9fafdd8f5f3452107748fd04c24930d500b9aba9738f3ade642cc/pytokens-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79fc6b8699564e1f9b521582c35435f1bd32dd06822322ec44afdeba666d8cb3", size = 290473, upload-time = "2026-01-30T01:03:27.415Z" }, - { url = "https://files.pythonhosted.org/packages/cf/35/3aa899645e29b6375b4aed9f8d21df219e7c958c4c186b465e42ee0a06bf/pytokens-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d31b97b3de0f61571a124a00ffe9a81fb9939146c122c11060725bd5aea79975", size = 303485, upload-time = "2026-01-30T01:03:28.558Z" }, - { url = "https://files.pythonhosted.org/packages/52/a0/07907b6ff512674d9b201859f7d212298c44933633c946703a20c25e9d81/pytokens-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:967cf6e3fd4adf7de8fc73cd3043754ae79c36475c1c11d514fc72cf5490094a", size = 306698, upload-time = "2026-01-30T01:03:29.653Z" }, - { url = "https://files.pythonhosted.org/packages/39/2a/cbbf9250020a4a8dd53ba83a46c097b69e5eb49dd14e708f496f548c6612/pytokens-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:584c80c24b078eec1e227079d56dc22ff755e0ba8654d8383b2c549107528918", size = 116287, upload-time = "2026-01-30T01:03:30.912Z" }, - { url = "https://files.pythonhosted.org/packages/c6/78/397db326746f0a342855b81216ae1f0a32965deccfd7c830a2dbc66d2483/pytokens-0.4.1-py3-none-any.whl", hash = "sha256:26cef14744a8385f35d0e095dc8b3a7583f6c953c2e3d269c7f82484bf5ad2de", size = 13729, upload-time = "2026-01-30T01:03:45.029Z" }, -] - [[package]] name = "pytz" version = "2026.6" @@ -4266,6 +4250,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/54/6f679c435d28e0a568d8e8a7c0a93a09010818634c3c3907fc98d8983770/roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7", size = 7676, upload-time = "2025-12-17T18:25:33.098Z" }, ] +[[package]] +name = "ruff" +version = "0.17.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/df/8e/6929d337aa5380aafc7355f3149f3ccfe55cba5fdd34a045697ebaceb5a0/ruff-0.17.6.tar.gz", hash = "sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c", size = 5374388, upload-time = "2026-11-19T15:56:27.106Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/5d/38ef6310c22cacb094e9ae0ff7964062e04ffeecb45ee296894c2b1acc54/ruff-0.17.6-py3-none-linux_armv6l.whl", hash = "sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b", size = 10174693, upload-time = "2026-11-19T15:55:52.414Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ed/fd35261049920a4888ef7c787a5c27089502077a4910f6ca8f1213157d6d/ruff-0.17.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c", size = 10221650, upload-time = "2026-11-19T15:55:54.962Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d4/c31391b36c729cd9fafa65b7a52a58850b99afb2b65da6be4263a53302f2/ruff-0.17.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5", size = 9580986, upload-time = "2026-11-19T15:55:57.391Z" }, + { url = "https://files.pythonhosted.org/packages/eb/11/f3032684dcb3a676d7924545153d76fb56f76753e038f2ea650b99c71bdf/ruff-0.17.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30", size = 10271368, upload-time = "2026-11-19T15:55:59.654Z" }, + { url = "https://files.pythonhosted.org/packages/08/30/c1e024eeb5bae99ae78c6b896ed108f64c9c845a03b56eaeff098e99b6e6/ruff-0.17.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb", size = 9981564, upload-time = "2026-11-19T15:56:01.807Z" }, + { url = "https://files.pythonhosted.org/packages/7d/a5/da3e0c2d4bf02b3ca6c1d7fa4bb04d0081e340b1dd03c4f83b1bec3e15c1/ruff-0.17.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf", size = 10641991, upload-time = "2026-11-19T15:56:03.981Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/6d7f981e86201c9db457cca99fd2c09b77574ebab37dff3e9239b218603c/ruff-0.17.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b", size = 11403484, upload-time = "2026-11-19T15:56:05.778Z" }, + { url = "https://files.pythonhosted.org/packages/c3/92/8182f07b94998541d5f8f38f53da465aa28062afce24ecc398f45bfc62f1/ruff-0.17.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173", size = 10892316, upload-time = "2026-11-19T15:56:08.016Z" }, + { url = "https://files.pythonhosted.org/packages/be/48/3df7d81249fd69ee6a49519b149fb5d11e13118fd7d0e8d65329a237087b/ruff-0.17.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4", size = 10645279, upload-time = "2026-11-19T15:56:09.785Z" }, + { url = "https://files.pythonhosted.org/packages/71/80/4d232281544345d7beb98d1d32c24dae804ed360780a6f7753738b81225e/ruff-0.17.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac", size = 10534501, upload-time = "2026-11-19T15:56:11.718Z" }, + { url = "https://files.pythonhosted.org/packages/98/0a/b477f075a4a94eb541bf1c759a3e72b2a3d6390af7a13a5be0887229f67c/ruff-0.17.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45", size = 10136036, upload-time = "2026-11-19T15:56:13.779Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d8/cf32fbfeb1fcda1470fb5c3bee50c69ee6bca257d487ec1eb17a0387edb4/ruff-0.17.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d", size = 9969640, upload-time = "2026-11-19T15:56:15.738Z" }, + { url = "https://files.pythonhosted.org/packages/a7/22/bb9f9752f7fcdfdc8b9c51576cc142bb377ade745290e35085173963c7be/ruff-0.17.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0", size = 10389427, upload-time = "2026-11-19T15:56:17.617Z" }, + { url = "https://files.pythonhosted.org/packages/81/c7/e09d220818ab146b736d62e0676dad215215d7de0884bbdad9fa075dc7d2/ruff-0.17.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582", size = 10760296, upload-time = "2026-11-19T15:56:19.463Z" }, + { url = "https://files.pythonhosted.org/packages/2e/09/28329441dfa2c463e2d377a69d4ebbe4d51665e9dbd49fb421f3bc80d775/ruff-0.17.6-py3-none-win32.whl", hash = "sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128", size = 9966266, upload-time = "2026-11-19T15:56:21.581Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9d/18ba9730addfc7554c70d6f171fb8dc2c08e774d9fb2b98e7946ef845c59/ruff-0.17.6-py3-none-win_amd64.whl", hash = "sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d", size = 10365847, upload-time = "2026-11-19T15:56:23.582Z" }, + { url = "https://files.pythonhosted.org/packages/70/8a/59c33e2a64a4f9672f7f842a0dc522915cfbbaffd13d37d0cec57d1c5c5d/ruff-0.17.6-py3-none-win_arm64.whl", hash = "sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0", size = 9926224, upload-time = "2026-11-19T15:56:25.269Z" }, +] + [[package]] name = "scikit-image" version = "0.25.2" @@ -4317,16 +4326,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -4460,10 +4469,10 @@ version = "1.17.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -4542,10 +4551,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -4667,111 +4676,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c6/1b/9a7e232c5b4b9bfb260c9967c6439417cc7ce34e1b2fd5220ae54d4f63c1/snowballstemmer-3.2.1-py3-none-any.whl", hash = "sha256:694eb9753e14fb8ad77297fe440605711166191bdffe332027a36c58b5085d78", size = 115895, upload-time = "2026-12-02T04:32:14.627Z" }, ] -[[package]] -name = "soupsieve" -version = "2.10" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version < '3.11'", -] -sdist = { url = "https://files.pythonhosted.org/packages/71/c3/1b817965ac12dc002d7c9cd7dfffdd7d4fbf9b45763ef2ffe7b86ee94670/soupsieve-2.10.tar.gz", hash = "sha256:49e9380d7d2905463583bafe285e818c7366a9ed7b3aee221c1ac79c905d8bc0", size = 124337, upload-time = "2026-09-24T02:36:35.048Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/66/87/5ed59e1d0290564e2027ed066c52b059892c4637741337fc0967183c8d4d/soupsieve-2.10-py3-none-any.whl", hash = "sha256:8596eb8967d744174820280fa62b4542a2e955bfaccca73ed8a13c6eb8e9b502", size = 38019, upload-time = "2026-09-24T02:36:33.709Z" }, -] - [[package]] name = "soupsieve" version = "4.1.4" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", - "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", -] sdist = { url = "https://files.pythonhosted.org/packages/0c/68/ea74670eae744f7da505778c4e555dbd7b59bf4458342f56fded9fac09f0/soupsieve-4.1.4.tar.gz", hash = "sha256:9f12cb9fabef3bbde8eea07539412512960fe2320d67834b3c5be71d9aea522f", size = 189763, upload-time = "2026-12-01T16:02:51.365Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e6/50/3ff53ec2d16bac3a7b21def7c2773a32a5aebe45d01c6adf96b685cb6504/soupsieve-4.1.4-py3-none-any.whl", hash = "sha256:03bbb16915c1e13a4746fdc84a97e5999888aae3208516604d7bfc786aba0aef", size = 62119, upload-time = "2026-12-01T16:02:49.801Z" }, ] -[[package]] -name = "sphinx" -version = "8.1.3" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "alabaster" }, - { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "docutils", version = "0.21.2", source = { registry = "https://pypi.org/simple" } }, - { name = "imagesize" }, - { name = "jinja2" }, - { name = "packaging" }, - { name = "pygments" }, - { name = "requests" }, - { name = "snowballstemmer" }, - { name = "sphinxcontrib-applehelp" }, - { name = "sphinxcontrib-devhelp" }, - { name = "sphinxcontrib-htmlhelp" }, - { name = "sphinxcontrib-jsmath" }, - { name = "sphinxcontrib-qthelp" }, - { name = "sphinxcontrib-serializinghtml" }, - { name = "tomli" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/be0b61178fe2cdcb67e2a92fc9ebb488e3c51c4f74a36a7824c0adf23425/sphinx-8.1.3.tar.gz", hash = "sha256:43c1911eecb0d3e161ad78611bc905d1ad0e523e4ddc202a58a821773dc4c927", size = 8184611, upload-time = "2024-10-13T20:27:13.93Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/26/60/1ddff83a56d33aaf6f10ec8ce84b4c007d9368b21008876fceda7e7381ef/sphinx-8.1.3-py3-none-any.whl", hash = "sha256:09719015511837b76bf6e03e42eb7595ac8c2e41eeb9c29c5b755c6b677992a2", size = 3487125, upload-time = "2024-10-13T20:27:10.448Z" }, -] - -[[package]] -name = "sphinx" -version = "9.0.4" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", - "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", -] -dependencies = [ - { name = "alabaster" }, - { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" } }, - { name = "imagesize" }, - { name = "jinja2" }, - { name = "packaging" }, - { name = "pygments" }, - { name = "requests" }, - { name = "roman-numerals" }, - { name = "snowballstemmer" }, - { name = "sphinxcontrib-applehelp" }, - { name = "sphinxcontrib-devhelp" }, - { name = "sphinxcontrib-htmlhelp" }, - { name = "sphinxcontrib-jsmath" }, - { name = "sphinxcontrib-qthelp" }, - { name = "sphinxcontrib-serializinghtml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/42/50/a8c6ccc36d5eacdfd7913ddccd15a9cee03ecafc5ee2bc40e1f168d85022/sphinx-9.0.4.tar.gz", hash = "sha256:594ef59d042972abbc581d8baa577404abe4e6c3b04ef61bd7fc2acbd51f3fa3", size = 8710502, upload-time = "2025-12-04T07:45:27.343Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c6/3f/4bbd76424c393caead2e1eb89777f575dee5c8653e2d4b6afd7a564f5974/sphinx-9.0.4-py3-none-any.whl", hash = "sha256:5bebc595a5e943ea248b99c13814c1c5e10b3ece718976824ffa7959ff95fffb", size = 3917713, upload-time = "2025-12-04T07:45:24.944Z" }, -] - [[package]] name = "sphinx" version = "9.1.1" @@ -4846,9 +4759,7 @@ name = "sphinx-basic-ng" version = "1.0.0b2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, - { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" }, { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/0b/a866924ded68efec7a1759587a4e478aec7559d8165fac8b2ad1c0e774d6/sphinx_basic_ng-1.0.0b2.tar.gz", hash = "sha256:9ec55a47c90c8c002b5960c57492ec3021f5193cb26cebc2dc4ea226848651c9", size = 20736, upload-time = "2023-07-08T18:40:54.166Z" } @@ -4966,10 +4877,10 @@ version = "2026.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -4989,10 +4900,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -5143,16 +5054,16 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -5422,10 +5333,10 @@ version = "3.1.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten'", - "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform == 'emscripten'", "python_full_version >= '3.11' and python_full_version < '3.11.5' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ @@ -5450,10 +5361,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ From 0619ef863651dffa83c6d20d4b143c65194df3a1 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 10:14:57 -0800 Subject: [PATCH 07/14] ruff reformatting to 100 columns --- examples/extract_band.py | 21 +- src/giant_python/cli.py | 53 +--- src/giant_python/cli_silo.py | 57 +--- src/giant_python/cli_spine.py | 25 +- src/giant_python/export/f0_events.py | 91 +++--- src/giant_python/export/f0_injected.py | 84 ++---- src/giant_python/export/f0_layout.py | 68 ++--- src/giant_python/export/f0_mask.py | 13 +- src/giant_python/export/f0_qc.py | 8 +- src/giant_python/export/f0_training.py | 98 ++----- src/giant_python/extraction/band/activity.py | 32 +-- .../extraction/band/annotation.py | 12 +- .../extraction/band/background.py | 79 ++--- src/giant_python/extraction/band/geometry.py | 18 +- src/giant_python/extraction/band/inputs.py | 55 +--- .../extraction/band/localization.py | 72 ++--- .../extraction/band/motion_binning.py | 12 +- src/giant_python/extraction/band/operators.py | 53 +--- .../extraction/band/result_assembly.py | 66 ++--- src/giant_python/extraction/band/rois.py | 17 +- .../extraction/band/summary_images.py | 160 +++-------- src/giant_python/extraction/band/traces.py | 76 ++--- src/giant_python/extraction/band/transient.py | 59 +--- .../extraction/band/trial_data.py | 69 ++--- src/giant_python/extraction/band/workflow.py | 60 +--- .../extraction/raster/alignment.py | 137 +++------ .../extraction/raster/annotations.py | 19 +- .../extraction/raster/baseline_map.py | 40 +-- .../extraction/raster/container.py | 71 ++--- .../extraction/raster/kinetics.py | 14 +- .../extraction/raster/localization.py | 71 ++--- src/giant_python/extraction/raster/null.py | 40 +-- src/giant_python/extraction/raster/peaks.py | 198 +++++-------- src/giant_python/extraction/raster/plan.py | 100 ++----- .../extraction/raster/refit_test.py | 24 +- src/giant_python/extraction/raster/results.py | 16 +- src/giant_python/extraction/raster/seeding.py | 35 +-- src/giant_python/extraction/raster/solver.py | 96 ++----- .../extraction/raster/solver_baseline.py | 65 ++--- .../extraction/raster/solver_fits.py | 28 +- .../extraction/raster/solver_setup.py | 52 +--- src/giant_python/extraction/raster/spots.py | 78 ++--- .../extraction/raster/stage_files.py | 12 +- src/giant_python/extraction/raster/summary.py | 71 ++--- src/giant_python/extraction/raster/trial.py | 24 +- .../extraction/raster/trial_data.py | 86 ++---- src/giant_python/gui/parameters_gui.py | 24 +- src/giant_python/gui/roi_editor.py | 31 +- src/giant_python/io/annotations.py | 8 +- src/giant_python/io/experiment_summary.py | 127 +++------ src/giant_python/io/hdf5.py | 8 +- src/giant_python/io/slap2.py | 8 +- src/giant_python/io/slap2_raster.py | 19 +- src/giant_python/io/trial_table.py | 4 +- src/giant_python/models/experiment_summary.py | 9 +- src/giant_python/models/params.py | 93 ++---- src/giant_python/models/trial_table.py | 12 +- src/giant_python/numerics/baseline.py | 23 +- src/giant_python/numerics/interpolation.py | 4 +- src/giant_python/numerics/peaks.py | 134 +++------ src/giant_python/parallel.py | 4 +- src/giant_python/pipeline/annotate.py | 4 +- src/giant_python/pipeline/extract.py | 11 +- src/giant_python/pipeline/pipeline.py | 8 +- src/giant_python/pipeline/reg_stats.py | 34 +-- src/giant_python/pipeline/register.py | 51 ++-- src/giant_python/pipeline/silo.py | 269 ++++++------------ src/giant_python/pipeline/silo_baseline.py | 29 +- src/giant_python/pipeline/silo_collect.py | 22 +- src/giant_python/pipeline/silo_session.py | 39 +-- src/giant_python/pipeline/silo_solve.py | 52 ++-- src/giant_python/pipeline/silo_spots.py | 110 ++----- src/giant_python/pipeline/trial_table.py | 77 ++--- src/giant_python/registration/compensation.py | 12 +- src/giant_python/registration/frames.py | 48 +--- src/giant_python/registration/growth.py | 63 ++-- .../registration/interpolation.py | 12 +- src/giant_python/registration/matching.py | 32 +-- src/giant_python/registration/multiroi.py | 64 ++--- src/giant_python/registration/outputs.py | 12 +- src/giant_python/registration/sources.py | 25 +- .../registration/stats/__init__.py | 4 +- .../registration/stats/accumulate.py | 36 +-- src/giant_python/registration/stats/gain.py | 30 +- .../registration/stats/geometry.py | 102 +++---- src/giant_python/registration/stats/maps.py | 30 +- .../registration/stats/session.py | 21 +- src/giant_python/registration/stats/worker.py | 4 +- src/giant_python/registration/template.py | 12 +- src/giant_python/simulation/injection.py | 268 +++++------------ src/giant_python/simulation/render.py | 7 +- src/giant_python/spine/coverage.py | 8 +- src/giant_python/spine/gains.py | 26 +- src/giant_python/spine/images.py | 12 +- src/giant_python/spine/pipeline.py | 126 +++----- src/giant_python/spine/product.py | 33 +-- src/giant_python/spine/qc.py | 8 +- src/giant_python/spine/readout.py | 6 +- src/giant_python/spine/rois.py | 24 +- src/giant_python/spine/summary_io.py | 15 +- src/giant_python/spine/trends.py | 53 +--- src/giant_python/spine/view/data.py | 108 +++---- src/giant_python/spine/view/export.py | 52 +--- src/giant_python/spine/view/server.py | 18 +- src/giant_python/viewer/render.py | 26 +- src/giant_python/viewer/run.py | 16 +- src/giant_python/viewer/server.py | 97 +++---- src/giant_python/viewer/trial.py | 50 ++-- tests/export/test_f0_injected.py | 4 +- tests/export/test_f0_layout.py | 61 +--- tests/export/test_f0_training.py | 166 +++++------ tests/raster/alignment_synthetic.py | 21 +- tests/raster/data/make_matlab_kinetics_h5.py | 4 +- tests/raster/test_raster_alignment.py | 27 +- tests/raster/test_raster_alignment_modes.py | 36 +-- tests/raster/test_raster_annotations.py | 11 +- tests/raster/test_raster_baseline_map.py | 12 +- tests/raster/test_raster_container.py | 28 +- tests/raster/test_raster_f0_images.py | 32 +-- tests/raster/test_raster_kinetics.py | 32 +-- tests/raster/test_raster_localization.py | 17 +- tests/raster/test_raster_null.py | 78 ++--- tests/raster/test_raster_peaks.py | 54 ++-- tests/raster/test_raster_plan.py | 108 ++----- tests/raster/test_raster_refit.py | 4 +- tests/raster/test_raster_results.py | 24 +- tests/raster/test_raster_seed_acceptance.py | 83 ++---- tests/raster/test_raster_seeding.py | 28 +- tests/raster/test_raster_silo_alignment.py | 32 +-- tests/raster/test_raster_silo_load_ahead.py | 32 +-- tests/raster/test_raster_silo_network.py | 111 +++----- tests/raster/test_raster_silo_params.py | 44 +-- tests/raster/test_raster_silo_stages.py | 119 +++----- tests/raster/test_raster_solver.py | 32 +-- tests/raster/test_raster_solver_baseline.py | 37 +-- .../test_raster_solver_baseline_modes.py | 24 +- tests/raster/test_raster_solver_fits.py | 64 ++--- tests/raster/test_raster_solver_setup.py | 13 +- tests/raster/test_raster_spots.py | 16 +- tests/raster/test_raster_stage_files.py | 8 +- tests/raster/test_raster_summary.py | 20 +- tests/raster/test_raster_summary_model.py | 22 +- tests/raster/test_raster_trial.py | 20 +- tests/raster/test_raster_trial_data.py | 163 +++-------- tests/registration/synthetic.py | 17 +- tests/registration/test_cli.py | 8 +- tests/registration/test_compensation.py | 36 +-- tests/registration/test_curtain.py | 52 +--- tests/registration/test_growth.py | 48 +--- tests/registration/test_kernels.py | 28 +- tests/registration/test_reg_stats.py | 69 ++--- tests/registration/test_synthetic.py | 119 ++------ tests/simulation/test_injection.py | 245 +++++----------- tests/spine/synthetic.py | 35 +-- tests/spine/test_spine_coverage.py | 4 +- tests/spine/test_spine_gains.py | 28 +- tests/spine/test_spine_images.py | 22 +- tests/spine/test_spine_pipeline.py | 102 ++----- tests/spine/test_spine_qc.py | 12 +- tests/spine/test_spine_readout.py | 4 +- tests/spine/test_spine_trends.py | 46 +-- tests/spine/test_spine_view.py | 64 +---- tests/trial_table/test_build_slap2.py | 127 +++------ tests/viewer/synthetic.py | 20 +- tests/viewer/test_viewer_render.py | 30 +- tests/viewer/test_viewer_server.py | 31 +- 166 files changed, 2213 insertions(+), 5830 deletions(-) diff --git a/examples/extract_band.py b/examples/extract_band.py index ce7c8053..fee65427 100644 --- a/examples/extract_band.py +++ b/examples/extract_band.py @@ -136,12 +136,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; " @@ -203,11 +198,7 @@ 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) @@ -227,9 +218,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 +274,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) diff --git a/src/giant_python/cli.py b/src/giant_python/cli.py index 6e305060..f77f002e 100644 --- a/src/giant_python/cli.py +++ b/src/giant_python/cli.py @@ -172,8 +172,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", @@ -204,15 +203,13 @@ def _add_reg_stats_command(subparsers) -> 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", @@ -222,8 +219,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", @@ -248,9 +244,7 @@ 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: @@ -269,12 +263,8 @@ def build_parser() -> argparse.ArgumentParser: 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, @@ -287,16 +277,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) @@ -442,9 +428,7 @@ def _cmd_trial_table(args: argparse.Namespace) -> int: """Handle ``giant trial-table`` (buildTrialTableSLAP2).""" 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 @@ -500,10 +484,7 @@ 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 @@ -539,22 +520,16 @@ def _report_registration(fields: dict, present) -> int: 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)) - ) + 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." - ) + 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 diff --git a/src/giant_python/cli_silo.py b/src/giant_python/cli_silo.py index f706e505..6434c9ca 100644 --- a/src/giant_python/cli_silo.py +++ b/src/giant_python/cli_silo.py @@ -173,8 +173,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", @@ -193,9 +192,7 @@ def _add_science(parser: argparse.ArgumentParser) -> None: def _add_session(parser: argparse.ArgumentParser) -> None: """Add the trial table and folder overrides.""" - parser.add_argument( - "trial_table", help="trial_table.h5 (or the folder holding it)." - ) + 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", @@ -233,8 +230,7 @@ def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool) -> None: 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 @@ -247,8 +243,7 @@ def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool) -> None: 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", @@ -266,9 +261,7 @@ def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool) -> None: ) -def _add_execution( - parser: argparse.ArgumentParser, solver: bool, fits: bool = True -) -> None: +def _add_execution(parser: argparse.ArgumentParser, solver: bool, fits: bool = True) -> None: """Add parameters to run SiloExecution. ``fits``: the solver's device, precision and batches (a job file brings its own). @@ -345,8 +338,7 @@ def add_silo_commands(subparsers) -> None: """Add SILo and the staged commands for the GIAnT 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) @@ -375,18 +367,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) @@ -397,18 +385,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) _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) @@ -439,8 +423,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) @@ -469,9 +452,7 @@ def add_silo_commands(subparsers) -> None: def _add_units(parser: argparse.ArgumentParser) -> None: """Add the selection of trial-paths.""" - parser.add_argument( - "--paths", default=None, help="Paths, e.g. 1,2 (default: all)." - ) + parser.add_argument("--paths", default=None, help="Paths, e.g. 1,2 (default: all).") parser.add_argument( "--trials", default=None, @@ -502,9 +483,7 @@ def params_from_args(args: argparse.Namespace) -> SiloParams: """SiloParams from ``--params``, ``--set`` and the explicit options.""" 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}") @@ -566,11 +545,7 @@ def _session(args: argparse.Namespace): """ 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, @@ -604,9 +579,7 @@ def run_silo_command(args: argparse.Namespace) -> int: # noqa: C901 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 aac5661e..781f9e80 100644 --- a/src/giant_python/cli_spine.py +++ b/src/giant_python/cli_spine.py @@ -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", @@ -95,9 +90,7 @@ def _add_common(p: argparse.ArgumentParser) -> 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." - ) + 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", @@ -210,16 +203,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/f0_events.py b/src/giant_python/export/f0_events.py index 0f03005d..30d97d64 100644 --- a/src/giant_python/export/f0_events.py +++ b/src/giant_python/export/f0_events.py @@ -104,12 +104,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: @@ -129,9 +124,7 @@ def synchrony(trials: list, window: int): } -def path_statistics( - run, d: int, sync_frames: int = 2, k: float = EVENT_K -) -> dict: +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. The run is a :class:`~giant_python.viewer.run.SiloRun`; events cross ``k`` @@ -161,14 +154,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) @@ -196,54 +183,44 @@ 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): + """Events per observed minute (None without observed time).""" + 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 d083af0a..470bd5d5 100644 --- a/src/giant_python/export/f0_injected.py +++ b/src/giant_python/export/f0_injected.py @@ -71,12 +71,9 @@ def _injection_settings(truth: dict): """Build the truth's :class:`~giant_python.simulation.injection.InjectionSettings`.""" 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): @@ -172,9 +169,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 @@ -182,9 +177,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: @@ -204,18 +197,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 @@ -223,13 +210,9 @@ 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] @@ -266,9 +249,9 @@ def peak_positions(truth_path: dict, pos) -> np.ndarray: from the source (zero for Gaussians; image footprints may peak off centre). """ 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 @@ -314,9 +297,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 @@ -324,9 +305,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] @@ -336,9 +315,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) @@ -366,9 +343,7 @@ 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 @@ -379,10 +354,7 @@ def _reconcile(out_dir: Path, d: int, present, summary, label, log) -> None: 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 - ] + 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 @@ -528,9 +500,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( @@ -572,18 +542,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, diff --git a/src/giant_python/export/f0_layout.py b/src/giant_python/export/f0_layout.py index 6f894a48..26b880ef 100644 --- a/src/giant_python/export/f0_layout.py +++ b/src/giant_python/export/f0_layout.py @@ -358,21 +358,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 @@ -384,22 +377,14 @@ 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 @@ -599,10 +584,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 @@ -660,9 +642,7 @@ def _second_visits(nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray): return [c[whole] for c in chain], None -def level_statistics( - samples, nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray -) -> dict: +def level_statistics(samples, 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. Both are taken by local brightness. With events that add up, both are @@ -756,9 +736,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 @@ -809,9 +787,7 @@ def trial_layout( 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 @@ -823,9 +799,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) @@ -839,9 +813,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)) @@ -969,12 +941,10 @@ def read_layout(path: Union[str, Path]) -> dict: 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) -> None: @@ -1066,9 +1036,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) @@ -1214,8 +1182,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None: 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", @@ -1225,8 +1192,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", diff --git a/src/giant_python/export/f0_mask.py b/src/giant_python/export/f0_mask.py index d1dfd8c2..72d22481 100644 --- a/src/giant_python/export/f0_mask.py +++ b/src/giant_python/export/f0_mask.py @@ -70,10 +70,7 @@ def check(self) -> None: 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}") @@ -120,9 +117,7 @@ def nearest_frames(ds_lines, lines200) -> np.ndarray: return np.where(left, i - 1, i).astype(np.int64) -def temporal_mask( - den, sigma, lines200, discard200, ds_lines, rule: MaskRule, tau200 -) -> np.ndarray: +def temporal_mask(den, sigma, lines200, discard200, ds_lines, rule: MaskRule, tau200) -> np.ndarray: """Mask each source's 80 Hz frames, ``(sources, frames80)`` bool. Parameters @@ -226,9 +221,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 031b639c..f301cf48 100644 --- a/src/giant_python/export/f0_qc.py +++ b/src/giant_python/export/f0_qc.py @@ -332,9 +332,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 @@ -342,9 +340,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 4a250bad..5484a675 100644 --- a/src/giant_python/export/f0_training.py +++ b/src/giant_python/export/f0_training.py @@ -194,8 +194,7 @@ def _settings(run: SiloRun) -> dict: "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)), } @@ -214,9 +213,7 @@ 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): @@ -359,10 +356,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, @@ -436,9 +430,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 = { @@ -541,13 +533,9 @@ def _write(job: TrialJob, arrays: dict, attrs: dict) -> 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:] - ) + 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:] - ) + 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 @@ -672,26 +660,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) 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 @@ -776,10 +756,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: @@ -902,18 +879,14 @@ def _selection(options, run, session) -> tuple: 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 @@ -954,11 +927,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 = [] @@ -1014,9 +983,7 @@ def _mask_inputs(run, p, st, x) -> dict: 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"] @@ -1106,9 +1073,7 @@ def export_run( _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 @@ -1162,11 +1127,7 @@ def write_event_statistics(out_dir, run, paths, label, options) -> dict: "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") @@ -1207,10 +1168,7 @@ def _check_channels(channels, num_channels: int) -> None: """Refuse channels outside the movie's one-based ``1..numChannels``.""" 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): @@ -1242,9 +1200,7 @@ def find_table(run_dir: Path) -> Path: 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 @@ -1296,16 +1252,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", @@ -1313,9 +1267,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="", @@ -1376,8 +1328,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", @@ -1390,8 +1341,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", diff --git a/src/giant_python/extraction/band/activity.py b/src/giant_python/extraction/band/activity.py index 3422843d..c1ffea36 100644 --- a/src/giant_python/extraction/band/activity.py +++ b/src/giant_python/extraction/band/activity.py @@ -28,9 +28,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 @@ -54,9 +52,7 @@ def _valid_sel_cols_for_motion( this bin's motion shift. """ 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 +66,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) @@ -133,14 +127,10 @@ def compute_rho( 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 +188,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 @@ -278,9 +266,7 @@ 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: +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 @@ -321,9 +307,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..9c15b38e 100644 --- a/src/giant_python/extraction/band/annotation.py +++ b/src/giant_python/extraction/band/annotation.py @@ -75,9 +75,7 @@ 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 @@ -103,9 +101,7 @@ def resolve_user_rois( ) -> dict: """Load usable annotations, or draw interactively or fail promptly.""" 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,9 +117,7 @@ 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( diff --git a/src/giant_python/extraction/band/background.py b/src/giant_python/extraction/band/background.py index bf45d3bd..7455bc57 100644 --- a/src/giant_python/extraction/band/background.py +++ b/src/giant_python/extraction/band/background.py @@ -14,9 +14,7 @@ bn = None -def _collect_interp_columns( - cols, s_c, s_r, sel_idxs_by_col_all, sel_rows, r0, r1 -): +def _collect_interp_columns(cols, s_c, s_r, sel_idxs_by_col_all, sel_rows, r0, r1): """Group a motion bin's reference pixels by column for interpolation. Columns with a single reference pixel become ``single_points`` (copied @@ -69,10 +67,7 @@ def _interp_columns( # noqa: C901 missing source values. """ 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 +81,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 +107,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 +117,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 +125,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 +137,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): @@ -222,10 +204,7 @@ def build_interp_data( 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 +216,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 @@ -298,9 +274,7 @@ def baseline_window_frames(align_hz: float, baseline_window_s: float) -> int: 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, @@ -353,7 +327,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() @@ -418,17 +393,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 @@ -465,18 +436,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 diff --git a/src/giant_python/extraction/band/geometry.py b/src/giant_python/extraction/band/geometry.py index dd14cc4b..b95c68f5 100644 --- a/src/giant_python/extraction/band/geometry.py +++ b/src/giant_python/extraction/band/geometry.py @@ -34,9 +34,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 @@ -152,9 +150,7 @@ def build_selected_pixel_mask( 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, @@ -225,10 +221,8 @@ def selected_pixels_2d_for_plane( 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..ec78f53c 100644 --- a/src/giant_python/extraction/band/inputs.py +++ b/src/giant_python/extraction/band/inputs.py @@ -50,19 +50,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, @@ -72,20 +64,13 @@ 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}") - ) + 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]: +def find_reference_file(datadr: Union[str, Path], dmd_ix: int) -> Optional[str]: """Find the REFERENCE tif for a DMD under ``datadr`` (recursive glob). Parameters @@ -173,12 +158,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) @@ -203,10 +183,7 @@ def load_psf(dilation: int, n_dmds: int) -> dict: """ 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: @@ -232,11 +209,7 @@ def _resolve_fn_adata(fn_adata: np.ndarray, moco_save_dr: str) -> np.ndarray: 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 @@ -262,16 +235,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, diff --git a/src/giant_python/extraction/band/localization.py b/src/giant_python/extraction/band/localization.py index 66087175..d9f945a3 100644 --- a/src/giant_python/extraction/band/localization.py +++ b/src/giant_python/extraction/band/localization.py @@ -187,9 +187,7 @@ 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 @@ -218,8 +216,7 @@ def build_x_support_mots( 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) ] @@ -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 @@ -270,9 +265,7 @@ def _motion_frames(mot_inds_yx: np.ndarray, i: int) -> np.ndarray: 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 @@ -311,9 +304,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 ) @@ -507,13 +498,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 +552,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,9 +561,7 @@ def fit_gaussian_profiles( ) -def variance_sortorder( - phi_low_res: torch.Tensor, n_sources: int -) -> np.ndarray: +def variance_sortorder(phi_low_res: torch.Tensor, n_sources: int) -> np.ndarray: """Return the descending-explained-variance source ordering.""" phi = phi_low_res[:, :n_sources].numpy() variance = np.nansum((phi - np.nanmean(phi, axis=0)) ** 2, axis=0) @@ -669,9 +653,7 @@ def compute_source_snr( 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) @@ -781,23 +763,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 +781,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 +795,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..1495510d 100644 --- a/src/giant_python/extraction/band/motion_binning.py +++ b/src/giant_python/extraction/band/motion_binning.py @@ -69,9 +69,7 @@ def select_motion_bins( """ 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 @@ -100,11 +98,7 @@ def bin_motion_yx( 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..0bbd8074 100644 --- a/src/giant_python/extraction/band/operators.py +++ b/src/giant_python/extraction/band/operators.py @@ -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,9 +63,7 @@ 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 @@ -115,9 +103,7 @@ 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, @@ -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]] @@ -234,9 +217,7 @@ def build_motion_h_matrices( 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): @@ -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..8b6d9e95 100644 --- a/src/giant_python/extraction/band/result_assembly.py +++ b/src/giant_python/extraction/band/result_assembly.py @@ -55,9 +55,7 @@ class PathResult: 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 - ) + out = np.full((arr.shape[1], num_channels, arr.shape[0]), np.nan, dtype=arr.dtype) out[:, 0, :] = arr.T return out @@ -84,15 +82,10 @@ def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary: 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 +97,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 +123,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 +149,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 91fcf72e..0f98be1f 100644 --- a/src/giant_python/extraction/band/rois.py +++ b/src/giant_python/extraction/band/rois.py @@ -10,10 +10,7 @@ def user_roi_superpixel_lists_from_masks( 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 [np.flatnonzero(np.asarray(mask)[sp_fastz, sp_rows, sp_cols]) for mask in roi_masks] def compute_user_roi_geometry( @@ -99,9 +96,7 @@ 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: +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.""" key = f"DMD{dmd_ix + 1}" path_key = f"Path{dmd_ix + 1}" @@ -126,16 +121,12 @@ 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: +def resolve_annotation_records(raw: dict, n_dmds: int, user_roi_geo: dict) -> tuple: """Return selection status, masks, superpixels, labels, and ROI records.""" out = { "user_roi_masks": {}, diff --git a/src/giant_python/extraction/band/summary_images.py b/src/giant_python/extraction/band/summary_images.py index 610b45fe..39db15b9 100644 --- a/src/giant_python/extraction/band/summary_images.py +++ b/src/giant_python/extraction/band/summary_images.py @@ -87,9 +87,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( @@ -169,9 +167,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 +180,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 +194,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 +227,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 @@ -309,9 +297,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 +313,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_], @@ -400,15 +382,9 @@ def phase_matched_nanmedian( # noqa: C901 """ 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 +410,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,16 +429,12 @@ 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:]): positions = order[start:stop] @@ -485,8 +447,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, ) @@ -509,35 +470,21 @@ def windows(output_positions): 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 +503,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 @@ -599,18 +544,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 +557,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 +585,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 ac673966..51bea8b5 100644 --- a/src/giant_python/extraction/band/traces.py +++ b/src/giant_python/extraction/band/traces.py @@ -40,9 +40,7 @@ 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 @@ -79,9 +77,7 @@ def _empty_trace_result( ) -def _interp_trial_alignment( - frames: np.ndarray, a_data: dict, background_ds: np.ndarray -): +def _interp_trial_alignment(frames: np.ndarray, a_data: dict, background_ds: np.ndarray): """Interpolate alignment motion/background onto the trial's frame grid. Motion and per-superpixel background are linearly interpolated from the @@ -108,12 +104,9 @@ def _interp_trial_alignment( 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"]) @@ -179,9 +172,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,9 +192,7 @@ 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 @@ -229,20 +218,13 @@ def _backproject(x: torch.Tensor, data: torch.Tensor) -> torch.Tensor: return (data.T @ x) / norm.masked_fill(norm <= 0, 1.0) -def _validate_transient_settings( - transient_options, simple_trace_extraction, analyze_hz -) -> None: +def _validate_transient_settings(transient_options, simple_trace_extraction, analyze_hz) -> None: """Validate mutually exclusive trace modes and the transient grid rate.""" 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) @@ -322,18 +304,14 @@ def _solve_trial_phi_f0( least-squares fit. The optional residual term is the backprojection of ``data - background - x @ phi`` (zero for simple extraction). """ - _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 +325,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: @@ -464,15 +434,11 @@ 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 @@ -569,9 +535,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 +594,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(), diff --git a/src/giant_python/extraction/band/transient.py b/src/giant_python/extraction/band/transient.py index e8125b08..9cd3896e 100644 --- a/src/giant_python/extraction/band/transient.py +++ b/src/giant_python/extraction/band/transient.py @@ -67,9 +67,7 @@ def __init__(self, analyze_hz, tau_s, kernel=None) -> None: _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,17 +75,13 @@ def __init__(self, analyze_hz, tau_s, kernel=None) -> 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): """Convolve all sources in chronological order, including gaps.""" 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.""" @@ -116,9 +110,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 +120,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)) @@ -184,9 +172,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] @@ -236,9 +222,7 @@ 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()) @@ -278,9 +262,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 +276,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..4adbda27 100644 --- a/src/giant_python/extraction/band/trial_data.py +++ b/src/giant_python/extraction/band/trial_data.py @@ -28,9 +28,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 @@ -48,9 +46,7 @@ def compute_ds_frames( 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 -): +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.""" dt_read = max(3 * dt, lines_per_cycle) max_line = num_cycles * lines_per_cycle @@ -62,9 +58,7 @@ 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 @@ -76,10 +70,7 @@ def _build_line_cycle_cache(line_indices: list, cycle_indices: list): 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 @@ -98,12 +89,8 @@ def _accumulate_line( 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: @@ -157,22 +144,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): @@ -257,9 +236,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 { @@ -295,29 +272,17 @@ def assemble_lowres_data(results: list, num_channels: int) -> dict: 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 diff --git a/src/giant_python/extraction/band/workflow.py b/src/giant_python/extraction/band/workflow.py index 2421078a..1e0a66b8 100644 --- a/src/giant_python/extraction/band/workflow.py +++ b/src/giant_python/extraction/band/workflow.py @@ -132,9 +132,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) @@ -194,9 +192,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) @@ -206,16 +202,12 @@ 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.""" @@ -241,11 +233,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"] ) @@ -298,9 +286,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, @@ -392,12 +378,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, @@ -449,12 +431,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, @@ -508,12 +486,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), @@ -523,15 +497,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/alignment.py b/src/giant_python/extraction/raster/alignment.py index c40119a6..0760034f 100644 --- a/src/giant_python/extraction/raster/alignment.py +++ b/src/giant_python/extraction/raster/alignment.py @@ -146,9 +146,7 @@ def __init__(self, im: np.ndarray) -> None: 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] @@ -239,20 +237,14 @@ def _first_nanmax(values: np.ndarray) -> int: def _parabola_offset(c: np.ndarray, rr: int, cc: int) -> tuple[float, float]: """xcorr2_nans' sub-pixel offset of the correlation maximum.""" 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) -def _shifted_template_values( - template: np.ndarray, t_valid: np.ndarray, d: int -): +def _shifted_template_values(template: np.ndarray, t_valid: np.ndarray, d: int): """Yield 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 @@ -264,10 +256,7 @@ def _shifted_template_values( 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() @@ -318,9 +307,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 @@ -454,9 +441,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 @@ -500,14 +485,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 ) @@ -637,9 +618,7 @@ def coords(self, trial: int, rows, cols) -> tuple[np.ndarray, np.ndarray]: a[1, 0] * r + a[1, 1] * c + a[1, 2], ) - def inverse( - self, trial: int, rows_t, cols_t - ) -> tuple[np.ndarray, np.ndarray]: + def inverse(self, trial: int, rows_t, cols_t) -> tuple[np.ndarray, np.ndarray]: """Consensus points that a trial's image points are read from. Port of ``trialWarpInverse.m`` (zero-based): the inverse of the @@ -662,12 +641,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]: @@ -679,9 +656,7 @@ 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]: + 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.""" rr = np.arange(shape[0], dtype=np.float64)[:, None] cc = np.arange(shape[1], dtype=np.float64)[None, :] @@ -722,13 +697,9 @@ def warp_trial_image( The resampled image, in the shape of ``im``. """ if method not in ("linear", "cubic"): - raise ValueError( - f"interpolation {method!r} is not 'linear' or 'cubic'" - ) + raise ValueError(f"interpolation {method!r} is not 'linear' or 'cubic'") 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): """One channel.""" @@ -743,9 +714,7 @@ 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: +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. @@ -802,9 +771,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 @@ -898,9 +865,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): @@ -908,12 +873,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) @@ -965,9 +926,7 @@ def _affine_template(s, tforms, trials): 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] - ) + 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 @@ -996,12 +955,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() @@ -1022,9 +979,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 @@ -1120,9 +1075,7 @@ def _plane_basis(nodes: np.ndarray, rows: np.ndarray, cols: np.ndarray): 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)) @@ -1142,9 +1095,7 @@ def _blend(nodes, sigma, rows, cols) -> np.ndarray: Relative to the nearest centre (so far points do not underflow). """ - d2 = (rows[:, None] - nodes[None, :, 0]) ** 2 + ( - cols[:, None] - nodes[None, :, 1] - ) ** 2 + 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) @@ -1179,9 +1130,7 @@ def patch_field_matrix( return l_plane + _blend(nodes, sigma, r, c) @ e, e, l_plane -def patch_field_apply( - nodes: np.ndarray, sigma: float, rows, cols, d: np.ndarray -) -> np.ndarray: +def patch_field_apply(nodes: np.ndarray, sigma: float, rows, cols, d: np.ndarray) -> np.ndarray: """``patch_field_matrix(nodes, sigma, rows, cols)[0] @ d`` without the matrix. Port of ``patchFieldApply.m``: the plane's coefficients and the centres' @@ -1258,10 +1207,7 @@ 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()) @@ -1470,9 +1416,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 @@ -1482,12 +1426,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) @@ -1677,9 +1616,7 @@ def __init__(self, patch, nodes) -> None: 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: @@ -1688,9 +1625,7 @@ 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, disp, trials): """Average the trials warped into the common frame at the fit pixels.""" diff --git a/src/giant_python/extraction/raster/annotations.py b/src/giant_python/extraction/raster/annotations.py index a4f0eb9a..afacd5e5 100644 --- a/src/giant_python/extraction/raster/annotations.py +++ b/src/giant_python/extraction/raster/annotations.py @@ -168,18 +168,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( @@ -214,10 +208,7 @@ 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) @@ -317,9 +308,7 @@ 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: Optional[Path], n_paths: int) -> list[Optional[PathAnnotations]]: """Each path's annotations from a session's file, if there is one. Parameters diff --git a/src/giant_python/extraction/raster/baseline_map.py b/src/giant_python/extraction/raster/baseline_map.py index 5c2965b4..f0a66d4b 100644 --- a/src/giant_python/extraction/raster/baseline_map.py +++ b/src/giant_python/extraction/raster/baseline_map.py @@ -101,10 +101,7 @@ def read_network_baseline(path) -> tuple[np.ndarray, dict]: 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 @@ -232,10 +229,7 @@ def interp_frames( 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) @@ -308,8 +302,7 @@ def map_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") @@ -320,8 +313,7 @@ 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(): @@ -336,10 +328,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) @@ -441,12 +430,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) @@ -461,9 +447,7 @@ def read_trial_baseline( # every neighbour inside the frame is inside the box; those # outside the frame are outside the box too stack = ds[:, c0 : c1 + 1, r0 : r1 + 1].transpose(0, 2, 1) - sampled, weight = sample_bilinear( - stack, trial_rc - np.array([r0, c0]), min_weight - ) + sampled, weight = sample_bilinear(stack, trial_rc - np.array([r0, c0]), min_weight) del stack values = (sampled / photon_scale).astype(np.float32) identity = { @@ -513,10 +497,6 @@ def subproblem_baseline( 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) diff --git a/src/giant_python/extraction/raster/container.py b/src/giant_python/extraction/raster/container.py index 7dcd7f1e..f472ceb0 100644 --- a/src/giant_python/extraction/raster/container.py +++ b/src/giant_python/extraction/raster/container.py @@ -254,10 +254,7 @@ 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" - ) + return solver_params is not None and getattr(solver_params, "baseline_mode", "fit") != "fit" def _check_index(k: int, n: int) -> None: @@ -274,9 +271,7 @@ def crop_of(pixel_rc: np.ndarray) -> np.ndarray: return np.array([lo[0], lo[1], hi[0] - lo[0] + 1, hi[1] - lo[1] + 1]) -def _subproblem( - y, finv, pixel_rc, sources_rc, pixels, sources, crop, baseline=None -): +def _subproblem(y, finv, pixel_rc, sources_rc, pixels, sources, crop, baseline=None): """Assemble a :class:`Subproblem` from its rows and index lists.""" row0, col0, rows, cols = (int(v) for v in crop) sel = np.zeros((rows, cols), dtype=bool) @@ -324,11 +319,7 @@ def _data_kwargs(shape, chunk_pixels, compression, compression_opts): """Chunking and filter of a ``(..., pixels, frames)`` dataset.""" 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( @@ -412,18 +403,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 zip(pix_off[:-1], pix_off[1:])], dtype=np.int32, ).reshape(-1, 4) params = _jsonable(params or {}) @@ -435,18 +420,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 +444,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) @@ -497,9 +476,7 @@ def _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts) -> N 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" @@ -509,18 +486,13 @@ def _write_baseline(g, baseline: TrialBaseline) -> None: 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) -> None: @@ -530,16 +502,13 @@ def _check_format(f) -> None: 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: """Split concatenated lists into index lists by their offsets.""" - return [ - flat[a:b].astype(np.int64) for a, b in zip(offsets[:-1], offsets[1:]) - ] + return [flat[a:b].astype(np.int64) for a, b in zip(offsets[:-1], offsets[1:])] def read_container(path, data: bool = True) -> Container: @@ -573,12 +542,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,9 +558,7 @@ 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 {} ), ) diff --git a/src/giant_python/extraction/raster/kinetics.py b/src/giant_python/extraction/raster/kinetics.py index b26bae09..f9ef1e39 100644 --- a/src/giant_python/extraction/raster/kinetics.py +++ b/src/giant_python/extraction/raster/kinetics.py @@ -160,9 +160,7 @@ def source_kinetics( 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) @@ -206,11 +204,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] @@ -309,9 +303,7 @@ 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: +def mean_snr(snrs: Sequence[Optional[np.ndarray]], n_sources: int) -> np.ndarray: """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 diff --git a/src/giant_python/extraction/raster/localization.py b/src/giant_python/extraction/raster/localization.py index 3457b8db..5c04b398 100644 --- a/src/giant_python/extraction/raster/localization.py +++ b/src/giant_python/extraction/raster/localization.py @@ -129,15 +129,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)) @@ -197,9 +193,7 @@ def movmean_nan(x: np.ndarray, window: int) -> np.ndarray: 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) @@ -221,13 +215,11 @@ def movmedian_nan(x: np.ndarray, window: int) -> np.ndarray: 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) @@ -280,9 +272,7 @@ def nanmedfilt2(a: np.ndarray, size: int = 5) -> np.ndarray: """ m = (size - 1) // 2 padded = np.pad(np.asarray(a, np.float64), m, constant_values=np.nan) - win = sliding_window_view(padded, (size, size)).reshape( - a.shape + (size * size,) - ) + win = sliding_window_view(padded, (size, size)).reshape(a.shape + (size * size,)) with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) return np.nanmedian(win, axis=-1) @@ -358,15 +348,11 @@ def activity_score( 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) n_obs = (~nans[1:last]).sum(0) return sk / (300.0 + n_obs), sd_u @@ -381,9 +367,7 @@ def _max3x3(stack: np.ndarray) -> np.ndarray: 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 @@ -404,17 +388,13 @@ def check_inputs( one of the same size would otherwise scramble the pixels). """ 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}") def summary_image(act_im: np.ndarray, valid: np.ndarray) -> np.ndarray: @@ -439,9 +419,7 @@ def _left_out(shape2d, find_peaks: bool, reason) -> RasterLocalization: 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 @@ -486,9 +464,7 @@ def localize_sources( # noqa: C901 peaks = np.zeros((0, 4)) if find_peaks else None return RasterLocalization(empty, empty.copy(), peaks, valid) - imf = np.array( - movie, dtype=np.float32, order="C" - ) # reshape must be a view + imf = np.array(movie, dtype=np.float32, order="C") # reshape must be a view imf[:, ~valid] = np.nan nans = np.isnan(imf) # per-pixel steps on frames x valid pixels (pixels outside are all NaN) @@ -538,9 +514,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)) @@ -560,10 +534,7 @@ def localize_sources( # noqa: C901 return _left_out(movie.shape[1:], find_peaks, exc) 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: @@ -591,9 +562,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 889decf4..fec5e1aa 100644 --- a/src/giant_python/extraction/raster/null.py +++ b/src/giant_python/extraction/raster/null.py @@ -86,11 +86,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) @@ -148,9 +144,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 @@ -325,22 +319,18 @@ def null_movie( drawn = drawn[drop:] d0 += drop 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]): g += np.float32(w) * f[j : j + n_out] f = g corr = _variance_factor(lam_all, a, b, h, vidx, rows, cols, kt, kr, kc) - flat_out[a:b, vidx] = ( - f.reshape(b - a, -1)[:, vidx] * gain_z[a:b] * corr - ) + flat_out[a:b, vidx] = f.reshape(b - a, -1)[:, vidx] * gain_z[a:b] * corr out[nans] = np.nan return out @@ -430,8 +420,7 @@ def null_calibration( t0 = time.time() with np.errstate(invalid="ignore", divide="ignore"): ph = np.nanmean( - baseline.astype(np.float64) - / (noise["gain"] * var_factor.astype(np.float64)), + baseline.astype(np.float64) / (noise["gain"] * var_factor.astype(np.float64)), axis=0, ) photons = np.full(valid.size, np.nan) @@ -440,9 +429,7 @@ def null_calibration( null_ims = [] for k in range(params.null_draws): - z0 = null_movie( - baseline, var_factor, std, nans, vidx, noise, params.null_seed + k - ) + z0 = null_movie(baseline, var_factor, std, nans, vidx, noise, params.null_seed + k) sk0, _ = activity_score(z0, nans, params, sd_u) sk0[~valid] = np.nan null_ims.append(sk0) @@ -453,12 +440,7 @@ def null_calibration( # imaged area) can never be maxima there; they do not set the scale 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 ok = valid & ~edge & (photons > 0) & np.isfinite(null_ims).all(0) if ok.sum() < 2: raise NullUnavailable("too few imaged pixels for the null calibration") diff --git a/src/giant_python/extraction/raster/peaks.py b/src/giant_python/extraction/raster/peaks.py index 54481755..ec641ac2 100644 --- a/src/giant_python/extraction/raster/peaks.py +++ b/src/giant_python/extraction/raster/peaks.py @@ -39,9 +39,7 @@ _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) @@ -85,9 +83,7 @@ def _edges(u: np.ndarray) -> np.ndarray: selection are wider, as in MATLAB). """ 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: @@ -141,9 +137,7 @@ def value(self, theta: np.ndarray) -> np.ndarray: def jacobian(self, theta: np.ndarray) -> np.ndarray: """Jacobian (pixels x parameters), parameters column-major.""" 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: @@ -179,31 +173,25 @@ def _fit(theta0, y, x, data, lb, ub): # 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.""" 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 @@ -296,19 +284,12 @@ def get_act_im_peaks( # noqa: C901 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) @@ -319,16 +300,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": @@ -356,8 +333,8 @@ def get_act_im_peaks( # noqa: C901 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")) + fit_im[(ys - 1).astype(int), (xs - 1).astype(int)] = _IntegratedGaussians(ys, xs).value( + theta_now.ravel(order="F") ) return fit_im @@ -375,20 +352,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 @@ -409,8 +382,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 @@ -430,9 +402,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, @@ -475,9 +445,7 @@ def _pixel_bounds(finite: np.ndarray): return out -def _finish( - theta, peak_thresh, excl, masked, rule="matlab", mu_bg=0.0, bounds=None -): +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``) masked peaks. Masked peaks are those whose centre ended in the exclusion mask; 0-based @@ -493,9 +461,7 @@ def _finish( 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] * ( @@ -504,9 +470,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) @@ -620,27 +584,23 @@ 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], - ] - ) + return np.concatenate([ + theta[:, 0], + theta[:, 1] - (starts[:, 0] + 1), + theta[:, 2] - (starts[:, 1] + 1), + theta[:, 3], + ]) def _from_offsets(x, starts): """Convert the local fit's x to ``N x 4`` [A, mu_y, mu_x, sigma] (1-based).""" 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, shape): @@ -650,22 +610,18 @@ def _offset_bounds(starts, shape): """ 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 @@ -708,9 +664,7 @@ def rows_of(self, mask): 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 - ) + model = _WindowedGaussians(self.idx_im, self.edges, starts, _LOCAL_WINDOW, rows) target = self.data[rows] if fixed is not None: target = target - fixed @@ -755,9 +709,7 @@ 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): @@ -787,25 +739,19 @@ def run(self, cand, merge_px): """Fit the candidates, then add residual peaks; ``N x 4`` theta.""" 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) @@ -840,12 +786,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: @@ -875,7 +819,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 2336fabc..37ef19ea 100644 --- a/src/giant_python/extraction/raster/plan.py +++ b/src/giant_python/extraction/raster/plan.py @@ -160,13 +160,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() @@ -188,8 +185,7 @@ def _check_acceptance(self) -> None: """Validate the seed threshold's settings.""" 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") @@ -440,9 +436,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, @@ -450,9 +444,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 @@ -780,9 +772,7 @@ def _soma_canvas(soma_mask, shape, warp=None, trial=None) -> np.ndarray: 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 @@ -854,9 +844,7 @@ def refine_alignment( start[valid] = warp.affine[valid] affine = warp.affine.copy() if params.inter_trial_alignment == "patchwise": - fit, info = align_trials_patchwise( - mean_sum, start, halves, params.align_patch_px - ) + fit, info = align_trials_patchwise(mean_sum, start, halves, params.align_patch_px) nodes = fit.nodes disp = np.full((n_trials, nodes.shape[0], 2), np.nan) for t in np.flatnonzero(warp.aligned): @@ -941,9 +929,7 @@ def plan_path( # noqa: C901 """ p = params or PlanParams() if seeds is None and p.peak_method != "getactimpeaks": - raise NotImplementedError( - "WMF seeding (findSourcesWMF) is not ported yet" - ) + raise NotImplementedError("WMF seeding (findSourcesWMF) is not ported yet") keep = np.array([t is not None for t in trials], dtype=bool) if keep_trials is not None: keep &= np.asarray(keep_trials, dtype=bool).ravel() @@ -968,20 +954,14 @@ def plan_path( # noqa: C901 mean_aligned = np.full(mean_ims.shape, np.nan) for t in aligned: act_aligned[t] = warp_trial_image(act_ims[t], warp, t) - valid, corr_thresh, covered = _valid_trials( - ali.corr, act_aligned, p.max_corr_thresh - ) + 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 + _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) if details is not None: details["alignment_info"] = refine_info refined = True @@ -994,9 +974,7 @@ def plan_path( # noqa: C901 mean_aligned[t] = warp_trial_image(mean_ims[t], warp, t, coords=grid) del grid - act_im, med_im, nan_frac = combined_activity_image( - act_aligned[valid], p.nan_thresh - ) + act_im, med_im, nan_frac = combined_activity_image(act_aligned[valid], p.nan_thresh) soma = _soma_canvas(soma_mask, shape, warp, soma_mask_trial) seed_info: dict = {} if seeds is None and valid.size == 0: @@ -1035,9 +1013,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, @@ -1052,9 +1028,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( @@ -1083,13 +1057,9 @@ 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 ], ) @@ -1098,11 +1068,7 @@ def _ragged(lists: Sequence[np.ndarray]) -> tuple[np.ndarray, np.ndarray]: """Index lists as one array and the offsets of each list in it.""" 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 @@ -1123,9 +1089,7 @@ def _write_images(g: h5py.Group, name: str, data: np.ndarray) -> None: g.create_dataset(name, data=data, **kwargs) -def write_plan( - path: str | Path, plan: ExtractionPlan, group: str = "/" -) -> None: +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 @@ -1201,18 +1165,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 ( @@ -1231,9 +1189,7 @@ def _read_groups(gr, rows, cols, src_rows, src_cols) -> list: 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 @@ -1244,9 +1200,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 @@ -1332,9 +1286,7 @@ 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), ) diff --git a/src/giant_python/extraction/raster/refit_test.py b/src/giant_python/extraction/raster/refit_test.py index f0735988..224a297f 100644 --- a/src/giant_python/extraction/raster/refit_test.py +++ b/src/giant_python/extraction/raster/refit_test.py @@ -117,8 +117,7 @@ def draw_refit_data( """ 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 +127,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: @@ -200,9 +197,7 @@ 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) @@ -243,11 +238,7 @@ def by_size(events: list[dict], edges=SIZE_EDGES) -> list[dict]: 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") - ), + recovered_found=(float(m1[f].sum() / m0[f].sum()) if f.any() else float("nan")), ) ) return rows @@ -386,8 +377,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 = [], [] @@ -476,9 +466,7 @@ 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 diff --git a/src/giant_python/extraction/raster/results.py b/src/giant_python/extraction/raster/results.py index df5b0254..d1079bdc 100644 --- a/src/giant_python/extraction/raster/results.py +++ b/src/giant_python/extraction/raster/results.py @@ -205,9 +205,7 @@ def write_results( g["snr"] = np.asarray(r.snr) if r.f0_image is not None: g["f0_image"] = np.asarray(r.f0_image, np.float64) - 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(): @@ -285,9 +283,7 @@ 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 @@ -354,8 +350,7 @@ def _merge(files: Sequence[ResultsFile]) -> dict: ) if _solve_settings(f.attrs) != _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" ) merged: dict = {} for f in files: @@ -436,7 +431,4 @@ def subproblem_results( 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 91cae394..65e4a238 100644 --- a/src/giant_python/extraction/raster/seeding.py +++ b/src/giant_python/extraction/raster/seeding.py @@ -152,9 +152,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 @@ -190,7 +188,7 @@ def seed_heights( 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() + win = act[max(r - 1, 0) : r + 2, max(c - 1, 0) : c + 2].ravel() win = np.sort(win[np.isfinite(win)]) if win.size: out[i] = (win[-2] if win.size > 1 else win[-1]) - mu @@ -257,9 +255,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)) @@ -347,14 +343,10 @@ def seed_sources( """ 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}") _check_acceptance(acceptance, null_im) if method == "wmf": - raise NotImplementedError( - "WMF seeding (findSourcesWMF) is not ported yet" - ) + raise NotImplementedError("WMF seeding (findSourcesWMF) is not ported yet") act_im = np.asarray(act_im, dtype=np.float64) mask = None if soma_mask is not None and np.any(soma_mask): @@ -362,9 +354,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, @@ -380,14 +370,9 @@ def seed_sources( def _check_acceptance(acceptance: str, null_im) -> None: """Reject an unknown acceptance, or a null one without the null.""" 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): @@ -397,9 +382,7 @@ def _threshold(acceptance, peak_th, null_im, false_per_field, mask, info): """ 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": diff --git a/src/giant_python/extraction/raster/solver.py b/src/giant_python/extraction/raster/solver.py index 77422a3f..f3cdc177 100644 --- a/src/giant_python/extraction/raster/solver.py +++ b/src/giant_python/extraction/raster/solver.py @@ -90,9 +90,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,9 +143,7 @@ class SolverOptions: def __post_init__(self) -> None: """Reject options the fits cannot run with.""" 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: @@ -156,13 +152,9 @@ 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``.""" @@ -222,9 +214,7 @@ def estimate_photon_scale(y: np.ndarray, finv: np.ndarray) -> float: mean = (w * y0).sum(1) / wsum var = (w * (y0 - mean[:, None]) ** 2).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) @@ -243,13 +233,10 @@ 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)" ) @@ -271,14 +258,10 @@ def __init__(self, subs, params: SolverParams, opt: SolverOptions) -> None: 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: """Put an array on the fits' device, in their precision.""" @@ -311,9 +294,7 @@ def pixels_sources(self, arrays, dtype=None) -> torch.Tensor: 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 - ) + 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 @@ -375,9 +356,7 @@ 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 @@ -405,18 +384,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 = [] @@ -435,8 +408,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 @@ -458,9 +430,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 - ) + _, noise, _ = activity_noise(y1[i], finv[i], b_np[i], hi, xi, p.tau_frames) floor = compute_floor(xi, p.denoise_window, p.baseline_window) xt = np.fmax(0, xi - floor - noise[:, None]) b_np[i] = _baseline_step( @@ -504,9 +474,7 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901 ls1 = [] for i in range(bt.n): xi = bt.member(x, i, bt.n_src[i]) - _, _, snr[i] = activity_noise( - y1[i], finv[i], b_np[i], h_np[i], xi, p.tau_frames - ) + _, _, snr[i] = activity_noise(y1[i], finv[i], b_np[i], h_np[i], xi, p.tau_frames) snr[i] = np.real(snr[i]) ls1.append(_lstsq(h_np[i], y1[i] - b_np[i])) @@ -521,9 +489,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") @@ -561,14 +527,10 @@ def _f0_image(base: list, frames) -> np.ndarray | 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( @@ -655,10 +617,7 @@ def _check_placement(index, count: int, size: int, what: str) -> None: """Reject indices that would put results in the wrong place.""" 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}; " @@ -699,13 +658,9 @@ def assemble_results( img_n = np.zeros(n_pixels) for sb, r in zip(subs, results): if sb.pixels is None or sb.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(sb.pixels, r.footprints.shape[0], n_pixels, "pixels") - _check_placement( - sb.sources, r.footprints.shape[1], n_sources, "sources" - ) + _check_placement(sb.sources, r.footprints.shape[1], n_sources, "sources") want = (n_ch, r.footprints.shape[1], n_t) for name in ("events", "ls", "f0"): if getattr(r, name).shape != want: @@ -777,9 +732,7 @@ 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: +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 @@ -791,8 +744,7 @@ def process_result( discard = np.asarray(discard, dtype=bool).ravel() if discard.size != trial.events.shape[2]: raise ValueError( - f"discard has {discard.size} frames; the trial has " - f"{trial.events.shape[2]}" + f"discard has {discard.size} frames; the trial has {trial.events.shape[2]}" ) denoised = np.empty_like(trial.events) denoised[0] = conv_same(trial.events[0], params.k) diff --git a/src/giant_python/extraction/raster/solver_baseline.py b/src/giant_python/extraction/raster/solver_baseline.py index 9c0c2fa4..1a3d1acc 100644 --- a/src/giant_python/extraction/raster/solver_baseline.py +++ b/src/giant_python/extraction/raster/solver_baseline.py @@ -62,9 +62,7 @@ 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: +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; @@ -76,9 +74,7 @@ def ordfilt_rows( 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 @@ -112,9 +108,7 @@ 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]: +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`` @@ -134,9 +128,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) @@ -156,9 +148,7 @@ def initial_baseline(y: np.ndarray, params: SolverParams) -> np.ndarray: return np.fmax(params.min_baseline, lp) -def compute_floor( - x: np.ndarray, denoise_window: float, baseline_window: float -) -> np.ndarray: +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 @@ -249,9 +239,7 @@ def bspline_basis(n_t: int, delta: float) -> sparse.csr_matrix: 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: @@ -430,15 +418,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): @@ -461,10 +445,7 @@ def surround_operators(sel: np.ndarray, params: SolverParams) -> list: subproblem), sparse otherwise. """ 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: @@ -505,9 +486,7 @@ def baseline_programs( 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) @@ -563,9 +542,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 dict(g=g, c=c, lb=lb, ub=wide, surround=sur, spline=bs, n_sources=n_src) def baseline_from_coef( @@ -636,12 +613,8 @@ def fit_baseline( ``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) @@ -735,9 +708,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 @@ -976,12 +947,8 @@ 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 diff --git a/src/giant_python/extraction/raster/solver_fits.py b/src/giant_python/extraction/raster/solver_fits.py index 9e48d908..2ebff816 100644 --- a/src/giant_python/extraction/raster/solver_fits.py +++ b/src/giant_python/extraction/raster/solver_fits.py @@ -142,9 +142,7 @@ def conv(self, x: torch.Tensor) -> torch.Tensor: if self.decay is not None: y = _geometric_sum(x, self.decay, self.lag + 1, True) return self.gain * y - 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: @@ -152,9 +150,7 @@ def conv_adj(self, x: torch.Tensor) -> torch.Tensor: if self.decay is not None: y = _geometric_sum(x, self.decay, self.lag + 1, False) return self.gain * y - 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) @@ -242,9 +238,7 @@ def value(self, s: torch.Tensor) -> torch.Tensor: def value_grad(self, s: torch.Tensor): """Loss and gradient at S; keeps the curvature for the products.""" fixed_q = self.s0 is not None and self.q is not None - f, g, c = variance_loss( - self.z, self.model(s), self.w, self.s0, 1 if fixed_q else 2 - ) + f, g, c = variance_loss(self.z, self.model(s), self.w, self.s0, 1 if fixed_q else 2) if not fixed_q: # curvature summed over pixels: source pairs x frames self.q = self.hht @ c @@ -305,9 +299,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 @@ -316,9 +308,7 @@ 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) @@ -548,9 +538,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; @@ -641,9 +629,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())) diff --git a/src/giant_python/extraction/raster/solver_setup.py b/src/giant_python/extraction/raster/solver_setup.py index 985bab9a..f8eaa400 100644 --- a/src/giant_python/extraction/raster/solver_setup.py +++ b/src/giant_python/extraction/raster/solver_setup.py @@ -223,14 +223,10 @@ def __post_init__(self) -> None: """Reject values the solver cannot run with.""" 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.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)") @@ -238,9 +234,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) @@ -304,9 +298,7 @@ def bfilter(self) -> np.ndarray: """ 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 @@ -370,20 +362,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): @@ -444,20 +430,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( @@ -529,8 +508,7 @@ def _mat_valid_kernel(g: h5py.Group, default: int) -> int: 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]) @@ -565,9 +543,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), @@ -587,9 +563,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", @@ -615,9 +589,7 @@ def _trial_pixel_index(trial_file: Path, row0, col0, sel) -> np.ndarray: return index[r + row0, c + col0] -def load_matlab_subproblem( - path, dtype=np.float64 -) -> tuple[Subproblem, SolverParams]: +def load_matlab_subproblem(path, dtype=np.float64) -> tuple[Subproblem, SolverParams]: """One of MATLAB's saved subproblems (``sub_###.mat``) and its params. ``extractTrial`` saves them with ``params.saveSubproblemsDir`` set: diff --git a/src/giant_python/extraction/raster/spots.py b/src/giant_python/extraction/raster/spots.py index 3cbd107c..42b79648 100644 --- a/src/giant_python/extraction/raster/spots.py +++ b/src/giant_python/extraction/raster/spots.py @@ -162,11 +162,7 @@ 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, axis=None): @@ -195,9 +191,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) @@ -245,9 +239,7 @@ def localize_events( 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): @@ -259,9 +251,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)) @@ -270,12 +260,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")]: @@ -286,9 +271,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 @@ -355,9 +338,7 @@ def _xd(x, S, K, center, rng, n_init, iters, w=1e-3): Plus the fixed outlier component at ``center``. """ 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() @@ -390,8 +371,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 @@ -401,9 +381,7 @@ def _xd(x, S, K, center, rng, n_init, iters, w=1e-3): return best -def mixture_fit( - x, S, center, kmax=3, n_init=6, iters=200, seed=0, bic_margin=0.0 -): +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 @@ -425,13 +403,9 @@ def mixture_fit( 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 @@ -446,9 +420,7 @@ def bic_gain(fits) -> float: 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 -): +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 from point sources. Events are drawn equally from point sources at ``points`` with the events' @@ -465,9 +437,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, @@ -518,9 +490,7 @@ 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: +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 @@ -535,20 +505,14 @@ def event_test( 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())) 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 - ) + 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), @@ -569,9 +533,7 @@ def event_test( return out -def spot_label( - n_sources: int, event_corr: float, test: dict, settings: SpotSettings -) -> str: +def spot_label(n_sources: int, event_corr: float, test: dict, settings: SpotSettings) -> str: """Assign a spot's label (:data:`LABELS`) from its tests.""" if n_sources < 2: return "single" diff --git a/src/giant_python/extraction/raster/stage_files.py b/src/giant_python/extraction/raster/stage_files.py index 98170d70..e57dbadf 100644 --- a/src/giant_python/extraction/raster/stage_files.py +++ b/src/giant_python/extraction/raster/stage_files.py @@ -153,9 +153,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) @@ -207,9 +205,7 @@ def localization_attrs(path) -> Optional[dict]: return attrs -def read_localization( - path, peaks: bool = True, half_ims: bool = True -) -> LocalizationRecord: +def read_localization(path, peaks: bool = True, half_ims: bool = True) -> LocalizationRecord: """Read a localization file (and its peaks' sidecar, if there is one). Parameters @@ -245,9 +241,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: diff --git a/src/giant_python/extraction/raster/summary.py b/src/giant_python/extraction/raster/summary.py index 18f30211..9f60e15c 100644 --- a/src/giant_python/extraction/raster/summary.py +++ b/src/giant_python/extraction/raster/summary.py @@ -186,9 +186,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: @@ -203,9 +201,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 @@ -342,13 +338,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", @@ -375,9 +369,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) @@ -501,9 +493,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) @@ -518,13 +508,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) @@ -543,14 +531,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", @@ -560,9 +544,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( @@ -637,8 +619,7 @@ 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] @@ -669,9 +650,7 @@ 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 @@ -700,9 +679,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) @@ -728,9 +705,7 @@ def _write_per_trial( 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] @@ -750,9 +725,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))): diff --git a/src/giant_python/extraction/raster/trial.py b/src/giant_python/extraction/raster/trial.py index 41b578a6..b77d9f3b 100644 --- a/src/giant_python/extraction/raster/trial.py +++ b/src/giant_python/extraction/raster/trial.py @@ -132,9 +132,7 @@ 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: +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 @@ -216,9 +214,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 " @@ -299,9 +295,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) @@ -338,9 +332,7 @@ def load_registered_trial( # HDF5 holds MATLAB's rows x cols x frames as (frames, cols, rows) 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) movie[discard] = np.nan return RegisteredTrial(movie, vf, mean_im, discard, align_hz, halves) @@ -399,14 +391,10 @@ def localize_trial( ) check_inputs(trial.movie.shape, p, baseline, trial.var_factor) try: - loc = localize_sources( - trial.movie, trial.var_factor, p, baseline, find_peaks=find_peaks - ) + loc = localize_sources(trial.movie, trial.var_factor, p, baseline, find_peaks=find_peaks) except Exception: # MATLAB's catch: retry without the outer pixels movie = trial.movie.copy() movie[:, [0, -1], :] = np.nan movie[:, :, [0, -1]] = np.nan - loc = localize_sources( - movie, trial.var_factor, p, baseline, find_peaks=find_peaks - ) + loc = localize_sources(movie, trial.var_factor, p, baseline, find_peaks=find_peaks) return loc, trial diff --git a/src/giant_python/extraction/raster/trial_data.py b/src/giant_python/extraction/raster/trial_data.py index f04a5a23..63a23160 100644 --- a/src/giant_python/extraction/raster/trial_data.py +++ b/src/giant_python/extraction/raster/trial_data.py @@ -105,8 +105,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)) @@ -304,9 +303,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]) @@ -339,9 +336,7 @@ def block_compensation(comp: Optional[OnlineCompensation], lines): 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])) @@ -440,9 +435,7 @@ 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, cols, dr: int, dc: int) -> np.ndarray: """Index into ``ids`` of pixels moved by ``(dr, dc)``; -1 if none.""" @@ -477,14 +470,10 @@ def frames(self, times): 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 - ((_, _, s_num, s_den),) = f.pixel_sums( - times, self.dt, self.channels - ) + ((_, _, s_num, s_den),) = f.pixel_sums(times, self.dt, self.channels) 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]) @@ -656,23 +645,16 @@ def interpolate(self, values, weight, m_r, m_c): 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) @@ -783,19 +765,12 @@ 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) 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) @@ -859,9 +834,7 @@ 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])) @@ -1074,11 +1047,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) @@ -1114,9 +1083,7 @@ def finish_pixels( ) -def nansvd( - d: np.ndarray, num_comps: int = 3, max_iter: int = 20, nan_frac=0.3 -): +def nansvd(d: np.ndarray, num_comps: int = 3, max_iter: int = 20, nan_frac=0.3): """Compute the truncated SVD of data with gaps (``nansvd.m``). Rows and columns with at least ``nan_frac`` of their values missing are @@ -1304,19 +1271,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).""" 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() @@ -1435,8 +1396,7 @@ 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: diff --git a/src/giant_python/gui/parameters_gui.py b/src/giant_python/gui/parameters_gui.py index d6894eae..0b785873 100644 --- a/src/giant_python/gui/parameters_gui.py +++ b/src/giant_python/gui/parameters_gui.py @@ -57,9 +57,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,15 +76,11 @@ 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 @@ -109,14 +103,10 @@ def on_ok() -> None: "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"] = ( @@ -135,9 +125,7 @@ def on_cancel() -> None: 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 fd4cdde7..9c8a69ce 100644 --- a/src/giant_python/gui/roi_editor.py +++ b/src/giant_python/gui/roi_editor.py @@ -25,8 +25,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() @@ -52,14 +51,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 @@ -102,11 +97,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]) @@ -167,12 +158,8 @@ def _edit_rois( ) -> 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 +174,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/annotations.py b/src/giant_python/io/annotations.py index 73e61f9d..9109d9d8 100644 --- a/src/giant_python/io/annotations.py +++ b/src/giant_python/io/annotations.py @@ -75,9 +75,7 @@ def _write_roi_group(grp, i: int, rec: dict, mask_list: list, str_dt) -> None: 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 +84,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 ed363a31..a29a47e1 100644 --- a/src/giant_python/io/experiment_summary.py +++ b/src/giant_python/io/experiment_summary.py @@ -75,9 +75,7 @@ def _decode_path(assembled: dict, path_index: int) -> PathSummary: Parts the file lacks are None: per-source traces, ``SNR`` (raster SILo writes none when no trial gave one), the raster-only fields. """ - 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], @@ -116,20 +114,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} @@ -142,9 +132,7 @@ def _decode_path(assembled: dict, path_index: int) -> PathSummary: ) -def _stack_required_arrays( - arrays: Iterable[np.ndarray | None], field: str -) -> np.ndarray: +def _stack_required_arrays(arrays: Iterable[np.ndarray | None], field: str) -> np.ndarray: """Stack arrays; identify missing fields by their 0-based index.""" required: list[np.ndarray] = [] for index, array in enumerate(arrays): @@ -157,17 +145,11 @@ def _stack_required_arrays( def _optional_array(array, reference: np.ndarray, field: str) -> np.ndarray: """Validate a supplied trace, or mark unavailable samples with NaNs.""" 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 @@ -175,17 +157,13 @@ 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) - ] - ) + 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]: +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 @@ -198,10 +176,7 @@ 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 @@ -218,9 +193,7 @@ 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 @@ -228,25 +201,17 @@ def _source_scalars(path: PathSummary) -> dict: def _source_arrays(path: PathSummary) -> dict: """Stack the populated sources' arrays (and raster SILo's fields).""" 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"), @@ -267,17 +232,13 @@ def _roi_arrays(rois: list) -> dict: some ROIs is an error. """ 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 @@ -305,15 +266,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) @@ -334,9 +293,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) @@ -352,9 +309,7 @@ def _write_spots(sources: h5py.Group, spots: dict) -> None: 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)) @@ -399,9 +354,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: @@ -515,20 +468,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()} @@ -550,6 +497,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 f68e6210..a54bdb57 100644 --- a/src/giant_python/io/hdf5.py +++ b/src/giant_python/io/hdf5.py @@ -223,18 +223,14 @@ 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)) diff --git a/src/giant_python/io/slap2.py b/src/giant_python/io/slap2.py index a0d5d7b0..2bb0326a 100644 --- a/src/giant_python/io/slap2.py +++ b/src/giant_python/io/slap2.py @@ -69,9 +69,7 @@ def is_cycle_split(path: Union[str, Path]) -> bool: """ 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 @@ -189,9 +187,7 @@ def _text(value) -> str: return str(value) -def read_mat_datetime_ms( - path: Union[str, Path], name: str, offset_ms: float = 0.0 -): +def read_mat_datetime_ms(path: Union[str, Path], name: str, offset_ms: float = 0.0): """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 diff --git a/src/giant_python/io/slap2_raster.py b/src/giant_python/io/slap2_raster.py index 2f864924..23af516d 100644 --- a/src/giant_python/io/slap2_raster.py +++ b/src/giant_python/io/slap2_raster.py @@ -169,9 +169,7 @@ def _dmd_curtain(meta, n_rows: int): 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 @@ -239,9 +237,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, @@ -309,9 +305,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 +329,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, @@ -496,9 +489,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/trial_table.py b/src/giant_python/io/trial_table.py index bc2b3f38..4dc70317 100644 --- a/src/giant_python/io/trial_table.py +++ b/src/giant_python/io/trial_table.py @@ -36,9 +36,7 @@ def read_trial_table(path: Union[str, 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/experiment_summary.py b/src/giant_python/models/experiment_summary.py index 47af6321..ba4b67b6 100644 --- a/src/giant_python/models/experiment_summary.py +++ b/src/giant_python/models/experiment_summary.py @@ -210,13 +210,8 @@ class PathSummary: 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" - ) + 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 diff --git a/src/giant_python/models/params.py b/src/giant_python/models/params.py index d55bd5dd..4c6c7a26 100644 --- a/src/giant_python/models/params.py +++ b/src/giant_python/models/params.py @@ -265,9 +265,7 @@ 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.""" @@ -279,11 +277,7 @@ 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: @@ -307,9 +301,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), @@ -372,9 +364,7 @@ def __post_init__(self) -> None: """Validate the explicit and automatic annotation policies.""" 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") @@ -460,9 +450,7 @@ def resolve_registration_options( Fresh validated objects. """ return ( - MultiRoiRegistrationParams( - **_option_values(params, MultiRoiRegistrationParams) - ), + MultiRoiRegistrationParams(**_option_values(params, MultiRoiRegistrationParams)), ExecutionOptions(**_option_values(execution, ExecutionOptions)), ) @@ -886,8 +874,7 @@ def __post_init__(self) -> None: ) if self.peak_method != "getactimpeaks": raise NotImplementedError( - f"peakMethod {self.peak_method!r} is not ported yet; only " - "'getactimpeaks'" + f"peakMethod {self.peak_method!r} is not ported yet; only 'getactimpeaks'" ) if not self.nan_thresh <= 1: # a share of missing samples: above 1 pixels without any sample @@ -904,24 +891,16 @@ def _check_spots(self) -> None: _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``.""" _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) @@ -959,17 +938,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: @@ -977,12 +953,8 @@ 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: """Check the localization options in ways that their type cannot.""" @@ -991,24 +963,14 @@ def _check_localization(self) -> None: self.localization_baseline, ("median", "network"), ) - 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: @@ -1108,10 +1070,7 @@ def needs_network_baseline(self) -> bool: Localization, or the solver's baseline mode. """ - return ( - self.localization_baseline == "network" - or self.baseline_mode != "fit" - ) + return self.localization_baseline == "network" or self.baseline_mode != "fit" def localization_params(self, align_hz: float): """Build the per-trial localization's parameters. @@ -1261,18 +1220,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 @@ -1524,9 +1479,7 @@ def __post_init__(self) -> None: 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) @@ -1541,9 +1494,7 @@ def solver_options(self): """ 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) SiloParamsInput = Optional[Union[SiloParams, dict]] diff --git a/src/giant_python/models/trial_table.py b/src/giant_python/models/trial_table.py index ea96baec..5345fbfe 100644 --- a/src/giant_python/models/trial_table.py +++ b/src/giant_python/models/trial_table.py @@ -30,12 +30,8 @@ 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 - ) + 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) @dataclass @@ -78,9 +74,7 @@ class TrialTable: motion_correction: Optional[dict] = None source_extraction: Optional[dict] = None # Provenance only; never a trial-table HDF5 field. - source_path: Optional[Path] = field( - default=None, repr=False, compare=False - ) + source_path: Optional[Path] = field(default=None, repr=False, compare=False) @classmethod def from_h5(cls, path: Union[str, Path]) -> "TrialTable": diff --git a/src/giant_python/numerics/baseline.py b/src/giant_python/numerics/baseline.py index 67b56b08..2e245a16 100644 --- a/src/giant_python/numerics/baseline.py +++ b/src/giant_python/numerics/baseline.py @@ -67,9 +67,7 @@ def _compute_f0_column( 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,9 +88,7 @@ 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: +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 @@ -123,22 +119,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 +143,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) diff --git a/src/giant_python/numerics/interpolation.py b/src/giant_python/numerics/interpolation.py index 5933975a..63aa8dfe 100644 --- a/src/giant_python/numerics/interpolation.py +++ b/src/giant_python/numerics/interpolation.py @@ -3,9 +3,7 @@ import numpy as np -def nearest_interp( - x: np.ndarray, xp: np.ndarray, yp: np.ndarray -) -> np.ndarray: +def nearest_interp(x: np.ndarray, xp: np.ndarray, yp: np.ndarray) -> np.ndarray: """Nearest-neighbor interpolation (MATLAB ``interp1(...,'nearest')``). Parameters diff --git a/src/giant_python/numerics/peaks.py b/src/giant_python/numerics/peaks.py index eaaeb5d8..21c5cb64 100644 --- a/src/giant_python/numerics/peaks.py +++ b/src/giant_python/numerics/peaks.py @@ -50,9 +50,7 @@ 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 @@ -200,12 +198,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 @@ -264,9 +258,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 +291,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 @@ -362,9 +352,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,14 +367,10 @@ 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]: +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 @@ -406,24 +390,20 @@ 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() @@ -440,9 +420,7 @@ 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).""" 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 @@ -493,9 +471,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 +490,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): @@ -595,11 +568,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 +596,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 @@ -692,24 +659,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 +704,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] @@ -804,9 +762,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 +772,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 +790,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 12915f5e..0e0ac6a4 100644 --- a/src/giant_python/parallel.py +++ b/src/giant_python/parallel.py @@ -61,9 +61,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 diff --git a/src/giant_python/pipeline/annotate.py b/src/giant_python/pipeline/annotate.py index 0e2f2a26..0f21b179 100644 --- a/src/giant_python/pipeline/annotate.py +++ b/src/giant_python/pipeline/annotate.py @@ -50,6 +50,4 @@ def annotate_rois( 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..42a7fcc4 100644 --- a/src/giant_python/pipeline/extract.py +++ b/src/giant_python/pipeline/extract.py @@ -26,14 +26,11 @@ def _require_band_mode( ) -> None: """Reject unsupported routing before loading data or a backend.""" 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" ) @@ -74,9 +71,7 @@ def extract_sources( 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( diff --git a/src/giant_python/pipeline/pipeline.py b/src/giant_python/pipeline/pipeline.py index ac5751b8..940a2d86 100644 --- a/src/giant_python/pipeline/pipeline.py +++ b/src/giant_python/pipeline/pipeline.py @@ -106,9 +106,7 @@ 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: @@ -141,9 +139,7 @@ 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 diff --git a/src/giant_python/pipeline/reg_stats.py b/src/giant_python/pipeline/reg_stats.py index 15ad9aef..658b87a6 100644 --- a/src/giant_python/pipeline/reg_stats.py +++ b/src/giant_python/pipeline/reg_stats.py @@ -67,17 +67,13 @@ def read_alignment(path: Union[str, Path]) -> dict: 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, } @@ -139,8 +135,7 @@ 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" ) @@ -181,9 +176,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"]) @@ -216,10 +209,7 @@ 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) @@ -291,9 +281,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) @@ -334,14 +322,8 @@ 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: diff --git a/src/giant_python/pipeline/register.py b/src/giant_python/pipeline/register.py index fdf36c35..cd6dfbaf 100644 --- a/src/giant_python/pipeline/register.py +++ b/src/giant_python/pipeline/register.py @@ -185,9 +185,7 @@ def _check_column_major(f: h5py.File) -> None: """Reject trial tables that are not MATLAB-written (column-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: @@ -206,8 +204,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}" ) @@ -234,9 +231,7 @@ def _stage(grp: h5py.Group, fields: dict) -> dict: return staged -def _update_trial_table( - path: Path, fields: dict, group: str = "motion_correction" -) -> None: +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 @@ -309,12 +304,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) @@ -335,29 +326,25 @@ 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 = 1 if device.type == "cpu": - workers = max( - 1, min(execution.max_workers, len(jobs), os.cpu_count() or 1) - ) + workers = max(1, min(execution.max_workers, len(jobs), os.cpu_count() or 1)) if workers > 1: for job in jobs: job["threads"] = max(1, (os.cpu_count() or 1) // workers) diff --git a/src/giant_python/pipeline/silo.py b/src/giant_python/pipeline/silo.py index 0f1c37a1..b660d198 100644 --- a/src/giant_python/pipeline/silo.py +++ b/src/giant_python/pipeline/silo.py @@ -83,15 +83,13 @@ def _localize_hash(session: SiloSession, params: SiloParams, d, t, baseline): """Compute the 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, - } - ) + 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]: @@ -127,9 +125,7 @@ def _network_baseline(session, params, d, t, baseline_dir) -> Path: """ 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 " @@ -160,9 +156,7 @@ def _recorded(path, name: str, default: str = "median") -> str: return default if value is None else str(value) -def _check_same( - what: str, used, given, option: str, flag: str = "--baseline" -) -> None: +def _check_same(what: str, used, given, option: str, flag: str = "--baseline") -> None: """Refuse a stage whose settings differ from the stage before it.""" if used != given: raise ValueError( @@ -274,9 +268,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"], @@ -345,11 +337,7 @@ def _peaks_job(job: dict) -> dict: def _units(session: SiloSession, units, paths=None) -> list: """Kept trial-paths ``(d, t)``, zero-based, of ``units`` or all.""" 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: @@ -393,59 +381,48 @@ 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 @@ -466,16 +443,14 @@ 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 @@ -497,16 +472,12 @@ def localize( 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 @@ -524,9 +495,7 @@ def _plan_inputs(session: SiloSession, d: int, half_ims: bool = False): 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 @@ -567,15 +536,13 @@ def check_plan_localizations(session, d) -> None: def _plan_hash(session, params, d, seeds, annotations) -> str: """Compute the settings hash of a path's plan.""" locs = _localization_hashes(session, d) - return _hash( - { - "stage": "plan", - "settings": params.stage_settings("plan"), - "localization": locs, - "seeds": None if seeds is None else np.asarray(seeds).tolist(), - "annotations": annotations, - } - ) + return _hash({ + "stage": "plan", + "settings": params.stage_settings("plan"), + "localization": locs, + "seeds": None if seeds is None else np.asarray(seeds).tolist(), + "annotations": annotations, + }) def write_user_rois(path: Path, labels: Sequence[str], masks) -> None: @@ -684,9 +651,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 @@ -791,9 +756,7 @@ def plan( # ---------------------------------------------------------------- prepare -def load_trial_for( - session: SiloSession, params: SiloParams, plan, d, t, rois, device="cpu" -): +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. Returns @@ -907,9 +870,7 @@ def localization_baseline(session: SiloSession, d: int, t: int): return json.loads(v) if v else None -def load_trial_baseline( - session: SiloSession, params: SiloParams, trial, base: Path, d, t -): +def load_trial_baseline(session: SiloSession, params: SiloParams, trial, base: Path, d, t): """Read the network's baseline at a loaded trial's selected pixels. :func:`~giant_python.extraction.raster.baseline_map.read_trial_baseline`, @@ -922,9 +883,7 @@ def load_trial_baseline( with h5py.File(session.alignment(d, t), "r") as f: # the registered frames' lines (DSframes, as read_alignment) ds_lines = np.asarray(f["DSframes"], np.float64).ravel() - tb = read_trial_baseline( - base, trial.trial_rc, ds_lines, trial.photon_scale - ) + tb = read_trial_baseline(base, trial.trial_rc, ds_lines, trial.photon_scale) rec = check_baseline_record(base, None, session.alignment(d, t), params) if rec is not None: # identified when it was predicted; a file without a record names @@ -1025,16 +984,12 @@ def prepare( 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): continue 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 @@ -1042,11 +997,7 @@ def prepare( continue 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, @@ -1065,9 +1016,7 @@ def prepare( # the hash of the settings (not of the params JSON, see settings_hash) with h5py.File(out, "a") as f: f.attrs["settings_hash"] = h - done.append( - {"unit": (d, t), "file": out, "seconds": time.perf_counter() - t0} - ) + done.append({"unit": (d, t), "file": out, "seconds": time.perf_counter() - t0}) return done @@ -1090,9 +1039,7 @@ def _mark_skipped(session, d, t, reason, prepare_hash, plan_hash) -> None: p.unlink() -def _container_params( - params: SiloParams, plan_hash: str, d: int, t: int, baseline=None -) -> dict: +def _container_params(params: SiloParams, plan_hash: str, d: int, t: int, baseline=None) -> dict: """Build what a container records of its settings. With the network this includes the baseline source, and the identity of the @@ -1179,10 +1126,7 @@ def _finish(p: _Pending) -> float: 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 @@ -1267,9 +1211,7 @@ def _submit(subs, sp, options, pool, done: Optional[_Done] = None): return [by_index[i] for i in range(len(subs))], [] -def _save_container( - folder, session, params, plan, ph, chash, trial, d, t, baseline=None -) -> None: +def _save_container(folder, session, params, plan, ph, chash, trial, d, t, baseline=None) -> None: """Write a loaded trial's container (``--save-subproblems``).""" from ..extraction.raster.container import write_container @@ -1397,9 +1339,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 @@ -1504,25 +1444,18 @@ def units(d=d, ph=ph, n_sub=n_sub): that a later trial's missing file does not stop the earlier ones. """ 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).""" @@ -1547,14 +1480,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( @@ -1614,9 +1543,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 @@ -1625,9 +1552,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) @@ -1644,14 +1569,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 " @@ -1667,9 +1590,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: @@ -1709,9 +1630,7 @@ def _ready_paths( # noqa: C901 still planned. With one worker everything runs here, in order. """ 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()] @@ -1728,13 +1647,9 @@ 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)), max(1, cpus // max(1, len(paths))) - ) + plan_pool = make_pool(max(1, len(paths)), max(1, cpus // max(1, len(paths)))) pools.append(plan_pool) pending = {d: 0 for d in paths} futures = {} @@ -1868,16 +1783,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): @@ -1941,9 +1852,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 []): diff --git a/src/giant_python/pipeline/silo_baseline.py b/src/giant_python/pipeline/silo_baseline.py index 4db8ce2d..e9b0f65b 100644 --- a/src/giant_python/pipeline/silo_baseline.py +++ b/src/giant_python/pipeline/silo_baseline.py @@ -136,10 +136,7 @@ def same_file(recorded: Optional[dict], path: Path) -> bool: 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 @@ -212,9 +209,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}" @@ -260,9 +255,7 @@ def f0_movie(moco_dir, stem: str) -> Optional[Path]: 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 @@ -294,9 +287,7 @@ def _check_kept(session, params, baseline_dir, units, todo, identity) -> None: 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( @@ -339,14 +330,10 @@ def _run(args: list, log: Path, verbose: bool): 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 -) -> list: +def _predict_args(exe, session, params, ckpt, baseline_dir, todo, device, out_frames) -> list: """Build the ``predict-registered`` command line for the trial-paths ``todo``. It uses the run's trial preparation settings. @@ -465,9 +452,7 @@ def predict_baselines( done=False, digests=digests, ) - args = _predict_args( - exe, session, params, ckpt, baseline_dir, todo, device, out_frames - ) + args = _predict_args(exe, session, params, ckpt, baseline_dir, todo, device, out_frames) t0 = time.perf_counter() log = baseline_dir / "predict.log" proc = _run(args, log, verbose) diff --git a/src/giant_python/pipeline/silo_collect.py b/src/giant_python/pipeline/silo_collect.py index 2bc314f8..379d601b 100644 --- a/src/giant_python/pipeline/silo_collect.py +++ b/src/giant_python/pipeline/silo_collect.py @@ -40,15 +40,11 @@ def _results_files(session: SiloSession, d: int, t: int) -> list: 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]: +def _container_hash(session, params, plan_hash, d, t, baseline_dir=None) -> Optional[str]: """Compute 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 @@ -95,10 +91,7 @@ def _current( 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: @@ -281,10 +274,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: @@ -329,9 +319,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 diff --git a/src/giant_python/pipeline/silo_session.py b/src/giant_python/pipeline/silo_session.py index 54209492..ebf8c214 100644 --- a/src/giant_python/pipeline/silo_session.py +++ b/src/giant_python/pipeline/silo_session.py @@ -98,13 +98,9 @@ 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] @@ -326,15 +322,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") @@ -409,16 +401,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( @@ -428,9 +413,7 @@ 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 @@ -444,9 +427,7 @@ def plan_file(self, d: int) -> Path: 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 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.""" @@ -481,9 +462,7 @@ def baselines_dir(self) -> Path: return self.work_dir / "baselines" -def write_skip( - path: Path, reason: str, settings_hash: str, plan_hash: str = "" -) -> None: +def write_skip(path: Path, reason: str, settings_hash: str, plan_hash: str = "") -> None: """Mark a trial-path as not extracted. Writes ``*.skip.json``: the reason, the settings hash of the prepare stage diff --git a/src/giant_python/pipeline/silo_solve.py b/src/giant_python/pipeline/silo_solve.py index 67794965..debb69e9 100644 --- a/src/giant_python/pipeline/silo_solve.py +++ b/src/giant_python/pipeline/silo_solve.py @@ -115,13 +115,11 @@ def solve_hash(params: SiloParams, options, container_hash: str, span) -> str: How, which container, which subproblems. """ - return stage_hash( - { - **_solve_record(params, options), - "container": container_hash, - "span": [int(span[0]), int(span[1])], - } - ) + return stage_hash({ + **_solve_record(params, options), + "container": container_hash, + "span": [int(span[0]), int(span[1])], + }) def with_f0_frames(subs: list, discard, params: SiloParams) -> list: @@ -165,10 +163,7 @@ 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))] @@ -206,9 +201,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), @@ -323,9 +316,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( @@ -454,23 +445,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) @@ -509,9 +494,7 @@ def read_job(path) -> dict: 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 @@ -561,8 +544,7 @@ def solve_job( h = attr(f, "settings_hash") if h != it["container_hash"]: raise ValueError( - f"{f} is not the container the job was made for " - "(settings hash differs)" + f"{f} is not the container the job was made for (settings hash differs)" ) done[it["results"]] = solve_container( f, diff --git a/src/giant_python/pipeline/silo_spots.py b/src/giant_python/pipeline/silo_spots.py index 7af48804..de9b282e 100644 --- a/src/giant_python/pipeline/silo_spots.py +++ b/src/giant_python/pipeline/silo_spots.py @@ -79,9 +79,7 @@ def _read_pixels( def take(blk, n_r, n_c): """Take the pixels of frames ``blk`` of an image ``n_r x n_c``.""" 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 @@ -91,19 +89,13 @@ 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) 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 @@ -112,9 +104,7 @@ def take(blk, n_r, n_c): def _check_pages(path, n_pages, pages_per_frame, page0, n) -> None: """Check that a file holds every page of the ``n`` frames asked for.""" 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, pages_per_frame, page0, n_frames, take): @@ -214,10 +204,7 @@ def _windows(warp, t, spots, settings): 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( @@ -241,9 +228,7 @@ def _delta_f(session, params, inputs, rows, cols): NaN at SILo's motion discards and outside the image. """ 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], @@ -283,11 +268,7 @@ 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 @@ -387,12 +368,8 @@ def coords(self, trial: int, rows, cols): 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 ( @@ -477,9 +454,7 @@ def _path_numbers(summary) -> int: Its paths need not all be there: a path without results is left out. """ 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) @@ -562,9 +537,7 @@ def annotate_spots( return report -def _annotate_path( - session, params, settings, summary, d, warp, bdir, verbose, pool -): +def _annotate_path(session, params, settings, summary, d, warp, bdir, verbose, pool): """Group, test, label and write one path's spots (``d`` zero-based). Return the number of spots per label, or None for a path without sources. @@ -577,9 +550,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) @@ -593,34 +564,23 @@ def _annotate_path( extent = float(np.max(np.hypot(*(src - c).T))) spots.append(dict(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] @@ -657,9 +617,7 @@ 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)} @@ -667,18 +625,10 @@ def row(v, dt): """Make a MATLAB row vector.""" 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( @@ -689,15 +639,9 @@ 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()) @@ -716,8 +660,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 3354c399..bc6fc13d 100644 --- a/src/giant_python/pipeline/trial_table.py +++ b/src/giant_python/pipeline/trial_table.py @@ -142,11 +142,7 @@ def _recording_mtime(dat_dir: Path, name: str, all_names) -> float: 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) @@ -154,26 +150,14 @@ def _name_timestamp(stamp: str) -> float: """``datenum`` of a yyyyMMddHHmmss string, or NaN if not a valid date.""" 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]: @@ -201,9 +185,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)) @@ -247,10 +229,7 @@ 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 "" @@ -274,25 +253,16 @@ def find(pattern): """Files below ``dat_dir`` matching a pattern, 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] @@ -355,9 +325,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"]), } @@ -430,9 +398,9 @@ def _paths_in_order(names, info, mtime): def _warn_copy_times(p1, p2, line_period_s, names_ok) -> 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 " @@ -579,10 +547,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} @@ -625,17 +590,13 @@ 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 @@ -685,9 +646,7 @@ def cols(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/registration/compensation.py b/src/giant_python/registration/compensation.py index 0eb1c7b4..fac5d87c 100644 --- a/src/giant_python/registration/compensation.py +++ b/src/giant_python/registration/compensation.py @@ -92,9 +92,7 @@ def dmd_y(x, y, switch_lines, lead=Y_LEAD) -> np.ndarray: return y_eff -def line_offsets( - layout: RasterLayout, lines: Tuple[int, int], lead=Y_LEAD -) -> LineOffsets: +def line_offsets(layout: RasterLayout, lines: Tuple[int, int], lead=Y_LEAD) -> LineOffsets: """Read the headers covering ``lines`` (``getLineOnlineOffsets``). Parameters @@ -138,9 +136,7 @@ def line_offsets( ) -def frame_offsets( - offsets: LineOffsets, times, dt: int, lines_per_cycle: int -) -> np.ndarray: +def frame_offsets(offsets: LineOffsets, times, dt: int, lines_per_cycle: int) -> np.ndarray: """Compute the offset each frame mostly saw (``frameOnlineOffsets``). Parameters @@ -167,9 +163,7 @@ 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 diff --git a/src/giant_python/registration/frames.py b/src/giant_python/registration/frames.py index 1814a75e..88fcf3a4 100644 --- a/src/giant_python/registration/frames.py +++ b/src/giant_python/registration/frames.py @@ -108,9 +108,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 +117,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,9 +127,7 @@ 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: @@ -155,9 +149,7 @@ 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") @@ -177,9 +169,7 @@ def _accumulate(self, local, w, channels, band=None): 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)) @@ -218,9 +208,7 @@ def _accumulate_band(self, local, w, used, channels, group, num, den) -> None: 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] @@ -230,9 +218,7 @@ def _accumulate_band(self, local, w, used, channels, group, num, den) -> None: num[k].index_add_(0, rows, add_n) den[k].index_add_(0, rows, add_d) - def sums( - self, times, dt: int, channels=None - ) -> Tuple[torch.Tensor, torch.Tensor]: + def sums(self, times, dt: int, channels=None) -> Tuple[torch.Tensor, torch.Tensor]: """Weighted sample sums of frames. Parameters @@ -299,9 +285,7 @@ def shifted_sums(self, times, dt: int, shift_fn, channels=None): num, den = self._accumulate(local[sel], wg, channels) yield (int(r), int(c)), sel, num, den - def frames( - self, times, dt: int, channels=None - ) -> Tuple[torch.Tensor, torch.Tensor]: + def frames(self, times, dt: int, channels=None) -> Tuple[torch.Tensor, torch.Tensor]: """Frames and freshness, as ``slap2Frames`` returns them. Returns @@ -344,9 +328,7 @@ def __init__(self, *args, **kwargs) -> None: ) 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, dt: int, channels=None, shift_fn=None): """Yield sums of frames, grouped by the displacement of their samples. @@ -395,9 +377,7 @@ def _pixel_accumulate(self, local, w, channels): lo = np.where(used, local, np.iinfo(np.int64).max).min((1, 2)) hi = np.where(used, local, -1).max((1, 2)) for group in _bands(lo, hi, self.band): - self._pixel_band( - local[group], w[group], used[group], channels, group, num, den - ) + self._pixel_band(local[group], w[group], used[group], channels, group, num, den) return num, den def _to_pixels(self, sums: torch.Tensor, index: torch.Tensor): @@ -435,14 +415,10 @@ def _pixel_band(self, local, w, used, channels, group, num, den) -> None: 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)) if bool(valid.all()): 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: s_den = torch.bmm(valid.to(torch.float64), wt) diff --git a/src/giant_python/registration/growth.py b/src/giant_python/registration/growth.py index 31d49268..ddfd7cef 100644 --- a/src/giant_python/registration/growth.py +++ b/src/giant_python/registration/growth.py @@ -71,9 +71,7 @@ class FrameCache: Larger caches are kept in CPU memory and moved per batch. """ - def __init__( - self, source, ds, chunk: int = 64, max_device_bytes: float = 3e9 - ) -> None: + def __init__(self, source, ds, chunk: int = 64, max_device_bytes: float = 3e9) -> None: """Form and store all frames.""" self.window = source.window self.device = source.former.device @@ -138,9 +136,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) @@ -217,14 +213,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 @@ -287,9 +280,7 @@ 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 @@ -325,9 +316,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]) @@ -358,9 +347,7 @@ def _accept(self, ks, motions, peaks, margins, anchors, kinds, roots) -> None: 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) @@ -402,13 +389,7 @@ def _plausible(self, k: int, motion) -> bool: def try_seeds(self, ks) -> 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) @@ -650,16 +631,11 @@ def _resolve(self, k: int, g: int, jump: float) -> None: } 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( @@ -702,8 +678,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, @@ -722,9 +697,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) @@ -778,9 +751,7 @@ def seeds_from_consensus(cons, init, ds, reach=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: @@ -793,9 +764,7 @@ def seeds_from_consensus(cons, init, ds, reach=None): members = set(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..bcd3fa91 100644 --- a/src/giant_python/registration/interpolation.py +++ b/src/giant_python/registration/interpolation.py @@ -18,9 +18,7 @@ def _corner(x: torch.Tensor, ri: torch.Tensor, ci: torch.Tensor): """Values at rows ``ri`` and columns ``ci``, NaN outside ``x``.""" 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")) @@ -85,9 +83,7 @@ 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) ] @@ -110,9 +106,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..c72ea374 100644 --- a/src/giant_python/registration/matching.py +++ b/src/giant_python/registration/matching.py @@ -57,9 +57,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 @@ -120,9 +118,7 @@ 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 @@ -146,21 +142,15 @@ def peak_motion( 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) @@ -276,9 +266,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) @@ -301,9 +289,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( @@ -346,9 +332,7 @@ def match( """ 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 79a1ee48..74995f19 100644 --- a/src/giant_python/registration/multiroi.py +++ b/src/giant_python/registration/multiroi.py @@ -126,8 +126,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 @@ -266,9 +265,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,24 +274,18 @@ 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 - ) + 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 - ) -> torch.Tensor: + def add(self, k: int, regs, var_factor: torch.Tensor, motion=None) -> torch.Tensor: """Record frame ``k``'s registered channels; return their sum. ``motion`` (row, column) is the frame's motion, which the summary @@ -454,9 +445,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) @@ -493,12 +482,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: @@ -531,10 +516,7 @@ def motion_failed(motion_r, motion_c) -> bool: 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( @@ -553,9 +535,7 @@ def alignment_fields( 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 { @@ -586,9 +566,7 @@ def alignment_fields( } -def open_trial( - dat_path, first_line, last_line, params, device, mask_unlit=True -): +def open_trial(dat_path, first_line, last_line, params, device, mask_unlit=True): """Read a trial's samples and frame times. ``mask_unlit`` (default) marks the samples taken behind the DMD curtain @@ -622,9 +600,7 @@ def open_trial( return layout, FrameFormer(layout, samples, c0, 1, device), init, ds, dtk -def trial_stats( - source, ds, margin: int, n_channels: int -) -> Optional[StatsWorker]: +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 @@ -756,9 +732,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") @@ -773,9 +747,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)) @@ -784,9 +756,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 0e0391f3..3d689c6f 100644 --- a/src/giant_python/registration/outputs.py +++ b/src/giant_python/registration/outputs.py @@ -122,9 +122,7 @@ def _compressors() -> ThreadPoolExecutor: """Shared pool that deflates chunks in parallel (zlib releases the GIL).""" 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 @@ -217,9 +215,7 @@ 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: @@ -414,9 +410,7 @@ def downsample2(image: np.ndarray) -> np.ndarray: """Sum 2 x 2 blocks (trailing odd row/column dropped; NaN propagates).""" 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): diff --git a/src/giant_python/registration/sources.py b/src/giant_python/registration/sources.py index cf229861..79ccc7a1 100644 --- a/src/giant_python/registration/sources.py +++ b/src/giant_python/registration/sources.py @@ -104,10 +104,7 @@ def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int) -> None: 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) @@ -147,9 +144,7 @@ class CompensatedFrames: Every frame time the trial will request (sets the pixel list). """ - def __init__( - self, former: FrameFormer, offsets: LineOffsets, dt: int, times - ) -> None: + def __init__(self, former: FrameFormer, offsets: LineOffsets, dt: int, times) -> None: """Trim to the raster's extent and list every reachable pixel.""" self.former = former self.compensation = offsets @@ -160,9 +155,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) @@ -232,18 +225,14 @@ def frames(self, 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.""" 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) @@ -308,9 +297,7 @@ def _sampled(former: FrameFormer, times, dt: int) -> np.ndarray: return out -def make_source( - layout, former, first_line, last_line, init, ds, dt, compensate: bool -): +def make_source(layout, former, first_line, last_line, init, ds, dt, compensate: bool): """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 549a5bac..14ebffd4 100644 --- a/src/giant_python/registration/stats/__init__.py +++ b/src/giant_python/registration/stats/__init__.py @@ -70,9 +70,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 1f09f5a4..d94055e9 100644 --- a/src/giant_python/registration/stats/accumulate.py +++ b/src/giant_python/registration/stats/accumulate.py @@ -127,9 +127,7 @@ def put(self, name: str, frames, values: torch.Tensor, fill) -> 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: @@ -149,8 +147,7 @@ def extend(self, n_new: int) -> None: 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() } @@ -187,9 +184,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 @@ -228,9 +223,7 @@ def __init__(self, geometry, gains, n_channels: int) -> None: 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) @@ -307,9 +300,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 = { @@ -322,18 +313,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 @@ -438,10 +425,7 @@ def _block(self, j: int) -> None: 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)) @@ -457,9 +441,7 @@ def finish(self) -> dict: See :func:`.maps.finish_maps`. """ 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() diff --git a/src/giant_python/registration/stats/gain.py b/src/giant_python/registration/stats/gain.py index 1f30cc67..98a5bb4e 100644 --- a/src/giant_python/registration/stats/gain.py +++ b/src/giant_python/registration/stats/gain.py @@ -199,9 +199,7 @@ def slot_sums(samples: torch.Tensor, channel: int) -> np.ndarray: 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) @@ -297,9 +295,7 @@ def pair_curve(sums: np.ndarray, n_bins: int = N_BINS) -> dict: mean and split into ``n_bins`` groups of equal size. """ # 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 = [] @@ -314,11 +310,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, @@ -345,9 +337,7 @@ def curve_from_sums(sums: np.ndarray, n_bins: int = N_BINS) -> GainCurve: without zeros keeps its gains; its non-zero rate is NaN. """ # 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")] @@ -359,9 +349,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] @@ -374,9 +362,7 @@ 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 -) -> list: +def measure_gain_curves(samples: torch.Tensor, nxt=None, n_bins: int = N_BINS) -> list: """Every channel's :class:`GainCurve` from a trial's raw samples. Parameters @@ -397,9 +383,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 b83626c9..3a1124df 100644 --- a/src/giant_python/registration/stats/geometry.py +++ b/src/giant_python/registration/stats/geometry.py @@ -77,9 +77,7 @@ CORNERS = ((0, 0), (0, 1), (1, 0), (1, 1)) """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.""" @@ -113,17 +111,15 @@ 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) @@ -162,9 +158,7 @@ def pair_bin_factor(frac, shares: dict) -> float: 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]) @@ -241,9 +235,7 @@ def __init__(self, source, ds, margin: int) -> None: 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 " @@ -254,9 +246,7 @@ def __init__(self, source, ds, margin: int) -> None: 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 @@ -272,9 +262,7 @@ def __init__(self, source, ds, margin: int) -> None: 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 @@ -303,9 +291,7 @@ 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] @@ -322,9 +308,7 @@ def _pair_shares(self) -> dict: 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) -> torch.Tensor: """``(P, n_win + 1)`` float32: slots on line ``l`` of the window pixel. @@ -336,9 +320,7 @@ def adjacency(self, dr: int, dc: int, delta) -> torch.Tensor: 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) @@ -367,9 +349,7 @@ def incidence(self, dr: int, dc: int) -> torch.Tensor: 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]): @@ -386,13 +366,9 @@ def _groups(self, f0: int, f_ext: int, lines, ok): """``[((dr, dc), mask)]``: samples of each displacement.""" 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. @@ -417,9 +393,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 @@ -447,20 +423,16 @@ 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]) @@ -509,9 +481,7 @@ 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 @@ -535,15 +505,11 @@ def corners(self, motion: np.ndarray, present: np.ndarray): 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 @@ -616,9 +582,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): @@ -752,8 +716,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/maps.py b/src/giant_python/registration/stats/maps.py index 7f4ae8bc..e8572a13 100644 --- a/src/giant_python/registration/stats/maps.py +++ b/src/giant_python/registration/stats/maps.py @@ -72,12 +72,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, @@ -134,14 +130,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 { @@ -226,18 +218,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") @@ -254,9 +240,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, diff --git a/src/giant_python/registration/stats/session.py b/src/giant_python/registration/stats/session.py index 2d44aa5a..d5d34c1e 100644 --- a/src/giant_python/registration/stats/session.py +++ b/src/giant_python/registration/stats/session.py @@ -63,9 +63,7 @@ def _normalised(m: dict) -> dict: return out -def _resample( - img: np.ndarray, warp, trial: int, shape, coords=None -) -> np.ndarray: +def _resample(img: np.ndarray, warp, trial: int, shape, coords=None) -> np.ndarray: """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 @@ -79,9 +77,7 @@ def _resample( 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, ) @@ -122,15 +118,10 @@ def combine_trials(stats: list, warp=None, shifts=None) -> dict: 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 = {}, {}, {} @@ -157,9 +148,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/worker.py b/src/giant_python/registration/stats/worker.py index ef99a418..204a0a5c 100644 --- a/src/giant_python/registration/stats/worker.py +++ b/src/giant_python/registration/stats/worker.py @@ -131,9 +131,7 @@ def add(self, k: int, regs, var_factor, motion) -> None: 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. diff --git a/src/giant_python/registration/template.py b/src/giant_python/registration/template.py index 2bee4040..5029897a 100644 --- a/src/giant_python/registration/template.py +++ b/src/giant_python/registration/template.py @@ -101,14 +101,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) @@ -165,9 +161,7 @@ def _template(self) -> torch.Tensor: 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() diff --git a/src/giant_python/simulation/injection.py b/src/giant_python/simulation/injection.py index 745c204a..bc881090 100644 --- a/src/giant_python/simulation/injection.py +++ b/src/giant_python/simulation/injection.py @@ -122,9 +122,7 @@ def _rng(seed: int, *key: int) -> np.random.Generator: """Make 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) - ) + ss = np.random.SeedSequence(int(seed), spawn_key=tuple(int(k) for k in key)) return np.random.default_rng(ss) @@ -233,12 +231,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", ), ( @@ -267,10 +260,7 @@ def __post_init__(self): ), ( 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"), @@ -357,9 +347,7 @@ 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) - ) + return peak_delay_s(settings.tau_s, settings.rise_s) + settings.tau_s * (6 * math.log(10)) @dataclass @@ -391,27 +379,23 @@ class Events: def empty(cls) -> "Events": """No 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.""" 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: """Return the number of events.""" @@ -508,9 +492,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), @@ -560,9 +542,7 @@ def event_traces( 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 @@ -641,9 +621,7 @@ def __init__(self, image, center: Optional[Sequence[float]] = None) -> 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]), @@ -655,9 +633,7 @@ def __call__(self, dr, dc) -> np.ndarray: 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: @@ -897,11 +873,7 @@ def place_sources( 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]) @@ -1006,9 +978,7 @@ def shift_image(image: np.ndarray, shift, shape=None) -> np.ndarray: 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 @@ -1136,12 +1106,8 @@ def motion_at(alignment: Alignment, lines) -> np.ndarray: 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 @@ -1329,9 +1295,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 @@ -1431,11 +1395,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( @@ -1460,9 +1420,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) @@ -1544,10 +1502,7 @@ 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 @@ -1615,9 +1570,7 @@ def _frame_lines(first, last, line_hz: float, hz: float) -> np.ndarray: """``ceil(first:dt:last)`` (SILo's 200 Hz frame lines).""" 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 @@ -1669,25 +1622,16 @@ def plan_path( 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 @@ -1785,9 +1729,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 @@ -1799,9 +1741,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) @@ -1923,9 +1863,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, @@ -1944,12 +1882,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: @@ -2050,8 +1985,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), @@ -2066,9 +2000,7 @@ def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]: def _path_gain(settings: InjectionSettings, layout: RasterLayout): """Raw units per photon: given, or measured on the reference trial.""" 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) @@ -2126,8 +2058,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, @@ -2140,9 +2071,7 @@ def _inject_path(ctx: dict, cells: list, options: dict) -> dict: """Plan, calibrate and inject one path (see :func:`inject_session`).""" 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"], @@ -2157,9 +2086,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( @@ -2170,9 +2097,7 @@ 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 @@ -2208,8 +2133,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(), @@ -2299,18 +2223,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 @@ -2318,10 +2237,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(), @@ -2373,19 +2289,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), @@ -2394,9 +2303,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"]), @@ -2465,20 +2372,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 = int(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) @@ -2487,16 +2388,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"]} @@ -2629,9 +2524,7 @@ def registration_offset(original: Alignment, copy: Alignment) -> dict: 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: @@ -2666,9 +2559,7 @@ def record_copy_registration(out_dir: Union[str, Path]) -> dict: 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: @@ -2685,9 +2576,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"] @@ -2716,9 +2605,7 @@ def _add_inject_args(ap: argparse.ArgumentParser) -> None: 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, @@ -2736,9 +2623,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) @@ -2770,25 +2655,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( @@ -2806,9 +2686,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 " @@ -2822,9 +2700,7 @@ def _settings_from_args(args) -> Tuple[InjectionSettings, PlacementSettings]: """Build the settings of ``inject``.""" 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, diff --git a/src/giant_python/simulation/render.py b/src/giant_python/simulation/render.py index 10bb0997..a194070a 100644 --- a/src/giant_python/simulation/render.py +++ b/src/giant_python/simulation/render.py @@ -63,15 +63,12 @@ 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: +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). Parameters diff --git a/src/giant_python/spine/coverage.py b/src/giant_python/spine/coverage.py index 8fb0a43f..c8f70ec8 100644 --- a/src/giant_python/spine/coverage.py +++ b/src/giant_python/spine/coverage.py @@ -129,9 +129,7 @@ def _dark(chans: list, missing: np.ndarray, frac: float) -> np.ndarray: # 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: with warnings.catch_warnings(): @@ -171,9 +169,7 @@ 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 diff --git a/src/giant_python/spine/gains.py b/src/giant_python/spine/gains.py index 7aab918c..0697c1a2 100644 --- a/src/giant_python/spine/gains.py +++ b/src/giant_python/spine/gains.py @@ -106,9 +106,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." @@ -142,14 +140,9 @@ def _subproblem_gains(path, k: int, g: h5py.Group): """ 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 " @@ -158,9 +151,7 @@ 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 @@ -205,10 +196,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: @@ -238,9 +226,7 @@ def results_files(work_dir, path: int, trial: int) -> list: 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 [] diff --git a/src/giant_python/spine/images.py b/src/giant_python/spine/images.py index 4238568e..56b12436 100644 --- a/src/giant_python/spine/images.py +++ b/src/giant_python/spine/images.py @@ -96,9 +96,7 @@ def read_rec_neg_err(alignment_path) -> np.ndarray: return np.asarray(f["recNegErr"][()], dtype=np.float64).ravel() -def baseline_trial_mean( - path, keep: np.ndarray, chunk: int = 64 -) -> tuple[np.ndarray, int]: +def baseline_trial_mean(path, keep: np.ndarray, chunk: int = 64) -> tuple[np.ndarray, int]: """Mean of a network baseline file over the kept frames. The file is read in blocks of ``chunk`` frames, so a trial never has to @@ -126,9 +124,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) for i0 in range(0, ds.shape[0], chunk): @@ -144,9 +140,7 @@ def baseline_trial_mean( return np.ascontiguousarray(mean.T), int(keep.sum()) -def to_consensus( - image: np.ndarray, trial_map, trial: int, shape: tuple[int, int] -) -> np.ndarray: +def to_consensus(image: np.ndarray, trial_map, trial: int, shape: tuple[int, int]) -> np.ndarray: """Resample a trial's image into the consensus frame. Parameters diff --git a/src/giant_python/spine/pipeline.py b/src/giant_python/spine/pipeline.py index e95031f6..a8cf3d75 100644 --- a/src/giant_python/spine/pipeline.py +++ b/src/giant_python/spine/pipeline.py @@ -136,8 +136,7 @@ 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 @@ -194,9 +193,7 @@ def _normalize(r: dict, images: dict, window: list, used) -> dict: return norm -def _trends( - n, norm: dict, acq, opts: dict, workers, say, note, activity_channel=1 -) -> tuple: +def _trends(n, norm: dict, acq, opts: dict, workers, say, note, activity_channel=1) -> tuple: """Run the trend tests of every image's normalized source sizes. :func:`~giant_python.spine.trends.trend_tests`, over the trials in which @@ -270,9 +267,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) @@ -308,15 +303,11 @@ def _check_coverage_settings(frac, dilate, min_window, max_share) -> None: 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, images: dict, opts: tuple, report, note): @@ -329,22 +320,15 @@ def _leave_out_unimaged(n, images: dict, opts: tuple, report, note): 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,18 +339,13 @@ 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 @@ -398,9 +377,7 @@ def _sized_images(norm: dict) -> list: An image can keep its key with none, e.g. one that covers no window. """ 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() ] @@ -498,9 +475,7 @@ def _write_atomic(dest, write) -> None: 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: @@ -528,12 +503,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", @@ -727,9 +700,7 @@ def make_spine_summary( # noqa: C901 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) @@ -774,9 +745,7 @@ def make_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), @@ -792,8 +761,7 @@ def make_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) @@ -826,10 +794,7 @@ def prog(t, total, stem, n=n) -> None: 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)) ], } @@ -903,12 +868,8 @@ def note(msg) -> None: 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] @@ -925,9 +886,7 @@ def note(msg) -> None: ) 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 " @@ -959,10 +918,7 @@ def note(msg) -> None: # 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(): @@ -977,12 +933,8 @@ def note(msg) -> None: 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: @@ -1009,9 +961,7 @@ def note(msg) -> None: 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, @@ -1052,22 +1002,18 @@ def note(msg) -> None: "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 d8dca5bf..abc47481 100644 --- a/src/giant_python/spine/product.py +++ b/src/giant_python/spine/product.py @@ -138,9 +138,7 @@ def write_roiset(g: h5py.Group, rois: RoiSet) -> None: def read_roiset(g: h5py.Group, shape: tuple) -> RoiSet: """Read an :class:`RoiSet` stored by :func:`write_roiset`.""" - labels = [ - x.decode() if isinstance(x, bytes) else str(x) for x in g["labels"][()] - ] + labels = [x.decode() if isinstance(x, bytes) else str(x) for x in g["labels"][()]] return RoiSet( kind=str(g.attrs["kind"]), shape=tuple(shape), @@ -206,14 +204,10 @@ def _write_unimaged(g: h5py.Group, unimaged) -> None: if unimaged is None: return un = np.asarray(unimaged, np.uint8) - g.create_dataset( - "unimaged", data=un, chunks=(1,) + un.shape[1:], **_IMAGE_OPTS - ) + g.create_dataset("unimaged", data=un, chunks=(1,) + un.shape[1:], **_IMAGE_OPTS) -def write_product( - path, paths: dict, settings: dict, inputs: dict, run_dir, report=None -) -> None: +def write_product(path, paths: dict, settings: dict, inputs: dict, run_dir, report=None) -> None: """Write a ``spine_summary`` file. Parameters @@ -257,12 +251,8 @@ def write_product( **_IMAGE_OPTS, ) for ak, av in attrs.items(): - d.attrs[ak] = ( - av if not isinstance(av, dict) else json.dumps(av) - ) - g.create_dataset( - "valid", data=np.asarray(p["valid"], np.uint8), **_IMAGE_OPTS - ) + d.attrs[ak] = av if not isinstance(av, dict) else json.dumps(av) + g.create_dataset("valid", data=np.asarray(p["valid"], np.uint8), **_IMAGE_OPTS) _write_unimaged(g, p.get("unimaged")) for set_name, rois in p["rois"].items(): write_roiset(g.create_group(f"rois/{set_name}"), rois) @@ -305,20 +295,13 @@ def read_product(path) -> dict: } for grp in ("trials", "reference", "images"): p[grp] = {k: g[grp][k][()] for k in g.get(grp, {})} - p["image_attrs"] = { - k: dict(g["images"][k].attrs) for k in g.get("images", {}) - } + p["image_attrs"] = {k: dict(g["images"][k].attrs) for k in g.get("images", {})} p["valid"] = g["valid"][()].astype(bool) if "unimaged" in g: p["unimaged"] = g["unimaged"][()].astype(bool) - p["rois"] = { - k: read_roiset(g["rois"][k], shape) for k in g.get("rois", {}) - } + p["rois"] = {k: read_roiset(g["rois"][k], shape) for k in g.get("rois", {})} for grp in ("readout", "normalized", "activity"): - p[grp] = { - s: {k: g[grp][s][k][()] for k in g[grp][s]} - for s in g.get(grp, {}) - } + p[grp] = {s: {k: g[grp][s][k][()] for k in g[grp][s]} for s in g.get(grp, {})} p["trends"] = { s: { name: dict({k: t[k][()] for k in t}, attrs=dict(t.attrs)) diff --git a/src/giant_python/spine/qc.py b/src/giant_python/spine/qc.py index 2ccc8fd4..9dbea8c9 100644 --- a/src/giant_python/spine/qc.py +++ b/src/giant_python/spine/qc.py @@ -64,9 +64,7 @@ def structural_image(names, activity_channel: int) -> str | None: return f"mean_ch{min(chans)}" if chans else None -def window_motion( - tmap, rois: RoiSet, valid: np.ndarray, trials, shape -) -> np.ndarray: +def window_motion(tmap, rois: RoiSet, valid: np.ndarray, trials, shape) -> np.ndarray: """Each window's movement beyond its trial's overall shift. Given as a spread across ``trials`` (pixels; see the module's notes). @@ -105,9 +103,7 @@ def window_motion( idx, w = rois.pixels(k) keep = vflat[idx] & (w > 0) idx, w = idx[keep], w[keep] - weights.append( - (idx, w / w.sum()) if idx.size and w.sum() > 0 else None - ) + weights.append((idx, w / w.sum()) if idx.size and w.sum() > 0 else None) rr = np.arange(shape[0], dtype=np.float64)[:, None] cc = np.arange(shape[1], dtype=np.float64)[None, :] rr, cc = np.broadcast_arrays(rr, cc) diff --git a/src/giant_python/spine/readout.py b/src/giant_python/spine/readout.py index 2885c7c8..752a17b7 100644 --- a/src/giant_python/spine/readout.py +++ b/src/giant_python/spine/readout.py @@ -4,7 +4,7 @@ pixels valid in every trial and normalized to sum 1, and a trial's image ``x``:: - F = (h . x) / (h . h) + F = (h.x) / (h.h) as GIAnT-MATLAB's ``spineTrends.m``. Restricting ``h`` to pixels valid in all trials keeps the window identical across trials, so a pixel that drops @@ -47,9 +47,7 @@ def common_valid(stacks, trials=None) -> np.ndarray: stacks = [np.asarray(s) for s in stacks] if trials is None: first = stacks[0] - trials = np.flatnonzero( - np.isfinite(first.reshape(first.shape[0], -1)).any(axis=1) - ) + trials = np.flatnonzero(np.isfinite(first.reshape(first.shape[0], -1)).any(axis=1)) trials = np.asarray(trials, dtype=np.int64) if trials.size == 0: return np.zeros(stacks[0].shape[1:], bool) diff --git a/src/giant_python/spine/rois.py b/src/giant_python/spine/rois.py index d4cb6495..b682899b 100644 --- a/src/giant_python/spine/rois.py +++ b/src/giant_python/spine/rois.py @@ -79,9 +79,7 @@ def image(self, k: int) -> np.ndarray: return out -def _from_images( - kind: str, weights: np.ndarray, ids, labels, min_rel: float -) -> RoiSet: +def _from_images(kind: str, weights: np.ndarray, ids, labels, min_rel: float) -> RoiSet: """Build an :class:`RoiSet` from dense weight images ``(R, rows, cols)``. Keeps pixels above ``min_rel`` of each image's maximum. @@ -101,12 +99,8 @@ def _from_images( weight.append(vals) ptr.append(ptr[-1] + flat.size) total = vals.sum() - rows.append( - (rr.ravel()[flat] * vals).sum() / total if total else np.nan - ) - cols.append( - (cc.ravel()[flat] * vals).sum() / total if total else np.nan - ) + rows.append((rr.ravel()[flat] * vals).sum() / total if total else np.nan) + cols.append((cc.ravel()[flat] * vals).sum() / total if total else np.nan) return RoiSet( kind=kind, shape=(h, w), @@ -115,9 +109,7 @@ def _from_images( rows=np.asarray(rows, dtype=np.float64), cols=np.asarray(cols, dtype=np.float64), ptr=np.asarray(ptr, dtype=np.int64), - index=( - np.concatenate(index) if index else np.zeros(0, np.int64) - ).astype(np.int64), + index=(np.concatenate(index) if index else np.zeros(0, np.int64)).astype(np.int64), weight=np.concatenate(weight) if weight else np.zeros(0), ) @@ -143,14 +135,10 @@ def masks_roiset(masks: np.ndarray, labels: list) -> RoiSet: masks = np.asarray(masks, dtype=bool) if len(labels) != masks.shape[0]: raise ValueError(f"{masks.shape[0]} masks but {len(labels)} labels") - return _from_images( - "user", masks.astype(np.float64), np.arange(masks.shape[0]), labels, 0 - ) + return _from_images("user", masks.astype(np.float64), np.arange(masks.shape[0]), labels, 0) -def disks_roiset( - rows, cols, radius: float, shape: tuple, labels: list | None = None -) -> RoiSet: +def disks_roiset(rows, cols, radius: float, shape: tuple, labels: list | None = None) -> RoiSet: """Disks of ``radius`` pixels around points (weight 1).""" rows = np.asarray(rows, dtype=np.float64).ravel() cols = np.asarray(cols, dtype=np.float64).ravel() diff --git a/src/giant_python/spine/summary_io.py b/src/giant_python/spine/summary_io.py index b307d2d4..d01718ed 100644 --- a/src/giant_python/spine/summary_io.py +++ b/src/giant_python/spine/summary_io.py @@ -131,9 +131,7 @@ def aligned(self) -> np.ndarray: return np.isfinite(d).any(axis=1) return np.isfinite(self.affine).all(axis=(1, 2)) - def grid_coords( - self, trial: int, shape: tuple[int, int] - ) -> tuple[np.ndarray, np.ndarray]: + def grid_coords(self, trial: int, shape: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]: """Positions in the trial's registered image of every consensus pixel. One per pixel of the ``(rows, cols)`` consensus grid (zero-based). @@ -145,8 +143,7 @@ def grid_coords( d = self.displacement[trial].astype(np.float64) if d.shape[1:] != tuple(shape): raise ValueError( - f"displacement field {d.shape[1:]} does not match the " - f"frame {tuple(shape)}" + f"displacement field {d.shape[1:]} does not match the frame {tuple(shape)}" ) return rr + d[0], cc + d[1] a = self.affine[trial] @@ -178,9 +175,7 @@ def __init__(self, run_dir) -> None: with h5py.File(self.experiment_path, "r") as f: self._row_major = _row_major(f) self.paths = sorted( - int(k[4:]) - for k in f.keys() - if k.startswith("Path") and k[4:].isdigit() + int(k[4:]) for k in f.keys() if k.startswith("Path") and k[4:].isdigit() ) def _exp(self) -> h5py.File: @@ -365,9 +360,7 @@ def activity(self, path: int) -> dict: n_src = ds.shape[0] if self._row_major else ds.shape[-1] # one trial at a time: a session's traces can take GBs out[name] = _per_trial( - lambda a, b: read_array( - ds, self._row_major, (slice(None), ch, slice(a, b)) - ), + lambda a, b: read_array(ds, self._row_major, (slice(None), ch, slice(a, b))), edges, n_src, name == "mean_dF", diff --git a/src/giant_python/spine/trends.py b/src/giant_python/spine/trends.py index f9594b93..43f949f1 100644 --- a/src/giant_python/spine/trends.py +++ b/src/giant_python/spine/trends.py @@ -135,9 +135,7 @@ def image_blocks(path_blocks, rows) -> np.ndarray: return np.cumsum(new).astype(np.int64) -def check_trend_settings( - n_perm, fdr_q, max_brief, seed, min_change=0.1 -) -> None: +def check_trend_settings(n_perm, fdr_q, max_brief, seed, min_change=0.1) -> None: """Refuse settings the tests cannot use (ValueError). ``n_perm`` must be at least 0, ``max_brief`` at least 1, ``fdr_q`` in @@ -150,9 +148,7 @@ def check_trend_settings( if int(n_perm) != n_perm or n_perm < 0: raise ValueError(f"n_perm must be a whole number >= 0, not {n_perm}") if int(max_brief) != max_brief or max_brief < 1: - raise ValueError( - f"max_brief must be a whole number >= 1, not {max_brief}" - ) + raise ValueError(f"max_brief must be a whole number >= 1, not {max_brief}") if not 0 < fdr_q <= 1: raise ValueError(f"fdr_q must be in (0, 1], not {fdr_q}") if int(seed) != seed or seed < 0: @@ -238,9 +234,7 @@ def step_at(x: np.ndarray, k): if ss <= _SS_RTOL * ((x[i] - x[i].mean()) ** 2).sum(): ss = 0.0 with np.errstate(invalid="ignore", divide="ignore"): - t[i] = d[i] / ( - math.sqrt(ss / (T - 2)) * math.sqrt(1 / k[i] + 1 / (T - k[i])) - ) + t[i] = d[i] / (math.sqrt(ss / (T - 2)) * math.sqrt(1 / k[i] + 1 / (T - k[i]))) return t, d @@ -273,10 +267,7 @@ def _median_without(srt, removed, m: int) -> np.ndarray: return np.full(srt.shape[0], np.nan) if m % 2: return _kth_without(srt, removed, (m - 1) // 2) - return ( - _kth_without(srt, removed, m // 2 - 1) - + _kth_without(srt, removed, m // 2) - ) / 2 + return (_kth_without(srt, removed, m // 2 - 1) + _kth_without(srt, removed, m // 2)) / 2 def brief_stat(x: np.ndarray, blocks, max_len: int = 3): @@ -320,9 +311,7 @@ def brief_stat(x: np.ndarray, blocks, max_len: int = 3): order = np.argsort(sub, axis=1, kind="stable") srt = np.take_along_axis(sub, order, axis=1) rank = np.empty_like(order) - np.put_along_axis( - rank, order, np.broadcast_to(np.arange(m_all), order.shape), axis=1 - ) + np.put_along_axis(rank, order, np.broadcast_to(np.arange(m_all), order.shape), axis=1) col_of = np.full(T - 1, -1, np.int64) col_of[cols] = np.arange(m_all) for w in range(1, max_len + 1): @@ -333,15 +322,9 @@ def brief_stat(x: np.ndarray, blocks, max_len: int = 3): continue # the steps that touch the run (a-1 .. e) are all within the block removed = rank[:, col_of[a - 1 : e + 1]] - sg = _median_without(srt, removed, m_all - (w + 1)) / ( - _MAD_SD * math.sqrt(2) - ) + sg = _median_without(srt, removed, m_all - (w + 1)) / (_MAD_SD * math.sqrt(2)) left = [i for i in range(max(a - 2, 0), a) if blocks[i] == b] - right = [ - i - for i in range(e + 1, min(e + 2, T - 1) + 1) - if blocks[i] == b - ] + right = [i for i in range(e + 1, min(e + 2, T - 1) + 1) if blocks[i] == b] m = x[:, a : e + 1].mean(axis=1) ml = x[:, left].mean(axis=1) mr = x[:, right].mean(axis=1) @@ -429,9 +412,7 @@ def trial_orders(seed: int, source: int, n_perm: int, n_trials: int): """ if n_perm <= 0: return np.zeros((0, n_trials), np.int64) - return np.concatenate( - list(_order_chunks(seed, source, n_perm, n_trials, n_perm)) - ) + return np.concatenate(list(_order_chunks(seed, source, n_perm, n_trials, n_perm))) def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): @@ -470,9 +451,7 @@ def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): ) -def _perm_p( - x, resid, t_obs, seed, source, n_perm, blocks, max_brief, rows=None -): +def _perm_p(x, resid, t_obs, seed, source, n_perm, blocks, max_brief, rows=None): """One source's permutation p-values of the step, brief and resid tests. ``t_obs``: the observed statistics, in that order. From the trial orders @@ -494,9 +473,7 @@ def _perm_p( return [(1 + h) / (n_perm + 1) for h in hits] -def _permute( - out, idx, x, resid, seed, n_perm, blocks, max_brief, workers, progress -) -> None: +def _permute(out, idx, x, resid, seed, n_perm, blocks, max_brief, workers, progress) -> None: """Fill ``out``'s step, brief and resid p-values of the sources ``idx``. The sources are rows of ``x`` and ``resid``; in threads (numpy releases @@ -513,9 +490,7 @@ def one(j): """p-values of the j-th tested source.""" s = idx[j] t_obs = [out[f"{nm}_t"][s] for nm in names] - return _perm_p( - x[j], resid[j], t_obs, seed, s, n_perm, blocks, max_brief - ) + return _perm_p(x[j], resid[j], t_obs, seed, s, n_perm, blocks, max_brief) with ThreadPoolExecutor(max(1, int(workers))) as pool: for j, ps in enumerate(pool.map(one, range(idx.size))): @@ -660,11 +635,7 @@ def trend_tests( } with np.errstate(invalid="ignore"): d = out["resid_d"] - out["call"] = ( - tested - & (out["resid_q"] <= fdr_q) - & (np.abs(np.expm1(d)) >= min_change) - ) + out["call"] = tested & (out["resid_q"] <= fdr_q) & (np.abs(np.expm1(d)) >= min_change) counts["call"] = { "up": int(np.count_nonzero(out["call"] & (d > 0))), "down": int(np.count_nonzero(out["call"] & (d < 0))), diff --git a/src/giant_python/spine/view/data.py b/src/giant_python/spine/view/data.py index 546cfae7..9eeef14f 100644 --- a/src/giant_python/spine/view/data.py +++ b/src/giant_python/spine/view/data.py @@ -73,9 +73,7 @@ def blur_nan(img: np.ndarray, sigma: float = BLUR_SIGMA) -> np.ndarray: a = np.where(m, img, 0.0).astype(np.float64) trunc = math.ceil(2 * sigma) / sigma num = gaussian_filter(a, sigma, mode="nearest", truncate=trunc) - den = gaussian_filter( - m.astype(np.float64), sigma, mode="nearest", truncate=trunc - ) + den = gaussian_filter(m.astype(np.float64), sigma, mode="nearest", truncate=trunc) with np.errstate(invalid="ignore", divide="ignore"): out = num / den out[~m] = np.nan @@ -167,9 +165,7 @@ def get(self, key, make): self.d[key] = val self.sizes[key] = _nbytes(val) self.d.move_to_end(key) - while len(self.d) > 1 and ( - sum(self.sizes.values()) > self.max_bytes - ): + while len(self.d) > 1 and (sum(self.sizes.values()) > self.max_bytes): old, _ = self.d.popitem(last=False) self.sizes.pop(old, None) return val @@ -193,9 +189,7 @@ class SpineProduct: activity) are read at once; the per-trial images per request. """ - def __init__( - self, path, name: str | None = None, cache_bytes: int = 2 * 1024**3 - ) -> None: + def __init__(self, path, name: str | None = None, cache_bytes: int = 2 * 1024**3) -> None: """Open ``path`` (checked for the format).""" self.file = Path(path) self.name = name or self.file.stem @@ -267,10 +261,7 @@ def _read_path(g) -> dict: rois = g.get("rois", {}) p["rois"] = {k: read_roiset(rois[k], shape) for k in rois} for grp in ("readout", "normalized", "activity"): - p[grp] = { - s: {k: g[grp][s][k][()] for k in g[grp][s]} - for s in g.get(grp, {}) - } + p[grp] = {s: {k: g[grp][s][k][()] for k in g[grp][s]} for s in g.get(grp, {})} p["trends"] = { s: { name: dict({k: t[k][()] for k in t}, attrs=dict(t.attrs)) @@ -278,9 +269,7 @@ def _read_path(g) -> dict: } for s in g.get("trends", {}) } - p["reference"] = { - k: g["reference"][k][()] for k in g.get("reference", {}) - } + p["reference"] = {k: g["reference"][k][()] for k in g.get("reference", {})} return p def path(self, n: int) -> dict: @@ -313,9 +302,7 @@ def make(): has = np.isfinite(st.reshape(st.shape[0], -1)).any(axis=1) trials = np.flatnonzero(has) common = ( - np.isfinite(st[trials]).all(axis=0) - if trials.size - else np.zeros(st.shape[1:], bool) + np.isfinite(st[trials]).all(axis=0) if trials.size else np.zeros(st.shape[1:], bool) ) med = np.full(st.shape[0], np.nan, np.float32) for t in trials: @@ -482,9 +469,7 @@ def meta(self) -> dict: paths[n] = { "shape": list(p["shape"]), "acquisition": tr["acquisition"].tolist(), - "used": tr.get("used", np.ones(len(tr["acquisition"]))) - .astype(bool) - .tolist(), + "used": tr.get("used", np.ones(len(tr["acquisition"]))).astype(bool).tolist(), "blocks": pr.blocks(n).tolist(), "images": [ { @@ -495,9 +480,7 @@ def meta(self) -> dict: for k, a in p["images"].items() ], "normalized": sorted( - k - for k in p["normalized"].get("sources", {}) - if k != "ok" + k for k in p["normalized"].get("sources", {}) if k != "ok" ), "trends": sorted(p["trends"].get("sources", {})), "n_sources": len(p["rois"].get("sources", [])), @@ -506,18 +489,16 @@ def meta(self) -> dict: "primary_image": p.get("primary_image"), "has_activity_image": "act_im" in p["reference"], } - out.append( - { - "index": i, - "name": pr.name, - "file": str(pr.file), - "run_dir": sm["attrs"]["run_dir"], - "created": sm["attrs"]["created"], - "settings": sm["attrs"]["settings"], - "notes": sm["attrs"]["report"].get("notes", []), - "paths": paths, - } - ) + out.append({ + "index": i, + "name": pr.name, + "file": str(pr.file), + "run_dir": sm["attrs"]["run_dir"], + "created": sm["attrs"]["created"], + "settings": sm["attrs"]["settings"], + "notes": sm["attrs"]["report"].get("notes", []), + "paths": paths, + }) return { "products": out, "marks_file": str(self.marks_path) if self.marks_path else None, @@ -557,32 +538,23 @@ def sources(self, i: int, n: int) -> dict: if k != "attrs" } trends[name]["attrs"] = { - k: (v.item() if hasattr(v, "item") else v) - for k, v in t["attrs"].items() + k: (v.item() if hasattr(v, "item") else v) for k, v in t["attrs"].items() } return { "n": len(rs), "ids": rs.ids.tolist(), "rows": rs.rows.tolist(), "cols": rs.cols.tolist(), - "n_pixels": p["readout"] - .get("sources", {}) - .get("n_pixels", np.zeros(len(rs))) - .tolist(), + "n_pixels": p["readout"].get("sources", {}).get("n_pixels", np.zeros(len(rs))).tolist(), # summaries before format 4 have no window-motion column "align_px": p["readout"] .get("sources", {}) .get("align_px", np.full(len(rs), np.nan)) .tolist(), "ok": norm.get("ok", np.zeros(len(rs), bool)).tolist(), - "normalized": { - k: v.tolist() for k, v in norm.items() if k != "ok" - }, + "normalized": {k: v.tolist() for k, v in norm.items() if k != "ok"}, "trends": trends, - "activity": { - k: v.tolist() - for k, v in p["activity"].get("sources", {}).items() - }, + "activity": {k: v.tolist() for k, v in p["activity"].get("sources", {}).items()}, "marks": self.marks_for(i, n), } @@ -678,9 +650,7 @@ def marks_for(self, i: int, n: int) -> dict: } return {"by_source": by, "unattached": off} - def set_mark( - self, i: int, n: int, k: int, label, note: str, row=None, col=None - ): + def set_mark(self, i: int, n: int, k: int, label, note: str, row=None, col=None): """Mark source ``k``, keyed by its position; returns the path's marks. ``label`` '' clears its marks; None keeps the label the source has, @@ -715,17 +685,15 @@ def set_mark( drop = {id(m) for m in mine} marks = [m for m in marks if id(m) not in drop] if label: - marks.append( - { - "Path": n, - "Source": int(rs.ids[k]) + 1, - "Label": label, - "Note": note or "", - "Row0": float(rs.rows[k]), - "Col0": float(rs.cols[k]), - "Updated": time.strftime("%Y-%m-%d %H:%M:%S"), - } - ) + marks.append({ + "Path": n, + "Source": int(rs.ids[k]) + 1, + "Label": label, + "Note": note or "", + "Row0": float(rs.rows[k]), + "Col0": float(rs.cols[k]), + "Updated": time.strftime("%Y-%m-%d %H:%M:%S"), + }) # by path, in the order written within it (stable), so that of # two marks with the same time the later one still wins marks.sort(key=lambda m: m["Path"]) @@ -741,9 +709,7 @@ def _check_position(rs, k: int, row, col) -> None: """ if row is None or col is None: return - moved = np.hypot( - float(rs.rows[k]) - float(row), float(rs.cols[k]) - float(col) - ) + moved = np.hypot(float(rs.rows[k]) - float(row), float(rs.cols[k]) - float(col)) if not moved <= 1e-3: raise ValueError( "the summary has changed since the page read its sources " @@ -780,9 +746,7 @@ def _crop(img: np.ndarray, r0: int, c0: int, hw: int, fill) -> np.ndarray: r1, r2 = max(0, r0 - hw), min(h, r0 + hw + 1) c1, c2 = max(0, c0 - hw), min(w, c0 + hw + 1) if r1 < r2 and c1 < c2: - out[ - r1 - (r0 - hw) : r2 - (r0 - hw), c1 - (c0 - hw) : c2 - (c0 - hw) - ] = img[r1:r2, c1:c2] + out[r1 - (r0 - hw) : r2 - (r0 - hw), c1 - (c0 - hw) : c2 - (c0 - hw)] = img[r1:r2, c1:c2] return out @@ -792,9 +756,7 @@ def _write_marks_atomic(path: Path, marks: list) -> None: import tempfile path.parent.mkdir(parents=True, exist_ok=True) - fd, tmp = tempfile.mkstemp( - prefix=f"{path.name}.", suffix=".tmp", dir=path.parent - ) + fd, tmp = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent) os.close(fd) try: write_marks(tmp, marks) diff --git a/src/giant_python/spine/view/export.py b/src/giant_python/spine/view/export.py index ff1d8228..cd8df098 100644 --- a/src/giant_python/spine/view/export.py +++ b/src/giant_python/spine/view/export.py @@ -122,16 +122,10 @@ def arr(key, missing): # the smallest q, and the largest statistic among the tests at it q_best = q.min(axis=0) t_best = np.where(q == q_best[None, :], t_abs, -np.inf).max(axis=0) - call = np.array( - [bool(x) for x in tr.get("call", [False] * len(q_best))] - ) + call = np.array([bool(x) for x in tr.get("call", [False] * len(q_best))]) order = np.lexsort((-t_best, q_best, ~call)) marked = set(picked) - picked += [ - int(k) - for k in order - if np.isfinite(q_best[k]) and int(k) not in marked - ][:top] + picked += [int(k) for k in order if np.isfinite(q_best[k]) and int(k) not in marked][:top] seen: list = [] for k in picked: if k not in seen: @@ -173,8 +167,7 @@ def _check_choices(store, paths: dict, sources, crop_images, product) -> None: bad = [x for x in crop_images if x not in have] if bad: raise ValueError( - f"{name} has no image(s) {', '.join(bad)} (it has " - f"{', '.join(sorted(have))})" + f"{name} has no image(s) {', '.join(bad)} (it has {', '.join(sorted(have))})" ) if sources: have = set() @@ -183,8 +176,7 @@ def _check_choices(store, paths: dict, sources, crop_images, product) -> None: bad = [s for s in sources if s not in have] if bad: raise ValueError( - f"{name} has no source(s) {', '.join(str(s) for s in bad)} " - "in the chosen paths" + f"{name} has no source(s) {', '.join(str(s) for s in bad)} in the chosen paths" ) @@ -285,11 +277,9 @@ def export_html( data["crops"][crop_key(n, k, image, "image", "")] = pack( store.crops(0, n, k, image, "image", "average"), "image" ) - data["crops"][crop_key(n, k, image, "change", "average")] = ( - pack( - store.crops(0, n, k, image, "change", "average"), - "change", - ) + data["crops"][crop_key(n, k, image, "change", "average")] = pack( + store.crops(0, n, k, image, "change", "average"), + "change", ) included[n] = [src["ids"][k] + 1 for k in ks] say(f"Path{n}: crops of {len(ks)} sources in {', '.join(cimgs)}") @@ -297,13 +287,8 @@ def export_html( b64 = base64.b64encode(gzip.compress(blob, 6)).decode("ascii") page = PAGE.read_text(encoding="utf-8") t = title or f"Spine sizes {pr.name}" - page = page.replace( - "Spine size viewer", f"{_esc(t)}", 1 - ) - tag = ( - '\n\n\n\n - - + + + + + +Spine size viewer + + + +
+
+

Spine size viewer

+ + + + loading… + +
+
+ + + + + + + + +
+
+ + + + + keys: ←/→ trial, a mean, n/p next/previous source, r other product, g/s/u/x mark, c clear +
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ +
+
+
+
+ +
+
+
Mark
+
+ + + + + + + +
+
+
+
+
+
+
+ What is shown +
    +
  • Size: each source's readout of a per-trial image in its fixed window (the mean footprint over the pixels with a value in every trial), normalized as spineTrends.m: log, minus each trial's median over the sources, minus the source's own mean; shown as % against that mean.
  • +
  • Call: a change beyond the shared trend with q ≤ the FDR level and at least the summary's minimum change (10% by default); the table opens sorted by calls, then by that q. ch2 % (or the run's other structural channel): that channel's change beyond its own trend at the same split; a change of a spine's volume shows there too, a change of the indicator's brightness does not (a change of focus does). align px: how much the window moves between trials beyond the trial's overall shift (spread across trials); a change at a source with a large value depends more on the alignment.
  • +
  • Step: the largest t of a change between the trials before and after a split (after trial: the last trial before it); brief: the strongest change of 1–3 trials that comes back, against the 2 trials on each side; beyond trend: the step test once the source's part of the shared trend (first singular vector over the sources) is removed. p from random trial orders of the source, q from Benjamini–Hochberg per path; bold where q ≤ the FDR level.
  • +
  • Field: each trial divided by its median (bleach-normalized), or their mean. Change: trials blurred 0.7 px, against the mean of all trials or the previous trial in the same block of consecutive acquisitions; at the mean, the last block against the earlier ones (one block: second half against first); brightness follows the mean image. Activity: the run's activity image as a robust z.
  • +
  • Crops: the window (footprint weights; contours at 50% and 10% of the peak; hatched: pixels left out because some trial has no value there), then the mean and every trial, on one contrast.
  • +
  • Marks belong to a position and attach to the nearest source within 2.5 px, in any product of the session.
  • +
+
+
+
+
+ + + diff --git a/src/giant_python/spine/view/server.py b/src/giant_python/spine/view/server.py index 68ec1736..f7fd7db6 100644 --- a/src/giant_python/spine/view/server.py +++ b/src/giant_python/spine/view/server.py @@ -1,327 +1,398 @@ -"""``giant spine view``: a local page for spine sizes, trends and marks. - -``giant spine view PRODUCT [PRODUCT ...] --marks spine_marks.csv`` serves -http://127.0.0.1:8790 (one page, :data:`PAGE`) for one or more -``spine_summary`` files of a session (:mod:`.data`): the field with the -sources, per-trial crops of the selected source, its size over the trials -in every image with the shared trend and its activity, a sortable table of -the trend tests, and marks written at once to the CSV. Several products -(runs or readout variants) are compared by switching between them at the -same path, trial, view and nearest source. - -API (used by the page): GET ``/api/meta``, ``/api/sources?prod=&path=``, -``/api/field?prod=&path=&image=&trial=&view=image|change|activity&vs=`` -(float32 ``layers x rows x cols``, shape in ``X-Shape``), -``/api/roi?prod=&path=&id=`` (JSON), ``/api/crops?prod=&path=&id=&image= -&view=&vs=`` (float32 ``layers x tiles x s x s``); POST ``/api/mark`` -(JSON ``{prod, path, id, label, note}``; ``label`` null keeps the -source's label and sets the note). -""" - -from __future__ import annotations - -import argparse -import json -import socket -import threading -import webbrowser -from collections.abc import Callable, Iterable -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse - -import numpy as np - -from .data import SpineStore - -PAGE = Path(__file__).with_name("page.html") -DEFAULT_PORT = 8790 - - -def json_safe(o: object) -> object: - """``o`` with non-finite floats as None (the browser rejects NaN).""" - if isinstance(o, float): - return o if np.isfinite(o) else None - if isinstance(o, dict): - return {str(k): json_safe(v) for k, v in o.items()} - if isinstance(o, (list, tuple)): - return [json_safe(v) for v in o] - if isinstance(o, np.generic): - return json_safe(o.item()) - return o - - -def route( - store: SpineStore, path: str, q: dict[str, str] -) -> tuple[str, dict | np.ndarray, dict[str, str]]: - """Answer one GET request: ``(kind, payload, headers)``.""" - if path == "/api/meta": - return "json", store.meta(), {} - i = int(q.get("prod", 0)) - if path == "/api/sources": - return "json", store.sources(i, int(q["path"])), {} - if path == "/api/field": - img = store.product(i).field( - int(q["path"]), - q.get("image", ""), - int(q.get("trial", -1)), - q.get("view", "image"), - q.get("vs", "average"), - ) - return "bin", img, {"X-Shape": json.dumps(list(img.shape))} - if path == "/api/roi": - return "json", store.roi(i, int(q["path"]), int(q["id"])), {} - if path == "/api/crops": - a = store.crops( - i, - int(q["path"]), - int(q["id"]), - q["image"], - q.get("view", "image"), - q.get("vs", "average"), - ) - return "bin", a, {"X-Shape": json.dumps(list(a.shape))} - raise LookupError(path) - - -class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of ``store`` (set by :func:`make_handler`). - - Every request must name a trusted host (``allowed``, set by - :func:`make_server`: the loopback names and the bound host at the - server's port), so that a page reaching the server through DNS - rebinding (its own name resolving to 127.0.0.1) gets nothing; marks - must also come as JSON from a trusted origin. - """ - - store: SpineStore - allowed: frozenset = frozenset() - - def log_message(self, *a: object) -> None: - """Quiet.""" - - def _send( - self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None - ) -> None: - """Send one response.""" - self.send_response(code) - self.send_header("Content-Type", ctype) - self.send_header("Content-Length", str(len(body))) - self.send_header("Cache-Control", "no-store") - for k, v in (headers or {}).items(): - self.send_header(k, v) - self.end_headers() - self.wfile.write(body) - - def _json( - self, obj: object, code: int = 200, headers: dict[str, str] | None = None - ) -> None: - """Send JSON (non-finite floats as null).""" - body = json.dumps(json_safe(obj), allow_nan=False).encode() - self._send(code, body, "application/json", headers) - - def _guard(self, fn: Callable[[], None]) -> None: - """Run ``fn`` and answer errors as JSON.""" - try: - fn() - except (KeyError, ValueError) as e: - self._json({"error": f"{type(e).__name__}: {e}"}, 400) - except LookupError as e: - self._json({"error": f"not found: {e}"}, 404) - except (BrokenPipeError, ConnectionResetError): - pass - except Exception as e: # noqa: BLE001 (shown on the page) - self._json({"error": f"{type(e).__name__}: {e}"}, 500) - - def _untrusted_host(self) -> bool: - """Whether the request's ``Host`` is not one of ``allowed``. - - An empty ``allowed`` trusts every host: a server bound to all - interfaces. - """ - if not self.allowed: - return False - return self.headers.get("Host", "").lower() not in self.allowed - - 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() -> None: - """Answer it.""" - if self._untrusted_host(): - self._json({"error": "untrusted Host"}, 403) - return - if u.path in ("/", "/index.html"): - self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") - return - kind, payload, headers = route(self.store, u.path, q) - if kind == "json": - self._json(payload, headers=headers) - return - body = np.ascontiguousarray(payload, np.float32).tobytes() - self._send(200, body, "application/octet-stream", headers) - - self._guard(go) - - def _cross_origin(self) -> bool: - """Whether the request comes from a page of another origin. - - That is, its ``Origin`` (or ``Referer``) is not ``http://`` and a - trusted host (with ``allowed`` empty, not the request's own ``Host``). - """ - src = self.headers.get("Origin") or self.headers.get("Referer") - if not src: - return False - o = urlparse(src) - if o.scheme != "http": - return True - if self.allowed: - return o.netloc.lower() not in self.allowed - return o.netloc.lower() != self.headers.get("Host", "").lower() - - def do_POST(self) -> None: - """Set a mark (JSON from a page of this server only). - - A page of another origin cannot send JSON without a preflight, which - this server does not answer, and its Origin is refused. - """ - u = urlparse(self.path) - - def go() -> None: - """Answer it.""" - if self._untrusted_host(): - self._json({"error": "untrusted Host"}, 403) - return - if u.path != "/api/mark": - raise LookupError(u.path) - ctype = self.headers.get("Content-Type", "") - if ctype.split(";")[0].strip().lower() != "application/json": - self._json({"error": "marks take application/json"}, 415) - return - if self._cross_origin(): - self._json({"error": "marks only from this server's page"}, 403) - return - n = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(n) or b"{}") - marks = self.store.set_mark( - int(body.get("prod", 0)), - int(body["path"]), - int(body["id"]), - (None if body.get("label", "") is None else str(body.get("label", ""))), - str(body.get("note", "")), - row=body.get("row"), - col=body.get("col"), - ) - self._json(marks) - - self._guard(go) - - -def make_handler(store: SpineStore) -> type[_Handler]: - """Build the request handler class serving ``store``.""" - return type("Handler", (_Handler,), {"store": store}) - - -_LOOPBACK = ("127.0.0.1", "localhost", "[::1]") - - -def make_server( - store: SpineStore, host: str = "127.0.0.1", port: int = DEFAULT_PORT -) -> ThreadingHTTPServer: - """Create an HTTP server for ``store`` (not started). - - It answers only requests whose ``Host`` is a loopback name or ``host`` - at the bound port; bound to all interfaces (``0.0.0.0``, ``::``), it - trusts every host name. - """ - handler = make_handler(store) - cls = _Server6 if ":" in host else ThreadingHTTPServer - srv = cls((host.strip("[]"), port), handler) - handler.allowed = allowed_hosts(host, srv.server_address[1]) - return srv - - -def allowed_hosts(host: str, port: int) -> frozenset: - """Return the ``Host`` values a server bound to ``host`` and ``port`` trusts. - - These are the loopback names and ``host``, with the port (and without - it at port 80, which browsers leave out); empty (every name) when - bound to all interfaces. - """ - if host in ("0.0.0.0", "::", "[::]", ""): - return frozenset() - names = {_bracket(h) for h in set(_LOOPBACK) | {host.lower()}} - allowed = {f"{h}:{port}" for h in names} - if port == 80: - allowed |= names - return frozenset(allowed) - - -class _Server6(ThreadingHTTPServer): - """The threading server on an IPv6 address.""" - - address_family = socket.AF_INET6 - - -def _bracket(host: str) -> str: - """Put an IPv6 literal in brackets, as URLs and Host headers write it.""" - host = host.strip("[]") - return f"[{host}]" if ":" in host else host - - -def product_args(items: Iterable[str | Path]) -> list[tuple[str | None, str | Path]]: - """``NAME=FILE`` or ``FILE`` arguments as ``(name, file)``.""" - out = [] - for item in items: - name, sep, f = str(item).partition("=") - if sep and name and not Path(item).exists(): - out.append((name, f)) - else: - out.append((None, item)) - return out - - -def add_arguments(p: argparse.ArgumentParser) -> None: - """``giant spine view``'s options.""" - p.add_argument( - "products", - nargs="+", - metavar="PRODUCT", - help="spine_summary_.h5 files of one session, optionally as " - "NAME=FILE; several are compared", - ) - p.add_argument( - "--marks", - default=None, - help="spine_marks.csv to read and write (created on the first " - "mark; without it the page cannot mark)", - ) - p.add_argument( - "--crop-half", - type=int, - default=9, - help="half-width of the per-trial crops, px (default 9)", - ) - 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") - - -def serve(args: argparse.Namespace) -> int: - """Run ``giant spine view`` until interrupted.""" - store = SpineStore(product_args(args.products), args.marks, crop_half=args.crop_half) - server = make_server(store, args.host, args.port) - url = f"http://{_bracket(args.host)}:{server.server_address[1]}/" - names = ", ".join(p.name for p in store.products) - print(f"spine viewer: {names}; serving {url} (Ctrl+C to stop)", flush=True) - if not args.no_browser: - threading.Timer(0.5, lambda: webbrowser.open(url)).start() - try: - server.serve_forever() - except KeyboardInterrupt: - pass - finally: - server.server_close() - return 0 +"""giant spine view: a local page for spine sizes, trends and marks. + +giant spine view PRODUCT [PRODUCT ...] --marks spine_marks.csv serves +http://127.0.0.1:8790 (one page, :data:`PAGE`) for one or more +spine_summary files of a session (:mod:`.data`): the field with the +sources, per-trial crops of the selected source, its size over the trials +in every image with the shared trend and its activity, a sortable table of +the trend tests, and marks written at once to the CSV. Several products +(runs or readout variants) are compared by switching between them at the +same path, trial, view and nearest source. + +API (used by the page): GET /api/meta, /api/sources?prod=&path=, +``/api/field?prod=&path=&image=&trial=&view=image|change|activity&vs=`` +(float32 layers x rows x cols, shape in X-Shape), +/api/roi?prod=&path=&id= (JSON), /api/crops?prod=&path=&id=&image= +&view=&vs= (float32 layers x tiles x s x s); POST /api/mark +(JSON {prod, path, id, label, note}; label null keeps the +source's label and sets the note). +""" + +from __future__ import annotations + +import argparse +import json +import socket +import threading +import webbrowser +from collections.abc import Callable, Iterable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +import numpy as np + +from .data import SpineStore + +PAGE = Path(__file__).with_name("page.html") +DEFAULT_PORT = 8790 + + +def json_safe(o: object) -> object: + """``o`` with non-finite floats as None (the browser rejects NaN). + + Returns + ------- + object + o with non-finite floats replaced by None, and dicts, lists, tuples and numpy + scalars converted to JSON-compatible Python values (recursively). + """ + if isinstance(o, float): + return o if np.isfinite(o) else None + if isinstance(o, dict): + return {str(k): json_safe(v) for k, v in o.items()} + if isinstance(o, (list, tuple)): + return [json_safe(v) for v in o] + if isinstance(o, np.generic): + return json_safe(o.item()) + return o + + +def route( + store: SpineStore, path: str, q: dict[str, str] +) -> tuple[str, dict | np.ndarray, dict[str, str]]: + """Answer one GET request: (kind, payload, headers). + + Returns + ------- + kind : str + "json" or "bin". + payload : dict or np.ndarray + The JSON-serializable answer for "json", or the float32 array for "bin". + headers : dict[str, str] + Extra response headers (X-Shape for arrays). + + Raises + ------ + LookupError + If the path is not one of the API's GET routes. + """ + if path == "/api/meta": + return "json", store.meta(), {} + i = int(q.get("prod", 0)) + if path == "/api/sources": + return "json", store.sources(i, int(q["path"])), {} + if path == "/api/field": + img = store.product(i).field( + int(q["path"]), + q.get("image", ""), + int(q.get("trial", -1)), + q.get("view", "image"), + q.get("vs", "average"), + ) + return "bin", img, {"X-Shape": json.dumps(list(img.shape))} + if path == "/api/roi": + return "json", store.roi(i, int(q["path"]), int(q["id"])), {} + if path == "/api/crops": + a = store.crops( + i, + int(q["path"]), + int(q["id"]), + q["image"], + q.get("view", "image"), + q.get("vs", "average"), + ) + return "bin", a, {"X-Shape": json.dumps(list(a.shape))} + raise LookupError(path) + + +class _Handler(BaseHTTPRequestHandler): + """Serves the page and the API of store (set by :func:`make_handler`). + + Every request must name a trusted host (allowed, set by + :func:`make_server`: the loopback names and the bound host at the + server's port), so that a page reaching the server through DNS + rebinding (its own name resolving to 127.0.0.1) gets nothing; marks + must also come as JSON from a trusted origin. + """ + + store: SpineStore + allowed: frozenset = frozenset() + + def log_message(self, *a: object) -> None: + """Quiet.""" + + def _send( + self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None + ) -> None: + """Send one response.""" + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: + """Send JSON (non-finite floats as null).""" + body = json.dumps(json_safe(obj), allow_nan=False).encode() + self._send(code, body, "application/json", headers) + + def _guard(self, fn: Callable[[], None]) -> None: + """Run fn and answer errors as JSON.""" + try: + fn() + except (KeyError, ValueError) as e: + self._json({"error": f"{type(e).__name__}: {e}"}, 400) + except LookupError as e: + self._json({"error": f"not found: {e}"}, 404) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception as e: # noqa: BLE001 (shown on the page) + self._json({"error": f"{type(e).__name__}: {e}"}, 500) + + def _untrusted_host(self) -> bool: + """Whether the request's Host is not one of allowed. + + An empty allowed trusts every host: a server bound to all + interfaces. + + Returns + ------- + bool + True if allowed is non-empty and the request's Host is not in it. + """ + if not self.allowed: + return False + return self.headers.get("Host", "").lower() not in self.allowed + + 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() -> None: + """Answer it.""" + if self._untrusted_host(): + self._json({"error": "untrusted Host"}, 403) + return + if u.path in ("/", "/index.html"): + self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") + return + kind, payload, headers = route(self.store, u.path, q) + if kind == "json": + self._json(payload, headers=headers) + return + body = np.ascontiguousarray(payload, np.float32).tobytes() + self._send(200, body, "application/octet-stream", headers) + + self._guard(go) + + def _cross_origin(self) -> bool: + """Whether the request comes from a page of another origin. + + That is, its Origin (or Referer) is not http:// and a + trusted host (with allowed empty, not the request's own Host). + + Returns + ------- + bool + True if the request has an Origin or Referer from another origin. + """ + src = self.headers.get("Origin") or self.headers.get("Referer") + if not src: + return False + o = urlparse(src) + if o.scheme != "http": + return True + if self.allowed: + return o.netloc.lower() not in self.allowed + return o.netloc.lower() != self.headers.get("Host", "").lower() + + def do_POST(self) -> None: + """Set a mark (JSON from a page of this server only). + + A page of another origin cannot send JSON without a preflight, which + this server does not answer, and its Origin is refused. + """ + u = urlparse(self.path) + + def go() -> None: + """Answer it. + + Raises + ------ + LookupError + If the path is not /api/mark. + """ + if self._untrusted_host(): + self._json({"error": "untrusted Host"}, 403) + return + if u.path != "/api/mark": + raise LookupError(u.path) + ctype = self.headers.get("Content-Type", "") + if ctype.split(";")[0].strip().lower() != "application/json": + self._json({"error": "marks take application/json"}, 415) + return + if self._cross_origin(): + self._json({"error": "marks only from this server's page"}, 403) + return + n = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(n) or b"{}") + marks = self.store.set_mark( + int(body.get("prod", 0)), + int(body["path"]), + int(body["id"]), + (None if body.get("label", "") is None else str(body.get("label", ""))), + str(body.get("note", "")), + row=body.get("row"), + col=body.get("col"), + ) + self._json(marks) + + self._guard(go) + + +def make_handler(store: SpineStore) -> type[_Handler]: + """Build the request handler class serving store. + + Returns + ------- + type[_Handler] + A subclass of the handler with store set. + """ + return type("Handler", (_Handler,), {"store": store}) + + +_LOOPBACK = ("127.0.0.1", "localhost", "[::1]") + + +def make_server( + store: SpineStore, host: str = "127.0.0.1", port: int = DEFAULT_PORT +) -> ThreadingHTTPServer: + """Create an HTTP server for store (not started). + + It answers only requests whose Host is a loopback name or host + at the bound port; bound to all interfaces (0.0.0.0, ::), it + trusts every host name. + + Returns + ------- + ThreadingHTTPServer + The server, bound but not serving. + """ + handler = make_handler(store) + cls = _Server6 if ":" in host else ThreadingHTTPServer + srv = cls((host.strip("[]"), port), handler) + handler.allowed = allowed_hosts(host, srv.server_address[1]) + return srv + + +def allowed_hosts(host: str, port: int) -> frozenset: + """Return the Host values a server bound to host and port trusts. + + These are the loopback names and host, with the port (and without + it at port 80, which browsers leave out); empty (every name) when + bound to all interfaces. + + Returns + ------- + frozenset + The trusted Host header values, lower case; empty when every name is trusted. + """ + if host in ("0.0.0.0", "::", "[::]", ""): + return frozenset() + names = {_bracket(h) for h in set(_LOOPBACK) | {host.lower()}} + allowed = {f"{h}:{port}" for h in names} + if port == 80: + allowed |= names + return frozenset(allowed) + + +class _Server6(ThreadingHTTPServer): + """The threading server on an IPv6 address.""" + + address_family = socket.AF_INET6 + + +def _bracket(host: str) -> str: + """Put an IPv6 literal in brackets, as URLs and Host headers write it. + + Returns + ------- + str + host in brackets if it is an IPv6 literal, otherwise host unchanged. + """ + host = host.strip("[]") + return f"[{host}]" if ":" in host else host + + +def product_args(items: Iterable[str | Path]) -> list[tuple[str | None, str | Path]]: + """NAME=FILE or FILE arguments as (name, file). + + Returns + ------- + list[tuple[str | None, str | Path]] + One (name, file) pair per argument; name is None when the argument has no + NAME= prefix (or is an existing file path containing =). + """ + out = [] + for item in items: + name, sep, f = str(item).partition("=") + if sep and name and not Path(item).exists(): + out.append((name, f)) + else: + out.append((None, item)) + return out + + +def add_arguments(p: argparse.ArgumentParser) -> None: + """``giant spine view``'s options.""" + p.add_argument( + "products", + nargs="+", + metavar="PRODUCT", + help="spine_summary_.h5 files of one session, optionally as " + "NAME=FILE; several are compared", + ) + p.add_argument( + "--marks", + default=None, + help="spine_marks.csv to read and write (created on the first " + "mark; without it the page cannot mark)", + ) + p.add_argument( + "--crop-half", + type=int, + default=9, + help="half-width of the per-trial crops, px (default 9)", + ) + 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") + + +def serve(args: argparse.Namespace) -> int: + """Run giant spine view until interrupted. + + Returns + ------- + int + Exit status, 0 once the server has stopped. + """ + store = SpineStore(product_args(args.products), args.marks, crop_half=args.crop_half) + server = make_server(store, args.host, args.port) + url = f"http://{_bracket(args.host)}:{server.server_address[1]}/" + names = ", ".join(p.name for p in store.products) + print(f"spine viewer: {names}; serving {url} (Ctrl+C to stop)", flush=True) + if not args.no_browser: + threading.Timer(0.5, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 diff --git a/src/giant_python/viewer/__init__.py b/src/giant_python/viewer/__init__.py index e82ba112..e880bba2 100644 --- a/src/giant_python/viewer/__init__.py +++ b/src/giant_python/viewer/__init__.py @@ -1,7 +1,7 @@ -"""Browser viewer of SILo runs (``giant view``). - -:mod:`~giant_python.viewer.run` reads a run's summaries, -:mod:`~giant_python.viewer.render` renders its fitted activity in a -trial's registered 80 Hz movie, and :mod:`~giant_python.viewer.server` -serves the page (``page.html``). -""" +"""Browser viewer of SILo runs (giant view). + +:mod:`~giant_python.viewer.run` reads a run's summaries, +:mod:`~giant_python.viewer.render` renders its fitted activity in a +trial's registered 80 Hz movie, and :mod:`~giant_python.viewer.server` +serves the page (page.html). +""" diff --git a/src/giant_python/viewer/page.html b/src/giant_python/viewer/page.html index 815d4733..16533dbf 100644 --- a/src/giant_python/viewer/page.html +++ b/src/giant_python/viewer/page.html @@ -1,1086 +1,1086 @@ - - - - - -SILo run viewer - - - -
-
-

SILo run viewer

- - - - - loading… - -
-
- -
- - - - - - - - - - -
-
Over the images: scroll zooms · drag pans · click a marker for the source · double-click fits. - Markers:
- - - - - - - -
-
-
-
-
-
-

Source

Click a marker or a table row.

-
-
-
-
Source tracespick a kept source - 200 Hz, all trials (grey lines: trial boundaries) · scroll zooms time · drag pans · double-click shows everything
-
-
dF: least squares and denoised (the fit) (raw counts, footprint units)
-
-
Events (the denoised dF is their convolution with the indicator kernel)
-
-
F0 (raw counts, footprint units)
-
-
-
-
- -
- What the panels show -
    -
  • Activity image (Sources view): SILo's combined activity image of the path on its consensus canvas (all trials), or one trial's, as in experiment_summary.h5 and per_trial_summary.h5. Markers sit at the kept sources' footprint centroids, the kinetics-rejected sources' pixels and, when the run kept its plan, the seeds whose pixel got no source.
  • -
  • Aligned movie (Movie view): the trial's registered 80 Hz movie (*_REGISTERED_DOWNSAMPLED-80Hz, activity channel) in the trial's own registered frame, not resampled. Blank (NaN) at SILo's motion discards and at frames whose kernel weight lies mostly on SILo's discarded 200 Hz frames; only pixels missing in less than nanThresh of the frames, counting the motion discards (as SILo's trial loader and the exporter count them), are shown.
  • -
  • Fitted activity: every kept source's footprint times its denoised trace (dF_denoised), rendered in the movie's pixels and frames following the F0 network's training-data exporter. Time: each 80 Hz frame averages SILo's 200 Hz traces at its frame lines with weights exp(−|Δline| / dt) within max(3 dt, P) lines (P: lines per cycle), leaving out SILo's discarded frames. With the exporter's kernel (the one the current F0 training targets were made with) dt is the movie's own (ceil(mean(diff(DSframes))), 134 lines on these rigs), as the training-data exporter does; but the 200 Hz frames are themselves averages (dt200 = 54 lines), so this smooths fast events twice and keeps 93–95% of an event's 80 Hz peak on noiseless injected events. The matched kernel (the default) uses √(dt² − dt200²) (≈ 123 lines) and keeps 97–99%. The Time kernel menu switches between them. Space: the trial's footprints are moved from the consensus canvas into the trial's frame through the trial's across-trial map (rigid, affine or patchwise), bilinearly; the exporter instead searched a rigid offset per trial by correlation and blurred the footprints to match the movie's shape (here a fixed blur, 0 unless the server was started with --blur). Kinetics-rejected sources are not included (their traces are not in the summary).
  • -
  • Residual = aligned movie − fitted activity: what a training target made from this run would be. Residual − baseline = movie − activity − the F0 network's baseline (only with --baseline-dir).
  • -
  • Units: raw counts of the registered movie (each pixel's weighted mean of its raw SLAP2 samples); SILo's traces and F0 are in the same units (footprints sum to 1, so a trace is the source's total over its footprint).
  • -
-
-
-
- - - + + + + + +SILo run viewer + + + +
+
+

SILo run viewer

+ + + + + loading… + +
+
+ +
+ + + + + + + + + + +
+
Over the images: scroll zooms · drag pans · click a marker for the source · double-click fits. + Markers:
+ + + + + + + +
+
+
+
+
+
+

Source

Click a marker or a table row.

+
+
+
+
Source tracespick a kept source + 200 Hz, all trials (grey lines: trial boundaries) · scroll zooms time · drag pans · double-click shows everything
+
+
dF: least squares and denoised (the fit) (raw counts, footprint units)
+
+
Events (the denoised dF is their convolution with the indicator kernel)
+
+
F0 (raw counts, footprint units)
+
+
+
+
+ +
+ What the panels show +
    +
  • Activity image (Sources view): SILo's combined activity image of the path on its consensus canvas (all trials), or one trial's, as in experiment_summary.h5 and per_trial_summary.h5. Markers sit at the kept sources' footprint centroids, the kinetics-rejected sources' pixels and, when the run kept its plan, the seeds whose pixel got no source.
  • +
  • Aligned movie (Movie view): the trial's registered 80 Hz movie (*_REGISTERED_DOWNSAMPLED-80Hz, activity channel) in the trial's own registered frame, not resampled. Blank (NaN) at SILo's motion discards and at frames whose kernel weight lies mostly on SILo's discarded 200 Hz frames; only pixels missing in less than nanThresh of the frames, counting the motion discards (as SILo's trial loader and the exporter count them), are shown.
  • +
  • Fitted activity: every kept source's footprint times its denoised trace (dF_denoised), rendered in the movie's pixels and frames following the F0 network's training-data exporter. Time: each 80 Hz frame averages SILo's 200 Hz traces at its frame lines with weights exp(−|Δline| / dt) within max(3 dt, P) lines (P: lines per cycle), leaving out SILo's discarded frames. With the exporter's kernel (the one the current F0 training targets were made with) dt is the movie's own (ceil(mean(diff(DSframes))), 134 lines on these rigs), as the training-data exporter does; but the 200 Hz frames are themselves averages (dt200 = 54 lines), so this smooths fast events twice and keeps 93–95% of an event's 80 Hz peak on noiseless injected events. The matched kernel (the default) uses √(dt² − dt200²) (≈ 123 lines) and keeps 97–99%. The Time kernel menu switches between them. Space: the trial's footprints are moved from the consensus canvas into the trial's frame through the trial's across-trial map (rigid, affine or patchwise), bilinearly; the exporter instead searched a rigid offset per trial by correlation and blurred the footprints to match the movie's shape (here a fixed blur, 0 unless the server was started with --blur). Kinetics-rejected sources are not included (their traces are not in the summary).
  • +
  • Residual = aligned movie − fitted activity: what a training target made from this run would be. Residual − baseline = movie − activity − the F0 network's baseline (only with --baseline-dir).
  • +
  • Units: raw counts of the registered movie (each pixel's weighted mean of its raw SLAP2 samples); SILo's traces and F0 are in the same units (footprints sum to 1, so a trace is the source's total over its footprint).
  • +
+
+
+
+ + + diff --git a/src/giant_python/viewer/render.py b/src/giant_python/viewer/render.py index f0a9108e..f4ba0ffc 100644 --- a/src/giant_python/viewer/render.py +++ b/src/giant_python/viewer/render.py @@ -1,469 +1,518 @@ -"""SILo's fitted activity rendered in a trial's registered 80 Hz movie. - -The rendering follows the F0 network's training-data exporter -(``exportF0TrainingData.m`` in slap2-F0-network), so that the movie minus -the rendered activity is what a training target made from the run would -be, with these changes: - -* **Time.** An 80 Hz frame is the registration's weighted mean of the - samples within ``max(3 dt, P)`` lines of its line, with weights - ``exp(-|dline| / dt)``, ``dt = ceil(mean(diff(DSframes)))`` lines and - ``P`` the recording's lines per cycle. The 200 Hz traces are averaged - at SILo's frame lines with such weights, leaving out SILo's discarded - frames (:func:`frame_weights`); an 80 Hz frame whose weight falls more - than half on discarded 200 Hz frames is discarded. The exporter uses - the movie's ``dt``; since the 200 Hz frames are already averages, the - viewer's default narrows it to ``sqrt(dt**2 - dt200**2)`` - (:func:`~giant_python.viewer.trial.render_dt`). The ``exact`` kernel - (:func:`exact_weights`) undoes the double smoothing exactly for - densely sampled frames: ``r x200(line) + (1 - r)`` times the exporter's - average, ``r = (dt200 / dt80)**2`` (:func:`kernel_weights` chooses). -* **Space.** Footprints live on SILo's consensus canvas; each trial's - footprints are moved into the trial's registered frame through the - trial's across-trial map (rigid, affine or patchwise), the one SILo read - the trial's data with: the trial-frame footprint at pixel ``q`` is the - canvas footprint at the map's inverse of ``q``, interpolated bilinearly - (:class:`TrialMap`, :func:`place_footprints`). The exporter instead - searches each trial's offset (integer offset of the mean images plus a - sub-pixel search that maximizes the movie-activity correlation at the - source peaks) and applies it to the canvas as a rigid shift. -* **Blur.** Optionally a Gaussian blur of the moved footprints (the - exporter chooses one per trial by matching the movie's core and ring - slopes; here it is a fixed setting, 0 by default). -* **Scale.** None: the activity is SILo's footprints (each sums to 1) - times its denoised traces (``dF_denoised``, movie units), as the - exporter writes it (``activityGain`` 1). -""" - -from __future__ import annotations - -import math - -import numpy as np -from numpy.typing import ArrayLike -from scipy import sparse -from scipy.ndimage import gaussian_filter, map_coordinates - - -def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float) -> int: - """Return the kernel's time constant in lines (the exporter's ``dt``). - - ``ceil(mean(diff(DSframes)))``; with one registered frame, the 200 Hz - frame spacing times ``ratio`` (analysis rate over movie rate). - """ - ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel() - if ds_lines.size > 1: - return int(math.ceil(np.mean(np.diff(ds_lines)))) - step = np.median(np.diff(np.asarray(lines200, dtype=np.float64))) - return int(math.ceil(step * ratio)) - - -def frame_weights( - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt: int, - reach: float, -) -> tuple[sparse.csc_matrix, np.ndarray]: - """Weights that average 200 Hz frames into the movie's 80 Hz frames. - - Parameters - ---------- - lines200 : ndarray, shape (n200,) - SILo's frame lines of the trial (one-based, increasing). - discard200 : ndarray of bool, shape (n200,) - SILo's discarded frames. - ds_lines : ndarray, shape (n80,) - The registered frames' lines (``DSframes``). - dt : int - Kernel time constant in lines. - reach : float - Frames within this many lines count (``max(3 dt, P)``). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - Each 80 Hz frame's weights over the kept 200 Hz frames (columns sum - to 1, or are empty). - discard_share : ndarray, shape (n80,) - Share of each frame's weight on discarded 200 Hz frames (1 where - no 200 Hz frame is within reach). - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - disc = np.asarray(discard200, dtype=bool).ravel() - ds = np.asarray(ds_lines, dtype=np.float64).ravel() - lo = np.searchsorted(lines200, ds - reach, side="left") - hi = np.searchsorted(lines200, ds + reach, side="right") - ii, jj, ww = [], [], [] - share = np.ones(ds.size) - for j in range(ds.size): - idx = np.arange(lo[j], hi[j]) - if idx.size == 0: - continue - w = np.exp(-np.abs(lines200[idx] - ds[j]) / dt) - share[j] = w[disc[idx]].sum() / max(w.sum(), np.finfo(float).eps) - keep = ~disc[idx] - if keep.any(): - ii.append(idx[keep]) - jj.append(np.full(int(keep.sum()), j)) - ww.append(w[keep] / w[keep].sum()) - if ii: - ii, jj, ww = map(np.concatenate, (ii, jj, ww)) - m = sparse.csc_matrix((ww, (ii, jj)), shape=(lines200.size, ds.size)) - return m, share - - -def interp_weights( - lines200: np.ndarray, keep: np.ndarray, ds_lines: np.ndarray -) -> sparse.csc_matrix: - """Linear interpolation of the kept 200 Hz frames at the 80 Hz lines. - - Each 80 Hz frame takes the two kept 200 Hz frames around its line - (discarded frames are skipped, so a gap is bridged by its kept - neighbours); before the first or after the last kept frame, the - nearest kept frame. - - Parameters - ---------- - lines200 : ndarray, shape (n200,) - SILo's frame lines (increasing). - keep : ndarray of bool, shape (n200,) - Frames that may be used. - ds_lines : ndarray, shape (n80,) - The registered frames' lines. - - Returns - ------- - scipy.sparse.csc_matrix, shape (n200, n80) - Columns sum to 1 (all empty without a kept frame). - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - ds = np.asarray(ds_lines, dtype=np.float64).ravel() - k = np.flatnonzero(np.asarray(keep, dtype=bool).ravel()) - shape = (lines200.size, ds.size) - j = np.arange(ds.size) - if k.size == 0: - return sparse.csc_matrix(shape) - if k.size == 1: - return sparse.csc_matrix((np.ones(ds.size), (np.full(ds.size, k[0]), j)), shape=shape) - lk = lines200[k] - i = np.clip(np.searchsorted(lk, ds, side="right") - 1, 0, k.size - 2) - f = np.clip((ds - lk[i]) / (lk[i + 1] - lk[i]), 0.0, 1.0) - return sparse.csc_matrix((np.r_[1 - f, f], (np.r_[k[i], k[i + 1]], np.r_[j, j])), shape=shape) - - -def frame_dt200(lines200: np.ndarray, default: float) -> float: - """Return the 200 Hz frames' own kernel ``dt`` in lines. - - ``ceil(mean(diff(lines)))`` (``default`` with fewer than 2 frames). - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - if lines200.size < 2: - return float(default) - return float(math.ceil(float(np.mean(np.diff(lines200))))) - - -def exact_weights( - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt80: float, - dt200: float, - reach: float, -) -> tuple[sparse.csc_matrix, np.ndarray, float]: - """Weights that turn 200 Hz frames into the movie's 80 Hz frames without smoothing twice. - - Both frame rates are weighted means of the same samples with - ``exp(-|dline| / dt)``, whose spectrum is ``1 / (1 + dt**2 w**2)``. - The 80 Hz frame over the 200 Hz frame is therefore ``(1 + dt200**2 - w**2) / (1 + dt80**2 w**2) = r + (1 - r) / (1 + dt80**2 w**2)``, - ``r = (dt200 / dt80)**2``: the 80 Hz frame is ``r`` times the 200 Hz - frames interpolated at its line (:func:`interp_weights`) plus ``1 - - r`` times their average with the movie's own kernel - (:func:`frame_weights`, the exporter's weights). Exact for densely - sampled pixels and untruncated kernels (on such data fast events keep - 0.99-1.01 of their 80 Hz peak); kernels cut at ``3 dt`` put them 1-2% - high, and pixels sampled once per cycle deviate by about 1% either - way (noiseless injected SLAP2 events: 0.99 and 1.01 on the two paths - of the GFP copy). Discarded 200 Hz frames are left out of both terms. - - Parameters - ---------- - lines200, discard200, ds_lines, reach - As :func:`frame_weights`. - dt80, dt200 : float - The movie's and the 200 Hz frames' kernel ``dt`` (lines). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - Columns sum to 1, or are empty where no kept 200 Hz frame lies - within reach. - discard_share : ndarray, shape (n80,) - As :func:`frame_weights` (of the movie's kernel). - r : float - The interpolated term's weight. - """ - wk, share = frame_weights(lines200, discard200, ds_lines, dt80, reach) - r = min(1.0, (float(dt200) / float(dt80)) ** 2) - keep = ~np.asarray(discard200, dtype=bool).ravel() - wi = interp_weights(lines200, keep, ds_lines) - empty = np.asarray(wk.sum(0)).ravel() == 0 - if empty.any(): # nothing within reach: no activity, as frame_weights - wi = wi @ sparse.diags((~empty).astype(np.float64)) - w = (r * wi + (1.0 - r) * wk).tocsc() - w.eliminate_zeros() - return w, share, r - - -KERNELS = ("exporter", "matched", "exact") - - -def kernel_weights( - kernel: str, - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt80: float, - lines_per_cycle: float = 0, -) -> tuple[sparse.csc_matrix, np.ndarray, dict[str, float]]: - """Compute a time kernel's weights from a trial's 200 Hz frames to its 80 Hz frames. - - Parameters - ---------- - kernel : {"exporter", "matched", "exact"} - ``exporter``: ``exp(-|dline| / dt80)``, the training-data - exporter's (smooths fast events twice); ``matched``: the same with - ``dt = sqrt(dt80**2 - dt200**2)``; ``exact``: - :func:`exact_weights`. ``dt200`` comes from the frame lines - (:func:`frame_dt200`). - lines200, discard200, ds_lines - As :func:`frame_weights`. - dt80 : float - The movie's kernel ``dt`` (:func:`kernel_dt`). - lines_per_cycle : float - ``P``; the kernels reach ``max(3 dt, P)`` lines (0: unknown). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - discard_share : ndarray, shape (n80,) - Share of each frame's weight on discarded 200 Hz frames under the - movie's kernel (``dt80``) for ``exporter`` and ``exact``, under - the narrower kernel for ``matched``. - info : dict - ``dt`` (the averaging kernel's), ``reach``, ``dt200`` and ``r`` - (the interpolated share; 0 except for ``exact``). - """ - if kernel not in KERNELS: - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - dt200 = frame_dt200(lines200, dt80) - if kernel == "matched" and np.size(lines200) >= 2: - dt = math.sqrt(max(float(dt80) ** 2 - dt200**2, 1.0)) - else: # (with fewer than 2 frames the movie's dt, as render_dt) - dt = float(dt80) - reach = max(3 * dt, float(lines_per_cycle)) - info = {"dt": dt, "reach": reach, "dt200": dt200, "r": 0.0} - if kernel == "exact": - w, share, r = exact_weights(lines200, discard200, ds_lines, dt80, dt200, reach) - info["r"] = r - return w, share, info - w, share = frame_weights(lines200, discard200, ds_lines, dt, reach) - return w, share, info - - -def _bilinear( - img: np.ndarray, r: ArrayLike, c: ArrayLike, mode: str = "nearest", cval: float = 0.0 -) -> np.ndarray: - """Bilinear samples of ``img`` at zero-based ``(r, c)``.""" - return map_coordinates(img, [np.ravel(r), np.ravel(c)], order=1, mode=mode, cval=cval).reshape( - np.shape(r) - ) - - -class TrialMap: - """A trial's map from the consensus canvas to its registered frame. - - Zero-based pixel coordinates, as GIAnT-Python's summaries store them - (``frame_info/trial_alignment_affine``: ``[row_t, col_t] = A @ [row, - col, 1]``; ``frame_info/trial_alignment_displacement`` for patchwise - maps: canvas pixel ``(r, c)`` lies at ``(r, c) + displacement`` in the - trial). With a displacement field, the field (sampled on the canvas, - interpolated bilinearly, edge values beyond it) is the map; without, - the affine map. - - Parameters - ---------- - affine : ndarray of shape (2, 3) - field : ndarray of shape (2, rows, cols), optional - """ - - def __init__(self, affine: np.ndarray, field: np.ndarray | None = None) -> None: - """Store the map.""" - self.affine = np.asarray(affine, dtype=np.float64).reshape(2, 3) - self.field = None if field is None else np.asarray(field, np.float64) - - @property - def valid(self) -> bool: - """Whether the trial has a map (it was aligned).""" - if self.field is not None: - return bool(np.isfinite(self.field).all()) - return bool(np.isfinite(self.affine).all()) - - def forward(self, r: ArrayLike, c: ArrayLike) -> tuple[np.ndarray, np.ndarray]: - """Trial-frame position of canvas positions ``(r, c)``.""" - r = np.asarray(r, dtype=np.float64) - c = np.asarray(c, dtype=np.float64) - if self.field is not None: - return ( - r + _bilinear(self.field[0], r, c), - c + _bilinear(self.field[1], r, c), - ) - a = self.affine - return ( - a[0, 0] * r + a[0, 1] * c + a[0, 2], - a[1, 0] * r + a[1, 1] * c + a[1, 2], - ) - - def inverse( - self, rt: ArrayLike, ct: ArrayLike, iters: int = 20, tol: float = 1e-6 - ) -> tuple[np.ndarray, np.ndarray]: - """Canvas position of trial-frame positions ``(rt, ct)``. - - Exact for an affine map; for a displacement field the fixed point - of ``p = q - d(p)``, started at the affine map's inverse. - """ - rt = np.asarray(rt, dtype=np.float64) - ct = np.asarray(ct, dtype=np.float64) - a = self.affine - if not np.isfinite(a).all(): - a = np.array([[1.0, 0, 0], [0, 1.0, 0]]) - m = np.linalg.inv(a[:, :2]) - dr, dc = rt - a[0, 2], ct - a[1, 2] - r = m[0, 0] * dr + m[0, 1] * dc - c = m[1, 0] * dr + m[1, 1] * dc - if self.field is None: - return r, c - for _ in range(iters): - r_new = rt - _bilinear(self.field[0], r, c) - c_new = ct - _bilinear(self.field[1], r, c) - step = max( - float(np.max(np.abs(r_new - r), initial=0)), - float(np.max(np.abs(c_new - c), initial=0)), - ) - r, c = r_new, c_new - if step < tol: - break - return r, c - - -def _patch( - rows: np.ndarray, cols: np.ndarray, vals: np.ndarray, margin: int -) -> tuple[np.ndarray, int, int]: - """Build a footprint's dense canvas patch with a zero margin. - - Returns the patch and its origin ``(row, col)``. - """ - r0, c0 = int(rows.min()) - margin, int(cols.min()) - margin - h = int(rows.max()) - r0 + margin + 1 - w = int(cols.max()) - c0 + margin + 1 - patch = np.zeros((h, w)) - patch[rows - r0, cols - c0] = vals - return patch, r0, c0 - - -def _place_one( - rows: np.ndarray, - cols: np.ndarray, - vals: np.ndarray, - tmap: TrialMap, - shape: tuple, - sigma: float, - interp: int = 1, -) -> tuple[np.ndarray, np.ndarray]: - """One footprint in the trial frame: flat pixel indices and values.""" - margin = 2 + int(math.ceil(3 * sigma)) + int(interp > 1) - patch, r0, c0 = _patch(rows, cols, vals, margin) - h, w = patch.shape - pr, pc = np.mgrid[r0 : r0 + h, c0 : c0 + w] - tr, tc = tmap.forward(pr, pc) - lo_r = max(0, int(math.floor(np.min(tr)))) - hi_r = min(shape[0] - 1, int(math.ceil(np.max(tr)))) - lo_c = max(0, int(math.floor(np.min(tc)))) - hi_c = min(shape[1] - 1, int(math.ceil(np.max(tc)))) - if hi_r < lo_r or hi_c < lo_c: - return np.zeros(0, np.int64), np.zeros(0) - qr, qc = np.mgrid[lo_r : hi_r + 1, lo_c : hi_c + 1] - sr, sc = tmap.inverse(qr, qc) - if interp == 1: - out = _bilinear(patch, sr - r0, sc - c0, mode="constant", cval=0.0) - else: # spline of the zero-padded patch (small negative lobes kept) - out = map_coordinates( - patch, - [np.ravel(sr - r0), np.ravel(sc - c0)], - order=interp, - mode="grid-constant", - cval=0.0, - ).reshape(sr.shape) - if sigma > 0: - out = gaussian_filter(out, sigma, mode="constant", cval=0.0) - peak = float(out.max(initial=0.0)) - if peak > 0: - ok = np.abs(out) > 1e-6 * peak - else: - ok = np.zeros(out.shape, bool) - return (qr[ok] * shape[1] + qc[ok]).astype(np.int64), out[ok] - - -def place_footprints( - footprints: tuple, - n_sources: int, - tmap: TrialMap, - shape: tuple, - sigma: float = 0.0, - interp_order: int = 1, -) -> sparse.csr_matrix: - """Move a trial's footprints into its registered frame. - - Parameters - ---------- - footprints : tuple of ndarray - ``(rows, cols, sources, values)``: the trial's footprints on the - canvas, one entry per nonzero pixel (zero-based). - n_sources : int - Number of sources (columns of the result). - tmap : TrialMap - The trial's map. - shape : tuple of int - ``(rows, cols)`` of the registered frame. - sigma : float - Gaussian blur (px) after the move; 0 for none. - interp_order : int - Interpolation of the canvas footprint at the map's inverse of each - trial pixel: 1 bilinear (the viewer's; it blurs a footprint moved - by a fraction of a pixel, by up to ~10% at the peak pixel of a - 1.3 px footprint), 3 cubic spline (keeps the shape; small negative - lobes at the edge are kept so the flux is unchanged). - - Returns - ------- - scipy.sparse.csr_matrix, shape (rows * cols, n_sources) - Row-major flat pixel index by source. - """ - rows, cols, src, vals = (np.asarray(x) for x in footprints) - order = np.argsort(src, kind="stable") - rows, cols, src, vals = rows[order], cols[order], src[order], vals[order] - edges = np.flatnonzero(np.diff(src)) + 1 - ii, jj, vv = [], [], [] - for k in np.split(np.arange(src.size), edges): - if k.size == 0: - continue - idx, val = _place_one(rows[k], cols[k], vals[k], tmap, shape, sigma, interp_order) - ii.append(idx) - jj.append(np.full(idx.size, int(src[k[0]]))) - vv.append(val) - n_px = int(shape[0]) * int(shape[1]) - if not ii: - return sparse.csr_matrix((n_px, n_sources)) - ii, jj, vv = map(np.concatenate, (ii, jj, vv)) - return sparse.csr_matrix((vv, (ii, jj)), shape=(n_px, n_sources)) +"""SILo's fitted activity rendered in a trial's registered 80 Hz movie. + +The rendering follows the F0 network's training-data exporter +(exportF0TrainingData.m in slap2-F0-network), so that the movie minus +the rendered activity is what a training target made from the run would +be, with these changes: + +* **Time.** An 80 Hz frame is the registration's weighted mean of the + samples within max(3 dt, P) lines of its line, with weights + ``exp(-|dline| / dt)``, dt = ceil(mean(diff(DSframes))) lines and + P the recording's lines per cycle. The 200 Hz traces are averaged + at SILo's frame lines with such weights, leaving out SILo's discarded + frames (:func:`frame_weights`); an 80 Hz frame whose weight falls more + than half on discarded 200 Hz frames is discarded. The exporter uses + the movie's dt; since the 200 Hz frames are already averages, the + viewer's default narrows it to sqrt(dt**2 - dt200**2) + (:func:`~giant_python.viewer.trial.render_dt`). The exact kernel + (:func:`exact_weights`) undoes the double smoothing exactly for + densely sampled frames: r x200(line) + (1 - r) times the exporter's + average, r = (dt200 / dt80)**2 (:func:`kernel_weights` chooses). +* **Space.** Footprints live on SILo's consensus canvas; each trial's + footprints are moved into the trial's registered frame through the + trial's across-trial map (rigid, affine or patchwise), the one SILo read + the trial's data with: the trial-frame footprint at pixel q is the + canvas footprint at the map's inverse of q, interpolated bilinearly + (:class:`TrialMap`, :func:`place_footprints`). The exporter instead + searches each trial's offset (integer offset of the mean images plus a + sub-pixel search that maximizes the movie-activity correlation at the + source peaks) and applies it to the canvas as a rigid shift. +* **Blur.** Optionally a Gaussian blur of the moved footprints (the + exporter chooses one per trial by matching the movie's core and ring + slopes; here it is a fixed setting, 0 by default). +* **Scale.** None: the activity is SILo's footprints (each sums to 1) + times its denoised traces (dF_denoised, movie units), as the + exporter writes it (activityGain 1). +""" + +from __future__ import annotations + +import math + +import numpy as np +from numpy.typing import ArrayLike +from scipy import sparse +from scipy.ndimage import gaussian_filter, map_coordinates + + +def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float) -> int: + """Return the kernel's time constant in lines (the exporter's dt). + + ceil(mean(diff(DSframes))); with one registered frame, the 200 Hz + frame spacing times ratio (analysis rate over movie rate). + + Returns + ------- + int + The kernel's time constant in lines. + """ + ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel() + if ds_lines.size > 1: + return int(math.ceil(np.mean(np.diff(ds_lines)))) + step = np.median(np.diff(np.asarray(lines200, dtype=np.float64))) + return int(math.ceil(step * ratio)) + + +def frame_weights( + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt: int, + reach: float, +) -> tuple[sparse.csc_matrix, np.ndarray]: + """Weights that average 200 Hz frames into the movie's 80 Hz frames. + + Parameters + ---------- + lines200 : ndarray, shape (n200,) + SILo's frame lines of the trial (one-based, increasing). + discard200 : ndarray of bool, shape (n200,) + SILo's discarded frames. + ds_lines : ndarray, shape (n80,) + The registered frames' lines (DSframes). + dt : int + Kernel time constant in lines. + reach : float + Frames within this many lines count (max(3 dt, P)). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + Each 80 Hz frame's weights over the kept 200 Hz frames (columns sum + to 1, or are empty). + discard_share : ndarray, shape (n80,) + Share of each frame's weight on discarded 200 Hz frames (1 where + no 200 Hz frame is within reach). + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + disc = np.asarray(discard200, dtype=bool).ravel() + ds = np.asarray(ds_lines, dtype=np.float64).ravel() + lo = np.searchsorted(lines200, ds - reach, side="left") + hi = np.searchsorted(lines200, ds + reach, side="right") + ii, jj, ww = [], [], [] + share = np.ones(ds.size) + for j in range(ds.size): + idx = np.arange(lo[j], hi[j]) + if idx.size == 0: + continue + w = np.exp(-np.abs(lines200[idx] - ds[j]) / dt) + share[j] = w[disc[idx]].sum() / max(w.sum(), np.finfo(float).eps) + keep = ~disc[idx] + if keep.any(): + ii.append(idx[keep]) + jj.append(np.full(int(keep.sum()), j)) + ww.append(w[keep] / w[keep].sum()) + if ii: + ii, jj, ww = map(np.concatenate, (ii, jj, ww)) + m = sparse.csc_matrix((ww, (ii, jj)), shape=(lines200.size, ds.size)) + return m, share + + +def interp_weights( + lines200: np.ndarray, keep: np.ndarray, ds_lines: np.ndarray +) -> sparse.csc_matrix: + """Linear interpolation of the kept 200 Hz frames at the 80 Hz lines. + + Each 80 Hz frame takes the two kept 200 Hz frames around its line + (discarded frames are skipped, so a gap is bridged by its kept + neighbours); before the first or after the last kept frame, the + nearest kept frame. + + Parameters + ---------- + lines200 : ndarray, shape (n200,) + SILo's frame lines (increasing). + keep : ndarray of bool, shape (n200,) + Frames that may be used. + ds_lines : ndarray, shape (n80,) + The registered frames' lines. + + Returns + ------- + scipy.sparse.csc_matrix, shape (n200, n80) + Columns sum to 1 (all empty without a kept frame). + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + ds = np.asarray(ds_lines, dtype=np.float64).ravel() + k = np.flatnonzero(np.asarray(keep, dtype=bool).ravel()) + shape = (lines200.size, ds.size) + j = np.arange(ds.size) + if k.size == 0: + return sparse.csc_matrix(shape) + if k.size == 1: + return sparse.csc_matrix((np.ones(ds.size), (np.full(ds.size, k[0]), j)), shape=shape) + lk = lines200[k] + i = np.clip(np.searchsorted(lk, ds, side="right") - 1, 0, k.size - 2) + f = np.clip((ds - lk[i]) / (lk[i + 1] - lk[i]), 0.0, 1.0) + return sparse.csc_matrix((np.r_[1 - f, f], (np.r_[k[i], k[i + 1]], np.r_[j, j])), shape=shape) + + +def frame_dt200(lines200: np.ndarray, default: float) -> float: + """Return the 200 Hz frames' own kernel dt in lines. + + ceil(mean(diff(lines))) (default with fewer than 2 frames). + + Returns + ------- + float + The 200 Hz frames' kernel dt in lines. + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + if lines200.size < 2: + return float(default) + return float(math.ceil(float(np.mean(np.diff(lines200))))) + + +def exact_weights( + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt80: float, + dt200: float, + reach: float, +) -> tuple[sparse.csc_matrix, np.ndarray, float]: + """Weights that turn 200 Hz frames into the movie's 80 Hz frames without smoothing twice. + + Both frame rates are weighted means of the same samples with + ``exp(-|dline| / dt)``, whose spectrum is 1 / (1 + dt**2 w**2). + The 80 Hz frame over the 200 Hz frame is therefore (1 + dt200**2 + w**2) / (1 + dt80**2 w**2) = r + (1 - r) / (1 + dt80**2 w**2), + r = (dt200 / dt80)**2: the 80 Hz frame is r times the 200 Hz + frames interpolated at its line (:func:`interp_weights`) plus 1 - + r times their average with the movie's own kernel + (:func:`frame_weights`, the exporter's weights). Exact for densely + sampled pixels and untruncated kernels (on such data fast events keep + 0.99-1.01 of their 80 Hz peak); kernels cut at 3 dt put them 1-2% + high, and pixels sampled once per cycle deviate by about 1% either + way (noiseless injected SLAP2 events: 0.99 and 1.01 on the two paths + of the GFP copy). Discarded 200 Hz frames are left out of both terms. + + Parameters + ---------- + lines200, discard200, ds_lines, reach + As :func:`frame_weights`. + dt80, dt200 : float + The movie's and the 200 Hz frames' kernel dt (lines). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + Columns sum to 1, or are empty where no kept 200 Hz frame lies + within reach. + discard_share : ndarray, shape (n80,) + As :func:`frame_weights` (of the movie's kernel). + r : float + The interpolated term's weight. + """ + wk, share = frame_weights(lines200, discard200, ds_lines, dt80, reach) + r = min(1.0, (float(dt200) / float(dt80)) ** 2) + keep = ~np.asarray(discard200, dtype=bool).ravel() + wi = interp_weights(lines200, keep, ds_lines) + empty = np.asarray(wk.sum(0)).ravel() == 0 + if empty.any(): # nothing within reach: no activity, as frame_weights + wi = wi @ sparse.diags((~empty).astype(np.float64)) + w = (r * wi + (1.0 - r) * wk).tocsc() + w.eliminate_zeros() + return w, share, r + + +KERNELS = ("exporter", "matched", "exact") + + +def kernel_weights( + kernel: str, + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt80: float, + lines_per_cycle: float = 0, +) -> tuple[sparse.csc_matrix, np.ndarray, dict[str, float]]: + """Compute a time kernel's weights from a trial's 200 Hz frames to its 80 Hz frames. + + Parameters + ---------- + kernel : {"exporter", "matched", "exact"} + exporter: ``exp(-|dline| / dt80)``, the training-data + exporter's (smooths fast events twice); matched: the same with + dt = sqrt(dt80**2 - dt200**2); exact: + :func:`exact_weights`. dt200 comes from the frame lines + (:func:`frame_dt200`). + lines200, discard200, ds_lines + As :func:`frame_weights`. + dt80 : float + The movie's kernel dt (:func:`kernel_dt`). + lines_per_cycle : float + P; the kernels reach max(3 dt, P) lines (0: unknown). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + discard_share : ndarray, shape (n80,) + Share of each frame's weight on discarded 200 Hz frames under the + movie's kernel (dt80) for exporter and exact, under + the narrower kernel for matched. + info : dict + dt (the averaging kernel's), reach, dt200 and r + (the interpolated share; 0 except for exact). + + Raises + ------ + ValueError + If kernel is not one of the accepted kernels. + """ + if kernel not in KERNELS: + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + dt200 = frame_dt200(lines200, dt80) + if kernel == "matched" and np.size(lines200) >= 2: + dt = math.sqrt(max(float(dt80) ** 2 - dt200**2, 1.0)) + else: # (with fewer than 2 frames the movie's dt, as render_dt) + dt = float(dt80) + reach = max(3 * dt, float(lines_per_cycle)) + info = {"dt": dt, "reach": reach, "dt200": dt200, "r": 0.0} + if kernel == "exact": + w, share, r = exact_weights(lines200, discard200, ds_lines, dt80, dt200, reach) + info["r"] = r + return w, share, info + w, share = frame_weights(lines200, discard200, ds_lines, dt, reach) + return w, share, info + + +def _bilinear( + img: np.ndarray, r: ArrayLike, c: ArrayLike, mode: str = "nearest", cval: float = 0.0 +) -> np.ndarray: + """Bilinear samples of img at zero-based (r, c). + + Returns + ------- + np.ndarray + The samples, in the shape of r. + """ + return map_coordinates(img, [np.ravel(r), np.ravel(c)], order=1, mode=mode, cval=cval).reshape( + np.shape(r) + ) + + +class TrialMap: + """A trial's map from the consensus canvas to its registered frame. + + Zero-based pixel coordinates, as GIAnT-Python's summaries store them + (frame_info/trial_alignment_affine: [row_t, col_t] = A @ [row, + col, 1]; frame_info/trial_alignment_displacement for patchwise + maps: canvas pixel (r, c) lies at (r, c) + displacement in the + trial). With a displacement field, the field (sampled on the canvas, + interpolated bilinearly, edge values beyond it) is the map; without, + the affine map. + + Parameters + ---------- + affine : ndarray of shape (2, 3) + field : ndarray of shape (2, rows, cols), optional + """ + + def __init__(self, affine: np.ndarray, field: np.ndarray | None = None) -> None: + """Store the map.""" + self.affine = np.asarray(affine, dtype=np.float64).reshape(2, 3) + self.field = None if field is None else np.asarray(field, np.float64) + + @property + def valid(self) -> bool: + """Whether the trial has a map (it was aligned).""" + if self.field is not None: + return bool(np.isfinite(self.field).all()) + return bool(np.isfinite(self.affine).all()) + + def forward(self, r: ArrayLike, c: ArrayLike) -> tuple[np.ndarray, np.ndarray]: + """Trial-frame position of canvas positions (r, c). + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The trial-frame (rows, cols) of the canvas positions. + """ + r = np.asarray(r, dtype=np.float64) + c = np.asarray(c, dtype=np.float64) + if self.field is not None: + return ( + r + _bilinear(self.field[0], r, c), + c + _bilinear(self.field[1], r, c), + ) + a = self.affine + return ( + a[0, 0] * r + a[0, 1] * c + a[0, 2], + a[1, 0] * r + a[1, 1] * c + a[1, 2], + ) + + def inverse( + self, rt: ArrayLike, ct: ArrayLike, iters: int = 20, tol: float = 1e-6 + ) -> tuple[np.ndarray, np.ndarray]: + """Canvas position of trial-frame positions (rt, ct). + + Exact for an affine map; for a displacement field the fixed point + of p = q - d(p), started at the affine map's inverse. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The canvas (rows, cols) of the trial-frame positions. + """ + rt = np.asarray(rt, dtype=np.float64) + ct = np.asarray(ct, dtype=np.float64) + a = self.affine + if not np.isfinite(a).all(): + a = np.array([[1.0, 0, 0], [0, 1.0, 0]]) + m = np.linalg.inv(a[:, :2]) + dr, dc = rt - a[0, 2], ct - a[1, 2] + r = m[0, 0] * dr + m[0, 1] * dc + c = m[1, 0] * dr + m[1, 1] * dc + if self.field is None: + return r, c + for _ in range(iters): + r_new = rt - _bilinear(self.field[0], r, c) + c_new = ct - _bilinear(self.field[1], r, c) + step = max( + float(np.max(np.abs(r_new - r), initial=0)), + float(np.max(np.abs(c_new - c), initial=0)), + ) + r, c = r_new, c_new + if step < tol: + break + return r, c + + +def _patch( + rows: np.ndarray, cols: np.ndarray, vals: np.ndarray, margin: int +) -> tuple[np.ndarray, int, int]: + """Build a footprint's dense canvas patch with a zero margin. + + Returns the patch and its origin (row, col). + + Returns + ------- + patch : np.ndarray + The dense patch of the footprint's values. + row0 : int + Canvas row of the patch's origin. + col0 : int + Canvas column of the patch's origin. + """ + r0, c0 = int(rows.min()) - margin, int(cols.min()) - margin + h = int(rows.max()) - r0 + margin + 1 + w = int(cols.max()) - c0 + margin + 1 + patch = np.zeros((h, w)) + patch[rows - r0, cols - c0] = vals + return patch, r0, c0 + + +def _place_one( + rows: np.ndarray, + cols: np.ndarray, + vals: np.ndarray, + tmap: TrialMap, + shape: tuple, + sigma: float, + interp: int = 1, +) -> tuple[np.ndarray, np.ndarray]: + """One footprint in the trial frame: flat pixel indices and values. + + Returns + ------- + indices : np.ndarray + Flat pixel indices (row-major) in the trial frame. + values : np.ndarray + The footprint's values at those pixels. + """ + margin = 2 + int(math.ceil(3 * sigma)) + int(interp > 1) + patch, r0, c0 = _patch(rows, cols, vals, margin) + h, w = patch.shape + pr, pc = np.mgrid[r0 : r0 + h, c0 : c0 + w] + tr, tc = tmap.forward(pr, pc) + lo_r = max(0, int(math.floor(np.min(tr)))) + hi_r = min(shape[0] - 1, int(math.ceil(np.max(tr)))) + lo_c = max(0, int(math.floor(np.min(tc)))) + hi_c = min(shape[1] - 1, int(math.ceil(np.max(tc)))) + if hi_r < lo_r or hi_c < lo_c: + return np.zeros(0, np.int64), np.zeros(0) + qr, qc = np.mgrid[lo_r : hi_r + 1, lo_c : hi_c + 1] + sr, sc = tmap.inverse(qr, qc) + if interp == 1: + out = _bilinear(patch, sr - r0, sc - c0, mode="constant", cval=0.0) + else: # spline of the zero-padded patch (small negative lobes kept) + out = map_coordinates( + patch, + [np.ravel(sr - r0), np.ravel(sc - c0)], + order=interp, + mode="grid-constant", + cval=0.0, + ).reshape(sr.shape) + if sigma > 0: + out = gaussian_filter(out, sigma, mode="constant", cval=0.0) + peak = float(out.max(initial=0.0)) + if peak > 0: + ok = np.abs(out) > 1e-6 * peak + else: + ok = np.zeros(out.shape, bool) + return (qr[ok] * shape[1] + qc[ok]).astype(np.int64), out[ok] + + +def place_footprints( + footprints: tuple, + n_sources: int, + tmap: TrialMap, + shape: tuple, + sigma: float = 0.0, + interp_order: int = 1, +) -> sparse.csr_matrix: + """Move a trial's footprints into its registered frame. + + Parameters + ---------- + footprints : tuple of ndarray + (rows, cols, sources, values): the trial's footprints on the + canvas, one entry per nonzero pixel (zero-based). + n_sources : int + Number of sources (columns of the result). + tmap : TrialMap + The trial's map. + shape : tuple of int + (rows, cols) of the registered frame. + sigma : float + Gaussian blur (px) after the move; 0 for none. + interp_order : int + Interpolation of the canvas footprint at the map's inverse of each + trial pixel: 1 bilinear (the viewer's; it blurs a footprint moved + by a fraction of a pixel, by up to ~10% at the peak pixel of a + 1.3 px footprint), 3 cubic spline (keeps the shape; small negative + lobes at the edge are kept so the flux is unchanged). + + Returns + ------- + scipy.sparse.csr_matrix, shape (rows * cols, n_sources) + Row-major flat pixel index by source. + """ + rows, cols, src, vals = (np.asarray(x) for x in footprints) + order = np.argsort(src, kind="stable") + rows, cols, src, vals = rows[order], cols[order], src[order], vals[order] + edges = np.flatnonzero(np.diff(src)) + 1 + ii, jj, vv = [], [], [] + for k in np.split(np.arange(src.size), edges): + if k.size == 0: + continue + idx, val = _place_one(rows[k], cols[k], vals[k], tmap, shape, sigma, interp_order) + ii.append(idx) + jj.append(np.full(idx.size, int(src[k[0]]))) + vv.append(val) + n_px = int(shape[0]) * int(shape[1]) + if not ii: + return sparse.csr_matrix((n_px, n_sources)) + ii, jj, vv = map(np.concatenate, (ii, jj, vv)) + return sparse.csr_matrix((vv, (ii, jj)), shape=(n_px, n_sources)) diff --git a/src/giant_python/viewer/run.py b/src/giant_python/viewer/run.py index 1f1776b1..3adb85ec 100644 --- a/src/giant_python/viewer/run.py +++ b/src/giant_python/viewer/run.py @@ -1,468 +1,607 @@ -"""A SILo run's outputs as the viewer reads them. - -A run is a folder with ``experiment_summary.h5`` and ``per_trial_summary.h5`` -(directly or in ``source_extraction/``), as ``giant silo`` writes them -(GIAnT-MATLAB's schema). The viewer reads only these two files, so runs -whose work folder is gone (Code Ocean results) work too; the plan files -(``work/plan/path.h5``, or ``source_extraction/silo/plan``), when -present, add the seeds that did not become sources. - -The summaries are written in MATLAB's orientation (h5py shows the -dimensions reversed); everything here is returned in MATLAB's orientation -with zero-based pixel coordinates. Arrays of one path are read when the -path is first used and kept. -""" - -from __future__ import annotations - -import math -import threading -from dataclasses import dataclass, field -from pathlib import Path -from typing import Optional - -import h5py -import numpy as np -from numpy.typing import ArrayLike - -from .render import TrialMap - -_Scalar = str | int | float | bool | list -"""What an HDF5 parameter becomes (see :func:`_scalar`).""" - - -def _mat(f: h5py.File, name: str) -> np.ndarray | None: - """Read a summary dataset in MATLAB orientation, or None.""" - if name not in f: - return None - a = f[name][()] - return a.T if getattr(a, "ndim", 0) > 1 else a - - -def _scalar(v: object) -> _Scalar: - """Convert an HDF5 value to a Python scalar or string.""" - a = np.asarray(v) - if a.dtype.kind in "SO": - x = a.ravel()[0] if a.size else "" - return x.decode() if isinstance(x, bytes) else str(x) - if a.dtype.kind in "U": - return str(a.ravel()[0]) if a.size else "" - return a.ravel()[0].item() if a.size == 1 else a.tolist() - - -def find_summaries(run_dir: str | Path) -> Path: - """Find the folder holding a run's ``experiment_summary.h5``.""" - run_dir = Path(run_dir) - for d in (run_dir, run_dir / "source_extraction"): - if (d / "experiment_summary.h5").exists(): - return d - found = sorted(run_dir.glob("**/experiment_summary.h5")) - if len(found) == 1: - return found[0].parent - raise FileNotFoundError( - f"{run_dir}: no experiment_summary.h5" + (" (several below it; give one)" if found else "") - ) - - -def _plan_file(run_dir: Path, summaries: Path, d: int) -> Optional[Path]: - """Find the plan file of path ``d`` (one-based), if the run kept it.""" - for p in ( - run_dir / "work" / "plan" / f"path{d}.h5", - summaries / "silo" / "plan" / f"path{d}.h5", - ): - if p.exists(): - return p - return None - - -def footprint_width(profile: np.ndarray, r0: float, c0: float, radius: int = 6) -> float: - """RMS width per axis (px) of a footprint image around its source pixel. - - It is taken over the disk of ``radius`` px around ``(r0, c0)``, values - clipped at 0 (the measure of the footprint-support comparisons). - """ - r0, c0 = int(round(r0)), int(round(c0)) - rr, cc = np.mgrid[-radius : radius + 1, -radius : radius + 1] - m = rr**2 + cc**2 <= radius**2 - rr, cc = rr[m] + r0, cc[m] + c0 - ok = (rr >= 0) & (rr < profile.shape[0]) & (cc >= 0) & (cc < profile.shape[1]) - rr, cc = rr[ok], cc[ok] - x = np.clip(np.nan_to_num(profile[rr, cc]), 0, None) - if x.sum() <= 0: - return float("nan") - mr, mc = (x * rr).sum() / x.sum(), (x * cc).sum() / x.sum() - var = (x * ((rr - mr) ** 2 + (cc - mc) ** 2)).sum() / x.sum() / 2 - return float(math.sqrt(var)) - - -@dataclass -class Sources: - """One path's sources in a run (consensus canvas, zero-based). - - Attributes - ---------- - rc : ndarray (n, 2) - Kept sources' footprint centroids (``sources/spatial/coords``). - pixel : ndarray (n, 2) - Their source pixels (``visualizations/act_im_peaks``). - snr, kinetic_score, kinetic_n_events, width : ndarray (n,) - rejected_rc : ndarray (m, 2) - Sources the kinetics test rejected (their pixels). - rejected_score, rejected_n_events : ndarray (m,) - unused_seeds : ndarray (k, 2) or None - Seeds without a source (from the plan file; None without it). - """ - - rc: np.ndarray - pixel: np.ndarray - snr: np.ndarray - kinetic_score: np.ndarray - kinetic_n_events: np.ndarray - width: np.ndarray - rejected_rc: np.ndarray - rejected_score: np.ndarray - rejected_n_events: np.ndarray - unused_seeds: Optional[np.ndarray] = None - - @property - def n(self) -> int: - """Number of kept sources.""" - return int(self.rc.shape[0]) - - -def _vec(a: ArrayLike | None, n: int, fill: float = np.nan) -> np.ndarray: - """Return a summary vector as float64 of length ``n``.""" - if a is None: - return np.full(n, fill) - return np.asarray(a, dtype=np.float64).ravel()[:n] - - -def _rc(a: ArrayLike | None) -> np.ndarray: - """``[0, row, col]`` rows as ``(n, 2)`` (empty when missing).""" - if a is None: - return np.zeros((0, 2)) - return np.asarray(a, dtype=np.float64).reshape(-1, 3)[:, 1:3] - - -@dataclass -class PathData: - """One path of a run: images, sources, traces, footprints, maps. - - Attributes - ---------- - path : int - One-based imaging path. - shape : tuple of int - ``(rows, cols)`` of the consensus canvas. - act_im, mean_im : ndarray (rows, cols) - Combined activity image; mean image of the activity channel. - trial_act, trial_mean : ndarray (trials, rows, cols) or None - n_frames : ndarray of int (trials,) - SILo's 200 Hz frames per trial (0: not analysed). - lines, discard : ndarray (total,) - SILo's frame lines and discarded frames, trials concatenated. - maps : list of (TrialMap or None) - Each trial's map from the canvas to its registered frame. - sources : Sources - """ - - path: int - shape: tuple - act_im: np.ndarray - mean_im: np.ndarray - trial_act: Optional[np.ndarray] - trial_mean: Optional[np.ndarray] - n_frames: np.ndarray - lines: np.ndarray - discard: np.ndarray - maps: list - sources: Sources - alignment: str = "rigid" - _traces: dict = field(default_factory=dict, repr=False) - _footprints: Optional[list] = field(default=None, repr=False) - _trial_rc: Optional[np.ndarray] = field(default=None, repr=False) - - @property - def offsets(self) -> np.ndarray: - """First 200 Hz frame of each trial in the concatenated traces.""" - return np.concatenate([[0], np.cumsum(self.n_frames)]).astype(int) - - def trial_span(self, t: int) -> slice: - """Return the concatenated frames of trial ``t`` (zero-based).""" - o = self.offsets - return slice(int(o[t]), int(o[t + 1])) - - -TRACES = ("dF_denoised", "dF_ls", "events", "F0") - - -class SiloRun: - """A SILo run's summaries, read path by path on demand. - - Parameters - ---------- - run_dir : str or Path - The run folder (or its ``source_extraction`` folder). - name : str, optional - Label shown on the page (default: the folder's name). - """ - - def __init__(self, run_dir: str | Path, name: Optional[str] = None) -> None: - """Open the run and read its parameters.""" - self.run_dir = Path(run_dir) - self.summaries = find_summaries(self.run_dir) - self.experiment = self.summaries / "experiment_summary.h5" - self.per_trial = self.summaries / "per_trial_summary.h5" - self.name = name or self.run_dir.name - with h5py.File(self.experiment, "r") as f: - # scalars and short vectors; validKernel is the kernel itself - # (a width x width matrix), kept whatever its size - self.params = { - k: _scalar(f["params"][k][()]) - for k in f.get("params", {}) - if f["params"][k].size <= 64 or k == "validKernel" - } - self.attrs = {k: _scalar(v) for k, v in f.attrs.items()} - self.paths = sorted(int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()) - self._paths: dict = {} - self._lock = threading.Lock() - - def param(self, name: str, default: _Scalar | None = None) -> _Scalar | None: - """Return a value of the run's ``params`` (MATLAB names).""" - v = self.params.get(name, default) - return default if v is None or v == "" else v - - @property - def activity_channel(self) -> int: - """Zero-based file channel of the activity signal.""" - return int(self.param("activityChannel", 1)) - 1 - - def describe(self) -> dict: - """Return the run's settings that the page shows.""" - keys = ( - "baselineSource", - "baselineMode", - "localizationBaseline", - "interTrialAlignment", - "validKernel", - "peakth", - "minSourceEventRate", - "footprintVariance", - "seedFit", - "seedMergePx", - "minKineticScore", - "photonScale", - "alignHz", - "analyzeHz", - ) - out = {k: self.params[k] for k in keys if k in self.params} - out.setdefault("baselineSource", "median") - vk = out.get("validKernel") - if isinstance(vk, list): # the kernel itself: report its width - out["validKernel"] = int(round(math.sqrt(len(np.ravel(vk))))) - return out - - def path(self, d: int) -> PathData: - """Path ``d`` (one-based), read on first use.""" - with self._lock: - if d not in self._paths: - self._paths[d] = self._read_path(d) - return self._paths[d] - - def _read_path(self, d: int) -> PathData: - """Read one path's images, frames, maps and sources.""" - g = f"Path{d}" - ch = self.activity_channel - with h5py.File(self.experiment, "r") as f: - act = _mat(f, f"{g}/visualizations/act_im")[0] - mean = _mat(f, f"{g}/visualizations/mean_im") - mean = mean[min(ch, mean.shape[0] - 1), 0] - fi = f"{g}/frame_info" - n_frames = np.asarray(_mat(f, f"{fi}/trial_num_frames")).ravel() - lines = _vec(_mat(f, f"{fi}/frame_line_idxs"), int(n_frames.sum())) - disc = _vec(_mat(f, f"{fi}/discard_frames"), lines.size, 0) - maps, mode = _read_maps(f, fi, n_frames.size) - sources = _read_sources(f, g, act.shape) - trial_act = trial_mean = None - if self.per_trial.exists(): - with h5py.File(self.per_trial, "r") as f: - ta = _mat(f, f"{g}/visualizations/per_trial_act_im") - tm = _mat(f, f"{g}/visualizations/per_trial_mean_im") - trial_act = None if ta is None else ta[:, 0].astype(np.float32) - if tm is not None: - trial_mean = tm[:, min(ch, tm.shape[1] - 1), 0] - trial_mean = trial_mean.astype(np.float32) - plan = _plan_file(self.run_dir, self.summaries, d) - if plan is not None: - sources.unused_seeds = _unused_seeds(plan) - return PathData( - path=d, - shape=tuple(act.shape), - act_im=act.astype(np.float32), - mean_im=mean.astype(np.float32), - trial_act=trial_act, - trial_mean=trial_mean, - n_frames=n_frames.astype(int), - lines=lines, - discard=disc.astype(bool), - maps=maps, - sources=sources, - alignment=mode, - ) - - def traces(self, d: int) -> dict: - """Return the activity channel's traces of path ``d``. - - A dict from name to array ``(total frames, kept sources)`` (dF_denoised, - dF_ls, events, F0). - """ - p = self.path(d) - with self._lock: - if not p._traces: - p._traces = self._read_traces(d) - return p._traces - - def _read_traces(self, d: int) -> dict: - """Read the four trace datasets of one path (activity channel).""" - out = {} - ch = self.activity_channel - with h5py.File(self.experiment, "r") as f: - for name in TRACES: - key = f"Path{d}/sources/temporal/{name}" - if key in f: # h5py: (frames, channels, sources) - ds = f[key] - c = min(ch, ds.shape[1] - 1) - out[name] = np.asarray(ds[:, c, :], np.float32) - return out - - def profile_patch(self, d: int, s: int, half: int = 7) -> tuple[np.ndarray, int, int]: - """Source ``s``'s mean footprint (``sources/spatial/profiles``) around its pixel. - - Returned as ``(patch, row0, col0)``. - """ - p = self.path(d) - r0, c0 = (int(v) for v in p.sources.pixel[s]) - ra = slice(max(0, r0 - half), min(p.shape[0], r0 + half + 1)) - ca = slice(max(0, c0 - half), min(p.shape[1], c0 + half + 1)) - with h5py.File(self.experiment, "r") as f: - prof = f[f"Path{d}/sources/spatial/profiles"] # (c, r, 1, n) - patch = np.asarray(prof[ca, ra, 0, s], np.float32).T - return patch, ra.start, ca.start - - def footprints(self, d: int) -> list: - """Each trial's footprints of path ``d`` on the canvas. - - Given as ``(rows, cols, sources, values)`` (None for a trial without). - """ - p = self.path(d) - with self._lock: - if p._footprints is None: - p._footprints, p._trial_rc = self._read_footprints(d, p) - return p._footprints - - def trial_centroids(self, d: int) -> np.ndarray: - """Per-trial footprint centroids ``(trials, sources, 2)``. - - NaN where a trial has none. - """ - self.footprints(d) - return self.path(d)._trial_rc - - def _read_footprints(self, d: int, p: PathData) -> tuple[list, np.ndarray]: - """Read ``per_trial_profiles`` in blocks of columns.""" - n_t, n_s = p.n_frames.size, p.sources.n - parts: list = [[] for _ in range(n_t)] - rc = np.full((n_t, n_s, 2), np.nan) - if not self.per_trial.exists() or n_s == 0: - return [None] * n_t, rc - g = f"Path{d}/sources" - with h5py.File(self.per_trial, "r") as f: - if f"{g}/spatial/per_trial_profiles" not in f: - return [None] * n_t, rc - ds = f[f"{g}/spatial/per_trial_profiles"] # (cols, rows, 1, s, t) - step = max(1, int(2e8 // max(1, ds.shape[1] * n_s * n_t * 4))) - for c0 in range(0, ds.shape[0], step): - blk = np.nan_to_num(ds[c0 : c0 + step, :, 0]) - c, r, s, t = np.nonzero(blk) - v = blk[c, r, s, t] - for k in np.unique(t): - m = t == k - parts[k].append((r[m], c[m] + c0, s[m], v[m])) - coords = _mat(f, f"{g}/spatial/per_trial_coords") - if coords is not None: # MATLAB (trials, sources, 3) - rc[:] = np.asarray(coords, np.float64)[:n_t, :n_s, 1:3] - out = [] - for k in range(n_t): - if not parts[k]: - out.append(None) - continue - out.append(tuple(np.concatenate(x) for x in zip(*parts[k]))) - return out, rc - - -def _read_maps(f: h5py.File, fi: str, n_trials: int) -> tuple[list[TrialMap | None], str]: - """Each trial's ``TrialMap`` and the alignment mode.""" - affine = _mat(f, f"{fi}/trial_alignment_affine") - disp = _mat(f, f"{fi}/trial_alignment_displacement") - if affine is None: # only offline shifts: unknown - return [None] * n_trials, "unknown" - affine = np.asarray(affine, np.float64).reshape(-1, 2, 3) - maps = [] - for t in range(n_trials): - a = affine[t] if t < affine.shape[0] else np.full((2, 3), np.nan) - fld = None - if disp is not None and t < disp.shape[0]: - fld = np.asarray(disp[t], np.float64) # (2, rows, cols) - m = TrialMap(a, fld) - maps.append(m if m.valid else None) - if disp is not None: - return maps, "patchwise" - eye = np.isfinite(affine[:, 0, 0]) - rigid = np.allclose(affine[eye][:, :, :2], np.eye(2)) if eye.any() else 1 - return maps, "rigid" if rigid else "affine" - - -def _read_sources(f: h5py.File, g: str, shape: tuple[int, ...]) -> Sources: - """Read a path's kept and rejected sources from the experiment summary.""" - rc = _rc(_mat(f, f"{g}/sources/spatial/coords")) - n = rc.shape[0] - pixel = _rc(_mat(f, f"{g}/visualizations/act_im_peaks")) - if pixel.shape[0] != n: - pixel = np.round(rc) - temporal = f"{g}/sources/temporal" - width = np.full(n, np.nan) - if n and f"{g}/sources/spatial/profiles" in f: - prof = f[f"{g}/sources/spatial/profiles"] # (cols, rows, 1, n) - for s in range(n): - r0, c0 = pixel[s] - ra = slice(max(0, int(r0) - 7), min(shape[0], int(r0) + 8)) - ca = slice(max(0, int(c0) - 7), min(shape[1], int(c0) + 8)) - img = prof[ca, ra, 0, s].T - width[s] = footprint_width(img, r0 - ra.start, c0 - ca.start) - rej = f"{g}/sources/rejected" - rej_rc = _rc(_mat(f, f"{rej}/seed_coords")) - m = rej_rc.shape[0] - return Sources( - rc=rc, - pixel=pixel, - snr=_vec(_mat(f, f"{temporal}/SNR"), n), - kinetic_score=_vec(_mat(f, f"{temporal}/kinetic_score"), n), - kinetic_n_events=_vec(_mat(f, f"{temporal}/kinetic_n_events"), n), - width=width, - rejected_rc=rej_rc, - rejected_score=_vec(_mat(f, f"{rej}/kinetic_score"), m), - rejected_n_events=_vec(_mat(f, f"{rej}/kinetic_n_events"), m), - ) - - -def _unused_seeds(plan_path: Path) -> np.ndarray: - """Seeds of a plan whose rounded pixel has no source.""" - with h5py.File(plan_path, "r") as f: - g = f["sources"] if "sources" in f else f - seeds = np.asarray(g["seeds"][()], np.float64).reshape(-1, 4) - rows = np.asarray(g["rows"][()]).ravel() - cols = np.asarray(g["cols"][()]).ravel() - have = set(zip(rows.tolist(), cols.tolist())) - pix = np.floor(seeds[:, 1:3] + 0.5).astype(int) - keep = [(int(r), int(c)) not in have for r, c in pix] - return seeds[np.asarray(keep, bool)][:, 1:3] +"""A SILo run's outputs as the viewer reads them. + +A run is a folder with experiment_summary.h5 and per_trial_summary.h5 +(directly or in source_extraction/), as giant silo writes them +(GIAnT-MATLAB's schema). The viewer reads only these two files, so runs +whose work folder is gone (Code Ocean results) work too; the plan files +(work/plan/path.h5, or source_extraction/silo/plan), when +present, add the seeds that did not become sources. + +The summaries are written in MATLAB's orientation (h5py shows the +dimensions reversed); everything here is returned in MATLAB's orientation +with zero-based pixel coordinates. Arrays of one path are read when the +path is first used and kept. +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional + +import h5py +import numpy as np +from numpy.typing import ArrayLike + +from .render import TrialMap + +_Scalar = str | int | float | bool | list +"""What an HDF5 parameter becomes (see :func:`_scalar`).""" + + +def _mat(f: h5py.File, name: str) -> np.ndarray | None: + """Read a summary dataset in MATLAB orientation, or None. + + Returns + ------- + np.ndarray or None + The dataset (transposed when it has more than one dimension); None when name is not in + the file. + """ + if name not in f: + return None + a = f[name][()] + return a.T if getattr(a, "ndim", 0) > 1 else a + + +def _scalar(v: object) -> _Scalar: + """Convert an HDF5 value to a Python scalar or string. + + Returns + ------- + str or int or float or bool or list + A string for text values, a Python scalar for a single value, otherwise the values as a + list. + """ + a = np.asarray(v) + if a.dtype.kind in "SO": + x = a.ravel()[0] if a.size else "" + return x.decode() if isinstance(x, bytes) else str(x) + if a.dtype.kind in "U": + return str(a.ravel()[0]) if a.size else "" + return a.ravel()[0].item() if a.size == 1 else a.tolist() + + +def find_summaries(run_dir: str | Path) -> Path: + """Find the folder holding a run's experiment_summary.h5. + + Returns + ------- + Path + The folder with experiment_summary.h5: the run folder, its source_extraction folder, + or the only folder below it that has one. + + Raises + ------ + FileNotFoundError + If no experiment_summary.h5 is found, or several are found below the run folder. + """ + run_dir = Path(run_dir) + for d in (run_dir, run_dir / "source_extraction"): + if (d / "experiment_summary.h5").exists(): + return d + found = sorted(run_dir.glob("**/experiment_summary.h5")) + if len(found) == 1: + return found[0].parent + raise FileNotFoundError( + f"{run_dir}: no experiment_summary.h5" + (" (several below it; give one)" if found else "") + ) + + +def _plan_file(run_dir: Path, summaries: Path, d: int) -> Optional[Path]: + """Find the plan file of path d (one-based), if the run kept it. + + Returns + ------- + Path or None + The plan file; None when the run has none. + """ + for p in ( + run_dir / "work" / "plan" / f"path{d}.h5", + summaries / "silo" / "plan" / f"path{d}.h5", + ): + if p.exists(): + return p + return None + + +def footprint_width(profile: np.ndarray, r0: float, c0: float, radius: int = 6) -> float: + """RMS width per axis (px) of a footprint image around its source pixel. + + It is taken over the disk of radius px around (r0, c0), values + clipped at 0 (the measure of the footprint-support comparisons). + + Returns + ------- + float + The RMS width in px; NaN when the footprint has no positive value in the disk. + """ + r0, c0 = int(round(r0)), int(round(c0)) + rr, cc = np.mgrid[-radius : radius + 1, -radius : radius + 1] + m = rr**2 + cc**2 <= radius**2 + rr, cc = rr[m] + r0, cc[m] + c0 + ok = (rr >= 0) & (rr < profile.shape[0]) & (cc >= 0) & (cc < profile.shape[1]) + rr, cc = rr[ok], cc[ok] + x = np.clip(np.nan_to_num(profile[rr, cc]), 0, None) + if x.sum() <= 0: + return float("nan") + mr, mc = (x * rr).sum() / x.sum(), (x * cc).sum() / x.sum() + var = (x * ((rr - mr) ** 2 + (cc - mc) ** 2)).sum() / x.sum() / 2 + return float(math.sqrt(var)) + + +@dataclass +class Sources: + """One path's sources in a run (consensus canvas, zero-based). + + Attributes + ---------- + rc : ndarray (n, 2) + Kept sources' footprint centroids (sources/spatial/coords). + pixel : ndarray (n, 2) + Their source pixels (visualizations/act_im_peaks). + snr, kinetic_score, kinetic_n_events, width : ndarray (n,) + rejected_rc : ndarray (m, 2) + Sources the kinetics test rejected (their pixels). + rejected_score, rejected_n_events : ndarray (m,) + unused_seeds : ndarray (k, 2) or None + Seeds without a source (from the plan file; None without it). + """ + + rc: np.ndarray + pixel: np.ndarray + snr: np.ndarray + kinetic_score: np.ndarray + kinetic_n_events: np.ndarray + width: np.ndarray + rejected_rc: np.ndarray + rejected_score: np.ndarray + rejected_n_events: np.ndarray + unused_seeds: Optional[np.ndarray] = None + + @property + def n(self) -> int: + """Number of kept sources.""" + return int(self.rc.shape[0]) + + +def _vec(a: ArrayLike | None, n: int, fill: float = np.nan) -> np.ndarray: + """Return a summary vector as float64 of length n. + + Returns + ------- + np.ndarray + The first n values as float64; n values of fill when a is None. + """ + if a is None: + return np.full(n, fill) + return np.asarray(a, dtype=np.float64).ravel()[:n] + + +def _rc(a: ArrayLike | None) -> np.ndarray: + """[0, row, col] rows as (n, 2) (empty when missing). + + Returns + ------- + np.ndarray + The (n, 2) row and column of each entry; shape (0, 2) when a is None. + """ + if a is None: + return np.zeros((0, 2)) + return np.asarray(a, dtype=np.float64).reshape(-1, 3)[:, 1:3] + + +@dataclass +class PathData: + """One path of a run: images, sources, traces, footprints, maps. + + Attributes + ---------- + path : int + One-based imaging path. + shape : tuple of int + (rows, cols) of the consensus canvas. + act_im, mean_im : ndarray (rows, cols) + Combined activity image; mean image of the activity channel. + trial_act, trial_mean : ndarray (trials, rows, cols) or None + n_frames : ndarray of int (trials,) + SILo's 200 Hz frames per trial (0: not analysed). + lines, discard : ndarray (total,) + SILo's frame lines and discarded frames, trials concatenated. + maps : list of (TrialMap or None) + Each trial's map from the canvas to its registered frame. + sources : Sources + """ + + path: int + shape: tuple + act_im: np.ndarray + mean_im: np.ndarray + trial_act: Optional[np.ndarray] + trial_mean: Optional[np.ndarray] + n_frames: np.ndarray + lines: np.ndarray + discard: np.ndarray + maps: list + sources: Sources + alignment: str = "rigid" + _traces: dict = field(default_factory=dict, repr=False) + _footprints: Optional[list] = field(default=None, repr=False) + _trial_rc: Optional[np.ndarray] = field(default=None, repr=False) + + @property + def offsets(self) -> np.ndarray: + """First 200 Hz frame of each trial in the concatenated traces.""" + return np.concatenate([[0], np.cumsum(self.n_frames)]).astype(int) + + def trial_span(self, t: int) -> slice: + """Return the concatenated frames of trial t (zero-based). + + Returns + ------- + slice + The span of trial t in the concatenated frames. + """ + o = self.offsets + return slice(int(o[t]), int(o[t + 1])) + + +TRACES = ("dF_denoised", "dF_ls", "events", "F0") + + +class SiloRun: + """A SILo run's summaries, read path by path on demand. + + Parameters + ---------- + run_dir : str or Path + The run folder (or its source_extraction folder). + name : str, optional + Label shown on the page (default: the folder's name). + """ + + def __init__(self, run_dir: str | Path, name: Optional[str] = None) -> None: + """Open the run and read its parameters.""" + self.run_dir = Path(run_dir) + self.summaries = find_summaries(self.run_dir) + self.experiment = self.summaries / "experiment_summary.h5" + self.per_trial = self.summaries / "per_trial_summary.h5" + self.name = name or self.run_dir.name + with h5py.File(self.experiment, "r") as f: + # scalars and short vectors; validKernel is the kernel itself + # (a width x width matrix), kept whatever its size + self.params = { + k: _scalar(f["params"][k][()]) + for k in f.get("params", {}) + if f["params"][k].size <= 64 or k == "validKernel" + } + self.attrs = {k: _scalar(v) for k, v in f.attrs.items()} + self.paths = sorted(int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()) + self._paths: dict = {} + self._lock = threading.Lock() + + def param(self, name: str, default: _Scalar | None = None) -> _Scalar | None: + """Return a value of the run's params (MATLAB names). + + Returns + ------- + str or int or float or bool or list or None + The parameter's value; default when it is missing, None or empty. + """ + v = self.params.get(name, default) + return default if v is None or v == "" else v + + @property + def activity_channel(self) -> int: + """Zero-based file channel of the activity signal.""" + return int(self.param("activityChannel", 1)) - 1 + + def describe(self) -> dict: + """Return the run's settings that the page shows. + + Returns + ------- + dict + The settings by MATLAB name; validKernel is its width, and baselineSource + defaults to "median". + """ + keys = ( + "baselineSource", + "baselineMode", + "localizationBaseline", + "interTrialAlignment", + "validKernel", + "peakth", + "minSourceEventRate", + "footprintVariance", + "seedFit", + "seedMergePx", + "minKineticScore", + "photonScale", + "alignHz", + "analyzeHz", + ) + out = {k: self.params[k] for k in keys if k in self.params} + out.setdefault("baselineSource", "median") + vk = out.get("validKernel") + if isinstance(vk, list): # the kernel itself: report its width + out["validKernel"] = int(round(math.sqrt(len(np.ravel(vk))))) + return out + + def path(self, d: int) -> PathData: + """Path d (one-based), read on first use. + + Returns + ------- + PathData + The path's images, sources, frames and maps. + """ + with self._lock: + if d not in self._paths: + self._paths[d] = self._read_path(d) + return self._paths[d] + + def _read_path(self, d: int) -> PathData: + """Read one path's images, frames, maps and sources. + + Returns + ------- + PathData + The path's data, read from the summaries. + """ + g = f"Path{d}" + ch = self.activity_channel + with h5py.File(self.experiment, "r") as f: + act = _mat(f, f"{g}/visualizations/act_im")[0] + mean = _mat(f, f"{g}/visualizations/mean_im") + mean = mean[min(ch, mean.shape[0] - 1), 0] + fi = f"{g}/frame_info" + n_frames = np.asarray(_mat(f, f"{fi}/trial_num_frames")).ravel() + lines = _vec(_mat(f, f"{fi}/frame_line_idxs"), int(n_frames.sum())) + disc = _vec(_mat(f, f"{fi}/discard_frames"), lines.size, 0) + maps, mode = _read_maps(f, fi, n_frames.size) + sources = _read_sources(f, g, act.shape) + trial_act = trial_mean = None + if self.per_trial.exists(): + with h5py.File(self.per_trial, "r") as f: + ta = _mat(f, f"{g}/visualizations/per_trial_act_im") + tm = _mat(f, f"{g}/visualizations/per_trial_mean_im") + trial_act = None if ta is None else ta[:, 0].astype(np.float32) + if tm is not None: + trial_mean = tm[:, min(ch, tm.shape[1] - 1), 0] + trial_mean = trial_mean.astype(np.float32) + plan = _plan_file(self.run_dir, self.summaries, d) + if plan is not None: + sources.unused_seeds = _unused_seeds(plan) + return PathData( + path=d, + shape=tuple(act.shape), + act_im=act.astype(np.float32), + mean_im=mean.astype(np.float32), + trial_act=trial_act, + trial_mean=trial_mean, + n_frames=n_frames.astype(int), + lines=lines, + discard=disc.astype(bool), + maps=maps, + sources=sources, + alignment=mode, + ) + + def traces(self, d: int) -> dict: + """Return the activity channel's traces of path d. + + A dict from name to array (total frames, kept sources) (dF_denoised, + dF_ls, events, F0). + + Returns + ------- + dict + The traces by name, each (total frames, kept sources); read on first use. + """ + p = self.path(d) + with self._lock: + if not p._traces: + p._traces = self._read_traces(d) + return p._traces + + def _read_traces(self, d: int) -> dict: + """Read the four trace datasets of one path (activity channel). + + Returns + ------- + dict + The float32 trace arrays by name (those present in the file). + """ + out = {} + ch = self.activity_channel + with h5py.File(self.experiment, "r") as f: + for name in TRACES: + key = f"Path{d}/sources/temporal/{name}" + if key in f: # h5py: (frames, channels, sources) + ds = f[key] + c = min(ch, ds.shape[1] - 1) + out[name] = np.asarray(ds[:, c, :], np.float32) + return out + + def profile_patch(self, d: int, s: int, half: int = 7) -> tuple[np.ndarray, int, int]: + """Source s's mean footprint (sources/spatial/profiles) around its pixel. + + Returned as (patch, row0, col0). + + Returns + ------- + patch : np.ndarray + The footprint's (rows, cols) patch, up to 2 * half + 1 px square. + row0 : int + Canvas row of the patch's first row. + col0 : int + Canvas column of the patch's first column. + """ + p = self.path(d) + r0, c0 = (int(v) for v in p.sources.pixel[s]) + ra = slice(max(0, r0 - half), min(p.shape[0], r0 + half + 1)) + ca = slice(max(0, c0 - half), min(p.shape[1], c0 + half + 1)) + with h5py.File(self.experiment, "r") as f: + prof = f[f"Path{d}/sources/spatial/profiles"] # (c, r, 1, n) + patch = np.asarray(prof[ca, ra, 0, s], np.float32).T + return patch, ra.start, ca.start + + def footprints(self, d: int) -> list: + """Each trial's footprints of path d on the canvas. + + Given as (rows, cols, sources, values) (None for a trial without). + + Returns + ------- + list + One entry per trial: the tuple (rows, cols, sources, values) of its footprints, or + None for a trial without; read on first use. + """ + p = self.path(d) + with self._lock: + if p._footprints is None: + p._footprints, p._trial_rc = self._read_footprints(d, p) + return p._footprints + + def trial_centroids(self, d: int) -> np.ndarray: + """Per-trial footprint centroids (trials, sources, 2). + + NaN where a trial has none. + + Returns + ------- + np.ndarray + The (trials, sources, 2) row and column of each source's footprint in each trial. + """ + self.footprints(d) + return self.path(d)._trial_rc + + def _read_footprints(self, d: int, p: PathData) -> tuple[list, np.ndarray]: + """Read per_trial_profiles in blocks of columns. + + Returns + ------- + footprints : list + One entry per trial: (rows, cols, sources, values), or None for a trial without. + trial_rc : np.ndarray + The (trials, sources, 2) per-trial footprint centroids (NaN where missing). + """ + n_t, n_s = p.n_frames.size, p.sources.n + parts: list = [[] for _ in range(n_t)] + rc = np.full((n_t, n_s, 2), np.nan) + if not self.per_trial.exists() or n_s == 0: + return [None] * n_t, rc + g = f"Path{d}/sources" + with h5py.File(self.per_trial, "r") as f: + if f"{g}/spatial/per_trial_profiles" not in f: + return [None] * n_t, rc + ds = f[f"{g}/spatial/per_trial_profiles"] # (cols, rows, 1, s, t) + step = max(1, int(2e8 // max(1, ds.shape[1] * n_s * n_t * 4))) + for c0 in range(0, ds.shape[0], step): + blk = np.nan_to_num(ds[c0 : c0 + step, :, 0]) + c, r, s, t = np.nonzero(blk) + v = blk[c, r, s, t] + for k in np.unique(t): + m = t == k + parts[k].append((r[m], c[m] + c0, s[m], v[m])) + coords = _mat(f, f"{g}/spatial/per_trial_coords") + if coords is not None: # MATLAB (trials, sources, 3) + rc[:] = np.asarray(coords, np.float64)[:n_t, :n_s, 1:3] + out = [] + for k in range(n_t): + if not parts[k]: + out.append(None) + continue + out.append(tuple(np.concatenate(x) for x in zip(*parts[k]))) + return out, rc + + +def _read_maps(f: h5py.File, fi: str, n_trials: int) -> tuple[list[TrialMap | None], str]: + """Each trial's TrialMap and the alignment mode. + + Returns + ------- + maps : list + One TrialMap per trial, None where it is not valid (or unknown). + mode : str + "patchwise", "rigid" or "affine"; "unknown" with only offline shifts. + """ + affine = _mat(f, f"{fi}/trial_alignment_affine") + disp = _mat(f, f"{fi}/trial_alignment_displacement") + if affine is None: # only offline shifts: unknown + return [None] * n_trials, "unknown" + affine = np.asarray(affine, np.float64).reshape(-1, 2, 3) + maps = [] + for t in range(n_trials): + a = affine[t] if t < affine.shape[0] else np.full((2, 3), np.nan) + fld = None + if disp is not None and t < disp.shape[0]: + fld = np.asarray(disp[t], np.float64) # (2, rows, cols) + m = TrialMap(a, fld) + maps.append(m if m.valid else None) + if disp is not None: + return maps, "patchwise" + eye = np.isfinite(affine[:, 0, 0]) + rigid = np.allclose(affine[eye][:, :, :2], np.eye(2)) if eye.any() else 1 + return maps, "rigid" if rigid else "affine" + + +def _read_sources(f: h5py.File, g: str, shape: tuple[int, ...]) -> Sources: + """Read a path's kept and rejected sources from the experiment summary. + + Returns + ------- + Sources + The path's kept and rejected sources. + """ + rc = _rc(_mat(f, f"{g}/sources/spatial/coords")) + n = rc.shape[0] + pixel = _rc(_mat(f, f"{g}/visualizations/act_im_peaks")) + if pixel.shape[0] != n: + pixel = np.round(rc) + temporal = f"{g}/sources/temporal" + width = np.full(n, np.nan) + if n and f"{g}/sources/spatial/profiles" in f: + prof = f[f"{g}/sources/spatial/profiles"] # (cols, rows, 1, n) + for s in range(n): + r0, c0 = pixel[s] + ra = slice(max(0, int(r0) - 7), min(shape[0], int(r0) + 8)) + ca = slice(max(0, int(c0) - 7), min(shape[1], int(c0) + 8)) + img = prof[ca, ra, 0, s].T + width[s] = footprint_width(img, r0 - ra.start, c0 - ca.start) + rej = f"{g}/sources/rejected" + rej_rc = _rc(_mat(f, f"{rej}/seed_coords")) + m = rej_rc.shape[0] + return Sources( + rc=rc, + pixel=pixel, + snr=_vec(_mat(f, f"{temporal}/SNR"), n), + kinetic_score=_vec(_mat(f, f"{temporal}/kinetic_score"), n), + kinetic_n_events=_vec(_mat(f, f"{temporal}/kinetic_n_events"), n), + width=width, + rejected_rc=rej_rc, + rejected_score=_vec(_mat(f, f"{rej}/kinetic_score"), m), + rejected_n_events=_vec(_mat(f, f"{rej}/kinetic_n_events"), m), + ) + + +def _unused_seeds(plan_path: Path) -> np.ndarray: + """Seeds of a plan whose rounded pixel has no source. + + Returns + ------- + np.ndarray + The (k, 2) row and column of each such seed. + """ + with h5py.File(plan_path, "r") as f: + g = f["sources"] if "sources" in f else f + seeds = np.asarray(g["seeds"][()], np.float64).reshape(-1, 4) + rows = np.asarray(g["rows"][()]).ravel() + cols = np.asarray(g["cols"][()]).ravel() + have = set(zip(rows.tolist(), cols.tolist())) + pix = np.floor(seeds[:, 1:3] + 0.5).astype(int) + keep = [(int(r), int(c)) not in have for r, c in pix] + return seeds[np.asarray(keep, bool)][:, 1:3] diff --git a/src/giant_python/viewer/server.py b/src/giant_python/viewer/server.py index 0364d0a2..9a32ea42 100644 --- a/src/giant_python/viewer/server.py +++ b/src/giant_python/viewer/server.py @@ -1,551 +1,713 @@ -"""``giant view``: a local page for inspecting SILo runs by eye. - -``giant view RUN [RUN ...]`` serves http://127.0.0.1:8766 with two views: - -* **Sources**: per path, the combined activity image, each trial's - activity image and the mean image of one or two runs, with the runs' - sources overlaid (kept, kinetics-rejected and, when the run kept its - plan files, seeds without a source), synchronized zoom and pan, a - flicker between two panels, and a source's footprint, traces (denoised - and least-squares dF, events, F0 over all trials), SNR, kinetic score - and footprint width. With two runs, sources are marked by whether the - other run has one within 1.5 px (one to one, closest first). -* **Movie**: one trial-path at a time, frame by frame: the registered - 80 Hz movie, each run's fitted activity rendered into it - (:mod:`~giant_python.viewer.render`) and the residual movie - activity; - with ``--baseline-dir`` also the network's baseline and movie - - activity - baseline. Scroll or play through time, average frames, zoom - and pan with all panels in step, traces of a pixel or small region. - -A trial-path is loaded when it is shown (``--cache-trials`` at once). -Memory: the movie (float32) and baseline (float16) at the valid pixels, -about 6 bytes x frames x valid pixels (0.5 GB for a 780125 trial of 2254 -frames x 36k pixels); the activity is computed per request from sparse -footprints. - -API (GET; used by the page): ``/api/meta``, ``/api/sources?path=``, -``/api/image?path=&run=&kind=act|mean|trial_act|trial_mean&trial=`` -(float32 rows x cols), ``/api/source?path=&run=&id=`` (JSON), -``/api/source_traces?path=&run=&id=`` (float32 4 x frames), -``/api/trial?path=&trial=`` (JSON), -``/api/frame?path=&trial=&t=&avg=&kernel=`` (float32 layers x valid -pixels), ``/api/trace?path=&trial=&r=&c=&rad=&kernel=`` (float32 layers x -frames; ``kernel`` exporter, matched or exact, default ``--kernel``), -``/api/progress?key=``. -""" - -from __future__ import annotations - -import argparse -import json -import threading -import time -import webbrowser -from collections import OrderedDict -from collections.abc import Iterable -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from typing import Optional -from urllib.parse import parse_qs, urlparse - -import numpy as np -import numpy.typing as npt - -from .run import TRACES, SiloRun -from .trial import Session, TrialMovie, load_trial, source_events - -PAGE = Path(__file__).with_name("page.html") -DEFAULT_PORT = 8766 - - -def _json_safe(o: object) -> object: - """``o`` with non-finite floats as None (the browser rejects NaN).""" - if isinstance(o, float): - return o if np.isfinite(o) else None - if isinstance(o, dict): - return {k: _json_safe(v) for k, v in o.items()} - if isinstance(o, (list, tuple)): - return [_json_safe(v) for v in o] - if isinstance(o, np.ndarray): - return _json_safe(o.tolist()) - if isinstance(o, np.generic): - return _json_safe(o.item()) - return o - - -def _r(a: npt.ArrayLike, nd: int = 3) -> list: - """Round an array to ``nd`` decimals as nested lists.""" - return np.round(np.asarray(a, dtype=np.float64), nd).tolist() - - -class Store: - """The runs of one session and the trial-paths loaded from them. - - Parameters - ---------- - runs : list of SiloRun - One or more runs of the same session (same paths and trials). - session : Session - The trial table and folders. - label : str - Session label for the page. - cache_trials : int - Trial-paths kept in memory. - blur : float - Gaussian blur (px) of the rendered footprints. - """ - - def __init__( - self, - runs: list[SiloRun], - session: Session, - label: str = "", - cache_trials: int = 2, - blur: float = 0.0, - kernel: str = "matched", - ) -> None: - """Check that the runs fit together.""" - if not runs: - raise ValueError("give at least one run") - names = [r.name for r in runs] - if len(set(names)) != len(names): - raise ValueError(f"run names must differ: {names}") - self.runs, self.session, self.label = runs, session, label - self.cache_trials, self.blur = max(1, int(cache_trials)), blur - self.kernel = kernel - self.paths = runs[0].paths - for r in runs[1:]: - if r.paths != self.paths: - raise ValueError( - f"runs have different paths: {runs[0].name} {self.paths}, {r.name} {r.paths}" - ) - # the movie is read once, as the first run's activity channel - # with the trial loader's defaults (trial._settings) - for key, default in (("numChannels", 2), ("activityChannel", 1)): - v0, v = runs[0].param(key, default), r.param(key, default) - if int(v) != int(v0): - raise ValueError(f"runs differ in {key}: {runs[0].name} {v0}, {r.name} {v}") - self._cache: OrderedDict = OrderedDict() - self._loading: dict = {} - # one trial-path loads at a time: each needs a whole movie in memory - self._load_slot = threading.Semaphore(1) - self._lock = threading.Lock() - self.progress: dict = {} - - def run(self, name: str) -> SiloRun: - """Return the run called ``name``.""" - for r in self.runs: - if r.name == name: - return r - raise KeyError(name) - - def meta(self) -> dict: - """List what the page shows: runs, paths, trials.""" - paths = [] - for d in self.paths: - p = self.runs[0].path(d) - trials = [] - for t in range(p.n_frames.size): - trials.append({ - "trial": t, - "frames200": int(p.n_frames[t]), - "movie": bool(self.session.has_movie(d - 1, t)), - "baseline": self.session.baseline_file(d - 1, t) is not None, - "aligned": [r.path(d).maps[t] is not None for r in self.runs], - }) - paths.append({ - "path": d, - "shape": list(p.shape), - "trials": trials, - "alignment": [r.path(d).alignment for r in self.runs], - }) - return { - "label": self.label, - "blur_px": self.blur, - "kernel": self.kernel, - "runs": [ - { - "name": r.name, - "dir": str(r.run_dir), - "settings": r.describe(), - } - for r in self.runs - ], - "table": str(self.session.table), - "moco_dir": str(self.session.moco_dir), - "baseline_dir": str(self.session.baseline_dir or ""), - "paths": paths, - } - - def sources(self, d: int) -> dict: - """Every run's sources of path ``d`` (canvas, zero-based).""" - out = {} - for r in self.runs: - s = r.path(d).sources - kept = ( - np.column_stack([ - s.rc, - s.snr, - s.kinetic_score, - s.kinetic_n_events, - s.width, - s.pixel, - ]) - if s.n - else np.zeros((0, 8)) - ) - rej = np.column_stack([s.rejected_rc, s.rejected_score, s.rejected_n_events]) - seeds = None if s.unused_seeds is None else _r(s.unused_seeds, 2) - out[r.name] = { - "kept": _r(kept), - "rejected": _r(rej), - "seeds": seeds, - "trials": int(r.path(d).n_frames.size), - } - return {"shape": list(self.runs[0].path(d).shape), "runs": out} - - def image(self, d: int, run: str, kind: str, trial: int) -> np.ndarray: - """Return an image of the canvas as float32 ``(rows, cols)``.""" - p = self.run(run).path(d) - if kind == "act": - img = p.act_im - elif kind == "mean": - img = p.mean_im - elif kind in ("trial_act", "trial_mean"): - stack = p.trial_act if kind == "trial_act" else p.trial_mean - if stack is None or not 0 <= trial < stack.shape[0]: - raise KeyError(f"{kind} of trial {trial}") - img = stack[trial] - else: - raise KeyError(kind) - return np.ascontiguousarray(img, np.float32) - - def source(self, d: int, run: str, s: int) -> dict: - """One kept source: values, footprint, trial positions, events.""" - r = self.run(run) - p = r.path(d) - src = p.sources - if not 0 <= s < src.n: - raise KeyError(f"source {s}") - patch, r0, c0 = r.profile_patch(d, s) - trc = r.trial_centroids(d) - pos = [] - for t, m in enumerate(p.maps): - rc = trc[t, s] if t < trc.shape[0] else src.rc[s] - if np.isnan(rc).any(): - rc = src.rc[s] - pos.append(None if m is None else _r(m.forward(*rc), 2)) - return { - "id": s, - "rc": _r(src.rc[s], 2), - "pixel": _r(src.pixel[s]), - "snr": float(src.snr[s]), - "kinetic_score": float(src.kinetic_score[s]), - "kinetic_n_events": float(src.kinetic_n_events[s]), - "width": float(src.width[s]), - "footprint": {"r0": r0, "c0": c0, "values": _r(patch, 5)}, - "trial_rc": pos, - "offsets": p.offsets.tolist(), - "hz": float(r.param("analyzeHz", 200.0)), - "events": source_events(r, self.session, d, s), - } - - def source_traces(self, d: int, run: str, s: int) -> np.ndarray: - """Return a source's four traces ``(4, frames)`` float32.""" - tr = self.run(run).traces(d) - n = self.run(run).path(d).lines.size - out = np.full((len(TRACES), n), np.nan, np.float32) - for i, name in enumerate(TRACES): - if name in tr and 0 <= s < tr[name].shape[1]: - out[i] = tr[name][:, s] - return out - - def trial(self, d: int, t: int) -> TrialMovie: - """Trial-path ``(d, t)``, loaded once (a second request waits).""" - key = (d, t) - while True: - with self._lock: - if key in self._cache: - self._cache.move_to_end(key) - return self._cache[key] - ev = self._loading.get(key) - mine = ev is None - if mine: - ev = self._loading[key] = threading.Event() - if not mine: - ev.wait() - continue - try: - with self._load_slot: - tr = self._load(d, t) - with self._lock: - self._cache[key] = tr - while len(self._cache) > self.cache_trials: - self._cache.popitem(last=False) - finally: - with self._lock: - self._loading.pop(key, None) - ev.set() - return tr - - def _load(self, d: int, t: int) -> TrialMovie: - """Load a trial-path and report the time.""" - if not self.session.has_movie(d - 1, t): - raise KeyError(f"no movie for path {d} trial {t + 1}") - key = f"{d}/{t}" - self.progress[key] = "reading the movie and rendering" - t0 = time.time() - try: - tr = load_trial(self.runs, self.session, d, t, self.blur, self.kernel) - finally: - self.progress.pop(key, None) - print( - f"loaded path {d} trial {t + 1}: {tr.T} frames x {tr.N} px in {time.time() - t0:.1f} s", - flush=True, - ) - return tr - - def trial_static(self, d: int, t: int) -> dict: - """Return what the page needs once per trial-path.""" - tr = self.trial(d, t) - runs = {} - for r in tr.runs: - runs[r.name] = { - "kept": _r(r.kept_rc, 2), - "rejected": _r(r.rejected_rc, 2), - "seeds": _r(r.seeds_rc, 2), - "rendered": r.rendered, - } - return { - "rows": tr.rows.tolist(), - "cols": tr.cols.tolist(), - "mean": _r(tr.mean, 2), - "discard": np.flatnonzero(tr.discard).tolist(), - "layers": tr.layers, - "shape": [tr.T, *tr.shape], - "markers": runs, - "info": tr.info, - "busiest": [tr.busiest_frame(i) for i in range(len(tr.runs))], - } - - -def _ints(q: dict, *names: str) -> list: - """Integer query values.""" - return [int(q[n]) for n in names] - - -def _route(store: Store, path: str, q: dict) -> tuple[str, dict | np.ndarray, dict[str, str]]: - """Answer one API request: ``(kind, payload, headers)``.""" - if path == "/api/meta": - return "json", store.meta(), {} - if path == "/api/sources": - return "json", store.sources(int(q["path"])), {} - if path == "/api/image": - img = store.image(int(q["path"]), q["run"], q["kind"], int(q.get("trial", -1))) - return "bin", img, {"X-Shape": json.dumps(list(img.shape))} - if path == "/api/source": - d, s = _ints(q, "path", "id") - return "json", store.source(d, q["run"], s), {} - if path == "/api/source_traces": - d, s = _ints(q, "path", "id") - return ( - "bin", - store.source_traces(d, q["run"], s), - {"X-Names": json.dumps(list(TRACES))}, - ) - if path == "/api/trial": - d, t = _ints(q, "path", "trial") - return "json", store.trial_static(d, t), {} - if path == "/api/frame": - d, t, f = _ints(q, "path", "trial", "t") - tr = store.trial(d, t) - f = min(max(f, 0), tr.T - 1) - a = tr.frame(f, max(1, int(q.get("avg", 1))), q.get("kernel")) - return "bin", a, {"X-Frame": str(f)} - if path == "/api/trace": - d, t, r, c = _ints(q, "path", "trial", "r", "c") - rad = max(0, int(q.get("rad", 0))) - a, n = store.trial(d, t).trace(r, c, rad, q.get("kernel")) - return "bin", a, {"X-Pixels": str(n)} - if path == "/api/progress": - return "json", {"msg": store.progress.get(q.get("key", ""), "")}, {} - raise LookupError(path) - - -class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of ``store``. - - The ``store`` is set by :func:`make_handler`. - """ - - store: Store - - def log_message(self, *a: object) -> None: - """Quiet.""" - - def _send( - self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None - ) -> None: - """Send one response.""" - self.send_response(code) - self.send_header("Content-Type", ctype) - self.send_header("Content-Length", str(len(body))) - self.send_header("Cache-Control", "no-store") - for k, v in (headers or {}).items(): - self.send_header(k, v) - self.end_headers() - self.wfile.write(body) - - def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: - """Send JSON (non-finite floats as null).""" - body = json.dumps(_json_safe(obj), allow_nan=False).encode() - self._send(code, body, "application/json", headers) - - 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()} - try: - if u.path in ("/", "/index.html"): - self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") - return - kind, payload, headers = _route(self.store, u.path, q) - if kind == "json": - self._json(payload, headers=headers) - return - body = np.ascontiguousarray(payload, np.float32).tobytes() - self._send(200, body, "application/octet-stream", headers) - except KeyError as e: - self._json({"error": f"missing or unknown {e}"}, 400) - except LookupError: - self._json({"error": f"not found: {u.path}"}, 404) - except (BrokenPipeError, ConnectionResetError): - pass - except Exception as e: # noqa: BLE001 (shown on the page) - self._json({"error": f"{type(e).__name__}: {e}"}, 500) - - -def make_handler(store: Store) -> type[_Handler]: - """Build the request handler class serving ``store``.""" - return type("Handler", (_Handler,), {"store": store}) - - -def _run_args(items: Iterable[str]) -> list: - """``NAME=DIR`` or ``DIR`` arguments as ``(name, dir)``.""" - out = [] - for item in items: - name, sep, d = str(item).partition("=") - if sep and name and not Path(item).exists(): - out.append((name, d)) - else: - out.append((None, item)) - return out - - -def _default_table(run_dir: Path) -> Optional[Path]: - """Find a trial table in or above a run folder.""" - for d in (run_dir, run_dir.parent, run_dir.parent.parent): - if (d / "trial_table.h5").exists(): - return d / "trial_table.h5" - return None - - -def make_store(args: argparse.Namespace) -> Store: - """Build the store for parsed ``giant view`` arguments.""" - runs = [SiloRun(d, name) for name, d in _run_args(args.runs)] - table = args.table or _default_table(runs[0].run_dir) - if table is None: - raise ValueError(f"no trial_table.h5 in or above {runs[0].run_dir}: give --table") - session = Session(table, args.moco_dir, args.baseline_dir, args.data_dir) - label = args.label or Path(session.table).parent.name - return Store(runs, session, label, args.cache_trials, args.blur, args.kernel) - - -def make_server( - store: Store, host: str = "127.0.0.1", port: int = DEFAULT_PORT -) -> ThreadingHTTPServer: - """Build an HTTP server for ``store`` (not started).""" - return ThreadingHTTPServer((host, port), make_handler(store)) - - -def add_arguments(p: argparse.ArgumentParser) -> None: - """``giant view``'s options.""" - p.add_argument( - "runs", - nargs="+", - metavar="RUN", - help="SILo run folders (holding experiment_summary.h5, " - "directly or in source_extraction/), optionally as " - "NAME=FOLDER; two or more runs of the same session are " - "compared", - ) - p.add_argument( - "--table", - default=None, - help="the session's trial_table.h5 (default: in or above the first run's folder)", - ) - p.add_argument( - "--moco-dir", - default=None, - help="registered movies and alignment files (default: " - "the table's savedr/motion_correction)", - ) - p.add_argument( - "--baseline-dir", - default=None, - help="F0 network baselines (_BASELINE-80Hz.h5); adds the baseline layers", - ) - p.add_argument( - "--data-dir", - default=None, - help="raw .dat/.meta folder, for the lines per cycle " - "(default: the table's datadr; without it the frame " - "kernel reaches 3 dt)", - ) - p.add_argument("--label", default="", help="session label on the page") - p.add_argument( - "--blur", - type=float, - default=0.0, - help="Gaussian blur (px) of the rendered footprints (default 0)", - ) - p.add_argument( - "--kernel", - choices=("matched", "exporter", "exact"), - default="matched", - help="how SILo's 200 Hz traces become the movie's 80 Hz " - "frames: matched (default; sqrt(dt80^2 - dt200^2), for the " - "200 Hz frames' own smoothing), the exporter's weights (the " - "movie's dt), or exact (r x200 + (1 - r) exporter's, r = " - "(dt200/dt80)^2); the page switches between them", - ) - p.add_argument( - "--cache-trials", - type=int, - default=2, - help="trial-paths kept in memory", - ) - 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") - - -def serve(args: argparse.Namespace) -> int: - """Run ``giant view`` until interrupted.""" - store = make_store(args) - server = make_server(store, args.host, args.port) - url = f"http://{args.host}:{server.server_address[1]}/" - names = ", ".join(r.name for r in store.runs) - print( - f"{store.label}: runs {names}; paths {store.paths}; serving {url} (Ctrl+C to stop)", - flush=True, - ) - if not args.no_browser: - threading.Timer(0.5, lambda: webbrowser.open(url)).start() - try: - server.serve_forever() - except KeyboardInterrupt: - pass - finally: - server.server_close() - return 0 +"""giant view: a local page for inspecting SILo runs by eye. + +giant view RUN [RUN ...] serves http://127.0.0.1:8766 with two views: + +* **Sources**: per path, the combined activity image, each trial's + activity image and the mean image of one or two runs, with the runs' + sources overlaid (kept, kinetics-rejected and, when the run kept its + plan files, seeds without a source), synchronized zoom and pan, a + flicker between two panels, and a source's footprint, traces (denoised + and least-squares dF, events, F0 over all trials), SNR, kinetic score + and footprint width. With two runs, sources are marked by whether the + other run has one within 1.5 px (one to one, closest first). +* **Movie**: one trial-path at a time, frame by frame: the registered + 80 Hz movie, each run's fitted activity rendered into it + (:mod:`~giant_python.viewer.render`) and the residual movie - activity; + with --baseline-dir also the network's baseline and movie - + activity - baseline. Scroll or play through time, average frames, zoom + and pan with all panels in step, traces of a pixel or small region. + +A trial-path is loaded when it is shown (--cache-trials at once). +Memory: the movie (float32) and baseline (float16) at the valid pixels, +about 6 bytes x frames x valid pixels (0.5 GB for a 780125 trial of 2254 +frames x 36k pixels); the activity is computed per request from sparse +footprints. + +API (GET; used by the page): /api/meta, /api/sources?path=, +``/api/image?path=&run=&kind=act|mean|trial_act|trial_mean&trial=`` +(float32 rows x cols), /api/source?path=&run=&id= (JSON), +/api/source_traces?path=&run=&id= (float32 4 x frames), +/api/trial?path=&trial= (JSON), +/api/frame?path=&trial=&t=&avg=&kernel= (float32 layers x valid +pixels), /api/trace?path=&trial=&r=&c=&rad=&kernel= (float32 layers x +frames; kernel exporter, matched or exact, default --kernel), +/api/progress?key=. +""" + +from __future__ import annotations + +import argparse +import json +import threading +import time +import webbrowser +from collections import OrderedDict +from collections.abc import Iterable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Optional +from urllib.parse import parse_qs, urlparse + +import numpy as np +import numpy.typing as npt + +from .run import TRACES, SiloRun +from .trial import Session, TrialMovie, load_trial, source_events + +PAGE = Path(__file__).with_name("page.html") +DEFAULT_PORT = 8766 + + +def _json_safe(o: object) -> object: + """``o`` with non-finite floats as None (the browser rejects NaN). + + Returns + ------- + object + o with dicts, lists, tuples (as lists) and numpy values converted + recursively to JSON-safe Python values. + """ + if isinstance(o, float): + return o if np.isfinite(o) else None + if isinstance(o, dict): + return {k: _json_safe(v) for k, v in o.items()} + if isinstance(o, (list, tuple)): + return [_json_safe(v) for v in o] + if isinstance(o, np.ndarray): + return _json_safe(o.tolist()) + if isinstance(o, np.generic): + return _json_safe(o.item()) + return o + + +def _r(a: npt.ArrayLike, nd: int = 3) -> list: + """Round an array to nd decimals as nested lists. + + Returns + ------- + list + The rounded values of a as nested lists. + """ + return np.round(np.asarray(a, dtype=np.float64), nd).tolist() + + +class Store: + """The runs of one session and the trial-paths loaded from them. + + Parameters + ---------- + runs : list of SiloRun + One or more runs of the same session (same paths and trials). + session : Session + The trial table and folders. + label : str + Session label for the page. + cache_trials : int + Trial-paths kept in memory. + blur : float + Gaussian blur (px) of the rendered footprints. + """ + + def __init__( + self, + runs: list[SiloRun], + session: Session, + label: str = "", + cache_trials: int = 2, + blur: float = 0.0, + kernel: str = "matched", + ) -> None: + """Check that the runs fit together. + + Raises + ------ + ValueError + If there are no runs, the run names are not unique, or the runs differ in their paths, + channel count, or activity channel. + """ + if not runs: + raise ValueError("give at least one run") + names = [r.name for r in runs] + if len(set(names)) != len(names): + raise ValueError(f"run names must differ: {names}") + self.runs, self.session, self.label = runs, session, label + self.cache_trials, self.blur = max(1, int(cache_trials)), blur + self.kernel = kernel + self.paths = runs[0].paths + for r in runs[1:]: + if r.paths != self.paths: + raise ValueError( + f"runs have different paths: {runs[0].name} {self.paths}, {r.name} {r.paths}" + ) + # the movie is read once, as the first run's activity channel + # with the trial loader's defaults (trial._settings) + for key, default in (("numChannels", 2), ("activityChannel", 1)): + v0, v = runs[0].param(key, default), r.param(key, default) + if int(v) != int(v0): + raise ValueError(f"runs differ in {key}: {runs[0].name} {v0}, {r.name} {v}") + self._cache: OrderedDict = OrderedDict() + self._loading: dict = {} + # one trial-path loads at a time: each needs a whole movie in memory + self._load_slot = threading.Semaphore(1) + self._lock = threading.Lock() + self.progress: dict = {} + + def run(self, name: str) -> SiloRun: + """Return the run called name. + + Returns + ------- + SiloRun + The run with that name. + + Raises + ------ + KeyError + If no run has that name. + """ + for r in self.runs: + if r.name == name: + return r + raise KeyError(name) + + def meta(self) -> dict: + """List what the page shows: runs, paths, trials. + + Returns + ------- + dict + The session label, blur_px, kernel, the runs (name, folder, + settings), the table, moco_dir and baseline_dir, and per paths + entry its shape, trials and alignment. + """ + paths = [] + for d in self.paths: + p = self.runs[0].path(d) + trials = [] + for t in range(p.n_frames.size): + trials.append({ + "trial": t, + "frames200": int(p.n_frames[t]), + "movie": bool(self.session.has_movie(d - 1, t)), + "baseline": self.session.baseline_file(d - 1, t) is not None, + "aligned": [r.path(d).maps[t] is not None for r in self.runs], + }) + paths.append({ + "path": d, + "shape": list(p.shape), + "trials": trials, + "alignment": [r.path(d).alignment for r in self.runs], + }) + return { + "label": self.label, + "blur_px": self.blur, + "kernel": self.kernel, + "runs": [ + { + "name": r.name, + "dir": str(r.run_dir), + "settings": r.describe(), + } + for r in self.runs + ], + "table": str(self.session.table), + "moco_dir": str(self.session.moco_dir), + "baseline_dir": str(self.session.baseline_dir or ""), + "paths": paths, + } + + def sources(self, d: int) -> dict: + """Every run's sources of path d (canvas, zero-based). + + Returns + ------- + dict + shape of the path's canvas and runs: per run name its kept and + rejected sources, unused seeds (or None) and number of trials. + """ + out = {} + for r in self.runs: + s = r.path(d).sources + kept = ( + np.column_stack([ + s.rc, + s.snr, + s.kinetic_score, + s.kinetic_n_events, + s.width, + s.pixel, + ]) + if s.n + else np.zeros((0, 8)) + ) + rej = np.column_stack([s.rejected_rc, s.rejected_score, s.rejected_n_events]) + seeds = None if s.unused_seeds is None else _r(s.unused_seeds, 2) + out[r.name] = { + "kept": _r(kept), + "rejected": _r(rej), + "seeds": seeds, + "trials": int(r.path(d).n_frames.size), + } + return {"shape": list(self.runs[0].path(d).shape), "runs": out} + + def image(self, d: int, run: str, kind: str, trial: int) -> np.ndarray: + """Return an image of the canvas as float32 (rows, cols). + + Returns + ------- + np.ndarray + The requested image (kind act, mean, trial_act or trial_mean). + + Raises + ------ + KeyError + If kind is unknown, or a per-trial image is asked for a trial it does not have. + """ + p = self.run(run).path(d) + if kind == "act": + img = p.act_im + elif kind == "mean": + img = p.mean_im + elif kind in ("trial_act", "trial_mean"): + stack = p.trial_act if kind == "trial_act" else p.trial_mean + if stack is None or not 0 <= trial < stack.shape[0]: + raise KeyError(f"{kind} of trial {trial}") + img = stack[trial] + else: + raise KeyError(kind) + return np.ascontiguousarray(img, np.float32) + + def source(self, d: int, run: str, s: int) -> dict: + """One kept source: values, footprint, trial positions, events. + + Returns + ------- + dict + The source's id, canvas position rc, pixel, snr, kinetic + scores, width, footprint patch, per-trial positions trial_rc, + offsets, hz and events. + + Raises + ------ + KeyError + If s is not a source index of the path. + """ + r = self.run(run) + p = r.path(d) + src = p.sources + if not 0 <= s < src.n: + raise KeyError(f"source {s}") + patch, r0, c0 = r.profile_patch(d, s) + trc = r.trial_centroids(d) + pos = [] + for t, m in enumerate(p.maps): + rc = trc[t, s] if t < trc.shape[0] else src.rc[s] + if np.isnan(rc).any(): + rc = src.rc[s] + pos.append(None if m is None else _r(m.forward(*rc), 2)) + return { + "id": s, + "rc": _r(src.rc[s], 2), + "pixel": _r(src.pixel[s]), + "snr": float(src.snr[s]), + "kinetic_score": float(src.kinetic_score[s]), + "kinetic_n_events": float(src.kinetic_n_events[s]), + "width": float(src.width[s]), + "footprint": {"r0": r0, "c0": c0, "values": _r(patch, 5)}, + "trial_rc": pos, + "offsets": p.offsets.tolist(), + "hz": float(r.param("analyzeHz", 200.0)), + "events": source_events(r, self.session, d, s), + } + + def source_traces(self, d: int, run: str, s: int) -> np.ndarray: + """Return a source's four traces (4, frames) float32. + + Returns + ------- + np.ndarray + One row per trace in TRACES; NaN where the run has no value. + """ + tr = self.run(run).traces(d) + n = self.run(run).path(d).lines.size + out = np.full((len(TRACES), n), np.nan, np.float32) + for i, name in enumerate(TRACES): + if name in tr and 0 <= s < tr[name].shape[1]: + out[i] = tr[name][:, s] + return out + + def trial(self, d: int, t: int) -> TrialMovie: + """Trial-path (d, t), loaded once (a second request waits). + + Returns + ------- + TrialMovie + The loaded trial-path (from the cache when it is there). + """ + key = (d, t) + while True: + with self._lock: + if key in self._cache: + self._cache.move_to_end(key) + return self._cache[key] + ev = self._loading.get(key) + mine = ev is None + if mine: + ev = self._loading[key] = threading.Event() + if not mine: + ev.wait() + continue + try: + with self._load_slot: + tr = self._load(d, t) + with self._lock: + self._cache[key] = tr + while len(self._cache) > self.cache_trials: + self._cache.popitem(last=False) + finally: + with self._lock: + self._loading.pop(key, None) + ev.set() + return tr + + def _load(self, d: int, t: int) -> TrialMovie: + """Load a trial-path and report the time. + + Returns + ------- + TrialMovie + The loaded trial-path. + + Raises + ------ + KeyError + If the session has no movie for the trial-path. + """ + if not self.session.has_movie(d - 1, t): + raise KeyError(f"no movie for path {d} trial {t + 1}") + key = f"{d}/{t}" + self.progress[key] = "reading the movie and rendering" + t0 = time.time() + try: + tr = load_trial(self.runs, self.session, d, t, self.blur, self.kernel) + finally: + self.progress.pop(key, None) + print( + f"loaded path {d} trial {t + 1}: {tr.T} frames x {tr.N} px in {time.time() - t0:.1f} s", + flush=True, + ) + return tr + + def trial_static(self, d: int, t: int) -> dict: + """Return what the page needs once per trial-path. + + Returns + ------- + dict + The trial's rows, cols, mean image, discard frames, layers, + shape, per-run markers, info and busiest frame of each run. + """ + tr = self.trial(d, t) + runs = {} + for r in tr.runs: + runs[r.name] = { + "kept": _r(r.kept_rc, 2), + "rejected": _r(r.rejected_rc, 2), + "seeds": _r(r.seeds_rc, 2), + "rendered": r.rendered, + } + return { + "rows": tr.rows.tolist(), + "cols": tr.cols.tolist(), + "mean": _r(tr.mean, 2), + "discard": np.flatnonzero(tr.discard).tolist(), + "layers": tr.layers, + "shape": [tr.T, *tr.shape], + "markers": runs, + "info": tr.info, + "busiest": [tr.busiest_frame(i) for i in range(len(tr.runs))], + } + + +def _ints(q: dict, *names: str) -> list: + """Integer query values. + + Returns + ------- + list + int(q[n]) for each name, in order. + """ + return [int(q[n]) for n in names] + + +def _route(store: Store, path: str, q: dict) -> tuple[str, dict | np.ndarray, dict[str, str]]: + """Answer one API request: (kind, payload, headers). + + Returns + ------- + kind : str + "json" or "bin". + payload : dict or np.ndarray + The JSON-able dict, or the array to send as float32 bytes. + headers : dict of str to str + Extra response headers. + + Raises + ------ + LookupError + If path is not an API route. + """ + if path == "/api/meta": + return "json", store.meta(), {} + if path == "/api/sources": + return "json", store.sources(int(q["path"])), {} + if path == "/api/image": + img = store.image(int(q["path"]), q["run"], q["kind"], int(q.get("trial", -1))) + return "bin", img, {"X-Shape": json.dumps(list(img.shape))} + if path == "/api/source": + d, s = _ints(q, "path", "id") + return "json", store.source(d, q["run"], s), {} + if path == "/api/source_traces": + d, s = _ints(q, "path", "id") + return ( + "bin", + store.source_traces(d, q["run"], s), + {"X-Names": json.dumps(list(TRACES))}, + ) + if path == "/api/trial": + d, t = _ints(q, "path", "trial") + return "json", store.trial_static(d, t), {} + if path == "/api/frame": + d, t, f = _ints(q, "path", "trial", "t") + tr = store.trial(d, t) + f = min(max(f, 0), tr.T - 1) + a = tr.frame(f, max(1, int(q.get("avg", 1))), q.get("kernel")) + return "bin", a, {"X-Frame": str(f)} + if path == "/api/trace": + d, t, r, c = _ints(q, "path", "trial", "r", "c") + rad = max(0, int(q.get("rad", 0))) + a, n = store.trial(d, t).trace(r, c, rad, q.get("kernel")) + return "bin", a, {"X-Pixels": str(n)} + if path == "/api/progress": + return "json", {"msg": store.progress.get(q.get("key", ""), "")}, {} + raise LookupError(path) + + +class _Handler(BaseHTTPRequestHandler): + """Serves the page and the API of store. + + The store is set by :func:`make_handler`. + """ + + store: Store + + def log_message(self, *a: object) -> None: + """Quiet.""" + + def _send( + self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None + ) -> None: + """Send one response.""" + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: + """Send JSON (non-finite floats as null).""" + body = json.dumps(_json_safe(obj), allow_nan=False).encode() + self._send(code, body, "application/json", headers) + + 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()} + try: + if u.path in ("/", "/index.html"): + self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") + return + kind, payload, headers = _route(self.store, u.path, q) + if kind == "json": + self._json(payload, headers=headers) + return + body = np.ascontiguousarray(payload, np.float32).tobytes() + self._send(200, body, "application/octet-stream", headers) + except KeyError as e: + self._json({"error": f"missing or unknown {e}"}, 400) + except LookupError: + self._json({"error": f"not found: {u.path}"}, 404) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception as e: # noqa: BLE001 (shown on the page) + self._json({"error": f"{type(e).__name__}: {e}"}, 500) + + +def make_handler(store: Store) -> type[_Handler]: + """Build the request handler class serving store. + + Returns + ------- + type[_Handler] + A handler class whose store is the given store. + """ + return type("Handler", (_Handler,), {"store": store}) + + +def _run_args(items: Iterable[str]) -> list: + """NAME=DIR or DIR arguments as (name, dir). + + Returns + ------- + list + One (name, dir) tuple per item; name is None for a plain DIR. + """ + out = [] + for item in items: + name, sep, d = str(item).partition("=") + if sep and name and not Path(item).exists(): + out.append((name, d)) + else: + out.append((None, item)) + return out + + +def _default_table(run_dir: Path) -> Optional[Path]: + """Find a trial table in or above a run folder. + + Returns + ------- + Path or None + The nearest trial_table.h5 (in the folder or up to two levels above), or None. + """ + for d in (run_dir, run_dir.parent, run_dir.parent.parent): + if (d / "trial_table.h5").exists(): + return d / "trial_table.h5" + return None + + +def make_store(args: argparse.Namespace) -> Store: + """Build the store for parsed giant view arguments. + + Returns + ------- + Store + The store of the given runs and session. + + Raises + ------ + ValueError + If no trial table was given and none is found in or above the first run folder. + """ + runs = [SiloRun(d, name) for name, d in _run_args(args.runs)] + table = args.table or _default_table(runs[0].run_dir) + if table is None: + raise ValueError(f"no trial_table.h5 in or above {runs[0].run_dir}: give --table") + session = Session(table, args.moco_dir, args.baseline_dir, args.data_dir) + label = args.label or Path(session.table).parent.name + return Store(runs, session, label, args.cache_trials, args.blur, args.kernel) + + +def make_server( + store: Store, host: str = "127.0.0.1", port: int = DEFAULT_PORT +) -> ThreadingHTTPServer: + """Build an HTTP server for store (not started). + + Returns + ------- + ThreadingHTTPServer + The server bound to host and port. + """ + return ThreadingHTTPServer((host, port), make_handler(store)) + + +def add_arguments(p: argparse.ArgumentParser) -> None: + """``giant view``'s options.""" + p.add_argument( + "runs", + nargs="+", + metavar="RUN", + help="SILo run folders (holding experiment_summary.h5, " + "directly or in source_extraction/), optionally as " + "NAME=FOLDER; two or more runs of the same session are " + "compared", + ) + p.add_argument( + "--table", + default=None, + help="the session's trial_table.h5 (default: in or above the first run's folder)", + ) + p.add_argument( + "--moco-dir", + default=None, + help="registered movies and alignment files (default: " + "the table's savedr/motion_correction)", + ) + p.add_argument( + "--baseline-dir", + default=None, + help="F0 network baselines (_BASELINE-80Hz.h5); adds the baseline layers", + ) + p.add_argument( + "--data-dir", + default=None, + help="raw .dat/.meta folder, for the lines per cycle " + "(default: the table's datadr; without it the frame " + "kernel reaches 3 dt)", + ) + p.add_argument("--label", default="", help="session label on the page") + p.add_argument( + "--blur", + type=float, + default=0.0, + help="Gaussian blur (px) of the rendered footprints (default 0)", + ) + p.add_argument( + "--kernel", + choices=("matched", "exporter", "exact"), + default="matched", + help="how SILo's 200 Hz traces become the movie's 80 Hz " + "frames: matched (default; sqrt(dt80^2 - dt200^2), for the " + "200 Hz frames' own smoothing), the exporter's weights (the " + "movie's dt), or exact (r x200 + (1 - r) exporter's, r = " + "(dt200/dt80)^2); the page switches between them", + ) + p.add_argument( + "--cache-trials", + type=int, + default=2, + help="trial-paths kept in memory", + ) + 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") + + +def serve(args: argparse.Namespace) -> int: + """Run giant view until interrupted. + + Returns + ------- + int + The exit code, 0. + """ + store = make_store(args) + server = make_server(store, args.host, args.port) + url = f"http://{args.host}:{server.server_address[1]}/" + names = ", ".join(r.name for r in store.runs) + print( + f"{store.label}: runs {names}; paths {store.paths}; serving {url} (Ctrl+C to stop)", + flush=True, + ) + if not args.no_browser: + threading.Timer(0.5, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 diff --git a/src/giant_python/viewer/trial.py b/src/giant_python/viewer/trial.py index 27024cd6..0a020aeb 100644 --- a/src/giant_python/viewer/trial.py +++ b/src/giant_python/viewer/trial.py @@ -1,604 +1,758 @@ -"""One trial-path in the viewer's movie view. - -The registered 80 Hz movie of the trial (the activity channel, in the -trial's own registered frame, not resampled), the runs' fitted activity -rendered into it (:mod:`~giant_python.viewer.render`), and the F0 -network's baseline when a baseline folder is given. Arrays are held for -the valid pixels only, as the exporter defines them: missing in less than -``nanThresh`` of the frames with SILo's motion discards counted as -missing. The frames blanked afterwards because their kernel weight lies -mostly on discarded 200 Hz frames do not count (they are blank at every -pixel, and the exporter's training targets cover the same pixels). The -activity is not stored per frame: a frame or a trace is the footprints -(sparse) times the sources' 80 Hz traces. -""" - -from __future__ import annotations - -import math -import threading -from dataclasses import dataclass, field -from pathlib import Path, PurePath -from typing import Optional - -import h5py -import numpy as np - -from ..extraction.raster.trial import discard_frames -from ..pipeline.silo_session import _grid, _read -from .render import ( - KERNELS, - TrialMap, - frame_dt200, - kernel_dt, - kernel_weights, - place_footprints, -) -from .run import SiloRun - - -class Session: - """The trial table and folders the runs of one session share. - - Parameters - ---------- - table : str or Path - ``trial_table.h5`` (or its folder). - moco_dir : str or Path, optional - Folder of the registered movies and alignment files (default: - ``/motion_correction``, else next to the table). - baseline_dir : str or Path, optional - Folder of ``_BASELINE-80Hz.h5`` (``slap2-f0 - predict-registered``); optional. - data_dir : str or Path, optional - Folder of the raw files, to read the lines per cycle (default: the - table's ``datadr``; without them the kernel reaches 3 dt). - """ - - def __init__( - self, - table: str | Path, - moco_dir: str | Path | None = None, - baseline_dir: str | Path | None = None, - data_dir: str | Path | None = None, - ) -> None: - """Read the table's file names.""" - table = Path(table) - if table.is_dir(): - table = table / "trial_table.h5" - self.table = table - with h5py.File(table, "r") as f: - rm = "row_major" in f and bool(np.ravel(f["row_major"][()])[0]) - filename = np.atleast_2d(_read(f, "filename", rm)) - shape = filename.shape - reg = _read(f, "motion_correction/fn_reg_ds", rm) - adata = _read(f, "motion_correction/fn_adata", rm) - savedr = _read(f, "savedr", rm) - datadr = _read(f, "datadr", rm) - if reg is None or adata is None: - raise ValueError(f"{table} has no registration") - self.filename = filename - self.fn_reg_ds = _grid(reg, shape) - self.fn_adata = _grid(adata, shape) - savedr = Path(str(np.ravel(savedr)[0])) if savedr is not None else None - if moco_dir is None: - moco_dir = (savedr / "motion_correction") if savedr else None - if moco_dir is None or not moco_dir.exists(): - moco_dir = table.parent / "motion_correction" - self.moco_dir = Path(moco_dir) - self.baseline_dir = Path(baseline_dir) if baseline_dir else None - if data_dir is None and datadr is not None: - data_dir = str(np.ravel(datadr)[0]) - self.data_dir = Path(data_dir) if data_dir else None - self._ds: dict = {} - self._lpc: dict = {} - - @staticmethod - def _name(value: object) -> str: - """Return a table file name without its folder.""" - return PurePath(str(value).replace("\\", "/")).name - - def movie_file(self, d: int, t: int) -> Path: - """Find the registered movie of path ``d``, trial ``t`` (zero-based). - - It is found by its stem as ``.tif`` or ``.h5``, as SILo finds it - (:meth:`SiloSession.movie`); the table's name if neither exists. - """ - name = self._name(self.fn_reg_ds[d, t]) - stem = PurePath(name).stem - for ext in (".tif", ".h5"): - p = self.moco_dir / (stem + ext) - if p.exists(): - return p - return self.moco_dir / name - - def alignment_file(self, d: int, t: int) -> Path: - """Return the alignment file of path ``d``, trial ``t`` (zero-based).""" - return self.moco_dir / self._name(self.fn_adata[d, t]) - - def has_movie(self, d: int, t: int) -> bool: - """Whether the trial's movie and alignment file are here.""" - if not str(self.fn_reg_ds[d, t]).strip(): - return False - return self.movie_file(d, t).exists() and self.alignment_file(d, t).exists() - - def baseline_file(self, d: int, t: int) -> Optional[Path]: - """Find the trial's network baseline, if there is one.""" - if self.baseline_dir is None: - return None - name = self._name(self.fn_reg_ds[d, t]) - if "_REGISTERED" not in name: - return None - stem = name[: name.index("_REGISTERED")] - p = self.baseline_dir / f"{stem}_BASELINE-80Hz.h5" - return p if p.exists() else None - - def ds_lines(self, d: int, t: int) -> np.ndarray: - """Read the registered frames' lines (``DSframes``) of a trial.""" - key = (d, t) - if key not in self._ds: - with h5py.File(self.alignment_file(d, t), "r") as f: - self._ds[key] = np.asarray(f["DSframes"][()], float).ravel() - return self._ds[key] - - def lines_per_cycle(self, d: int, t: int) -> int: - """Lines per cycle from the raw file's header (0 if unreadable).""" - key = (d, t) - if key not in self._lpc: - self._lpc[key] = 0 - if self.data_dir is not None: - try: - from ..io.slap2_raster import raster_layout - - fn = self.data_dir / self._name(self.filename[d, t]) - self._lpc[key] = int(raster_layout(fn).lines_per_cycle) - except Exception: # noqa: BLE001 (no raw data: 3 dt) - self._lpc[key] = 0 - return self._lpc[key] - - -def read_channel(path: Path, num_channels: int, channel: int) -> np.ndarray: - """One channel of a registered movie as ``(frames, rows, cols)`` float32. - - Zero-based channel; channels interleaved by frame. - """ - if path.suffix == ".h5": - with h5py.File(path, "r") as f: - ds = f[next(iter(f.keys()))] # (pages, MATLAB cols, rows) - n = ds.shape[0] // num_channels - # whole frames at a time: twice as fast as a strided selection - # of the (one page per chunk, compressed) dataset - step = 128 * num_channels - raw = np.concatenate([ - ds[a : min(a + step, n * num_channels)][channel::num_channels] - for a in range(0, n * num_channels, step) - ]) - else: - import tifffile - - with tifffile.TiffFile(path) as tf: - pages = tf.pages - n = len(pages) // num_channels - first = pages[channel].asarray() - raw = np.empty((n,) + first.shape, first.dtype) - raw[0] = first - for k in range(1, n): - raw[k] = pages[channel + k * num_channels].asarray() - return np.ascontiguousarray(np.asarray(raw, np.float32).transpose(0, 2, 1)) - - -@dataclass -class RunLayer: - """One run's activity in a trial. - - Attributes - ---------- - name : str - footprints : scipy.sparse.csr_matrix (valid pixels, sources) - x80 : dict - Time kernel (:data:`KERNELS`) to the sources' denoised traces at - the movie's frames, ``(sources, frames)``. - kept_rc, rejected_rc, seeds_rc : ndarray (n, 2) - Marker positions in the trial's registered frame. - kernels : dict - Time kernel to its ``(dt, reach)`` in lines, from this run's own - 200 Hz frame lines (:func:`render_dt`). - rendered : bool - False when the run has no footprints or no map for the trial. - """ - - name: str - footprints: object - x80: dict - kept_rc: np.ndarray - rejected_rc: np.ndarray - seeds_rc: np.ndarray - rendered: bool = True - kernels: dict = field(default_factory=dict) - - -@dataclass -class TrialMovie: - """A loaded trial-path: movie, baseline and each run's activity. - - ``kernel`` is the time kernel (:data:`KERNELS`) that :meth:`frame` and - :meth:`trace` use unless they are given another. - """ - - path: int - trial: int - shape: tuple - rows: np.ndarray - cols: np.ndarray - mean: np.ndarray - discard: np.ndarray - movie: np.ndarray - baseline: Optional[np.ndarray] - runs: list - info: dict = field(default_factory=dict) - kernel: str = "matched" - lock: threading.Lock = field(default_factory=threading.Lock, repr=False) - - @property - def T(self) -> int: - """Frames.""" - return int(self.movie.shape[0]) - - @property - def N(self) -> int: - """Valid pixels.""" - return int(self.movie.shape[1]) - - @property - def layers(self) -> list: - """Layer names in the order of :meth:`frame` and :meth:`trace`.""" - out = ["movie"] - for r in self.runs: - out += [f"activity:{r.name}", f"residual:{r.name}"] - if self.baseline is not None: - out.append("baseline") - out += [f"residual-baseline:{r.name}" for r in self.runs] - return out - - def span(self, t: int, avg: int) -> tuple: - """Return the frames ``[lo, hi)`` a mean of ``avg`` frames at ``t`` uses.""" - lo = min(max(t - (avg - 1) // 2, 0), self.T - 1) - return lo, min(max(lo + avg, lo + 1), self.T) - - def _stack( - self, frames: slice, pixels: np.ndarray | slice, kernel: str | None = None - ) -> list: - """Every layer's values ``(frames, pixels)`` at the given frames and pixels. - - The frames are a slice; the pixels an index array or a slice. - """ - kernel = kernel or self.kernel - if kernel not in KERNELS: - raise KeyError(f"kernel {kernel}") - m = self.movie[frames][:, pixels] - miss = np.isnan(m) - out = [m] - acts = [] - for r in self.runs: - h = r.footprints[pixels] if r.rendered else None - a = ( - np.asarray((h @ r.x80[kernel][:, frames]).T, np.float32) - if h is not None - else np.zeros_like(m) - ) - a[miss] = np.nan - acts.append(a) - out += [a, m - a] - if self.baseline is not None: - b = self.baseline[frames][:, pixels].astype(np.float32) - out.append(b) - out += [m - a - b for a in acts] - return out - - def frame(self, t: int, avg: int, kernel: str | None = None) -> np.ndarray: - """Each layer's mean over ``avg`` frames at ``t``. - - ``(layers, valid pixels)`` float32, NaN-aware. - """ - lo, hi = self.span(t, avg) - blocks = self._stack(slice(lo, hi), slice(None), kernel) - out = np.empty((len(blocks), self.N), np.float32) - with np.errstate(invalid="ignore"), _quiet(): - for i, b in enumerate(blocks): - out[i] = b[0] if hi - lo == 1 else np.nanmean(b, 0) - return out - - def trace(self, r: int, c: int, rad: int, kernel: str | None = None) -> tuple: - """Each layer's mean over the valid pixels within ``rad`` rows and columns of ``(r, c)``. - - Returns ``(layers, frames)`` float32, and the number of pixels. - """ - near = (np.abs(self.rows - r) <= rad) & (np.abs(self.cols - c) <= rad) - k = np.flatnonzero(near) - out = np.full((len(self.layers), self.T), np.nan, np.float32) - if k.size: - with _quiet(): - for i, b in enumerate(self._stack(slice(None), k, kernel)): - out[i] = np.nanmean(b, 1) - return out, int(k.size) - - def busiest_frame(self, run: int = 0) -> int: - """Find the frame with the most rendered activity of a run.""" - r = self.runs[run] - x = r.x80[self.kernel] - if not r.rendered or x.size == 0: - return 0 - total = np.asarray(r.footprints.sum(0)).ravel() @ x - total[self.discard] = -np.inf - return int(np.argmax(total)) - - -class _quiet: - """Silence NumPy's all-NaN warnings inside a block.""" - - def __enter__(self) -> None: - """Start ignoring RuntimeWarnings.""" - import warnings - - self._w = warnings.catch_warnings() - self._w.__enter__() - warnings.simplefilter("ignore", RuntimeWarning) - - def __exit__(self, *exc: object) -> None: - """Restore the warning filters.""" - self._w.__exit__(*exc) - - -def _marker_rc(tmap: TrialMap | None, rc: np.ndarray) -> np.ndarray: - """Canvas positions moved into the trial frame (NaN rows stay NaN).""" - rc = np.asarray(rc, np.float64).reshape(-1, 2) - if tmap is None or rc.size == 0: - return rc.copy() - r, c = tmap.forward(np.nan_to_num(rc[:, 0]), np.nan_to_num(rc[:, 1])) - out = np.column_stack([r, c]) - out[np.isnan(rc).any(1)] = np.nan - return out - - -def run_layer(run: SiloRun, session: Session, d: int, t: int, ctx: dict) -> RunLayer: - """One run's activity in trial ``t`` of path ``d`` (one-based path, zero-based trial). - - ``ctx`` holds the trial's ``shape``, valid flat pixel indices ``flat``, - ``ds_lines``, the movie's kernel ``dt``, the lines per cycle ``lpc`` and - ``blur``; the time kernels come from the run's own 200 Hz frame lines - (:func:`render_dt`), and the run's 80 Hz discard share under the - exporter's kernel is added to ``ctx``. - """ - p = run.path(d) - n = p.sources.n - tmap = p.maps[t] if t < len(p.maps) else None - fps = run.footprints(d) - fp = fps[t] if t < len(fps) else None - span = p.trial_span(t) if t < p.n_frames.size else slice(0, 0) - lines200 = p.lines[span] - rendered = bool(tmap is not None and fp is not None and lines200.size) - T = ctx["ds_lines"].size - kernels = {} - for k in KERNELS: - dtr = render_dt(k, ctx["dt"], lines200) - kernels[k] = (dtr, max(3 * dtr, ctx["lpc"])) - x80 = {k: np.zeros((n, T), np.float32) for k in kernels} - h = None - if rendered: - x200 = np.nan_to_num(run.traces(d)["dF_denoised"][span]) # (n200, n) - for k in kernels: - w, share, _ = kernel_weights( - k, - lines200, - p.discard[span], - ctx["ds_lines"], - ctx["dt"], - ctx["lpc"], - ) - if k == "exporter": - ctx.setdefault("shares", []).append(share) - x80[k] = np.asarray((w.T @ x200).T, np.float32) - h = place_footprints(fp, n, tmap, ctx["shape"], ctx["blur"]) - h = h[ctx["flat"]] - trc = run.trial_centroids(d) - rc = trc[t] if t < trc.shape[0] else np.full((n, 2), np.nan) - rc = np.where(np.isnan(rc), p.sources.rc, rc) - seeds = p.sources.unused_seeds - return RunLayer( - name=run.name, - footprints=h, - x80=x80, - kept_rc=_marker_rc(tmap, rc), - rejected_rc=_marker_rc(tmap, p.sources.rejected_rc), - seeds_rc=_marker_rc(tmap, seeds if seeds is not None else []), - rendered=rendered, - kernels=kernels, - ) - - -def _settings(run: SiloRun) -> dict: - """SILo's frame settings of a run (defaults: SILo's for SLAP2).""" - return { - "num_channels": int(run.param("numChannels", 2)), - "channel": run.activity_channel, - "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)), - } - - -def _read_alignment(path: Path, n_frames: int) -> tuple[float, np.ndarray]: - """``alignHz`` and ``recNegErr`` of a trial's alignment file.""" - with h5py.File(path, "r") as f: - hz = float(np.ravel(f["alignHz"][()])[0]) - rne = np.asarray(f["recNegErr"][()], np.float64).ravel()[:n_frames] - return hz, rne - - -def render_dt(kernel: str, dt80: int, lines200: np.ndarray) -> float: - """Return the time constant (lines) the 200 Hz traces are averaged with. - - ``exporter``: the movie's own ``dt``, as the exporter does. The 200 Hz - frames are already averaged with their own kernel (``dt200 = - ceil(mean(diff(lines)))``), so this smooths fast events twice; - ``matched`` uses ``sqrt(dt80**2 - dt200**2)``, the kernel whose - variance added to the 200 Hz frames' gives the movie's; ``exact`` - averages with the movie's ``dt`` and adds the interpolated 200 Hz - frames (:func:`~giant_python.viewer.render.exact_weights`). - """ - if kernel in ("exporter", "exact"): - return float(dt80) - if kernel != "matched": - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - lines200 = np.asarray(lines200, dtype=np.float64) - if lines200.size < 2: - return float(dt80) - dt200 = frame_dt200(lines200, dt80) - return math.sqrt(max(dt80**2 - dt200**2, 1.0)) - - -def load_trial( - runs: list, - session: Session, - d: int, - t: int, - blur: float = 0.0, - kernel: str = "matched", -) -> TrialMovie: - """Load trial ``t`` (zero-based) of path ``d`` (one-based) with every run's activity. - - The movie is NaN at SILo's motion discards (``recNegErr``, as - ``loadAndProcessTrialAsync``) and at the frames whose kernel weight - falls mostly on SILo's discarded 200 Hz frames (the exporter's rule). - Valid pixels are decided on the motion discards alone, as the - exporter decides them (see the module docstring). - Both time kernels (:func:`render_dt`) are rendered; ``kernel`` is the - one :meth:`TrialMovie.frame` uses by default. - """ - if kernel not in KERNELS: - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - st = _settings(runs[0]) - movie = read_channel(session.movie_file(d - 1, t), st["num_channels"], st["channel"]) - T, R, C = movie.shape - hz, rne = _read_alignment(session.alignment_file(d - 1, t), T) - disc = discard_frames(rne, hz, st["motion_thresh"], st["discard_initial_s"]) - movie[disc] = np.nan - with np.errstate(invalid="ignore"): - valid = np.isnan(movie).mean(0) < st["nan_thresh"] - rows, cols = np.nonzero(valid) - flat = rows * C + cols - ds = session.ds_lines(d - 1, t)[:T] - lines0 = runs[0].path(d).lines - dt = kernel_dt(ds, lines0, st["ratio"]) - lpc = session.lines_per_cycle(d - 1, t) - ctx = { - "shape": (R, C), - "flat": flat, - "ds_lines": ds, - "dt": dt, - "lpc": lpc, - "blur": float(blur), - } - layers = [run_layer(r, session, d, t, ctx) for r in runs] - for share in ctx.get("shares", []): - disc = disc | (share > 0.5) - mov = movie.reshape(T, R * C)[:, flat] - del movie - mov[disc] = np.nan - base = _read_baseline(session.baseline_file(d - 1, t), (T, R, C), flat) - if base is not None: - base[disc] = np.nan - with np.errstate(invalid="ignore"), _quiet(): - mean = np.nanmean(mov, 0) - info = { - "dt_lines": dt, - "render_dt_lines": { - r.name: {k: round(v[0], 2) for k, v in r.kernels.items()} for r in layers - }, - "reach_lines": {r.name: {k: round(v[1], 1) for k, v in r.kernels.items()} for r in layers}, - "lines_per_cycle": lpc, - "blur_px": float(blur), - "align_hz": hz, - "movie": session.movie_file(d - 1, t).name, - "baseline": (session.baseline_file(d - 1, t) or Path("")).name, - "discarded": int(disc.sum()), - } - return TrialMovie( - path=d, - trial=t, - shape=(R, C), - rows=rows, - cols=cols, - mean=mean, - discard=disc, - movie=mov, - baseline=base, - runs=layers, - info=info, - kernel=kernel, - ) - - -def _read_baseline(path: Optional[Path], shape: tuple, flat: np.ndarray) -> np.ndarray | None: - """Read a network baseline at the valid pixels, float16 ``(frames, N)``.""" - if path is None: - return None - T, R, C = shape - with h5py.File(path, "r") as f: - b = np.asarray(f["baseline"][()]) # (frames, MATLAB cols, rows) - if b.shape != (T, C, R): - raise ValueError(f"{path.name}: baseline {b.shape}, movie {shape}") - b = b.transpose(0, 2, 1).reshape(T, R * C)[:, flat] - return np.ascontiguousarray(b.astype(np.float16)) - - -def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: - """Return indices of the ``n`` largest local maxima of ``x`` at least ``gap`` samples apart. - - The indices are ordered largest first. - """ - x = np.nan_to_num(np.asarray(x, np.float64), nan=-np.inf) - if x.size < 3: - return np.zeros(0, int) - peak = np.flatnonzero((x[1:-1] > x[:-2]) & (x[1:-1] >= x[2:])) + 1 - peak = peak[x[peak] > 0] - order = peak[np.argsort(-x[peak], kind="stable")] - taken: list = [] - for i in order: - if all(abs(i - j) >= gap for j in taken): - taken.append(int(i)) - if len(taken) >= n: - break - return np.asarray(taken, int) - - -def source_events( - run: SiloRun, session: Session, d: int, s: int, n: int = 30 -) -> list[dict[str, float]]: - """Find a source's largest denoised events over all trials, as movie frames. - - Returns a list of ``{trial, frame, line, value}`` (largest first). - """ - p = run.path(d) - x = run.traces(d)["dF_denoised"][:, s] - hz = float(run.param("analyzeHz", 200.0)) - gap = max(1, int(math.ceil(0.25 * hz))) - out = [] - for t in range(p.n_frames.size): - span = p.trial_span(t) - if span.stop <= span.start or not session.has_movie(d - 1, t): - continue - xs = x[span] - ds = session.ds_lines(d - 1, t) - for i in largest_events(xs, n, gap): - line = float(p.lines[span][i]) - frame = int(np.argmin(np.abs(ds - line))) - out.append({ - "trial": t, - "frame": frame, - "value": float(xs[i]), - "line": line, - }) - out.sort(key=lambda e: -e["value"]) - return out[:n] +"""One trial-path in the viewer's movie view. + +The registered 80 Hz movie of the trial (the activity channel, in the +trial's own registered frame, not resampled), the runs' fitted activity +rendered into it (:mod:`~giant_python.viewer.render`), and the F0 +network's baseline when a baseline folder is given. Arrays are held for +the valid pixels only, as the exporter defines them: missing in less than +nanThresh of the frames with SILo's motion discards counted as +missing. The frames blanked afterwards because their kernel weight lies +mostly on discarded 200 Hz frames do not count (they are blank at every +pixel, and the exporter's training targets cover the same pixels). The +activity is not stored per frame: a frame or a trace is the footprints +(sparse) times the sources' 80 Hz traces. +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass, field +from pathlib import Path, PurePath +from typing import Optional + +import h5py +import numpy as np + +from ..extraction.raster.trial import discard_frames +from ..pipeline.silo_session import _grid, _read +from .render import ( + KERNELS, + TrialMap, + frame_dt200, + kernel_dt, + kernel_weights, + place_footprints, +) +from .run import SiloRun + + +class Session: + """The trial table and folders the runs of one session share. + + Parameters + ---------- + table : str or Path + trial_table.h5 (or its folder). + moco_dir : str or Path, optional + Folder of the registered movies and alignment files (default: + /motion_correction, else next to the table). + baseline_dir : str or Path, optional + Folder of _BASELINE-80Hz.h5 (slap2-f0 + predict-registered); optional. + data_dir : str or Path, optional + Folder of the raw files, to read the lines per cycle (default: the + table's datadr; without them the kernel reaches 3 dt). + """ + + def __init__( + self, + table: str | Path, + moco_dir: str | Path | None = None, + baseline_dir: str | Path | None = None, + data_dir: str | Path | None = None, + ) -> None: + """Read the table's file names. + + Raises + ------ + ValueError + If the table has no registration (fn_reg_ds or fn_adata is missing). + """ + table = Path(table) + if table.is_dir(): + table = table / "trial_table.h5" + self.table = table + with h5py.File(table, "r") as f: + rm = "row_major" in f and bool(np.ravel(f["row_major"][()])[0]) + filename = np.atleast_2d(_read(f, "filename", rm)) + shape = filename.shape + reg = _read(f, "motion_correction/fn_reg_ds", rm) + adata = _read(f, "motion_correction/fn_adata", rm) + savedr = _read(f, "savedr", rm) + datadr = _read(f, "datadr", rm) + if reg is None or adata is None: + raise ValueError(f"{table} has no registration") + self.filename = filename + self.fn_reg_ds = _grid(reg, shape) + self.fn_adata = _grid(adata, shape) + savedr = Path(str(np.ravel(savedr)[0])) if savedr is not None else None + if moco_dir is None: + moco_dir = (savedr / "motion_correction") if savedr else None + if moco_dir is None or not moco_dir.exists(): + moco_dir = table.parent / "motion_correction" + self.moco_dir = Path(moco_dir) + self.baseline_dir = Path(baseline_dir) if baseline_dir else None + if data_dir is None and datadr is not None: + data_dir = str(np.ravel(datadr)[0]) + self.data_dir = Path(data_dir) if data_dir else None + self._ds: dict = {} + self._lpc: dict = {} + + @staticmethod + def _name(value: object) -> str: + """Return a table file name without its folder. + + Returns + ------- + str + The file name, without its folder. + """ + return PurePath(str(value).replace("\\", "/")).name + + def movie_file(self, d: int, t: int) -> Path: + """Find the registered movie of path d, trial t (zero-based). + + It is found by its stem as .tif or .h5, as SILo finds it + (:meth:`SiloSession.movie`); the table's name if neither exists. + + Returns + ------- + Path + The movie's path in the motion-correction folder. + """ + name = self._name(self.fn_reg_ds[d, t]) + stem = PurePath(name).stem + for ext in (".tif", ".h5"): + p = self.moco_dir / (stem + ext) + if p.exists(): + return p + return self.moco_dir / name + + def alignment_file(self, d: int, t: int) -> Path: + """Return the alignment file of path d, trial t (zero-based). + + Returns + ------- + Path + The alignment file's path in the motion-correction folder. + """ + return self.moco_dir / self._name(self.fn_adata[d, t]) + + def has_movie(self, d: int, t: int) -> bool: + """Whether the trial's movie and alignment file are here. + + Returns + ------- + bool + True when the table names a movie and both files exist. + """ + if not str(self.fn_reg_ds[d, t]).strip(): + return False + return self.movie_file(d, t).exists() and self.alignment_file(d, t).exists() + + def baseline_file(self, d: int, t: int) -> Optional[Path]: + """Find the trial's network baseline, if there is one. + + Returns + ------- + Path or None + The baseline file; None when there is no baseline folder or file for the trial. + """ + if self.baseline_dir is None: + return None + name = self._name(self.fn_reg_ds[d, t]) + if "_REGISTERED" not in name: + return None + stem = name[: name.index("_REGISTERED")] + p = self.baseline_dir / f"{stem}_BASELINE-80Hz.h5" + return p if p.exists() else None + + def ds_lines(self, d: int, t: int) -> np.ndarray: + """Read the registered frames' lines (DSframes) of a trial. + + Returns + ------- + np.ndarray + The lines of the trial's registered frames, as a flat float vector. + """ + key = (d, t) + if key not in self._ds: + with h5py.File(self.alignment_file(d, t), "r") as f: + self._ds[key] = np.asarray(f["DSframes"][()], float).ravel() + return self._ds[key] + + def lines_per_cycle(self, d: int, t: int) -> int: + """Lines per cycle from the raw file's header (0 if unreadable). + + Returns + ------- + int + The lines per cycle; 0 when there is no raw data or its header is unreadable. + """ + key = (d, t) + if key not in self._lpc: + self._lpc[key] = 0 + if self.data_dir is not None: + try: + from ..io.slap2_raster import raster_layout + + fn = self.data_dir / self._name(self.filename[d, t]) + self._lpc[key] = int(raster_layout(fn).lines_per_cycle) + except Exception: # noqa: BLE001 (no raw data: 3 dt) + self._lpc[key] = 0 + return self._lpc[key] + + +def read_channel(path: Path, num_channels: int, channel: int) -> np.ndarray: + """One channel of a registered movie as (frames, rows, cols) float32. + + Zero-based channel; channels interleaved by frame. + + Returns + ------- + np.ndarray + The channel's frames, (frames, rows, cols) float32. + """ + if path.suffix == ".h5": + with h5py.File(path, "r") as f: + ds = f[next(iter(f.keys()))] # (pages, MATLAB cols, rows) + n = ds.shape[0] // num_channels + # whole frames at a time: twice as fast as a strided selection + # of the (one page per chunk, compressed) dataset + step = 128 * num_channels + raw = np.concatenate([ + ds[a : min(a + step, n * num_channels)][channel::num_channels] + for a in range(0, n * num_channels, step) + ]) + else: + import tifffile + + with tifffile.TiffFile(path) as tf: + pages = tf.pages + n = len(pages) // num_channels + first = pages[channel].asarray() + raw = np.empty((n,) + first.shape, first.dtype) + raw[0] = first + for k in range(1, n): + raw[k] = pages[channel + k * num_channels].asarray() + return np.ascontiguousarray(np.asarray(raw, np.float32).transpose(0, 2, 1)) + + +@dataclass +class RunLayer: + """One run's activity in a trial. + + Attributes + ---------- + name : str + footprints : scipy.sparse.csr_matrix (valid pixels, sources) + x80 : dict + Time kernel (:data:`KERNELS`) to the sources' denoised traces at + the movie's frames, (sources, frames). + kept_rc, rejected_rc, seeds_rc : ndarray (n, 2) + Marker positions in the trial's registered frame. + kernels : dict + Time kernel to its (dt, reach) in lines, from this run's own + 200 Hz frame lines (:func:`render_dt`). + rendered : bool + False when the run has no footprints or no map for the trial. + """ + + name: str + footprints: object + x80: dict + kept_rc: np.ndarray + rejected_rc: np.ndarray + seeds_rc: np.ndarray + rendered: bool = True + kernels: dict = field(default_factory=dict) + + +@dataclass +class TrialMovie: + """A loaded trial-path: movie, baseline and each run's activity. + + kernel is the time kernel (:data:`KERNELS`) that :meth:`frame` and + :meth:`trace` use unless they are given another. + """ + + path: int + trial: int + shape: tuple + rows: np.ndarray + cols: np.ndarray + mean: np.ndarray + discard: np.ndarray + movie: np.ndarray + baseline: Optional[np.ndarray] + runs: list + info: dict = field(default_factory=dict) + kernel: str = "matched" + lock: threading.Lock = field(default_factory=threading.Lock, repr=False) + + @property + def T(self) -> int: + """Frames.""" + return int(self.movie.shape[0]) + + @property + def N(self) -> int: + """Valid pixels.""" + return int(self.movie.shape[1]) + + @property + def layers(self) -> list: + """Layer names in the order of :meth:`frame` and :meth:`trace`.""" + out = ["movie"] + for r in self.runs: + out += [f"activity:{r.name}", f"residual:{r.name}"] + if self.baseline is not None: + out.append("baseline") + out += [f"residual-baseline:{r.name}" for r in self.runs] + return out + + def span(self, t: int, avg: int) -> tuple: + """Return the frames [lo, hi) a mean of avg frames at t uses. + + Returns + ------- + tuple + (lo, hi): the first frame and the end (exclusive) of the span. + """ + lo = min(max(t - (avg - 1) // 2, 0), self.T - 1) + return lo, min(max(lo + avg, lo + 1), self.T) + + def _stack(self, frames: slice, pixels: np.ndarray | slice, kernel: str | None = None) -> list: + """Every layer's values (frames, pixels) at the given frames and pixels. + + The frames are a slice; the pixels an index array or a slice. + + Returns + ------- + list + One (frames, pixels) array per layer, in the order of :attr:`layers`. + + Raises + ------ + KeyError + If kernel is not one of the known kernels. + """ + kernel = kernel or self.kernel + if kernel not in KERNELS: + raise KeyError(f"kernel {kernel}") + m = self.movie[frames][:, pixels] + miss = np.isnan(m) + out = [m] + acts = [] + for r in self.runs: + h = r.footprints[pixels] if r.rendered else None + a = ( + np.asarray((h @ r.x80[kernel][:, frames]).T, np.float32) + if h is not None + else np.zeros_like(m) + ) + a[miss] = np.nan + acts.append(a) + out += [a, m - a] + if self.baseline is not None: + b = self.baseline[frames][:, pixels].astype(np.float32) + out.append(b) + out += [m - a - b for a in acts] + return out + + def frame(self, t: int, avg: int, kernel: str | None = None) -> np.ndarray: + """Each layer's mean over avg frames at t. + + (layers, valid pixels) float32, NaN-aware. + + Returns + ------- + np.ndarray + The means, (layers, valid pixels) float32. + """ + lo, hi = self.span(t, avg) + blocks = self._stack(slice(lo, hi), slice(None), kernel) + out = np.empty((len(blocks), self.N), np.float32) + with np.errstate(invalid="ignore"), _quiet(): + for i, b in enumerate(blocks): + out[i] = b[0] if hi - lo == 1 else np.nanmean(b, 0) + return out + + def trace(self, r: int, c: int, rad: int, kernel: str | None = None) -> tuple: + """Each layer's mean over the valid pixels within rad rows and columns of (r, c). + + Returns (layers, frames) float32, and the number of pixels. + + Returns + ------- + trace : np.ndarray + Each layer's mean trace, (layers, frames) float32. + n_pixels : int + The number of valid pixels averaged. + """ + near = (np.abs(self.rows - r) <= rad) & (np.abs(self.cols - c) <= rad) + k = np.flatnonzero(near) + out = np.full((len(self.layers), self.T), np.nan, np.float32) + if k.size: + with _quiet(): + for i, b in enumerate(self._stack(slice(None), k, kernel)): + out[i] = np.nanmean(b, 1) + return out, int(k.size) + + def busiest_frame(self, run: int = 0) -> int: + """Find the frame with the most rendered activity of a run. + + Returns + ------- + int + The frame index; 0 when the run is not rendered or has no activity. + """ + r = self.runs[run] + x = r.x80[self.kernel] + if not r.rendered or x.size == 0: + return 0 + total = np.asarray(r.footprints.sum(0)).ravel() @ x + total[self.discard] = -np.inf + return int(np.argmax(total)) + + +class _quiet: + """Silence NumPy's all-NaN warnings inside a block.""" + + def __enter__(self) -> None: + """Start ignoring RuntimeWarnings.""" + import warnings + + self._w = warnings.catch_warnings() + self._w.__enter__() + warnings.simplefilter("ignore", RuntimeWarning) + + def __exit__(self, *exc: object) -> None: + """Restore the warning filters.""" + self._w.__exit__(*exc) + + +def _marker_rc(tmap: TrialMap | None, rc: np.ndarray) -> np.ndarray: + """Canvas positions moved into the trial frame (NaN rows stay NaN). + + Returns + ------- + np.ndarray + The positions (n, 2) in the trial's registered frame; a copy of rc when there + is no map. + """ + rc = np.asarray(rc, np.float64).reshape(-1, 2) + if tmap is None or rc.size == 0: + return rc.copy() + r, c = tmap.forward(np.nan_to_num(rc[:, 0]), np.nan_to_num(rc[:, 1])) + out = np.column_stack([r, c]) + out[np.isnan(rc).any(1)] = np.nan + return out + + +def run_layer(run: SiloRun, session: Session, d: int, t: int, ctx: dict) -> RunLayer: + """One run's activity in trial t of path d (one-based path, zero-based trial). + + ctx holds the trial's shape, valid flat pixel indices flat, + ds_lines, the movie's kernel dt, the lines per cycle lpc and + blur; the time kernels come from the run's own 200 Hz frame lines + (:func:`render_dt`), and the run's 80 Hz discard share under the + exporter's kernel is added to ctx. + + Returns + ------- + RunLayer + The run's footprints, denoised traces per time kernel and marker positions in the trial. + """ + p = run.path(d) + n = p.sources.n + tmap = p.maps[t] if t < len(p.maps) else None + fps = run.footprints(d) + fp = fps[t] if t < len(fps) else None + span = p.trial_span(t) if t < p.n_frames.size else slice(0, 0) + lines200 = p.lines[span] + rendered = bool(tmap is not None and fp is not None and lines200.size) + T = ctx["ds_lines"].size + kernels = {} + for k in KERNELS: + dtr = render_dt(k, ctx["dt"], lines200) + kernels[k] = (dtr, max(3 * dtr, ctx["lpc"])) + x80 = {k: np.zeros((n, T), np.float32) for k in kernels} + h = None + if rendered: + x200 = np.nan_to_num(run.traces(d)["dF_denoised"][span]) # (n200, n) + for k in kernels: + w, share, _ = kernel_weights( + k, + lines200, + p.discard[span], + ctx["ds_lines"], + ctx["dt"], + ctx["lpc"], + ) + if k == "exporter": + ctx.setdefault("shares", []).append(share) + x80[k] = np.asarray((w.T @ x200).T, np.float32) + h = place_footprints(fp, n, tmap, ctx["shape"], ctx["blur"]) + h = h[ctx["flat"]] + trc = run.trial_centroids(d) + rc = trc[t] if t < trc.shape[0] else np.full((n, 2), np.nan) + rc = np.where(np.isnan(rc), p.sources.rc, rc) + seeds = p.sources.unused_seeds + return RunLayer( + name=run.name, + footprints=h, + x80=x80, + kept_rc=_marker_rc(tmap, rc), + rejected_rc=_marker_rc(tmap, p.sources.rejected_rc), + seeds_rc=_marker_rc(tmap, seeds if seeds is not None else []), + rendered=rendered, + kernels=kernels, + ) + + +def _settings(run: SiloRun) -> dict: + """SILo's frame settings of a run (defaults: SILo's for SLAP2). + + Returns + ------- + dict + num_channels, channel, motion_thresh, discard_initial_s, + nan_thresh and ratio (analysis to alignment frame rate). + """ + return { + "num_channels": int(run.param("numChannels", 2)), + "channel": run.activity_channel, + "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)), + } + + +def _read_alignment(path: Path, n_frames: int) -> tuple[float, np.ndarray]: + """Return alignHz and recNegErr from a trial's alignment file. + + Returns + ------- + hz : float + The alignment frame rate, alignHz. + rne : np.ndarray + recNegErr of the first n_frames frames. + """ + with h5py.File(path, "r") as f: + hz = float(np.ravel(f["alignHz"][()])[0]) + rne = np.asarray(f["recNegErr"][()], np.float64).ravel()[:n_frames] + return hz, rne + + +def render_dt(kernel: str, dt80: int, lines200: np.ndarray) -> float: + """Return the time constant (lines) the 200 Hz traces are averaged with. + + exporter: the movie's own dt, as the exporter does. The 200 Hz + frames are already averaged with their own kernel (dt200 = + ceil(mean(diff(lines)))), so this smooths fast events twice; + matched uses sqrt(dt80**2 - dt200**2), the kernel whose + variance added to the 200 Hz frames' gives the movie's; exact + averages with the movie's dt and adds the interpolated 200 Hz + frames (:func:`~giant_python.viewer.render.exact_weights`). + + Returns + ------- + float + The time constant, in lines. + + Raises + ------ + ValueError + If kernel is not one of the known kernels. + """ + if kernel in ("exporter", "exact"): + return float(dt80) + if kernel != "matched": + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + lines200 = np.asarray(lines200, dtype=np.float64) + if lines200.size < 2: + return float(dt80) + dt200 = frame_dt200(lines200, dt80) + return math.sqrt(max(dt80**2 - dt200**2, 1.0)) + + +def load_trial( + runs: list, + session: Session, + d: int, + t: int, + blur: float = 0.0, + kernel: str = "matched", +) -> TrialMovie: + """Load trial t (zero-based) of path d (one-based) with every run's activity. + + The movie is NaN at SILo's motion discards (recNegErr, as + loadAndProcessTrialAsync) and at the frames whose kernel weight + falls mostly on SILo's discarded 200 Hz frames (the exporter's rule). + Valid pixels are decided on the motion discards alone, as the + exporter decides them (see the module docstring). + Both time kernels (:func:`render_dt`) are rendered; kernel is the + one :meth:`TrialMovie.frame` uses by default. + + Returns + ------- + TrialMovie + The trial's movie, baseline, valid-pixel layout, every run's activity and an info + dict of the settings used. + + Raises + ------ + ValueError + If kernel is not one of the known kernels. + """ + if kernel not in KERNELS: + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + st = _settings(runs[0]) + movie = read_channel(session.movie_file(d - 1, t), st["num_channels"], st["channel"]) + T, R, C = movie.shape + hz, rne = _read_alignment(session.alignment_file(d - 1, t), T) + disc = discard_frames(rne, hz, st["motion_thresh"], st["discard_initial_s"]) + movie[disc] = np.nan + with np.errstate(invalid="ignore"): + valid = np.isnan(movie).mean(0) < st["nan_thresh"] + rows, cols = np.nonzero(valid) + flat = rows * C + cols + ds = session.ds_lines(d - 1, t)[:T] + lines0 = runs[0].path(d).lines + dt = kernel_dt(ds, lines0, st["ratio"]) + lpc = session.lines_per_cycle(d - 1, t) + ctx = { + "shape": (R, C), + "flat": flat, + "ds_lines": ds, + "dt": dt, + "lpc": lpc, + "blur": float(blur), + } + layers = [run_layer(r, session, d, t, ctx) for r in runs] + for share in ctx.get("shares", []): + disc = disc | (share > 0.5) + mov = movie.reshape(T, R * C)[:, flat] + del movie + mov[disc] = np.nan + base = _read_baseline(session.baseline_file(d - 1, t), (T, R, C), flat) + if base is not None: + base[disc] = np.nan + with np.errstate(invalid="ignore"), _quiet(): + mean = np.nanmean(mov, 0) + info = { + "dt_lines": dt, + "render_dt_lines": { + r.name: {k: round(v[0], 2) for k, v in r.kernels.items()} for r in layers + }, + "reach_lines": {r.name: {k: round(v[1], 1) for k, v in r.kernels.items()} for r in layers}, + "lines_per_cycle": lpc, + "blur_px": float(blur), + "align_hz": hz, + "movie": session.movie_file(d - 1, t).name, + "baseline": (session.baseline_file(d - 1, t) or Path("")).name, + "discarded": int(disc.sum()), + } + return TrialMovie( + path=d, + trial=t, + shape=(R, C), + rows=rows, + cols=cols, + mean=mean, + discard=disc, + movie=mov, + baseline=base, + runs=layers, + info=info, + kernel=kernel, + ) + + +def _read_baseline(path: Optional[Path], shape: tuple, flat: np.ndarray) -> np.ndarray | None: + """Read a network baseline at the valid pixels, float16 (frames, N). + + Returns + ------- + np.ndarray or None + The baseline, float16 (frames, N); None when path is None. + + Raises + ------ + ValueError + If the baseline's shape does not match the movie's. + """ + if path is None: + return None + T, R, C = shape + with h5py.File(path, "r") as f: + b = np.asarray(f["baseline"][()]) # (frames, MATLAB cols, rows) + if b.shape != (T, C, R): + raise ValueError(f"{path.name}: baseline {b.shape}, movie {shape}") + b = b.transpose(0, 2, 1).reshape(T, R * C)[:, flat] + return np.ascontiguousarray(b.astype(np.float16)) + + +def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: + """Return indices of the n largest local maxima of x at least gap samples apart. + + The indices are ordered largest first. + + Returns + ------- + np.ndarray + The indices of the largest local maxima, largest first. + """ + x = np.nan_to_num(np.asarray(x, np.float64), nan=-np.inf) + if x.size < 3: + return np.zeros(0, int) + peak = np.flatnonzero((x[1:-1] > x[:-2]) & (x[1:-1] >= x[2:])) + 1 + peak = peak[x[peak] > 0] + order = peak[np.argsort(-x[peak], kind="stable")] + taken: list = [] + for i in order: + if all(abs(i - j) >= gap for j in taken): + taken.append(int(i)) + if len(taken) >= n: + break + return np.asarray(taken, int) + + +def source_events( + run: SiloRun, session: Session, d: int, s: int, n: int = 30 +) -> list[dict[str, float]]: + """Find a source's largest denoised events over all trials, as movie frames. + + Returns a list of {trial, frame, line, value} (largest first). + + Returns + ------- + list[dict[str, float]] + Up to n events, largest first, each with the trial, the movie frame, the + acquisition line and the value of the denoised trace. + """ + p = run.path(d) + x = run.traces(d)["dF_denoised"][:, s] + hz = float(run.param("analyzeHz", 200.0)) + gap = max(1, int(math.ceil(0.25 * hz))) + out = [] + for t in range(p.n_frames.size): + span = p.trial_span(t) + if span.stop <= span.start or not session.has_movie(d - 1, t): + continue + xs = x[span] + ds = session.ds_lines(d - 1, t) + for i in largest_events(xs, n, gap): + line = float(p.lines[span][i]) + frame = int(np.argmin(np.abs(ds - line))) + out.append({ + "trial": t, + "frame": frame, + "value": float(xs[i]), + "line": line, + }) + out.sort(key=lambda e: -e["value"]) + return out[:n] diff --git a/tests/__init__.py b/tests/__init__.py index 48622532..d4d2ae53 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1 @@ -"""Tests for giant_python.""" +"""Tests for giant_python.""" diff --git a/tests/export/__init__.py b/tests/export/__init__.py index f052d76c..ee894a2a 100644 --- a/tests/export/__init__.py +++ b/tests/export/__init__.py @@ -1 +1 @@ -"""Tests of the F0 training-data export (giant export-f0).""" +"""Tests of the F0 training-data export (giant export-f0).""" diff --git a/tests/export/test_f0_injected.py b/tests/export/test_f0_injected.py index 8f9e6b92..c42f64c3 100644 --- a/tests/export/test_f0_injected.py +++ b/tests/export/test_f0_injected.py @@ -1,279 +1,279 @@ -"""GFP kind of the F0 training data (giant export-f0-injected). - -The tests run on a synthetic recording with injected events. -""" - -from collections.abc import Iterator -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.export.f0_injected import export_injected -from giant_python.export.f0_training import ExportOptions -from giant_python.io import slap2_raster -from giant_python.io.slap2_raster import RasterLayout -from giant_python.pipeline.register import register_multiroi -from giant_python.registration import multiroi -from giant_python.simulation import injection as inj - -from ..registration.synthetic import ( - make_layout, - online_offsets, - write_recording, -) -from ..simulation.test_injection import ( - BRIGHT, - BRIGHT_AT, - N_CYCLES, - registered_table, -) - - -@pytest.fixture(scope="module") -def copy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Path]: - """Build a synthetic recording and a registered copy with injected events. - - The recording is registered as two trials; the copy gets bright injected - events and is registered and compared (positions on the copy's grid). The - raster layouts stay patched while the module's tests run (the synthetic - files have no real header). - - Yields - ------ - Path - The copy's folder. - """ - root = tmp_path_factory.mktemp("gfpkind") - path = root / "rec" / "inj_DMD1-TRIAL000001.dat" - path.parent.mkdir() - layout = make_layout(path, n_cycles=N_CYCLES, seed=5) - offs = online_offsets(layout.total_lines) - write_recording(layout, seed=6, online=offs) - path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) - mp = pytest.MonkeyPatch() - mp.setattr(multiroi, "raster_layout", lambda p: layout) - reg = root / "reg" - reg.mkdir() - table = registered_table(layout, reg, True, [(1, 4800), (4801, 9700)]) - out = root / "copy" - mp.setattr(inj, "raster_layout", lambda p: layout) - inj.inject_session(table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT) - copy_layout = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - mp.setattr(multiroi, "raster_layout", lambda p: copy_layout) - register_multiroi( - out / "trial_table.h5", - {"maxshift": 6, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert inj.main(["compare", str(out)]) == 0 - # f0_injected reads the original's layout and replaces its files - mp.setattr(slap2_raster, "raster_layout", lambda p: layout) - yield out - mp.undo() - - -def test_activity_is_the_injected_photons(copy: Path, tmp_path: Path) -> None: - """The activity holds the injected photons as drawn. - - Their sum matches the noiseless expectation within Poisson noise, nothing - is injected far from the sources, and the file has the training layout. - """ - s = export_injected(copy, tmp_path / "out", ExportOptions(label="syn"), expected=True) - assert [q["trial"] for q in s["trials"]] == [1, 2] - truth = inj.read_truth(copy / inj.TRUTH_NAME)["paths"][1] - for q in s["trials"]: - assert "error" not in q, q - assert q["kind"] == "gfp_injected" and q["nSources"] == 3 - assert q["drawnOverExpected"] == pytest.approx(1.0, abs=0.05) - with h5py.File(q["file"], "r") as f: - a, m = f["activity"][0], f["movie"][0] - e = f["activity_expected"][0] - sup = f["mask/footprint_support"][()].astype(bool) - r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) - assert a.shape == m.shape and e.shape == a.shape - assert f.attrs["kind"] == "gfp_injected" - assert int(f.attrs["originalTrial"]) == q["trial"] - assert f.attrs["registrationStem"] == q["registrationStem"] - assert f"DMD{q['path']}" in q["registrationStem"] - pr, pc = f["sources/peak_row"][()], f["sources/peak_col"][()] - pos = truth["trials_detail"][q["trial"]]["positions_copy_rc"] - np.testing.assert_array_equal(pr, np.rint(pos[:, 0]).astype(int) - r0) - np.testing.assert_array_equal(pc, np.rint(pos[:, 1]).astype(int) - c0) - assert sup.any() and np.abs(a[:, ~sup]).max() < 1e-2 * a.max() - assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx(e[:, sup].sum(), rel=0.05) - - -def test_cli_and_selection(copy: Path, tmp_path: Path) -> None: - """Giant export-f0-injected writes the chosen trial. - - Trials the copy does not have are refused. - """ - out = tmp_path / "out" - rc = main(["export-f0-injected", str(copy), str(out), "--trials", "2"]) - assert rc == 0 - assert (out / "Path1" / "trial_002.h5").exists() - assert not (out / "Path1" / "trial_001.h5").exists() - with pytest.raises(SystemExit) as e: - main(["export-f0-injected", str(copy), str(out), "--trials", "3"]) - assert e.value.code == 2 - - -def test_target_is_the_original_on_the_copys_grid(copy: Path, tmp_path: Path) -> None: - """Movie - activity equals the original's samples on the copy's grid. - - The samples are formed with the copy's registration (its kernel and - resampling weights): the injected events leave nothing in the target. - """ - from giant_python.export.f0_injected import kernel_lines - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.simulation.render import iter_registered_frames - - s = export_injected(copy, tmp_path / "out", ExportOptions(trials=(1,))) - q = s["trials"][0] - truth = inj.read_truth(copy / inj.TRUTH_NAME) - layout = slap2_raster.raster_layout("unused") # the patched layout - al = inj.read_alignment(copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - with h5py.File(q["file"], "r") as f: - m, a = f["movie"][0], f["activity"][0] - r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) - dt = float(f.attrs["movieDtLines"]) - disc = f["frame/discard"][()].astype(bool) - assert dt == kernel_lines(layout, 80.0) - orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype(np.float32) - times = np.asarray(al.ds_frames, np.int64)[: m.shape[0]] - ref = np.full((times.size,) + al.shape, np.nan, np.float32) - for idx, frames, _ in iter_registered_frames(layout, orig, 0, al, times, int(dt)): - ref[idx] = frames[0].numpy() - R, C = m.shape[1:] - ref = ref[:, r0 : r0 + R, c0 : c0 + C] - ok = np.isfinite(m) & np.isfinite(ref) & ~disc[:, None, None] - assert ok.mean() > 0.5 - np.testing.assert_allclose((m - a)[ok], ref[ok], atol=1e-2 * np.nanmax(a)) - assert truth["paths"][1]["events"]["source"].size > 0 - - -@pytest.mark.parametrize("channels", [(0,), (3,)]) -def test_channels_outside_the_movie_are_refused( - copy: Path, tmp_path: Path, channels: tuple[int, ...] -) -> None: - """Channels are one-based and within the alignment file's numChannels.""" - with pytest.raises(ValueError, match="channels"): - export_injected(copy, tmp_path / "out", ExportOptions(channels=channels)) - - -def test_footprints_rebuilt_from_the_truth() -> None: - """Gaussian footprints come back with their recorded widths and radius. - - An image footprint is refused when its model is needed. - """ - from giant_python.export.f0_injected import injected_footprints - - g = {"kind": "gaussian", "sigma_rc": [1.0, 2.0], "radius_px": 8.0} - fp = injected_footprints({"footprint": {"params": [g]}}, True)[0] - assert fp.sigma == (1.0, 2.0) and fp.radius == pytest.approx(8.0) - img = {"kind": "image", "center_rc": [1.0, 1.0], "radius_px": 3.0} - assert injected_footprints({"footprint": {"params": [img]}}, False) == [None] - with pytest.raises(ValueError, match="image"): - injected_footprints({"footprint": {"params": [img]}}, True) - - -def test_default_export_reconciles_and_selection_keeps(copy: Path, tmp_path: Path) -> None: - """A default export removes earlier trial files it does not write. - - An export of chosen trials leaves them. - """ - out = tmp_path / "out" - (out / "Path1").mkdir(parents=True) - (out / "Path1" / "trial_007.h5").write_bytes(b"old") - s = export_injected(copy, out, ExportOptions(trials=(2,))) - assert "removed" not in s and (out / "Path1" / "trial_007.h5").exists() - s = export_injected(copy, out) - assert s["removed"] == {"Path1": ["trial_007.h5"]} - assert sorted(f.name for f in (out / "Path1").iterdir()) == [ - "trial_001.h5", - "trial_002.h5", - ] - - -def test_ragged_copy_and_bounded_reads( - copy: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A column without a recording on the path is skipped (no error). - - A trial reads only the cycles its frames' kernels reach. - """ - import giant_python.export.f0_injected as fi - - real = inj.read_truth - - def ragged(path: str | Path) -> dict: - """Read the truth without trial 1 on path 1. - - Returns - ------- - dict - The truth, with trial 1 removed from path 1's ``trials_detail``. - """ - t = real(path) - t["paths"][1]["trials_detail"].pop(1) # trial 1 not on this path - return t - - monkeypatch.setattr(inj, "read_truth", ragged) - ranges = [] - real_read = slap2_raster.read_raster_samples - - def spy(layout: RasterLayout, cycles: tuple[int, int], *a: object, **k: object) -> np.ndarray: - """Record the cycles read. - - Returns - ------- - np.ndarray - The samples from the real ``read_raster_samples``. - """ - ranges.append(tuple(cycles)) - return real_read(layout, cycles, *a, **k) - - monkeypatch.setattr(slap2_raster, "read_raster_samples", spy) - s = fi.export_injected(copy, tmp_path / "out") - assert [q["trial"] for q in s["trials"]] == [2] - assert "error" not in s["trials"][0] - layout = slap2_raster.raster_layout("unused") - assert ranges and all(c0 > 0 for c0, _ in ranges) # trial 2 starts later - assert all(c1 - c0 < layout.num_cycles for c0, c1 in ranges) - - -def test_peaks_of_an_empty_source_list() -> None: - """A copy without placed sources has no peaks (no index error).""" - from giant_python.export.f0_injected import peak_positions - - pth = { - "peak_pixel_rc": np.zeros((0, 2)), - "positions_rc": np.zeros((0, 2)), - "footprint": {"params": []}, - } - assert peak_positions(pth, np.zeros((0, 2))).shape == (0, 2) - - -def test_moved_copy_duplicate_channels_and_stale_paths(copy: Path, tmp_path: Path) -> None: - """A copy moved to another folder exports from its own raw files. - - A repeated injected channel gets the activity in every occurrence; a full - export clears trial files of paths the copy does not have. - """ - import shutil - - moved = tmp_path / "moved" - shutil.copytree(copy, moved) - out = tmp_path / "out" - (out / "Path2").mkdir(parents=True) - (out / "Path2" / "trial_001.h5").write_bytes(b"old") - s = export_injected(moved, out, ExportOptions(channels=(1, 1))) - assert all("error" not in q for q in s["trials"]) - assert s["removed"]["Path2"] == ["trial_001.h5"] - with h5py.File(s["trials"][0]["file"], "r") as f: - a = f["activity"][()] - assert a.shape[0] == 2 and np.array_equal(a[0], a[1]) and a[0].max() > 0 +"""GFP kind of the F0 training data (giant export-f0-injected). + +The tests run on a synthetic recording with injected events. +""" + +from collections.abc import Iterator +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.export.f0_injected import export_injected +from giant_python.export.f0_training import ExportOptions +from giant_python.io import slap2_raster +from giant_python.io.slap2_raster import RasterLayout +from giant_python.pipeline.register import register_multiroi +from giant_python.registration import multiroi +from giant_python.simulation import injection as inj + +from ..registration.synthetic import ( + make_layout, + online_offsets, + write_recording, +) +from ..simulation.test_injection import ( + BRIGHT, + BRIGHT_AT, + N_CYCLES, + registered_table, +) + + +@pytest.fixture(scope="module") +def copy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Path]: + """Build a synthetic recording and a registered copy with injected events. + + The recording is registered as two trials; the copy gets bright injected + events and is registered and compared (positions on the copy's grid). The + raster layouts stay patched while the module's tests run (the synthetic + files have no real header). + + Yields + ------ + Path + The copy's folder. + """ + root = tmp_path_factory.mktemp("gfpkind") + path = root / "rec" / "inj_DMD1-TRIAL000001.dat" + path.parent.mkdir() + layout = make_layout(path, n_cycles=N_CYCLES, seed=5) + offs = online_offsets(layout.total_lines) + write_recording(layout, seed=6, online=offs) + path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) + mp = pytest.MonkeyPatch() + mp.setattr(multiroi, "raster_layout", lambda p: layout) + reg = root / "reg" + reg.mkdir() + table = registered_table(layout, reg, True, [(1, 4800), (4801, 9700)]) + out = root / "copy" + mp.setattr(inj, "raster_layout", lambda p: layout) + inj.inject_session(table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT) + copy_layout = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + mp.setattr(multiroi, "raster_layout", lambda p: copy_layout) + register_multiroi( + out / "trial_table.h5", + {"maxshift": 6, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert inj.main(["compare", str(out)]) == 0 + # f0_injected reads the original's layout and replaces its files + mp.setattr(slap2_raster, "raster_layout", lambda p: layout) + yield out + mp.undo() + + +def test_activity_is_the_injected_photons(copy: Path, tmp_path: Path) -> None: + """The activity holds the injected photons as drawn. + + Their sum matches the noiseless expectation within Poisson noise, nothing + is injected far from the sources, and the file has the training layout. + """ + s = export_injected(copy, tmp_path / "out", ExportOptions(label="syn"), expected=True) + assert [q["trial"] for q in s["trials"]] == [1, 2] + truth = inj.read_truth(copy / inj.TRUTH_NAME)["paths"][1] + for q in s["trials"]: + assert "error" not in q, q + assert q["kind"] == "gfp_injected" and q["nSources"] == 3 + assert q["drawnOverExpected"] == pytest.approx(1.0, abs=0.05) + with h5py.File(q["file"], "r") as f: + a, m = f["activity"][0], f["movie"][0] + e = f["activity_expected"][0] + sup = f["mask/footprint_support"][()].astype(bool) + r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) + assert a.shape == m.shape and e.shape == a.shape + assert f.attrs["kind"] == "gfp_injected" + assert int(f.attrs["originalTrial"]) == q["trial"] + assert f.attrs["registrationStem"] == q["registrationStem"] + assert f"DMD{q['path']}" in q["registrationStem"] + pr, pc = f["sources/peak_row"][()], f["sources/peak_col"][()] + pos = truth["trials_detail"][q["trial"]]["positions_copy_rc"] + np.testing.assert_array_equal(pr, np.rint(pos[:, 0]).astype(int) - r0) + np.testing.assert_array_equal(pc, np.rint(pos[:, 1]).astype(int) - c0) + assert sup.any() and np.abs(a[:, ~sup]).max() < 1e-2 * a.max() + assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx(e[:, sup].sum(), rel=0.05) + + +def test_cli_and_selection(copy: Path, tmp_path: Path) -> None: + """Giant export-f0-injected writes the chosen trial. + + Trials the copy does not have are refused. + """ + out = tmp_path / "out" + rc = main(["export-f0-injected", str(copy), str(out), "--trials", "2"]) + assert rc == 0 + assert (out / "Path1" / "trial_002.h5").exists() + assert not (out / "Path1" / "trial_001.h5").exists() + with pytest.raises(SystemExit) as e: + main(["export-f0-injected", str(copy), str(out), "--trials", "3"]) + assert e.value.code == 2 + + +def test_target_is_the_original_on_the_copys_grid(copy: Path, tmp_path: Path) -> None: + """Movie - activity equals the original's samples on the copy's grid. + + The samples are formed with the copy's registration (its kernel and + resampling weights): the injected events leave nothing in the target. + """ + from giant_python.export.f0_injected import kernel_lines + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.simulation.render import iter_registered_frames + + s = export_injected(copy, tmp_path / "out", ExportOptions(trials=(1,))) + q = s["trials"][0] + truth = inj.read_truth(copy / inj.TRUTH_NAME) + layout = slap2_raster.raster_layout("unused") # the patched layout + al = inj.read_alignment(copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + with h5py.File(q["file"], "r") as f: + m, a = f["movie"][0], f["activity"][0] + r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) + dt = float(f.attrs["movieDtLines"]) + disc = f["frame/discard"][()].astype(bool) + assert dt == kernel_lines(layout, 80.0) + orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype(np.float32) + times = np.asarray(al.ds_frames, np.int64)[: m.shape[0]] + ref = np.full((times.size,) + al.shape, np.nan, np.float32) + for idx, frames, _ in iter_registered_frames(layout, orig, 0, al, times, int(dt)): + ref[idx] = frames[0].numpy() + R, C = m.shape[1:] + ref = ref[:, r0 : r0 + R, c0 : c0 + C] + ok = np.isfinite(m) & np.isfinite(ref) & ~disc[:, None, None] + assert ok.mean() > 0.5 + np.testing.assert_allclose((m - a)[ok], ref[ok], atol=1e-2 * np.nanmax(a)) + assert truth["paths"][1]["events"]["source"].size > 0 + + +@pytest.mark.parametrize("channels", [(0,), (3,)]) +def test_channels_outside_the_movie_are_refused( + copy: Path, tmp_path: Path, channels: tuple[int, ...] +) -> None: + """Channels are one-based and within the alignment file's numChannels.""" + with pytest.raises(ValueError, match="channels"): + export_injected(copy, tmp_path / "out", ExportOptions(channels=channels)) + + +def test_footprints_rebuilt_from_the_truth() -> None: + """Gaussian footprints come back with their recorded widths and radius. + + An image footprint is refused when its model is needed. + """ + from giant_python.export.f0_injected import injected_footprints + + g = {"kind": "gaussian", "sigma_rc": [1.0, 2.0], "radius_px": 8.0} + fp = injected_footprints({"footprint": {"params": [g]}}, True)[0] + assert fp.sigma == (1.0, 2.0) and fp.radius == pytest.approx(8.0) + img = {"kind": "image", "center_rc": [1.0, 1.0], "radius_px": 3.0} + assert injected_footprints({"footprint": {"params": [img]}}, False) == [None] + with pytest.raises(ValueError, match="image"): + injected_footprints({"footprint": {"params": [img]}}, True) + + +def test_default_export_reconciles_and_selection_keeps(copy: Path, tmp_path: Path) -> None: + """A default export removes earlier trial files it does not write. + + An export of chosen trials leaves them. + """ + out = tmp_path / "out" + (out / "Path1").mkdir(parents=True) + (out / "Path1" / "trial_007.h5").write_bytes(b"old") + s = export_injected(copy, out, ExportOptions(trials=(2,))) + assert "removed" not in s and (out / "Path1" / "trial_007.h5").exists() + s = export_injected(copy, out) + assert s["removed"] == {"Path1": ["trial_007.h5"]} + assert sorted(f.name for f in (out / "Path1").iterdir()) == [ + "trial_001.h5", + "trial_002.h5", + ] + + +def test_ragged_copy_and_bounded_reads( + copy: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A column without a recording on the path is skipped (no error). + + A trial reads only the cycles its frames' kernels reach. + """ + import giant_python.export.f0_injected as fi + + real = inj.read_truth + + def ragged(path: str | Path) -> dict: + """Read the truth without trial 1 on path 1. + + Returns + ------- + dict + The truth, with trial 1 removed from path 1's trials_detail. + """ + t = real(path) + t["paths"][1]["trials_detail"].pop(1) # trial 1 not on this path + return t + + monkeypatch.setattr(inj, "read_truth", ragged) + ranges = [] + real_read = slap2_raster.read_raster_samples + + def spy(layout: RasterLayout, cycles: tuple[int, int], *a: object, **k: object) -> np.ndarray: + """Record the cycles read. + + Returns + ------- + np.ndarray + The samples from the real read_raster_samples. + """ + ranges.append(tuple(cycles)) + return real_read(layout, cycles, *a, **k) + + monkeypatch.setattr(slap2_raster, "read_raster_samples", spy) + s = fi.export_injected(copy, tmp_path / "out") + assert [q["trial"] for q in s["trials"]] == [2] + assert "error" not in s["trials"][0] + layout = slap2_raster.raster_layout("unused") + assert ranges and all(c0 > 0 for c0, _ in ranges) # trial 2 starts later + assert all(c1 - c0 < layout.num_cycles for c0, c1 in ranges) + + +def test_peaks_of_an_empty_source_list() -> None: + """A copy without placed sources has no peaks (no index error).""" + from giant_python.export.f0_injected import peak_positions + + pth = { + "peak_pixel_rc": np.zeros((0, 2)), + "positions_rc": np.zeros((0, 2)), + "footprint": {"params": []}, + } + assert peak_positions(pth, np.zeros((0, 2))).shape == (0, 2) + + +def test_moved_copy_duplicate_channels_and_stale_paths(copy: Path, tmp_path: Path) -> None: + """A copy moved to another folder exports from its own raw files. + + A repeated injected channel gets the activity in every occurrence; a full + export clears trial files of paths the copy does not have. + """ + import shutil + + moved = tmp_path / "moved" + shutil.copytree(copy, moved) + out = tmp_path / "out" + (out / "Path2").mkdir(parents=True) + (out / "Path2" / "trial_001.h5").write_bytes(b"old") + s = export_injected(moved, out, ExportOptions(channels=(1, 1))) + assert all("error" not in q for q in s["trials"]) + assert s["removed"]["Path2"] == ["trial_001.h5"] + with h5py.File(s["trials"][0]["file"], "r") as f: + a = f["activity"][()] + assert a.shape[0] == 2 and np.array_equal(a[0], a[1]) and a[0].max() > 0 diff --git a/tests/export/test_f0_layout.py b/tests/export/test_f0_layout.py index bdf11961..84d21b92 100644 --- a/tests/export/test_f0_layout.py +++ b/tests/export/test_f0_layout.py @@ -1,793 +1,839 @@ -"""The raster layout files of the F0 network's simulator.""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.export import f0_layout -from giant_python.export.f0_layout import ( - HEIGHT_BINS, - SPLIT_BINS, - export_layouts, - layout_path, - pulse_statistics, - read_layout, - reference_frames, - slot_statistics, -) -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples -from giant_python.registration import multiroi -from giant_python.registration.stats.gain import next_slots - -from ..registration.synthetic import make_layout, online_offsets, write_recording - -MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - -Registered = tuple[RasterLayout, Path, Path] -"""The layout of a registered synthetic trial, its trial table and its folder.""" - - -def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: - """Write a one-trial trial table of the recording ``dat``.""" - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[1.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[last]]), - }, - }, - ) - return table - - -@pytest.fixture(scope="module") -def registered(tmp_path_factory: pytest.TempPathFactory) -> Registered: - """Register a synthetic trial (moving scene, some invalid samples). - - Gives the layout, its trial table and its output folder. - """ - from giant_python.pipeline.register import register_multiroi - - root = tmp_path_factory.mktemp("layout") - layout = make_layout(root / "synthetic_DMD1-TRIAL000001.dat", 1400) - write_recording(layout, invalid=0.02) - table = _table(root, Path(layout.files[0])) - with pytest.MonkeyPatch.context() as mp: - mp.setattr(multiroi, "raster_layout", lambda path: layout) - register_multiroi( - table, - {"maxshift": 5}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - return layout, table, root - - -@pytest.fixture -def patched(registered: Registered, monkeypatch: pytest.MonkeyPatch) -> Registered: - """Serve the recording's layout to the exporter.""" - monkeypatch.setattr(multiroi, "raster_layout", lambda path: registered[0]) - return registered - - -def _movie(path: Path, n_channels: int) -> np.ndarray: - """Read a registered movie as ``(channels, frames, rows, cols)``.""" - with h5py.File(path, "r") as f: - pages = f[next(iter(f.keys()))][()] - pages = pages.reshape(-1, n_channels, *pages.shape[1:]) - return np.swapaxes(pages, -1, -2).transpose(1, 0, 2, 3) - - -def test_file_reproduces_the_registered_movie(patched: Registered, tmp_path: Path) -> None: - """Frames formed from the file and its slots' raw samples are registration's. - - Missing pixels included. - """ - layout, table, root = patched - out = tmp_path / "layouts" - res = export_layouts(table, out) - assert [r["error"] for r in res] == [None] - lay = read_layout(out / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - assert at["path"] == 1 and at["trial"] == 1 and not at["compensated"] - assert at["lines_per_cycle"] == layout.lines_per_cycle - assert at["margin"] == 5 - c0, n = at["cycle0"], at["n_cycles"] - raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) - samples = raw[:, lay["slots/index"]] - movie = _movie(root / "motion_correction" / MOVIE, at["num_channels"]) - assert movie.shape[1] == lay["frames/lines"].size - frames = np.r_[0, 1, 7, 40, movie.shape[1] - 1] - got = reference_frames(lay, samples, frames) - want = movie[:, frames] - assert got.shape == want.shape - assert np.array_equal(np.isnan(got), np.isnan(want)) - assert np.isfinite(want).mean() > 0.2 - np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) - - -def test_slots_and_their_statistics(patched: Registered, tmp_path: Path) -> None: - """The file's slots are the window's, with their means and zeros.""" - layout, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - idx = lay["slots/index"] - # every slot of the raster block is in the window (one plane) - assert idx.size == layout.slot_line.size - assert np.array_equal(lay["slots/line"], layout.slot_line[idx]) - rows = (layout.slot_pixel[idx] - 1) // layout.n_cols - at["window_row0"] - cols = (layout.slot_pixel[idx] - 1) % layout.n_cols - at["window_col0"] - assert np.array_equal(lay["pixels/row"][lay["slots/pixel"]], rows) - assert np.array_equal(lay["pixels/col"][lay["slots/pixel"]], cols) - nxt = lay["slots/next"] - has = nxt >= 0 - # the synthetic lines visit their pixels in random order: only some - # consecutive samples are neighbouring pixels and share pulses - assert 0 < has.sum() < 0.5 * has.size - step_r = np.abs(rows[nxt[has]] - rows[has]) - step_c = np.abs(cols[nxt[has]] - cols[has]) - assert step_r.max() <= 1 and step_c.max() <= 1 - assert np.array_equal(lay["slots/line"][nxt[has]], lay["slots/line"][has]) - assert np.array_equal(lay["slots/pos"][nxt[has]], lay["slots/pos"][has] + 1) - c0, n = at["cycle0"], at["n_cycles"] - raw = read_raster_samples(layout, (c0, c0 + n))[:, idx].astype(float) - ok = raw != INVALID_SAMPLE - mean = np.where(ok, raw, 0).sum(2) / ok.sum(2) - np.testing.assert_allclose(lay["slots/mean"], mean, rtol=1e-6) - zero = (ok & (raw == 0)).sum(2) / ok.sum(2) - np.testing.assert_allclose(lay["slots/zero_share"], zero, atol=1e-6) - np.testing.assert_allclose(lay["slots/valid_share"], ok.mean(2), atol=1e-6) - assert 0.97 < lay["slots/valid_share"].mean() < 0.99 - - -def test_existing_files_are_kept_and_selection(patched: Registered, tmp_path: Path) -> None: - """A second run keeps the file; ``--overwrite`` and the selection.""" - from giant_python.cli import main - - _, table, _ = patched - args = ["export-f0-layout", str(table), "--out", str(tmp_path)] - assert main(args) == 0 - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - stamp = out.stat().st_mtime_ns - assert main(args) == 0 - assert out.stat().st_mtime_ns == stamp - assert main(args + ["--overwrite"]) == 0 - assert out.stat().st_mtime_ns != stamp - assert export_layouts(table, tmp_path / "none", trials=[2]) == [] - assert layout_path("a/E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif") == Path( - "a/E1T1DMD1_F0LAYOUT.h5" - ) - assert layout_path("a/movie.h5") == Path("a/movie_F0LAYOUT.h5") - - -def test_missing_alignment_and_old_versions(patched: Registered, tmp_path: Path) -> None: - """A trial without its alignment file fails. - - Other versions are refused. - """ - from giant_python.cli import main - - _, table, _ = patched - moved = ["--out", str(tmp_path), "--moco", str(tmp_path / "moved")] - assert main(["export-f0-layout", str(table)] + moved) == 1 - assert not (tmp_path / "E1T1DMD1_F0LAYOUT.h5").exists() - export_layouts(table, tmp_path) - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - with h5py.File(out, "r+") as f: - f.attrs["layout_version"] = 0 - with pytest.raises(ValueError, match="layout version"): - read_layout(out) - - -def test_compensated_registration_is_reproduced( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A registration that undid the online correction is reproduced. - - The file holds the lines' offsets and the frames' own, and frames formed - from it, every sample moved by its line's offset, are registration's. - """ - from giant_python.pipeline.register import register_multiroi - - layout = make_layout(tmp_path / "comp_DMD1-TRIAL000001.dat", 500) - x, _, y_dmd = online_offsets(layout.total_lines) - write_recording(layout, seed=6, online=(x, _, y_dmd)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = _table(tmp_path, Path(layout.files[0]), last=2000.0) - register_multiroi( - table, - {"maxshift": 5, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - res = export_layouts(table, tmp_path / "out") - assert [r["error"] for r in res] == [None] - lay = read_layout(tmp_path / "out" / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - assert at["compensated"] and at["layout_version"] == 4 - assert list(at["y_lead"]) == [2, 6] - p, c0, n = at["lines_per_cycle"], at["cycle0"], at["n_cycles"] - # the offsets of the lines of the file's cycles: x as the header has - # it, y as it was on the DMD - lines = slice(c0 * p, (c0 + n) * p) - assert lay["lines/x"].shape == (n * p,) - np.testing.assert_array_equal(lay["lines/x"], x[lines]) - np.testing.assert_array_equal(lay["lines/y_eff"], y_dmd[lines]) - assert np.unique(lay["lines/x"]).size > 1 - assert np.unique(lay["lines/y_eff"]).size > 1 - ref = lay["frames/ref_xy"] - assert ref.shape == (lay["frames/lines"].size, 2) - assert np.unique(ref, axis=0).shape[0] > 1 - # the slots' raster positions; a slot whose own pixel is among the - # pixels that frames report points at it - w = at["window_cols"] - slot_flat = lay["slots/row"].astype(np.int64) * w + lay["slots/col"] - pix_flat = lay["pixels/row"].astype(np.int64) * w + lay["pixels/col"] - listed = lay["slots/pixel"] >= 0 - np.testing.assert_array_equal(pix_flat[lay["slots/pixel"][listed]], slot_flat[listed]) - assert np.isin(slot_flat[listed], pix_flat).all() and listed.mean() > 0.9 - raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) - samples = raw[:, lay["slots/index"]] - movie = _movie(tmp_path / "motion_correction" / MOVIE, at["num_channels"]) - assert movie.shape[1] == lay["frames/lines"].size - # frames whose lines span an offset switch among them - changed = np.flatnonzero(np.any(np.diff(ref, axis=0) != 0, axis=1)) - frames = np.unique(np.r_[0, 1, changed[:6], changed[:6] + 1, movie.shape[1] - 1]) - got = reference_frames(lay, samples, frames) - want = movie[:, frames] - assert np.array_equal(np.isnan(got), np.isnan(want)) - assert np.isfinite(want).mean() > 0.2 - np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) - # without the offsets the frames are others: the samples are moved - plain = dict(lay, attrs=dict(at, compensated=False)) - off = reference_frames(plain, samples, frames) - both = np.isfinite(off) & np.isfinite(want) - assert np.abs(off - want)[both].max() > 1.0 - - -def test_version_3_files_are_read(patched: Registered, tmp_path: Path) -> None: - """A file of version 3 is read with its slots' positions. - - Version 3 has no slot positions (registrations without online - compensation); such a file gives the same frames. - """ - layout, table, root = patched - export_layouts(table, tmp_path) - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - new = read_layout(out) - assert new["attrs"]["layout_version"] == 4 - assert not new["attrs"]["compensated"] and "lines/x" not in new - np.testing.assert_array_equal(new["slots/row"], new["pixels/row"][new["slots/pixel"]]) - with h5py.File(out, "r+") as f: - f.attrs["layout_version"] = 3 - del f["slots/row"], f["slots/col"] - old = read_layout(out) - assert old["attrs"]["layout_version"] == 3 - np.testing.assert_array_equal(old["slots/row"], new["slots/row"]) - np.testing.assert_array_equal(old["slots/col"], new["slots/col"]) - at = new["attrs"] - raw = read_raster_samples( - layout, - (at["cycle0"], at["cycle0"] + at["n_cycles"]), - mask_unlit=at["unlit_masked"], - ) - samples = raw[:, new["slots/index"]] - np.testing.assert_array_equal( - reference_frames(old, samples, [3, 20]), - reference_frames(new, samples, [3, 20]), - ) - - -def _shared_pulses( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - p_split: float = 0.35, - k: float = 5.0, - theta: float = 22.0, -) -> np.ndarray: - """Compound-Poisson samples ``(slots, cycles)`` with pulses shared with the next slot. - - The pulses (gamma heights) are split with the next slot on the line with - probability ``p_split``, by a uniform fraction. - """ - n_slots, n_cycles = rate.shape - out = np.zeros((n_slots, n_cycles)) - counts = rng.poisson(rate) - s, c = np.nonzero(counts) - s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) - height = rng.gamma(k, theta, s.size) - split = (rng.random(s.size) < p_split) & (nxt[s] >= 0) - frac = np.where(split, rng.random(s.size), 1.0) - np.add.at(out, (s, c), height * frac) - np.add.at(out, (nxt[s[split]], c[split]), height[split] * (1 - frac[split])) - return np.round(out) - - -def test_pulse_statistics_recover_the_pulses() -> None: - """Heights, split probability and split fractions of simulated shared pulses. - - Measured on the dim pairs only. - """ - rng = np.random.default_rng(0) - n_lines, per_line, n_cycles = 40, 30, 4000 - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - nxt = next_slots(slot_line, slot_pos) - # dim lines and bright lines; only the dim ones should be used - level = np.where(slot_line <= 30, 0.01, 1.5) - rate = np.repeat(level[:, None], n_cycles, 1) - x = _shared_pulses(rate, nxt, rng) - x[5, :50] = INVALID_SAMPLE - samples = torch.from_numpy(x.astype(np.int16))[None] - out = pulse_statistics(samples, nxt) - single, split = out["height_single"][0], out["height_split"][0] - assert out["pairs"][0] == 30 * (per_line - 2) - n1, n2 = single.sum(), split.sum() - assert n1 + n2 > 6_000 - # only the pulses of each pair's first slot are counted, and 0.35 of - # them are split into the pair - assert abs(n2 / (n1 + n2) - 0.35) < 0.02 - heights = np.arange(1, HEIGHT_BINS + 1) - mean_height = ((single + split) * heights).sum() / (n1 + n2) - assert abs(mean_height - 5.0 * 22.0) < 3.0 - frac = out["split_fraction"][0] - assert frac.sum() == n2 - joint = out["split_joint"][0] - assert joint.shape == (f0_layout.JOINT_BINS, SPLIT_BINS) - assert np.array_equal(joint.sum(0), frac) - width = HEIGHT_BINS // f0_layout.JOINT_BINS - assert np.array_equal(joint.sum(1), split.reshape(-1, width).sum(1)) - assert np.abs(frac / n2 - 1 / SPLIT_BINS).max() < 0.02 - # isolated pair-cycles: both slots valid, their neighbours zero - assert 0.9 < out["pair_cycles"][0] / (out["pairs"][0] * n_cycles) < 1.0 - stats = slot_statistics(samples) - assert abs(stats["valid_share"][0, 5] - (1 - 50 / n_cycles)) < 1e-6 - assert abs(np.nanmean(stats["mean"][0, slot_line <= 30]) - 1.1) < 0.1 - - -def test_pairs_next_to_unseen_samples_are_left_out() -> None: - """A line with a sample that is not a raster slot. - - A pulse split with it would be counted truncated, so the pair before the - gap is not used; a pair needs a slot before it, so none starts a run - either. - """ - rng = np.random.default_rng(2) - # one line of eight samples; the one at position 4 is not a raster slot - slot_line = np.ones(7, dtype=np.int64) - slot_pos = np.array([0, 1, 2, 3, 5, 6, 7]) - nxt = next_slots(slot_line, slot_pos) - assert list(nxt) == [1, 2, 3, -1, 5, 6, -1] - x = (rng.random((7, 2000)) < 0.02) * 100 - samples = torch.from_numpy(x.astype(np.int16))[None] - # without line ends, a slot without a next ends its run: pairs (1, 2), - # (2, 3) and (5, 6); (0, 1) and (4, 5) start a run - naive = pulse_statistics(samples, nxt) - assert naive["pairs"][0] == 3 - out = pulse_statistics(samples, nxt, slot_pos == 7) - # the sample after 3 is unseen: (2, 3) goes - assert out["pairs"][0] == 2 - alone = (x[0] == 0) & (x[3] == 0) - one = (x[1] > 0) & (x[2] == 0) - both = (x[1] > 0) & (x[2] > 0) - alone2 = x[4] == 0 # the pair (5, 6): slot 4 before it, nothing after it - one2 = (x[5] > 0) & (x[6] == 0) - both2 = (x[5] > 0) & (x[6] > 0) - assert out["pair_cycles"][0] == alone.sum() + alone2.sum() - assert out["height_single"][0].sum() == (one & alone).sum() + (one2 & alone2).sum() - assert out["height_split"][0].sum() == (both & alone).sum() + (both2 & alone2).sum() - - -def test_run_starts_are_not_measured() -> None: - """The sample before a run is not recorded but passes parts of its pulses on. - - Counted on the run's first slot they would look like small unsplit - pulses. - """ - rng = np.random.default_rng(6) - n_cycles = 6000 - # the recorded run is the last six samples of a line of eight - slot_line = np.ones(8, dtype=np.int64) - slot_pos = np.arange(8) - full = next_slots(slot_line, slot_pos) - x = _shared_pulses(np.full((8, n_cycles), 0.01), full, rng, p_split=0.5) - seen = x[2:] # slots 0 and 1 are not recorded - nxt = np.array([1, 2, 3, 4, 5, -1]) - out = pulse_statistics(torch.from_numpy(seen.astype(np.int16))[None], nxt) - assert out["pairs"][0] == 4 # the pair starting the run is not used - low = out["height_single"][0][:25].sum() / out["height_single"][0].sum() - assert low < 0.02 # the simulated pulses are rarely below 25 - # the run's first slot alone: many small "pulses" - first = seen[0][(seen[0] > 0) & (seen[1] == 0)] - assert (first < 25).mean() > 5 * max(low, 0.01) - - -def test_layout_file_marks_line_ends(patched: Registered, tmp_path: Path) -> None: - """``slots/next`` links consecutive samples of neighbouring pixels. - - ``slots/line_end`` marks the slots that nothing follows which could share - a pulse: a line's last sample, or one before a jump. - """ - from giant_python.export.f0_layout import LAYOUT_VERSION, sharing_slots - - layout, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - assert lay["attrs"]["layout_version"] == LAYOUT_VERSION - idx = lay["slots/index"] - consecutive = next_slots(layout.slot_line, layout.slot_pos) - nxt, start, end = sharing_slots(layout) - row = (layout.slot_pixel - 1) // layout.n_cols - col = (layout.slot_pixel - 1) % layout.n_cols - to = np.maximum(consecutive, 0) - near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) - assert np.array_equal(nxt >= 0, (consecutive >= 0) & near) - assert np.array_equal(nxt[nxt >= 0], consecutive[nxt >= 0]) - last = layout.slot_pos == layout.n_per_channel[layout.slot_line - 1] - 1 - assert np.array_equal(end, last | ((consecutive >= 0) & ~near)) - # a slot starts a run when it starts its line or follows a jump - follows_jump = np.zeros(nxt.size, bool) - follows_jump[consecutive[(consecutive >= 0) & ~near]] = True - assert np.array_equal(start, (layout.slot_pos == 0) | follows_jump) - # the synthetic lines hold raster slots only: every slot is in the file - assert np.array_equal(lay["slots/line_end"].astype(bool), end[idx]) - assert np.array_equal(lay["slots/next"] < 0, end[idx]) - - -def test_pulses_are_not_measured_across_jumps() -> None: - """A pair whose samples are not neighbouring pixels shares no pulse. - - It is not a pair; the slots on either side of the jump are measured as the - ends of their runs. - """ - rng = np.random.default_rng(4) - n_cycles = 4000 - # one line of 8 samples: pixels 0-3 of a row, then a jump to 20-23 - slot_line = np.ones(8, dtype=np.int64) - slot_pos = np.arange(8) - cols = np.array([0, 1, 2, 3, 20, 21, 22, 23]) - - class Layout: - """One line of 8 samples: pixels 0-3 of a row, then a jump to 20-23.""" - - n_cols = 50 - slot_pixel = 5 * 50 + cols + 1 - n_per_channel = np.array([8]) - - Layout.slot_line, Layout.slot_pos = slot_line, slot_pos - from giant_python.export.f0_layout import sharing_slots - - nxt, start, end = sharing_slots(Layout) - assert list(nxt) == [1, 2, 3, -1, 5, 6, 7, -1] - assert list(start) == [ - True, - False, - False, - False, - True, - False, - False, - False, - ] - assert list(end) == [False, False, False, True, False, False, False, True] - # pulses split with probability 0.4 inside each run, none across the jump - x = _shared_pulses(np.full((8, n_cycles), 0.01), nxt, rng, p_split=0.4) - samples = torch.from_numpy(x.astype(np.int16))[None] - out = pulse_statistics(samples, nxt, end) - assert out["pairs"][0] == 4 # two per run: none starts a run - n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() - assert abs(n2 / (n1 + n2) - 0.4) < 0.07 - # counting the jump as a pair adds a slot whose pulses are never split - naive = pulse_statistics(samples, next_slots(slot_line, slot_pos)) - assert naive["pairs"][0] == 6 - m1, m2 = naive["height_single"][0].sum(), naive["height_split"][0].sum() - assert m2 / (m1 + m2) < n2 / (n1 + n2) - - -def test_pulse_statistics_without_dim_pairs() -> None: - """Bright pairs, in which pulses coincide, are never used. - - A recording without dim pairs gets empty histograms. - """ - rng = np.random.default_rng(1) - slot_line = np.repeat(np.arange(1, 21), 20) - slot_pos = np.tile(np.arange(20), 20) - nxt = next_slots(slot_line, slot_pos) - # no sharing at all: any split pulse would be a coincidence - x = _shared_pulses(np.full((400, 500), 0.8), nxt, rng, p_split=0.0) - out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - assert out["pairs"][0] == 0 and out["pair_cycles"][0] == 0 - for key in ("height_single", "height_split", "split_fraction"): - assert out[key].sum() == 0 - # dim pairs without sharing: almost no pulse is counted as split - x = _shared_pulses(np.full((400, 4000), 0.005), nxt, rng, p_split=0.0) - out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() - assert out["pairs"][0] == 360 and n1 > 5000 and n2 / (n1 + n2) < 0.01 - rate = (n1 + n2) / out["pair_cycles"][0] - assert abs(n2 / (n1 + n2) - rate) < 0.004 # the coincidences - none = pulse_statistics(torch.zeros((1, 3, 10), dtype=torch.int16), np.full(3, -1)) - assert none["pairs"][0] == 0 and none["height_single"].sum() == 0 - - -def _bursts( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - lengths: tuple[float, ...] = (0.5, 0.35, 0.12, 0.03), -) -> np.ndarray: - """Draw samples ``(slots, cycles)`` of events that occupy 1-4 consecutive slots. - - The lengths have the given probabilities, every part 40 + 10 x its place - in the burst (so that a part tells where in its burst it is). - """ - n_slots, n_cycles = rate.shape - out = np.zeros((n_slots, n_cycles)) - counts = rng.poisson(rate) - s, c = np.nonzero(counts) - s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) - length = rng.choice(4, s.size, p=lengths) + 1 - slot = s.copy() - for k in range(4): - on = (length > k) & (slot >= 0) - np.add.at(out, (slot[on], c[on]), 40 + 10 * k) - slot = np.where(slot >= 0, nxt[np.maximum(slot, 0)], -1) - return out - - -def test_burst_cells() -> None: - """The type of a burst. - - Its length, total and, for two samples, the smaller part's share. - """ - from giant_python.export.f0_layout import N_CELLS, burst_cells - - assert N_CELLS == 162 - one = burst_cells(np.array([[35], [100], [405], [9000]])) - assert one.tolist() == [3, 10, 40, 40] - two = burst_cells(np.array([[10, 90], [90, 10], [50, 50], [300, 400]])) - assert two.tolist() == [41 + 15, 41 + 15, 41 + 17, 41 + 30 * 3 + 2] - assert burst_cells(np.array([[100, 100, 100]])).tolist() == [134 + 6] - assert burst_cells(np.array([[250, 250, 250, 250]])).tolist() == [161] - assert burst_cells(np.zeros((0, 2))).shape == (0,) - - -def test_burst_library_and_counts_by_stratum(patched: Registered, tmp_path: Path) -> None: - """The library's counts are the events' length distribution. - - Its examples are whole events, part by part; the counts by stratum tell - events whose rate follows brightness from events at a constant rate; the - file holds both. - """ - from giant_python.export.f0_layout import ( - BURST_EXAMPLES, - N_CELLS, - STRATA_EDGES, - burst_cells, - burst_statistics, - ) - - rng = np.random.default_rng(3) - n_lines, per_line, n_cycles = 16, 40, 6000 - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - nxt = next_slots(slot_line, slot_pos) - # lines of four brightnesses (events per sample) and four bright lines - levels = np.array([0.006, 0.016, 0.033, 0.066, 1.0]) - level = levels[np.minimum((slot_line - 1) // 3, 4)] - x = _bursts(np.repeat(level[:, None], n_cycles, 1), nxt, rng) - # events at one rate everywhere: one sample of 60 - extra = rng.random(x.shape) < 0.002 - x = x + 60 * extra - x[7, :100] = INVALID_SAMPLE - out = burst_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - counts = out["burst_counts"][0] - assert counts[:4].sum() > 5000 - assert counts[4] < 0.01 * counts[:4].sum() - for n in range(1, 5): - kept = out["burst_examples"][0, n - 1] - assert kept == min(BURST_EXAMPLES, counts[n - 1]) - parts = out[f"burst_{n}"][0, :kept] - assert parts.shape[1] == n and (parts > 0).all() - # almost all are one event: part k is 40 + 10 k, or the one of 60 - clean = (parts == 40 + 10 * np.arange(n)).all(1) - if n == 1: - clean |= parts[:, 0] == 60 - # (a long burst is more often two events that touch) - assert clean.mean() > (0.9 if n < 3 else 0.7) - assert (out[f"burst_{n}"][0, kept:] == 0).all() - cells = out[f"burst_cell_{n}"][0, :kept] - np.testing.assert_array_equal(cells, burst_cells(parts)) - # strata: the mean sample rises, the bright lines are not counted - free, mean = out["strata_free"][0], out["strata_mean"][0] - assert out["strata_edges"].tolist() == list(STRATA_EDGES) - assert out["strata_bursts"].shape == (1, len(STRATA_EDGES) - 1, N_CELLS) - used = free > 2e5 - assert used.sum() >= 4 and (np.diff(mean[used]) > 0).all() - assert mean[used].max() < 8 and free.sum() <= 12 * 35 * n_cycles - rate = out["strata_bursts"][0][used] / free[used][:, None] - # one-sample events of 40 follow the mean; those of 60 do not - photon = rate[:, 4] / mean[used] - assert photon.max() < 1.2 * photon.min() - np.testing.assert_allclose(rate[:, 6], 0.002, rtol=0.2) - assert out["strata_longer"][0].sum() < 0.02 * out["strata_bursts"].sum() - # nothing without dim chains - bright = burst_statistics( - torch.from_numpy(x[slot_line > 12].astype(np.int16))[None], - next_slots(slot_line[slot_line > 12], slot_pos[slot_line > 12]), - ) - assert bright["strata_free"].sum() == 0 - assert bright["burst_counts"].sum() == 0 - # the layout file carries the library and the tables - _, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - assert lay["photon/burst_counts"].shape == (2, 5) - assert lay["photon/burst_3"].shape == (2, BURST_EXAMPLES, 3) - assert lay["photon/burst_cell_2"].shape == (2, BURST_EXAMPLES) - assert lay["photon/strata_bursts"].shape == (2, 8, N_CELLS) - assert lay["photon/level_moments"].shape == (2, 18, 9) - assert lay["photon/level_revisits"] in (0, 1) - assert lay["attrs"]["burst_level"] == 2.0 - - -def _level_case( - rng: np.random.Generator, visits: int, n_cycles: int = 3000 -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Simulate a raster whose pixels are sampled ``visits`` times per cycle. - - It has lines of two brightnesses that change together from cycle to cycle; - also returns the moments its events have per unit of mean. - """ - per_line, n_pairs = 60, 24 - n_lines = n_pairs * visits - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - pair = (slot_line - 1) // visits - pixel = pair * per_line + slot_pos - nxt = next_slots(slot_line, slot_pos) - rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] - if visits > 1: # brightness that changes slowly: both visits see it - wave = 1 + 0.6 * np.sin(np.arange(n_cycles) / 40.0) - rate = rate * wave[None, :] - else: - rate = np.repeat(rate, n_cycles, 1) - x = _bursts(rate, nxt, rng) - lengths = np.array([0.5, 0.35, 0.12, 0.03]) - parts = 40.0 + 10 * np.arange(4) - total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) - want = np.zeros(9) - for k in range(4): - want[k] = sum( - lengths[n] * (parts[: n + 1 - k] * parts[k : n + 1]).sum() for n in range(k, 4) - ) - return x, nxt, pixel, slot_line, want / total - - -@pytest.mark.parametrize("visits", [2, 1]) -def test_level_statistics_measure_the_events(visits: int) -> None: - """The moments by level are those of the events, per unit of mean. - - At every brightness, also where the brightness changes between cycles (two - visits per cycle) and for a raster without second visits. - """ - from giant_python.export.f0_layout import LEVEL_EDGES, level_statistics - - rng = np.random.default_rng(5 + visits) - x, nxt, pixel, line, want = _level_case(rng, visits) - x[3, :50] = INVALID_SAMPLE - out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, line) - assert out["level_revisits"] == (1 if visits > 1 else 0) - assert out["level_edges"].tolist() == list(LEVEL_EDGES) - n = out["level_samples"][0] - full = np.flatnonzero(n > 2e5) - assert full.size >= 2 - mean = out["level_mean"][0][full] - assert mean.min() < 8 and mean.max() > 20 - per_mean = out["level_moments"][0][full] / mean[:, None] - np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) - np.testing.assert_allclose(per_mean[:, 2], want[2], rtol=0.15) - assert np.abs(per_mean[:, 4:]).max() < 0.03 * want[0] - # zeros: no event covers the sample - cover = 0.5 + 0.35 * 2 + 0.12 * 3 + 0.03 * 4 - total = 0.5 * 40 + 0.35 * 90 + 0.12 * 150 + 0.03 * 220 - dim = full[np.argmin(mean)] - zero = np.exp(-out["level_mean"][0][dim] / total * cover) - assert abs(out["level_zero"][0][dim] - zero) < 0.03 - if visits > 1: # against the next cycle, the changing brightness counts - naive = x.astype(np.float64).var(1).sum() / x.sum() * x.shape[1] - assert naive > 1.15 * want[0] - empty = level_statistics( - torch.zeros((1, 4, 10), dtype=torch.int16), - np.full(4, -1), - np.arange(4), - np.ones(4, dtype=np.int64), - ) - assert empty["level_samples"].sum() == 0 - - -def test_level_statistics_second_observation_is_on_a_later_line() -> None: - """A line that samples its pixels twice in a row. - - The second sample of a pixel on the same line can share pulses with the - first, so it is not taken as the second observation; the next line's is. - """ - from giant_python.export.f0_layout import _second_visits, level_statistics - - rng = np.random.default_rng(13) - n_lines, half, n_cycles = 48, 30, 3000 - slot_line = np.repeat(np.arange(1, n_lines + 1), 2 * half) - slot_pos = np.tile(np.arange(2 * half), n_lines) - pair = (slot_line - 1) // 2 # two lines sample the same pixels - pixel = pair * half + slot_pos % half - nxt = next_slots(slot_line, slot_pos) - chain, other = _second_visits(nxt, pixel, slot_line) - assert other is not None and chain[0].size > 1000 - assert (slot_line[other[0]] == slot_line[chain[0]] + 1).all() - assert (pixel[other[0]] == pixel[chain[0]]).all() - # the first of the later line's two samples, whichever copy asks - assert (slot_pos[other[0]] == slot_pos[chain[0]] % half).all() - # one line per pixel set: no second observation within the cycle - _, none = _second_visits(nxt, slot_line * half + slot_pos % half, slot_line) - assert none is None - rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] - x = _bursts(np.repeat(rate, n_cycles, 1), nxt, rng) - out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, slot_line) - lengths = np.array([0.5, 0.35, 0.12, 0.03]) - parts = 40.0 + 10 * np.arange(4) - total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) - var = sum(lengths[n] * (parts[: n + 1] ** 2).sum() for n in range(4)) - cov = sum(lengths[n] * (parts[:n] * parts[1 : n + 1]).sum() for n in range(1, 4)) - assert out["level_revisits"] == 1 - full = np.flatnonzero(out["level_samples"][0] > 2e5) - per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] - np.testing.assert_allclose(per_mean[:, 0], var / total, rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], cov / total, rtol=0.06) - - -def test_level_statistics_skip_the_visits_of_another_plane() -> None: - """Lines of another plane between a pixel's two visits are no visits. - - Those lines sample the same pixels; marked by a negative pixel, they do not - stand in as the next visit (which would leave no revisits and send the - measurement to the next cycle). - """ - from giant_python.export.f0_layout import _second_visits, level_statistics - - rng = np.random.default_rng(9) - x, nxt, pixel, line, want = _level_case(rng, 3) - # the middle line of each three is another plane: its slots link to - # nothing, as sharing_slots restricted to the plane leaves them - off = (line - 1) % 3 == 1 - nxt = np.where(off | off[np.maximum(nxt, 0)], -1, nxt) - _, other = _second_visits(nxt, pixel, line) - assert other is None # the other plane's visit is taken and fails - chain, other = _second_visits(nxt, np.where(off, -1, pixel), line) - assert other is not None and chain[0].size > 1000 - assert not off[chain[0]].any() and not off[other[0]].any() - assert (line[other[0]] - line[chain[0]] == 2).all() - out = level_statistics( - torch.from_numpy(x.astype(np.int16))[None], - nxt, - np.where(off, -1, pixel), - line, - ) - assert out["level_revisits"] == 1 - full = np.flatnonzero(out["level_samples"][0] > 2e5) - per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] - np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) +"""The raster layout files of the F0 network's simulator.""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.export import f0_layout +from giant_python.export.f0_layout import ( + HEIGHT_BINS, + SPLIT_BINS, + export_layouts, + layout_path, + pulse_statistics, + read_layout, + reference_frames, + slot_statistics, +) +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples +from giant_python.registration import multiroi +from giant_python.registration.stats.gain import next_slots + +from ..registration.synthetic import make_layout, online_offsets, write_recording + +MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + +Registered = tuple[RasterLayout, Path, Path] +"""The layout of a registered synthetic trial, its trial table and its folder.""" + + +def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: + """Write a one-trial trial table of the recording dat. + + Returns + ------- + Path + The path of the written trial table. + """ + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[1.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[last]]), + }, + }, + ) + return table + + +@pytest.fixture(scope="module") +def registered(tmp_path_factory: pytest.TempPathFactory) -> Registered: + """Register a synthetic trial (moving scene, some invalid samples). + + Gives the layout, its trial table and its output folder. + + Returns + ------- + Registered + The layout, its trial table and its output folder, as (layout, table, root). + """ + from giant_python.pipeline.register import register_multiroi + + root = tmp_path_factory.mktemp("layout") + layout = make_layout(root / "synthetic_DMD1-TRIAL000001.dat", 1400) + write_recording(layout, invalid=0.02) + table = _table(root, Path(layout.files[0])) + with pytest.MonkeyPatch.context() as mp: + mp.setattr(multiroi, "raster_layout", lambda path: layout) + register_multiroi( + table, + {"maxshift": 5}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + return layout, table, root + + +@pytest.fixture +def patched(registered: Registered, monkeypatch: pytest.MonkeyPatch) -> Registered: + """Serve the recording's layout to the exporter. + + Returns + ------- + Registered + The registered fixture's value, unchanged. + """ + monkeypatch.setattr(multiroi, "raster_layout", lambda path: registered[0]) + return registered + + +def _movie(path: Path, n_channels: int) -> np.ndarray: + """Read a registered movie as (channels, frames, rows, cols). + + Returns + ------- + np.ndarray + The movie's pages, reshaped and transposed to (channels, frames, rows, cols). + """ + with h5py.File(path, "r") as f: + pages = f[next(iter(f.keys()))][()] + pages = pages.reshape(-1, n_channels, *pages.shape[1:]) + return np.swapaxes(pages, -1, -2).transpose(1, 0, 2, 3) + + +def test_file_reproduces_the_registered_movie(patched: Registered, tmp_path: Path) -> None: + """Frames formed from the file and its slots' raw samples are registration's. + + Missing pixels included. + """ + layout, table, root = patched + out = tmp_path / "layouts" + res = export_layouts(table, out) + assert [r["error"] for r in res] == [None] + lay = read_layout(out / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + assert at["path"] == 1 and at["trial"] == 1 and not at["compensated"] + assert at["lines_per_cycle"] == layout.lines_per_cycle + assert at["margin"] == 5 + c0, n = at["cycle0"], at["n_cycles"] + raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) + samples = raw[:, lay["slots/index"]] + movie = _movie(root / "motion_correction" / MOVIE, at["num_channels"]) + assert movie.shape[1] == lay["frames/lines"].size + frames = np.r_[0, 1, 7, 40, movie.shape[1] - 1] + got = reference_frames(lay, samples, frames) + want = movie[:, frames] + assert got.shape == want.shape + assert np.array_equal(np.isnan(got), np.isnan(want)) + assert np.isfinite(want).mean() > 0.2 + np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) + + +def test_slots_and_their_statistics(patched: Registered, tmp_path: Path) -> None: + """The file's slots are the window's, with their means and zeros.""" + layout, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + idx = lay["slots/index"] + # every slot of the raster block is in the window (one plane) + assert idx.size == layout.slot_line.size + assert np.array_equal(lay["slots/line"], layout.slot_line[idx]) + rows = (layout.slot_pixel[idx] - 1) // layout.n_cols - at["window_row0"] + cols = (layout.slot_pixel[idx] - 1) % layout.n_cols - at["window_col0"] + assert np.array_equal(lay["pixels/row"][lay["slots/pixel"]], rows) + assert np.array_equal(lay["pixels/col"][lay["slots/pixel"]], cols) + nxt = lay["slots/next"] + has = nxt >= 0 + # the synthetic lines visit their pixels in random order: only some + # consecutive samples are neighbouring pixels and share pulses + assert 0 < has.sum() < 0.5 * has.size + step_r = np.abs(rows[nxt[has]] - rows[has]) + step_c = np.abs(cols[nxt[has]] - cols[has]) + assert step_r.max() <= 1 and step_c.max() <= 1 + assert np.array_equal(lay["slots/line"][nxt[has]], lay["slots/line"][has]) + assert np.array_equal(lay["slots/pos"][nxt[has]], lay["slots/pos"][has] + 1) + c0, n = at["cycle0"], at["n_cycles"] + raw = read_raster_samples(layout, (c0, c0 + n))[:, idx].astype(float) + ok = raw != INVALID_SAMPLE + mean = np.where(ok, raw, 0).sum(2) / ok.sum(2) + np.testing.assert_allclose(lay["slots/mean"], mean, rtol=1e-6) + zero = (ok & (raw == 0)).sum(2) / ok.sum(2) + np.testing.assert_allclose(lay["slots/zero_share"], zero, atol=1e-6) + np.testing.assert_allclose(lay["slots/valid_share"], ok.mean(2), atol=1e-6) + assert 0.97 < lay["slots/valid_share"].mean() < 0.99 + + +def test_existing_files_are_kept_and_selection(patched: Registered, tmp_path: Path) -> None: + """A second run keeps the file; --overwrite and the selection.""" + from giant_python.cli import main + + _, table, _ = patched + args = ["export-f0-layout", str(table), "--out", str(tmp_path)] + assert main(args) == 0 + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + stamp = out.stat().st_mtime_ns + assert main(args) == 0 + assert out.stat().st_mtime_ns == stamp + assert main(args + ["--overwrite"]) == 0 + assert out.stat().st_mtime_ns != stamp + assert export_layouts(table, tmp_path / "none", trials=[2]) == [] + assert layout_path("a/E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif") == Path( + "a/E1T1DMD1_F0LAYOUT.h5" + ) + assert layout_path("a/movie.h5") == Path("a/movie_F0LAYOUT.h5") + + +def test_missing_alignment_and_old_versions(patched: Registered, tmp_path: Path) -> None: + """A trial without its alignment file fails. + + Other versions are refused. + """ + from giant_python.cli import main + + _, table, _ = patched + moved = ["--out", str(tmp_path), "--moco", str(tmp_path / "moved")] + assert main(["export-f0-layout", str(table)] + moved) == 1 + assert not (tmp_path / "E1T1DMD1_F0LAYOUT.h5").exists() + export_layouts(table, tmp_path) + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + with h5py.File(out, "r+") as f: + f.attrs["layout_version"] = 0 + with pytest.raises(ValueError, match="layout version"): + read_layout(out) + + +def test_compensated_registration_is_reproduced( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A registration that undid the online correction is reproduced. + + The file holds the lines' offsets and the frames' own, and frames formed + from it, every sample moved by its line's offset, are registration's. + """ + from giant_python.pipeline.register import register_multiroi + + layout = make_layout(tmp_path / "comp_DMD1-TRIAL000001.dat", 500) + x, _, y_dmd = online_offsets(layout.total_lines) + write_recording(layout, seed=6, online=(x, _, y_dmd)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = _table(tmp_path, Path(layout.files[0]), last=2000.0) + register_multiroi( + table, + {"maxshift": 5, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + res = export_layouts(table, tmp_path / "out") + assert [r["error"] for r in res] == [None] + lay = read_layout(tmp_path / "out" / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + assert at["compensated"] and at["layout_version"] == 4 + assert list(at["y_lead"]) == [2, 6] + p, c0, n = at["lines_per_cycle"], at["cycle0"], at["n_cycles"] + # the offsets of the lines of the file's cycles: x as the header has + # it, y as it was on the DMD + lines = slice(c0 * p, (c0 + n) * p) + assert lay["lines/x"].shape == (n * p,) + np.testing.assert_array_equal(lay["lines/x"], x[lines]) + np.testing.assert_array_equal(lay["lines/y_eff"], y_dmd[lines]) + assert np.unique(lay["lines/x"]).size > 1 + assert np.unique(lay["lines/y_eff"]).size > 1 + ref = lay["frames/ref_xy"] + assert ref.shape == (lay["frames/lines"].size, 2) + assert np.unique(ref, axis=0).shape[0] > 1 + # the slots' raster positions; a slot whose own pixel is among the + # pixels that frames report points at it + w = at["window_cols"] + slot_flat = lay["slots/row"].astype(np.int64) * w + lay["slots/col"] + pix_flat = lay["pixels/row"].astype(np.int64) * w + lay["pixels/col"] + listed = lay["slots/pixel"] >= 0 + np.testing.assert_array_equal(pix_flat[lay["slots/pixel"][listed]], slot_flat[listed]) + assert np.isin(slot_flat[listed], pix_flat).all() and listed.mean() > 0.9 + raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) + samples = raw[:, lay["slots/index"]] + movie = _movie(tmp_path / "motion_correction" / MOVIE, at["num_channels"]) + assert movie.shape[1] == lay["frames/lines"].size + # frames whose lines span an offset switch among them + changed = np.flatnonzero(np.any(np.diff(ref, axis=0) != 0, axis=1)) + frames = np.unique(np.r_[0, 1, changed[:6], changed[:6] + 1, movie.shape[1] - 1]) + got = reference_frames(lay, samples, frames) + want = movie[:, frames] + assert np.array_equal(np.isnan(got), np.isnan(want)) + assert np.isfinite(want).mean() > 0.2 + np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) + # without the offsets the frames are others: the samples are moved + plain = dict(lay, attrs=dict(at, compensated=False)) + off = reference_frames(plain, samples, frames) + both = np.isfinite(off) & np.isfinite(want) + assert np.abs(off - want)[both].max() > 1.0 + + +def test_version_3_files_are_read(patched: Registered, tmp_path: Path) -> None: + """A file of version 3 is read with its slots' positions. + + Version 3 has no slot positions (registrations without online + compensation); such a file gives the same frames. + """ + layout, table, root = patched + export_layouts(table, tmp_path) + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + new = read_layout(out) + assert new["attrs"]["layout_version"] == 4 + assert not new["attrs"]["compensated"] and "lines/x" not in new + np.testing.assert_array_equal(new["slots/row"], new["pixels/row"][new["slots/pixel"]]) + with h5py.File(out, "r+") as f: + f.attrs["layout_version"] = 3 + del f["slots/row"], f["slots/col"] + old = read_layout(out) + assert old["attrs"]["layout_version"] == 3 + np.testing.assert_array_equal(old["slots/row"], new["slots/row"]) + np.testing.assert_array_equal(old["slots/col"], new["slots/col"]) + at = new["attrs"] + raw = read_raster_samples( + layout, + (at["cycle0"], at["cycle0"] + at["n_cycles"]), + mask_unlit=at["unlit_masked"], + ) + samples = raw[:, new["slots/index"]] + np.testing.assert_array_equal( + reference_frames(old, samples, [3, 20]), + reference_frames(new, samples, [3, 20]), + ) + + +def _shared_pulses( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + p_split: float = 0.35, + k: float = 5.0, + theta: float = 22.0, +) -> np.ndarray: + """Compound-Poisson samples (slots, cycles) with pulses shared with the next slot. + + The pulses (gamma heights) are split with the next slot on the line with + probability p_split, by a uniform fraction. + + Returns + ------- + np.ndarray + Rounded samples of shape (slots, cycles). + """ + n_slots, n_cycles = rate.shape + out = np.zeros((n_slots, n_cycles)) + counts = rng.poisson(rate) + s, c = np.nonzero(counts) + s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) + height = rng.gamma(k, theta, s.size) + split = (rng.random(s.size) < p_split) & (nxt[s] >= 0) + frac = np.where(split, rng.random(s.size), 1.0) + np.add.at(out, (s, c), height * frac) + np.add.at(out, (nxt[s[split]], c[split]), height[split] * (1 - frac[split])) + return np.round(out) + + +def test_pulse_statistics_recover_the_pulses() -> None: + """Heights, split probability and split fractions of simulated shared pulses. + + Measured on the dim pairs only. + """ + rng = np.random.default_rng(0) + n_lines, per_line, n_cycles = 40, 30, 4000 + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + nxt = next_slots(slot_line, slot_pos) + # dim lines and bright lines; only the dim ones should be used + level = np.where(slot_line <= 30, 0.01, 1.5) + rate = np.repeat(level[:, None], n_cycles, 1) + x = _shared_pulses(rate, nxt, rng) + x[5, :50] = INVALID_SAMPLE + samples = torch.from_numpy(x.astype(np.int16))[None] + out = pulse_statistics(samples, nxt) + single, split = out["height_single"][0], out["height_split"][0] + assert out["pairs"][0] == 30 * (per_line - 2) + n1, n2 = single.sum(), split.sum() + assert n1 + n2 > 6_000 + # only the pulses of each pair's first slot are counted, and 0.35 of + # them are split into the pair + assert abs(n2 / (n1 + n2) - 0.35) < 0.02 + heights = np.arange(1, HEIGHT_BINS + 1) + mean_height = ((single + split) * heights).sum() / (n1 + n2) + assert abs(mean_height - 5.0 * 22.0) < 3.0 + frac = out["split_fraction"][0] + assert frac.sum() == n2 + joint = out["split_joint"][0] + assert joint.shape == (f0_layout.JOINT_BINS, SPLIT_BINS) + assert np.array_equal(joint.sum(0), frac) + width = HEIGHT_BINS // f0_layout.JOINT_BINS + assert np.array_equal(joint.sum(1), split.reshape(-1, width).sum(1)) + assert np.abs(frac / n2 - 1 / SPLIT_BINS).max() < 0.02 + # isolated pair-cycles: both slots valid, their neighbours zero + assert 0.9 < out["pair_cycles"][0] / (out["pairs"][0] * n_cycles) < 1.0 + stats = slot_statistics(samples) + assert abs(stats["valid_share"][0, 5] - (1 - 50 / n_cycles)) < 1e-6 + assert abs(np.nanmean(stats["mean"][0, slot_line <= 30]) - 1.1) < 0.1 + + +def test_pairs_next_to_unseen_samples_are_left_out() -> None: + """A line with a sample that is not a raster slot. + + A pulse split with it would be counted truncated, so the pair before the + gap is not used; a pair needs a slot before it, so none starts a run + either. + """ + rng = np.random.default_rng(2) + # one line of eight samples; the one at position 4 is not a raster slot + slot_line = np.ones(7, dtype=np.int64) + slot_pos = np.array([0, 1, 2, 3, 5, 6, 7]) + nxt = next_slots(slot_line, slot_pos) + assert list(nxt) == [1, 2, 3, -1, 5, 6, -1] + x = (rng.random((7, 2000)) < 0.02) * 100 + samples = torch.from_numpy(x.astype(np.int16))[None] + # without line ends, a slot without a next ends its run: pairs (1, 2), + # (2, 3) and (5, 6); (0, 1) and (4, 5) start a run + naive = pulse_statistics(samples, nxt) + assert naive["pairs"][0] == 3 + out = pulse_statistics(samples, nxt, slot_pos == 7) + # the sample after 3 is unseen: (2, 3) goes + assert out["pairs"][0] == 2 + alone = (x[0] == 0) & (x[3] == 0) + one = (x[1] > 0) & (x[2] == 0) + both = (x[1] > 0) & (x[2] > 0) + alone2 = x[4] == 0 # the pair (5, 6): slot 4 before it, nothing after it + one2 = (x[5] > 0) & (x[6] == 0) + both2 = (x[5] > 0) & (x[6] > 0) + assert out["pair_cycles"][0] == alone.sum() + alone2.sum() + assert out["height_single"][0].sum() == (one & alone).sum() + (one2 & alone2).sum() + assert out["height_split"][0].sum() == (both & alone).sum() + (both2 & alone2).sum() + + +def test_run_starts_are_not_measured() -> None: + """The sample before a run is not recorded but passes parts of its pulses on. + + Counted on the run's first slot they would look like small unsplit + pulses. + """ + rng = np.random.default_rng(6) + n_cycles = 6000 + # the recorded run is the last six samples of a line of eight + slot_line = np.ones(8, dtype=np.int64) + slot_pos = np.arange(8) + full = next_slots(slot_line, slot_pos) + x = _shared_pulses(np.full((8, n_cycles), 0.01), full, rng, p_split=0.5) + seen = x[2:] # slots 0 and 1 are not recorded + nxt = np.array([1, 2, 3, 4, 5, -1]) + out = pulse_statistics(torch.from_numpy(seen.astype(np.int16))[None], nxt) + assert out["pairs"][0] == 4 # the pair starting the run is not used + low = out["height_single"][0][:25].sum() / out["height_single"][0].sum() + assert low < 0.02 # the simulated pulses are rarely below 25 + # the run's first slot alone: many small "pulses" + first = seen[0][(seen[0] > 0) & (seen[1] == 0)] + assert (first < 25).mean() > 5 * max(low, 0.01) + + +def test_layout_file_marks_line_ends(patched: Registered, tmp_path: Path) -> None: + """slots/next links consecutive samples of neighbouring pixels. + + slots/line_end marks the slots that nothing follows which could share + a pulse: a line's last sample, or one before a jump. + """ + from giant_python.export.f0_layout import LAYOUT_VERSION, sharing_slots + + layout, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + assert lay["attrs"]["layout_version"] == LAYOUT_VERSION + idx = lay["slots/index"] + consecutive = next_slots(layout.slot_line, layout.slot_pos) + nxt, start, end = sharing_slots(layout) + row = (layout.slot_pixel - 1) // layout.n_cols + col = (layout.slot_pixel - 1) % layout.n_cols + to = np.maximum(consecutive, 0) + near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) + assert np.array_equal(nxt >= 0, (consecutive >= 0) & near) + assert np.array_equal(nxt[nxt >= 0], consecutive[nxt >= 0]) + last = layout.slot_pos == layout.n_per_channel[layout.slot_line - 1] - 1 + assert np.array_equal(end, last | ((consecutive >= 0) & ~near)) + # a slot starts a run when it starts its line or follows a jump + follows_jump = np.zeros(nxt.size, bool) + follows_jump[consecutive[(consecutive >= 0) & ~near]] = True + assert np.array_equal(start, (layout.slot_pos == 0) | follows_jump) + # the synthetic lines hold raster slots only: every slot is in the file + assert np.array_equal(lay["slots/line_end"].astype(bool), end[idx]) + assert np.array_equal(lay["slots/next"] < 0, end[idx]) + + +def test_pulses_are_not_measured_across_jumps() -> None: + """A pair whose samples are not neighbouring pixels shares no pulse. + + It is not a pair; the slots on either side of the jump are measured as the + ends of their runs. + """ + rng = np.random.default_rng(4) + n_cycles = 4000 + # one line of 8 samples: pixels 0-3 of a row, then a jump to 20-23 + slot_line = np.ones(8, dtype=np.int64) + slot_pos = np.arange(8) + cols = np.array([0, 1, 2, 3, 20, 21, 22, 23]) + + class Layout: + """One line of 8 samples: pixels 0-3 of a row, then a jump to 20-23.""" + + n_cols = 50 + slot_pixel = 5 * 50 + cols + 1 + n_per_channel = np.array([8]) + + Layout.slot_line, Layout.slot_pos = slot_line, slot_pos + from giant_python.export.f0_layout import sharing_slots + + nxt, start, end = sharing_slots(Layout) + assert list(nxt) == [1, 2, 3, -1, 5, 6, 7, -1] + assert list(start) == [ + True, + False, + False, + False, + True, + False, + False, + False, + ] + assert list(end) == [False, False, False, True, False, False, False, True] + # pulses split with probability 0.4 inside each run, none across the jump + x = _shared_pulses(np.full((8, n_cycles), 0.01), nxt, rng, p_split=0.4) + samples = torch.from_numpy(x.astype(np.int16))[None] + out = pulse_statistics(samples, nxt, end) + assert out["pairs"][0] == 4 # two per run: none starts a run + n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() + assert abs(n2 / (n1 + n2) - 0.4) < 0.07 + # counting the jump as a pair adds a slot whose pulses are never split + naive = pulse_statistics(samples, next_slots(slot_line, slot_pos)) + assert naive["pairs"][0] == 6 + m1, m2 = naive["height_single"][0].sum(), naive["height_split"][0].sum() + assert m2 / (m1 + m2) < n2 / (n1 + n2) + + +def test_pulse_statistics_without_dim_pairs() -> None: + """Bright pairs, in which pulses coincide, are never used. + + A recording without dim pairs gets empty histograms. + """ + rng = np.random.default_rng(1) + slot_line = np.repeat(np.arange(1, 21), 20) + slot_pos = np.tile(np.arange(20), 20) + nxt = next_slots(slot_line, slot_pos) + # no sharing at all: any split pulse would be a coincidence + x = _shared_pulses(np.full((400, 500), 0.8), nxt, rng, p_split=0.0) + out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + assert out["pairs"][0] == 0 and out["pair_cycles"][0] == 0 + for key in ("height_single", "height_split", "split_fraction"): + assert out[key].sum() == 0 + # dim pairs without sharing: almost no pulse is counted as split + x = _shared_pulses(np.full((400, 4000), 0.005), nxt, rng, p_split=0.0) + out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() + assert out["pairs"][0] == 360 and n1 > 5000 and n2 / (n1 + n2) < 0.01 + rate = (n1 + n2) / out["pair_cycles"][0] + assert abs(n2 / (n1 + n2) - rate) < 0.004 # the coincidences + none = pulse_statistics(torch.zeros((1, 3, 10), dtype=torch.int16), np.full(3, -1)) + assert none["pairs"][0] == 0 and none["height_single"].sum() == 0 + + +def _bursts( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + lengths: tuple[float, ...] = (0.5, 0.35, 0.12, 0.03), +) -> np.ndarray: + """Draw samples (slots, cycles) of events that occupy 1-4 consecutive slots. + + The lengths have the given probabilities, every part 40 + 10 x its place + in the burst (so that a part tells where in its burst it is). + + Returns + ------- + np.ndarray + Samples of shape (slots, cycles). + """ + n_slots, n_cycles = rate.shape + out = np.zeros((n_slots, n_cycles)) + counts = rng.poisson(rate) + s, c = np.nonzero(counts) + s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) + length = rng.choice(4, s.size, p=lengths) + 1 + slot = s.copy() + for k in range(4): + on = (length > k) & (slot >= 0) + np.add.at(out, (slot[on], c[on]), 40 + 10 * k) + slot = np.where(slot >= 0, nxt[np.maximum(slot, 0)], -1) + return out + + +def test_burst_cells() -> None: + """The type of a burst. + + Its length, total and, for two samples, the smaller part's share. + """ + from giant_python.export.f0_layout import N_CELLS, burst_cells + + assert N_CELLS == 162 + one = burst_cells(np.array([[35], [100], [405], [9000]])) + assert one.tolist() == [3, 10, 40, 40] + two = burst_cells(np.array([[10, 90], [90, 10], [50, 50], [300, 400]])) + assert two.tolist() == [41 + 15, 41 + 15, 41 + 17, 41 + 30 * 3 + 2] + assert burst_cells(np.array([[100, 100, 100]])).tolist() == [134 + 6] + assert burst_cells(np.array([[250, 250, 250, 250]])).tolist() == [161] + assert burst_cells(np.zeros((0, 2))).shape == (0,) + + +def test_burst_library_and_counts_by_stratum(patched: Registered, tmp_path: Path) -> None: + """The library's counts are the events' length distribution. + + Its examples are whole events, part by part; the counts by stratum tell + events whose rate follows brightness from events at a constant rate; the + file holds both. + """ + from giant_python.export.f0_layout import ( + BURST_EXAMPLES, + N_CELLS, + STRATA_EDGES, + burst_cells, + burst_statistics, + ) + + rng = np.random.default_rng(3) + n_lines, per_line, n_cycles = 16, 40, 6000 + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + nxt = next_slots(slot_line, slot_pos) + # lines of four brightnesses (events per sample) and four bright lines + levels = np.array([0.006, 0.016, 0.033, 0.066, 1.0]) + level = levels[np.minimum((slot_line - 1) // 3, 4)] + x = _bursts(np.repeat(level[:, None], n_cycles, 1), nxt, rng) + # events at one rate everywhere: one sample of 60 + extra = rng.random(x.shape) < 0.002 + x = x + 60 * extra + x[7, :100] = INVALID_SAMPLE + out = burst_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + counts = out["burst_counts"][0] + assert counts[:4].sum() > 5000 + assert counts[4] < 0.01 * counts[:4].sum() + for n in range(1, 5): + kept = out["burst_examples"][0, n - 1] + assert kept == min(BURST_EXAMPLES, counts[n - 1]) + parts = out[f"burst_{n}"][0, :kept] + assert parts.shape[1] == n and (parts > 0).all() + # almost all are one event: part k is 40 + 10 k, or the one of 60 + clean = (parts == 40 + 10 * np.arange(n)).all(1) + if n == 1: + clean |= parts[:, 0] == 60 + # (a long burst is more often two events that touch) + assert clean.mean() > (0.9 if n < 3 else 0.7) + assert (out[f"burst_{n}"][0, kept:] == 0).all() + cells = out[f"burst_cell_{n}"][0, :kept] + np.testing.assert_array_equal(cells, burst_cells(parts)) + # strata: the mean sample rises, the bright lines are not counted + free, mean = out["strata_free"][0], out["strata_mean"][0] + assert out["strata_edges"].tolist() == list(STRATA_EDGES) + assert out["strata_bursts"].shape == (1, len(STRATA_EDGES) - 1, N_CELLS) + used = free > 2e5 + assert used.sum() >= 4 and (np.diff(mean[used]) > 0).all() + assert mean[used].max() < 8 and free.sum() <= 12 * 35 * n_cycles + rate = out["strata_bursts"][0][used] / free[used][:, None] + # one-sample events of 40 follow the mean; those of 60 do not + photon = rate[:, 4] / mean[used] + assert photon.max() < 1.2 * photon.min() + np.testing.assert_allclose(rate[:, 6], 0.002, rtol=0.2) + assert out["strata_longer"][0].sum() < 0.02 * out["strata_bursts"].sum() + # nothing without dim chains + bright = burst_statistics( + torch.from_numpy(x[slot_line > 12].astype(np.int16))[None], + next_slots(slot_line[slot_line > 12], slot_pos[slot_line > 12]), + ) + assert bright["strata_free"].sum() == 0 + assert bright["burst_counts"].sum() == 0 + # the layout file carries the library and the tables + _, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + assert lay["photon/burst_counts"].shape == (2, 5) + assert lay["photon/burst_3"].shape == (2, BURST_EXAMPLES, 3) + assert lay["photon/burst_cell_2"].shape == (2, BURST_EXAMPLES) + assert lay["photon/strata_bursts"].shape == (2, 8, N_CELLS) + assert lay["photon/level_moments"].shape == (2, 18, 9) + assert lay["photon/level_revisits"] in (0, 1) + assert lay["attrs"]["burst_level"] == 2.0 + + +def _level_case( + rng: np.random.Generator, visits: int, n_cycles: int = 3000 +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Simulate a raster whose pixels are sampled visits times per cycle. + + It has lines of two brightnesses that change together from cycle to cycle; + also returns the moments its events have per unit of mean. + + Returns + ------- + x : np.ndarray + Simulated samples of shape (slots, cycles). + nxt : np.ndarray + Index of the next slot on the line for each slot. + pixel : np.ndarray + Pixel index of each slot. + slot_line : np.ndarray + Line number of each slot. + moments : np.ndarray + The moments the events have per unit of mean. + """ + per_line, n_pairs = 60, 24 + n_lines = n_pairs * visits + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + pair = (slot_line - 1) // visits + pixel = pair * per_line + slot_pos + nxt = next_slots(slot_line, slot_pos) + rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] + if visits > 1: # brightness that changes slowly: both visits see it + wave = 1 + 0.6 * np.sin(np.arange(n_cycles) / 40.0) + rate = rate * wave[None, :] + else: + rate = np.repeat(rate, n_cycles, 1) + x = _bursts(rate, nxt, rng) + lengths = np.array([0.5, 0.35, 0.12, 0.03]) + parts = 40.0 + 10 * np.arange(4) + total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) + want = np.zeros(9) + for k in range(4): + want[k] = sum( + lengths[n] * (parts[: n + 1 - k] * parts[k : n + 1]).sum() for n in range(k, 4) + ) + return x, nxt, pixel, slot_line, want / total + + +@pytest.mark.parametrize("visits", [2, 1]) +def test_level_statistics_measure_the_events(visits: int) -> None: + """The moments by level are those of the events, per unit of mean. + + At every brightness, also where the brightness changes between cycles (two + visits per cycle) and for a raster without second visits. + """ + from giant_python.export.f0_layout import LEVEL_EDGES, level_statistics + + rng = np.random.default_rng(5 + visits) + x, nxt, pixel, line, want = _level_case(rng, visits) + x[3, :50] = INVALID_SAMPLE + out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, line) + assert out["level_revisits"] == (1 if visits > 1 else 0) + assert out["level_edges"].tolist() == list(LEVEL_EDGES) + n = out["level_samples"][0] + full = np.flatnonzero(n > 2e5) + assert full.size >= 2 + mean = out["level_mean"][0][full] + assert mean.min() < 8 and mean.max() > 20 + per_mean = out["level_moments"][0][full] / mean[:, None] + np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) + np.testing.assert_allclose(per_mean[:, 2], want[2], rtol=0.15) + assert np.abs(per_mean[:, 4:]).max() < 0.03 * want[0] + # zeros: no event covers the sample + cover = 0.5 + 0.35 * 2 + 0.12 * 3 + 0.03 * 4 + total = 0.5 * 40 + 0.35 * 90 + 0.12 * 150 + 0.03 * 220 + dim = full[np.argmin(mean)] + zero = np.exp(-out["level_mean"][0][dim] / total * cover) + assert abs(out["level_zero"][0][dim] - zero) < 0.03 + if visits > 1: # against the next cycle, the changing brightness counts + naive = x.astype(np.float64).var(1).sum() / x.sum() * x.shape[1] + assert naive > 1.15 * want[0] + empty = level_statistics( + torch.zeros((1, 4, 10), dtype=torch.int16), + np.full(4, -1), + np.arange(4), + np.ones(4, dtype=np.int64), + ) + assert empty["level_samples"].sum() == 0 + + +def test_level_statistics_second_observation_is_on_a_later_line() -> None: + """A line that samples its pixels twice in a row. + + The second sample of a pixel on the same line can share pulses with the + first, so it is not taken as the second observation; the next line's is. + """ + from giant_python.export.f0_layout import _second_visits, level_statistics + + rng = np.random.default_rng(13) + n_lines, half, n_cycles = 48, 30, 3000 + slot_line = np.repeat(np.arange(1, n_lines + 1), 2 * half) + slot_pos = np.tile(np.arange(2 * half), n_lines) + pair = (slot_line - 1) // 2 # two lines sample the same pixels + pixel = pair * half + slot_pos % half + nxt = next_slots(slot_line, slot_pos) + chain, other = _second_visits(nxt, pixel, slot_line) + assert other is not None and chain[0].size > 1000 + assert (slot_line[other[0]] == slot_line[chain[0]] + 1).all() + assert (pixel[other[0]] == pixel[chain[0]]).all() + # the first of the later line's two samples, whichever copy asks + assert (slot_pos[other[0]] == slot_pos[chain[0]] % half).all() + # one line per pixel set: no second observation within the cycle + _, none = _second_visits(nxt, slot_line * half + slot_pos % half, slot_line) + assert none is None + rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] + x = _bursts(np.repeat(rate, n_cycles, 1), nxt, rng) + out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, slot_line) + lengths = np.array([0.5, 0.35, 0.12, 0.03]) + parts = 40.0 + 10 * np.arange(4) + total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) + var = sum(lengths[n] * (parts[: n + 1] ** 2).sum() for n in range(4)) + cov = sum(lengths[n] * (parts[:n] * parts[1 : n + 1]).sum() for n in range(1, 4)) + assert out["level_revisits"] == 1 + full = np.flatnonzero(out["level_samples"][0] > 2e5) + per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] + np.testing.assert_allclose(per_mean[:, 0], var / total, rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], cov / total, rtol=0.06) + + +def test_level_statistics_skip_the_visits_of_another_plane() -> None: + """Lines of another plane between a pixel's two visits are no visits. + + Those lines sample the same pixels; marked by a negative pixel, they do not + stand in as the next visit (which would leave no revisits and send the + measurement to the next cycle). + """ + from giant_python.export.f0_layout import _second_visits, level_statistics + + rng = np.random.default_rng(9) + x, nxt, pixel, line, want = _level_case(rng, 3) + # the middle line of each three is another plane: its slots link to + # nothing, as sharing_slots restricted to the plane leaves them + off = (line - 1) % 3 == 1 + nxt = np.where(off | off[np.maximum(nxt, 0)], -1, nxt) + _, other = _second_visits(nxt, pixel, line) + assert other is None # the other plane's visit is taken and fails + chain, other = _second_visits(nxt, np.where(off, -1, pixel), line) + assert other is not None and chain[0].size > 1000 + assert not off[chain[0]].any() and not off[other[0]].any() + assert (line[other[0]] - line[chain[0]] == 2).all() + out = level_statistics( + torch.from_numpy(x.astype(np.int16))[None], + nxt, + np.where(off, -1, pixel), + line, + ) + assert out["level_revisits"] == 1 + full = np.flatnonzero(out["level_samples"][0] > 2e5) + per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] + np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) diff --git a/tests/export/test_f0_training.py b/tests/export/test_f0_training.py index 587bc735..0db5ffc4 100644 --- a/tests/export/test_f0_training.py +++ b/tests/export/test_f0_training.py @@ -1,943 +1,976 @@ -"""F0 training-data export (giant export-f0) on a synthetic SILo run.""" - -import json -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.export import f0_qc -from giant_python.export.f0_training import ExportOptions, export_run - -from ..viewer.synthetic import BASELINE, CENTRES, N_TRIALS, write_session - -N80 = 600 - - -@pytest.fixture(scope="module", params=["rigid", "patchwise"]) -def session( - request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory -) -> dict[str, Any]: - """Build a synthetic session (rigid or patchwise maps) of 600 frames.""" - root = tmp_path_factory.mktemp(f"syn_{request.param}") - return write_session(root, request.param, n80=N80) - - -def _export( - syn: dict[str, Any], - out: Path, - **kw: Any, # noqa: ANN401 - forwarded to ExportOptions, whose fields differ in type -) -> dict: - """Export the synthetic run with the given options.""" - return export_run( - syn["run"], - out, - syn["run"] / "trial_table.h5", - syn["moco"], - syn["base"], - options=ExportOptions(**kw), - log=lambda line: None, - ) - - -def test_layout_matches_the_training_reader(session: dict[str, Any], tmp_path: Path) -> None: - """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile reads them. - - The reader is not a dependency: its contract is checked here. - """ - s = _export(session, tmp_path, kernel="exporter") - assert [q["trial"] for q in s["trials"]] == [1, 2] - for q in s["trials"]: - assert "error" not in q - with h5py.File(q["file"], "r") as f: - n_ch, T, R, C = f["movie"].shape - assert (n_ch, T) == (1, N80) and f["movie"].dtype == np.float32 - assert f["activity"].shape == f["movie"].shape - for m in ("valid", "labeled", "footprint_support"): - assert f[f"mask/{m}"].shape == (R, C) - assert f[f"mask/{m}"].dtype == np.uint8 - assert f["mean_image"].shape == (1, R, C) - assert f["varfac"].shape == (R, C) - for k in ("discard", "valid_mean", "rec_neg_err"): - assert f[f"frame/{k}"].shape == (T,) - assert f["sources/peak_row"].shape == (CENTRES.shape[0],) - for k in ( - "label", - "path", - "trial", - "peakR", - "nSources", - "alignHz", - "channels", - "activityChannel", - "activityGain", - "kernel", - "exporter", - ): - assert k in f.attrs - assert int(f.attrs["trial"]) == q["trial"] - # the stem of the trial's registration files, as the summary - stem = f.attrs["registrationStem"] - assert stem == q["registrationStem"] - assert stem.endswith(f"T{q['trial']}DMD{q['path']}") - assert f["movie"].chunks == (1, 256, min(64, R), min(64, C)) - name = Path(q["file"]) - assert (name.parent.name, name.name) == ( - "Path1", - f"trial_{q['trial']:03d}.h5", - ) - - -def test_target_is_the_baseline(session: dict[str, Any], tmp_path: Path) -> None: - """With the movie's own kernel and cubic placement the noiseless target is the baseline. - - The target (movie - activity) is the baseline to 2% of the activity's - peak; QC says the activity matches the movie. - """ - s = _export(session, tmp_path, kernel="exporter", interp="cubic") - for q in s["trials"]: - with h5py.File(q["file"], "r") as f: - m, a = f["movie"][0], f["activity"][0] - sup = f["mask/footprint_support"][()].astype(bool) - res = (m - a - BASELINE)[:, sup] - assert np.nanmax(np.abs(res)) < 0.02 * a.max() - assert q["peakR"] > 0.99 and q["diskR"] > 0.99 - assert q["diskSlope"] == pytest.approx(1.0, abs=0.01) - assert q["peakSlope"] == pytest.approx(1.0, abs=0.02) - assert abs(q["eventResidualFraction"]) < 0.02 - assert q["blurShapeRatio"] == pytest.approx(1.0, abs=0.02) - assert q["targetOverBaselineSupport"] == pytest.approx(1.0, abs=1e-3) - - -def test_linear_placement_blurs_the_peaks(session: dict[str, Any], tmp_path: Path) -> None: - """Bilinear placement keeps the flux but lowers the peak pixels (the viewer's rendering). - - Cubic placement keeps both. - """ - lin = _export(session, tmp_path / "lin", kernel="exporter") - cub = _export(session, tmp_path / "cub", kernel="exporter", interp="cubic") - for a, b in zip(lin["trials"], cub["trials"]): - assert a["diskSlope"] == pytest.approx(b["diskSlope"], abs=0.02) - assert a["blurShapeRatio"] > b["blurShapeRatio"] - assert a["eventResidualFraction"] > b["eventResidualFraction"] - - -def test_exact_kernel_is_sharper(session: dict[str, Any], tmp_path: Path) -> None: - """The exact kernel keeps the activity's total and sharpens its peaks. - - The peaks are compared against the MATLAB exporter's kernel. - """ - e = _export(session, tmp_path / "e", kernel="exporter", interp="cubic") - x = _export(session, tmp_path / "x", kernel="exact", interp="cubic") - for qe, qx in zip(e["trials"], x["trials"]): - assert qx["kernelR"] == pytest.approx((54 / 134) ** 2) - assert np.isnan(qe["kernelR"]) or qe["kernelR"] == 0 - with ( - h5py.File(qe["file"], "r") as fe, - h5py.File(qx["file"], "r") as fx, - ): - ae, ax = fe["activity"][0], fx["activity"][0] - assert ax.sum() == pytest.approx(ae.sum(), rel=0.02) - assert ax.max() > ae.max() - - -def test_summary_and_skipped_trial(tmp_path: Path) -> None: - """export_summary.json holds every trial (NaN as null). - - A trial without an across-trial map is reported, not written. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - _export(syn, out) # a first export writes both trials - assert (out / "Path1" / "trial_002.h5").exists() - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - a = f["Path1/frame_info/trial_alignment_affine"][()] - a[..., 1] = np.nan # MATLAB orientation: trials last - f["Path1/frame_info/trial_alignment_affine"][...] = a - s = _export(syn, out) - by_trial = {q["trial"]: q for q in s["trials"]} - assert "error" not in by_trial[1] - assert "map" in by_trial[2]["error"] - assert "removed" in by_trial[2]["error"] # no stale file is left - assert not (out / "Path1" / "trial_002.h5").exists() - text = (out / "export_summary.json").read_text() - assert "NaN" not in text - j = json.loads(text) - assert len(j["trials"]) == N_TRIALS and j["options"]["kernel"] == "exact" - - -def test_default_export_reconciles_trial_files(tmp_path: Path) -> None: - """A default export removes earlier trial files it does not write and lists them. - - An export with chosen trials leaves other files alone. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - folder = out / "Path1" - folder.mkdir(parents=True) - for name in ("trial_009.h5", "trial_1000.h5", "notes.txt"): - (folder / name).write_bytes(b"old") - s = _export(syn, out, trials=(1,)) - assert "removed" not in s - assert (folder / "trial_009.h5").exists() - s = _export(syn, out) - assert s["removed"] == {"Path1": ["trial_009.h5", "trial_1000.h5"]} - assert sorted(f.name for f in folder.iterdir()) == [ - "notes.txt", - "trial_001.h5", - "trial_002.h5", - ] - j = json.loads((out / "export_summary.json").read_text()) - assert j["removed"] == s["removed"] - - -def test_repeated_selectors_export_once(tmp_path: Path) -> None: - """Repeated paths and trials give one job each. - - Two workers never write the same file. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", paths=(1, 1), trials=(2, 2, 1), workers=2) - assert [(q["path"], q["trial"]) for q in s["trials"]] == [(1, 1), (1, 2)] - assert all("error" not in q for q in s["trials"]) - - -@pytest.mark.parametrize( - "kw", - [ - {"trials": (0,)}, - {"trials": (-1,)}, - {"trials": (N_TRIALS + 1,)}, - {"paths": (2,)}, - ], -) -def test_selectors_outside_the_run_are_refused( - tmp_path: Path, kw: dict[str, tuple[int, ...]] -) -> None: - """Trials outside 1..the table's trials and paths the run does not have are refused. - - They are refused before any job starts; the CLI reports a usage error. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="trials|paths"): - _export(syn, tmp_path / "out", **kw) - assert not (tmp_path / "out" / "Path1").exists() - flag, values = next(iter(kw.items())) - with pytest.raises(SystemExit) as e: - main([ - "export-f0", - str(syn["run"]), - str(tmp_path / "o2"), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - f"--{flag}", - *[str(v) for v in values], - ]) - assert e.value.code == 2 - - -@pytest.fixture(scope="module") -def exported(tmp_path_factory: pytest.TempPathFactory) -> tuple[dict[str, Any], Path]: - """Export a synthetic session once (default options).""" - root = tmp_path_factory.mktemp("bad_options") - syn = write_session(root / "syn", "rigid", n80=200) - _export(syn, root / "out") - return syn, root / "out" - - -@pytest.mark.parametrize( - "kw, cli", - [ - ({"deflate": 10}, ["--deflate", "10"]), - ({"deflate": -1}, ["--deflate", "-1"]), - ({"blur": -1.0}, ["--blur", "-1"]), - ({"blur": float("nan")}, ["--blur", "nan"]), - ({"blur": float("inf")}, ["--blur", "inf"]), - ({"var_fac": "median"}, None), - ({"kernel": "box"}, None), - ({"interp": "nearest"}, None), - ], -) -def test_invalid_options_keep_earlier_files( - exported: tuple[dict[str, Any], Path], kw: dict[str, Any], cli: list[str] | None -) -> None: - """An option every trial would fail on is refused before any trial. - - So a rerun with it leaves the earlier export in place; the CLI reports a - usage error. - """ - syn, out = exported - files = sorted((out / "Path1").glob("trial_*.h5")) - assert len(files) == N_TRIALS - stamps = [f.stat().st_mtime_ns for f in files] - with pytest.raises(ValueError): - _export(syn, out, **kw) - assert [f.stat().st_mtime_ns for f in files] == stamps - if cli is None: # argparse's choices refuse these - return - with pytest.raises(SystemExit) as e: - main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - *cli, - ]) - assert e.value.code == 2 - assert [f.stat().st_mtime_ns for f in files] == stamps - - -def test_ignore_sources(tmp_path: Path) -> None: - """Without sources: zero activity, no sources group, no QC.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", ignore_sources=True) - for q in s["trials"]: - assert q["nSources"] == 0 and np.isnan(q["peakR"]) - with h5py.File(q["file"], "r") as f: - assert not f["activity"][()].any() - assert "sources" not in f - assert not f["mask/footprint_support"][()].any() - - -def test_cli(tmp_path: Path) -> None: - """Giant export-f0 writes the trials and returns 0.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - rc = main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--kernel", - "matched", - "--interp", - "cubic", - "--label", - "syn", - ]) - assert rc == 0 - with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: - assert f.attrs["label"] == "syn" and f.attrs["kernel"] == "matched" - - -def test_movmedian_omitnan() -> None: - """The running median ignores NaN and shrinks at the ends.""" - rng = np.random.default_rng(0) - x = rng.normal(size=(3, 300)) - x[0, 50:60] = np.nan - x[2, :] = np.nan - m = f0_qc.movmedian_omitnan(x, 81) - for i in range(2): - for t in (0, 10, 55, 150, 299): - w = x[i, max(0, t - 40) : t + 41] - assert m[i, t] == pytest.approx(np.median(w[~np.isnan(w)])) - assert np.isnan(m[2]).all() - - -def test_event_residual_and_peaks() -> None: - """The event-triggered residual is 0 when the activity is the movie's signal. - - It is 1 when no activity is removed. - """ - from scipy import sparse - - T = 400 - x = np.zeros((1, T)) - for e in (50, 150, 250, 350): - x[0, e : e + 20] += 10 * np.exp(-np.arange(20) / 4.0) - H = sparse.csr_matrix(np.array([[0.2], [0.5], [0.3]])) - Y = (np.asarray(H @ x).T + 5.0).astype(np.float64) - pk = f0_qc.peak_pixels(H) - assert pk.tolist() == [1] - frac, n = f0_qc.event_residual(H, x, Y, pk) - assert n > 0 and abs(frac) < 1e-9 - frac0, _ = f0_qc.event_residual(H, x, Y + np.asarray(H @ x).T, pk) - assert frac0 == pytest.approx(0.5) # half of the doubled movie left - sl, r = f0_qc.peak_fit(H, x, Y, pk) - assert sl[0] == pytest.approx(1.0) and r[0] == pytest.approx(1.0) - - -def _two_channels(syn: dict[str, Any]) -> None: - """Rewrite the synthetic movies with a second channel. - - The second channel is 2 x the first + 5, interleaved by frame; also set - ``numChannels`` 2. - """ - for mf in sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")): - with h5py.File(mf, "r+") as f: - a = f["mov"][()] # (pages, cols, rows) - del f["mov"] - st = np.empty((2 * a.shape[0],) + a.shape[1:], a.dtype) - st[0::2], st[1::2] = a, 2 * a + 5 - f["mov"] = st - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - f["params/numChannels"][...] = 2 - - -def test_written_channels_and_mean_image(tmp_path: Path) -> None: - """The mean image follows the written channels, as movie and activity do. - - The reader indexes all three alike. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - _two_channels(syn) - s = _export(syn, tmp_path / "c2", channels=(2,)) - with h5py.File(s["trials"][0]["file"], "r") as f: - m, mi = f["movie"][()], f["mean_image"][()] - valid = f["mask/valid"][()].astype(bool) - assert m.shape[0] == 1 and mi.shape[0] == 1 - np.testing.assert_allclose(mi[0][valid], np.nanmean(m[0], 0)[valid], rtol=1e-4) - assert int(f.attrs["activityChannel"]) == 1 - s = _export(syn, tmp_path / "c21", channels=(2, 1)) - with h5py.File(s["trials"][0]["file"], "r") as f: - mi = f["mean_image"][()] - np.testing.assert_allclose(mi[0], 2 * mi[1] + 5, rtol=1e-4) - - -def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path: Path) -> None: - """The mean image leaves out the discarded frames and is NaN outside the valid pixels. - - This is as slap2-f0 computes it at inference. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - alf = sorted(syn["moco"].glob("*_ALIGNMENTDATA.h5"))[0] - with h5py.File(alf, "r+") as f: - rne = f["recNegErr"][()] - rne[100:110] = 1.0 # a motion spike: those frames are discarded - f["recNegErr"][...] = rne - stem = alf.name.replace("_ALIGNMENTDATA.h5", "") - mf = syn["moco"] / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" - with h5py.File(mf, "r+") as f: - key = next(iter(f.keys())) - a = f[key][()] # (frames, cols, rows), one channel - a[100:110] += 1000.0 # what a mean over every frame would show - col = a.shape[1] // 2 - a[:150, col, :] = np.nan # a column imaged in a quarter of the frames - f[key][...] = a - s = _export(syn, tmp_path / "out", trials=(1,)) - q = s["trials"][0] - assert "error" not in q - with h5py.File(q["file"], "r") as f: - disc = f["frame/discard"][()].astype(bool) - m, mi = f["movie"][0], f["mean_image"][0] - valid = f["mask/valid"][()].astype(bool) - c0 = int(np.ravel(f.attrs["cropOriginRC"])[1]) - assert disc[100:110].all() - np.testing.assert_allclose(mi[valid], np.nanmean(m, 0)[valid], rtol=1e-4) - assert np.nanmax(mi) < 500 # the bright discarded frames are not in it - assert not valid[:, col - c0].any() and np.isnan(mi[:, col - c0]).all() - - -def test_sources_without_traces_are_refused(tmp_path: Path) -> None: - """Sources without dF_denoised traces would give zero activity. - - The target would keep every event, so the trials are reported, not - written. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["Path1/sources/temporal/dF_denoised"] - s = _export(syn, tmp_path / "out") - for q in s["trials"]: - assert "dF_denoised" in q["error"] - assert not list((tmp_path / "out" / "Path1").glob("trial_*.h5")) - - -@pytest.mark.parametrize("channels", [(0,), (3,), (1, 2)]) -def test_channels_outside_the_movie_are_refused(tmp_path: Path, channels: tuple[int, ...]) -> None: - """Channels are one-based and within numChannels (1 here).""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="channels"): - _export(syn, tmp_path / "out", channels=channels) - with pytest.raises(SystemExit) as e: # the CLI reports it as a usage error - main([ - "export-f0", - str(syn["run"]), - str(tmp_path / "o2"), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--channels", - *[str(c) for c in channels], - ]) - assert e.value.code == 2 - - -# ------------------------------------------------- activity mask, events - - -def _noisy_traces(syn: dict[str, Any], sd: float = 2.0) -> None: - """Give the synthetic run noisy dF_ls (noise SD ``sd`` around dF_denoised). - - Also give it an events trace at the denoised trace's jumps. - """ - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - den = g["dF_denoised"][()] # (frames, channels, sources) - rng = np.random.default_rng(5) - g["dF_ls"][...] = den + rng.normal(0, sd, den.shape) - jump = np.diff(den, axis=0, prepend=den[:1]) - g["events"][...] = np.where(jump > 5, jump, 0.0) - - -def _plan_file( - syn: dict[str, Any], unused: tuple[tuple[float, float], ...] = ((8.0, 40.0),) -) -> None: - """Write a minimal SILo plan file for path 1. - - It holds the sources' seeds plus ``unused`` seeds without a source (as - giant silo keeps it in source_extraction/silo/plan). - """ - plan = syn["run"] / "source_extraction" / "silo" / "plan" / "path1.h5" - plan.parent.mkdir(parents=True, exist_ok=True) - rc = np.vstack([CENTRES, np.asarray(unused, float)]) - seeds = np.column_stack([np.ones(len(rc)), rc, np.ones(len(rc))]) - pix = np.floor(CENTRES + 0.5).astype(int) - with h5py.File(plan, "w") as f: - g = f.create_group("sources") - g["seeds"] = seeds - g["rows"] = pix[:, 0] - g["cols"] = pix[:, 1] - - -def test_temporal_mask_rule() -> None: - """A crossing masks its frames, the widening after it and the shared frames on both sides. - - Nothing else is masked. - """ - from giant_python.export.f0_mask import MaskRule, temporal_mask - - n200 = 500 - lines200 = np.arange(n200) * 54.0 - ds = np.arange(0, n200 * 54, 134.0) - den = np.zeros((n200, 2)) - den[200:210, 0] = 10.0 # above 2 x 1 for 10 frames - den[300:310, 1] = 1.5 # below the threshold - rule = MaskRule(k=2, margin_px=0, widen_tau=1, share_frames=6) - tm = temporal_mask(den, np.ones(2), lines200, np.zeros(n200, bool), ds, rule, 30) - assert not tm[1].any() - f = np.flatnonzero(tm[0]) - first = int(np.argmin(np.abs(ds - 200 * 54))) - 6 - last = int(np.argmin(np.abs(ds - (209 + 30) * 54))) + 6 - assert f.min() == first and f.max() == last and f.size == last - first + 1 - - -def test_mask_widening_uses_the_activity_channel_decay() -> None: - """The widening's decay constant is the activity channel's, not channel 2's ``tau2``. - - The activity channel's is SILo's ``tau_full``, else ``tau_s`` times the - frame rate. - """ - from types import SimpleNamespace - - from giant_python.export.f0_training import _mask_inputs - - class Run: - """A run with only the given params (as SiloRun.param reads them).""" - - def __init__(self, params: dict[str, object]) -> None: - """Keep the params.""" - self.params = params - - def param(self, name: str, default: object = None) -> object: - """Return a param, the default when missing or empty.""" - v = self.params.get(name, default) - return default if v is None or v == "" else v - - p = SimpleNamespace( - sources=SimpleNamespace(n=0, rejected_rc=np.zeros((0, 2)), unused_seeds=None) - ) - # tau_full overrides tau_s (6 frames, not 0.024 s x 200 Hz = 4.8) - both = { - "analyzeHz": 200.0, - "tau_s": 0.024, - "tau_full": 6.0, - "tau2_s": 0.15, - "tau2_samps": 30.0, - } - m = _mask_inputs(Run(both), p, {}, None) - assert m["tau200"] == 6.0 and m["tau_seconds"] == pytest.approx(0.03) - # tau_s in the run's frames; the recorded constant in seconds - no_full = {"analyzeHz": 100.0, "tau_s": 0.05, "tau2_s": 0.15} - m = _mask_inputs(Run(no_full), p, {}, None) - assert m["tau200"] == pytest.approx(5.0) - assert m["tau_seconds"] == pytest.approx(0.05) - m = _mask_inputs(Run({}), p, {}, None) - assert m["tau200"] == pytest.approx(4.8) - assert m["tau_seconds"] == pytest.approx(0.024) - - -def test_activity_mask_written(tmp_path: Path) -> None: - """mask/activity covers the sources' activity, never pixels far from a footprint. - - It also leaves quiet stretches; spots add to it; the rule and the masked - shares are recorded. - """ - from scipy import ndimage - - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - _plan_file(syn) - rule = MaskRule(k=2, margin_px=1, widen_tau=1, share_frames=6, spots="none") - s = _export(syn, tmp_path / "m", interp="cubic", activity_mask=rule) - s2 = _export( - syn, - tmp_path / "m2", - interp="cubic", - activity_mask=MaskRule(k=2, margin_px=1, spots="seeds"), - ) - for q, q2 in zip(s["trials"], s2["trials"]): - assert "error" not in q - assert 0 < q["activityMaskFractionSupport"] < 1 - assert q["activityMaskFraction"] < q["activityMaskFractionSupport"] - assert q2["activityMaskFraction"] >= q["activityMaskFraction"] - with h5py.File(q["file"], "r") as f: - am = f["mask/activity"][()].astype(bool) - a = f["activity"][0] - sup = f["mask/footprint_support"][()].astype(bool) - assert f["mask/activity"].dtype == np.uint8 - assert f.attrs["activityMaskK"] == 2.0 - assert f.attrs["activityMaskSpots"] == "none" - # SILo's tau_s default (24 ms) at 200 Hz: the activity channel's - assert f.attrs["activityMaskTauSeconds"] == pytest.approx(0.024) - with h5py.File(q2["file"], "r") as f: - assert f.attrs["activityMaskWidenTau"] == 2.0 # the default - assert am.shape == a.shape - big = a > 0.2 * a.max() - assert big.any() and am[big].all() # the events are masked - far = ~ndimage.binary_dilation(sup, iterations=3) - assert not am[:, far].any() # nothing beyond footprint + margin - act = a.reshape(a.shape[0], -1).max(1) > 0 - near = ndimage.binary_dilation(act, np.ones(41, bool)) - if (~near).any(): # quiet stretches stay in the loss - assert not am[~near][:, sup].any() - - -def test_mask_and_event_stats_off_by_default(tmp_path: Path) -> None: - """Without the options neither the mask nor the statistics file.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out") - with h5py.File(s["trials"][0]["file"], "r") as f: - assert "mask/activity" not in f - assert not (tmp_path / "out" / "event_statistics.json").exists() - - -def test_event_statistics(tmp_path: Path) -> None: - """event_statistics.json: events are crossings of k noise SDs. - - SILo's small noise events in its events trace do not count; the file - also holds rate, sizes and the synchrony against chance. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - den = np.zeros(g["dF_denoised"].shape) # (frames, channels, sources) - T = den.shape[0] - kern = np.exp(-np.arange(40) / 4.8) - starts = np.arange(30, T - 60, 100) # well apart: one event each - for a in starts: - den[a : a + 40, 0, :] += 40.0 * kern[: min(40, T - a)][:, None] - rng = np.random.default_rng(3) - g["dF_denoised"][...] = den - g["dF_ls"][...] = den + rng.normal(0, 2.0, den.shape) - tiny = np.zeros_like(den) - tiny[::7] = 0.5 # SILo's small events: not activity - g["events"][...] = tiny - _export(syn, tmp_path / "out", event_stats=True) - j = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) - p = j["paths"][0] - assert p["path"] == 1 and len(p["sources"]) == CENTRES.shape[0] - assert p["thresholdSD"] == 6.0 - for src in p["sources"]: - assert src["noise"] == pytest.approx(2.0, rel=0.15) - assert src["events"] == starts.size - assert src["ratePerMin"] == pytest.approx(starts.size / p["keptMinutes"]) - assert src["sizeRaw"]["q50"] == pytest.approx(40.0) - assert src["sizeDff"]["q50"] == pytest.approx(40.0 / 50) - assert src["ratesPerMin"]["3"] == pytest.approx(src["ratePerMin"]) - sy = p["synchrony"] - assert 0 <= sy["observed"] <= 1 and 0 <= sy["expected"] <= 1 - - -@pytest.mark.parametrize( - "bad", - [{"k": 0}, {"margin_px": -1}, {"share_frames": 1.5}, {"spots": "all"}], -) -def test_invalid_mask_rule_refused(tmp_path: Path, bad: dict[str, Any]) -> None: - """An invalid mask rule is refused before any trial.""" - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="mask"): - _export(syn, tmp_path / "out", activity_mask=MaskRule(**bad)) - - -def test_cli_mask_and_event_stats(tmp_path: Path) -> None: - """Giant export-f0 --activity-mask --event-stats writes both.""" - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - out = tmp_path / "out" - rc = main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--activity-mask", - "--mask-k", - "3", - "--mask-spots", - "none", - "--event-stats", - ]) - assert rc == 0 - with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: - assert "mask/activity" in f and f.attrs["activityMaskK"] == 3.0 - assert (out / "event_statistics.json").exists() - - -def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path: Path) -> None: - """The exact and matched kernels cannot match the movie when 200 Hz frames are wider. - - With 200 Hz frames wider than the movie's (dt200 > dt80) the trials are - reported, not written with interpolated (too smooth) activity; the - MATLAB exporter's kernel still exports. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - ds = f["Path1/frame_info/frame_line_idxs"] - ds[...] = ds[()] * 3 # 200 Hz frames every ~160 lines, dt80 134 - for kernel in ("exact", "matched"): - s = _export(syn, tmp_path / kernel, kernel=kernel) - for q in s["trials"]: - assert "wider than the movie's" in q["error"] - s = _export(syn, tmp_path / "exporter", kernel="exporter") - assert all("error" not in q for q in s["trials"]) - - -def _trial_frames(syn: dict[str, Any]) -> np.ndarray: - """SILo's 200 Hz frames per trial of the synthetic run.""" - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - return np.ravel(f["Path1/frame_info/trial_num_frames"][()]).astype(int) - - -def _set_traces(syn: dict[str, Any], den: np.ndarray, ls: np.ndarray | None = None) -> None: - """Replace dF_denoised (and dF_ls: den + noise SD 2 unless given).""" - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - g["dF_denoised"][...] = den - if ls is None: - rng = np.random.default_rng(4) - ls = np.nan_to_num(den) + rng.normal(0, 2.0, den.shape) - g["dF_ls"][...] = ls - - -def test_event_statistics_per_trial_and_observed_time(tmp_path: Path) -> None: - """An event across a trial boundary counts once in each trial. - - A trial without traces adds no observation time. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - n1, n2 = _trial_frames(syn)[:2] - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = np.zeros(f["Path1/sources/temporal/dF_denoised"].shape) - den[n1 - 3 : n1 + 5, 0, :] = 40.0 # straddles the boundary - den[20:28, 0, :] = 40.0 # one more in trial 1 - den[n1:, 0, 1] = np.nan # source 1: trial 2 not extracted - _set_traces(syn, den) - _export(syn, tmp_path / "out", event_stats=True) - p = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) - s0, s1 = p["paths"][0]["sources"][:2] - assert s0["events"] == 3 # 2 in trial 1, 1 at the start of trial 2 - assert s1["events"] == 2 # trial 2 has no trace for it - assert s1["observedMinutes"] == pytest.approx(s0["observedMinutes"] * n1 / (n1 + n2), rel=0.02) - assert s1["ratePerMin"] == pytest.approx(2 / s1["observedMinutes"]) - - -def test_mask_refuses_active_sources_without_noise(tmp_path: Path) -> None: - """A source with activity but no dF_ls (no noise estimate) would stay unmasked. - - The trial is refused. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = f["Path1/sources/temporal/dF_denoised"][()] - ls = den + 0.0 - ls[:, 0, 0] = np.nan - _set_traces(syn, den, ls) - s = _export(syn, tmp_path / "out", activity_mask=MaskRule()) - for q in s["trials"]: - assert "no noise estimate" in q["error"] and "[0]" in q["error"] - - -def test_mask_fractions_count_finite_samples(tmp_path: Path) -> None: - """The masked shares count only finite samples of the activity channel. - - A valid pixel may miss some frames. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - mf = sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5"))[0] - with h5py.File(mf, "r+") as f: - key = next(iter(f.keys())) - a = f[key][()] # (frames, cols, rows) - a[::5, :, :] = np.where( - np.random.default_rng(1).random(a[::5].shape) < 0.5, np.nan, a[::5] - ) # 10% of the samples missing: every pixel stays valid - f[key][...] = a - s = _export(syn, tmp_path / "out", trials=(1,), activity_mask=MaskRule(k=2)) - q = s["trials"][0] - with h5py.File(q["file"], "r") as f: - am = f["mask/activity"][()].astype(bool) - m = f["movie"][0] - valid = f["mask/valid"][()].astype(bool) - ok = np.isfinite(m) & valid[None] - assert valid.sum() > 0 and (~np.isfinite(m[:, valid])).any() - assert q["activityMaskFraction"] == pytest.approx(am[ok].mean()) - - -def test_event_statistics_unavailable_and_stale_file(tmp_path: Path) -> None: - """An active source without a noise estimate is reported as unavailable, not as zero events. - - A rerun without --event-stats removes the earlier statistics. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = f["Path1/sources/temporal/dF_denoised"][()] - ls = den + np.random.default_rng(2).normal(0, 2.0, den.shape) - ls[:, 0, 0] = np.nan - _set_traces(syn, den, ls) - out = tmp_path / "out" - _export(syn, out, event_stats=True) - j = json.loads((out / "event_statistics.json").read_text()) - s0, s1 = j["paths"][0]["sources"][:2] - assert s0["events"] is None and s0["ratePerMin"] is None - assert "no noise estimate" in s0["unavailable"] - assert s1["events"] > 0 and "unavailable" not in s1 - _export(syn, out) # statistics off: the earlier file is not this run's - assert not (out / "event_statistics.json").exists() - - -def test_mask_seeds_refused_without_a_map(tmp_path: Path) -> None: - """With --mask-spots seeds, a trial whose seeds cannot be placed is refused. - - Such a trial (no across-trial map) is refused rather than written - without them. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - a = f["Path1/frame_info/trial_alignment_affine"][()] - a[..., 1] = np.nan # trial 2 has no map - f["Path1/frame_info/trial_alignment_affine"][...] = a - _plan_file(syn) - s = _export( - syn, - tmp_path / "out", - ignore_sources=True, - activity_mask=MaskRule(spots="seeds"), - ) - by_trial = {q["trial"]: q for q in s["trials"]} - assert "error" not in by_trial[1] - assert "cannot be placed" in by_trial[2]["error"] - s = _export( - syn, - tmp_path / "none", - ignore_sources=True, - activity_mask=MaskRule(spots="none"), - ) - assert all("error" not in q for q in s["trials"]) - - -def test_mask_seeds_refused_without_a_plan_file(tmp_path: Path) -> None: - """Without SILo's plan file the unused seeds are unknown, not absent. - - --mask-spots seeds is refused; the default (no spots) exports. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", activity_mask=MaskRule(spots="seeds")) - for q in s["trials"]: - assert "plan file" in q["error"] - s = _export(syn, tmp_path / "none", activity_mask=MaskRule()) - assert all("error" not in q for q in s["trials"]) - - -def test_event_statistics_without_denoised_traces_or_f0(tmp_path: Path) -> None: - """Without dF_denoised the path is reported as unavailable. - - Without F0 the counts and raw sizes remain and dF/F is null. - """ - from giant_python.export.f0_events import path_statistics - from giant_python.viewer.run import SiloRun - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["Path1/sources/temporal/F0"] - _export(syn, tmp_path / "a", event_stats=True) - j = json.loads((tmp_path / "a" / "event_statistics.json").read_text()) - src = j["paths"][0]["sources"][0] - assert src["events"] > 0 and src["sizeRaw"] is not None - assert src["sizeDff"] is None and src["f0Median"] is None - run = SiloRun(syn["run"]) - run.traces(1).pop("dF_denoised") - p = path_statistics(run, 1) - assert "dF_denoised" in p["unavailable"] and p["sources"] == [] - - -def test_synchrony_counts_only_observed_partners() -> None: - """A partner without a trace around an event neither coincides nor counts towards chance. - - With full traces chance follows the rates. - """ - from giant_python.export.f0_events import synchrony - - T = 1000 - a = np.array([100, 300, 500]) - b = np.array([101, 700]) - full = np.ones((2, T), bool) - r = synchrony([([a, b], full)], 2) - assert r["events"] == 5 and r["observed"] == pytest.approx(2 / 5) - gap = full.copy() - gap[1, :600] = False # b is not observed around a's events - b2 = b[1:] - r2 = synchrony([([a, b2], gap)], 2) - assert r2["events"] == 4 and r2["observed"] == 0.0 - # only b2's event has an observed partner (a, rate 3 x 5 / 1000) - assert r2["expected"] == pytest.approx((3 * 5 / 1000) / 4, rel=1e-6) +"""F0 training-data export (giant export-f0) on a synthetic SILo run.""" + +import json +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.export import f0_qc +from giant_python.export.f0_training import ExportOptions, export_run + +from ..viewer.synthetic import BASELINE, CENTRES, N_TRIALS, write_session + +N80 = 600 + + +@pytest.fixture(scope="module", params=["rigid", "patchwise"]) +def session( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> dict[str, Any]: + """Build a synthetic session (rigid or patchwise maps) of 600 frames. + + Returns + ------- + dict[str, Any] + The session written by write_session: its run, motion-correction and baseline + folders. + """ + root = tmp_path_factory.mktemp(f"syn_{request.param}") + return write_session(root, request.param, n80=N80) + + +def _export( + syn: dict[str, Any], + out: Path, + **kw: Any, # noqa: ANN401 - forwarded to ExportOptions, whose fields differ in type +) -> dict: + """Export the synthetic run with the given options. + + Returns + ------- + dict + The export summary from export_run, including the per-trial records (trials). + """ + return export_run( + syn["run"], + out, + syn["run"] / "trial_table.h5", + syn["moco"], + syn["base"], + options=ExportOptions(**kw), + log=lambda line: None, + ) + + +def test_layout_matches_the_training_reader(session: dict[str, Any], tmp_path: Path) -> None: + """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile reads them. + + The reader is not a dependency: its contract is checked here. + """ + s = _export(session, tmp_path, kernel="exporter") + assert [q["trial"] for q in s["trials"]] == [1, 2] + for q in s["trials"]: + assert "error" not in q + with h5py.File(q["file"], "r") as f: + n_ch, T, R, C = f["movie"].shape + assert (n_ch, T) == (1, N80) and f["movie"].dtype == np.float32 + assert f["activity"].shape == f["movie"].shape + for m in ("valid", "labeled", "footprint_support"): + assert f[f"mask/{m}"].shape == (R, C) + assert f[f"mask/{m}"].dtype == np.uint8 + assert f["mean_image"].shape == (1, R, C) + assert f["varfac"].shape == (R, C) + for k in ("discard", "valid_mean", "rec_neg_err"): + assert f[f"frame/{k}"].shape == (T,) + assert f["sources/peak_row"].shape == (CENTRES.shape[0],) + for k in ( + "label", + "path", + "trial", + "peakR", + "nSources", + "alignHz", + "channels", + "activityChannel", + "activityGain", + "kernel", + "exporter", + ): + assert k in f.attrs + assert int(f.attrs["trial"]) == q["trial"] + # the stem of the trial's registration files, as the summary + stem = f.attrs["registrationStem"] + assert stem == q["registrationStem"] + assert stem.endswith(f"T{q['trial']}DMD{q['path']}") + assert f["movie"].chunks == (1, 256, min(64, R), min(64, C)) + name = Path(q["file"]) + assert (name.parent.name, name.name) == ( + "Path1", + f"trial_{q['trial']:03d}.h5", + ) + + +def test_target_is_the_baseline(session: dict[str, Any], tmp_path: Path) -> None: + """With the movie's own kernel and cubic placement the noiseless target is the baseline. + + The target (movie - activity) is the baseline to 2% of the activity's + peak; QC says the activity matches the movie. + """ + s = _export(session, tmp_path, kernel="exporter", interp="cubic") + for q in s["trials"]: + with h5py.File(q["file"], "r") as f: + m, a = f["movie"][0], f["activity"][0] + sup = f["mask/footprint_support"][()].astype(bool) + res = (m - a - BASELINE)[:, sup] + assert np.nanmax(np.abs(res)) < 0.02 * a.max() + assert q["peakR"] > 0.99 and q["diskR"] > 0.99 + assert q["diskSlope"] == pytest.approx(1.0, abs=0.01) + assert q["peakSlope"] == pytest.approx(1.0, abs=0.02) + assert abs(q["eventResidualFraction"]) < 0.02 + assert q["blurShapeRatio"] == pytest.approx(1.0, abs=0.02) + assert q["targetOverBaselineSupport"] == pytest.approx(1.0, abs=1e-3) + + +def test_linear_placement_blurs_the_peaks(session: dict[str, Any], tmp_path: Path) -> None: + """Bilinear placement keeps the flux but lowers the peak pixels (the viewer's rendering). + + Cubic placement keeps both. + """ + lin = _export(session, tmp_path / "lin", kernel="exporter") + cub = _export(session, tmp_path / "cub", kernel="exporter", interp="cubic") + for a, b in zip(lin["trials"], cub["trials"]): + assert a["diskSlope"] == pytest.approx(b["diskSlope"], abs=0.02) + assert a["blurShapeRatio"] > b["blurShapeRatio"] + assert a["eventResidualFraction"] > b["eventResidualFraction"] + + +def test_exact_kernel_is_sharper(session: dict[str, Any], tmp_path: Path) -> None: + """The exact kernel keeps the activity's total and sharpens its peaks. + + The peaks are compared against the MATLAB exporter's kernel. + """ + e = _export(session, tmp_path / "e", kernel="exporter", interp="cubic") + x = _export(session, tmp_path / "x", kernel="exact", interp="cubic") + for qe, qx in zip(e["trials"], x["trials"]): + assert qx["kernelR"] == pytest.approx((54 / 134) ** 2) + assert np.isnan(qe["kernelR"]) or qe["kernelR"] == 0 + with ( + h5py.File(qe["file"], "r") as fe, + h5py.File(qx["file"], "r") as fx, + ): + ae, ax = fe["activity"][0], fx["activity"][0] + assert ax.sum() == pytest.approx(ae.sum(), rel=0.02) + assert ax.max() > ae.max() + + +def test_summary_and_skipped_trial(tmp_path: Path) -> None: + """export_summary.json holds every trial (NaN as null). + + A trial without an across-trial map is reported, not written. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + _export(syn, out) # a first export writes both trials + assert (out / "Path1" / "trial_002.h5").exists() + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + a = f["Path1/frame_info/trial_alignment_affine"][()] + a[..., 1] = np.nan # MATLAB orientation: trials last + f["Path1/frame_info/trial_alignment_affine"][...] = a + s = _export(syn, out) + by_trial = {q["trial"]: q for q in s["trials"]} + assert "error" not in by_trial[1] + assert "map" in by_trial[2]["error"] + assert "removed" in by_trial[2]["error"] # no stale file is left + assert not (out / "Path1" / "trial_002.h5").exists() + text = (out / "export_summary.json").read_text() + assert "NaN" not in text + j = json.loads(text) + assert len(j["trials"]) == N_TRIALS and j["options"]["kernel"] == "exact" + + +def test_default_export_reconciles_trial_files(tmp_path: Path) -> None: + """A default export removes earlier trial files it does not write and lists them. + + An export with chosen trials leaves other files alone. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + folder = out / "Path1" + folder.mkdir(parents=True) + for name in ("trial_009.h5", "trial_1000.h5", "notes.txt"): + (folder / name).write_bytes(b"old") + s = _export(syn, out, trials=(1,)) + assert "removed" not in s + assert (folder / "trial_009.h5").exists() + s = _export(syn, out) + assert s["removed"] == {"Path1": ["trial_009.h5", "trial_1000.h5"]} + assert sorted(f.name for f in folder.iterdir()) == [ + "notes.txt", + "trial_001.h5", + "trial_002.h5", + ] + j = json.loads((out / "export_summary.json").read_text()) + assert j["removed"] == s["removed"] + + +def test_repeated_selectors_export_once(tmp_path: Path) -> None: + """Repeated paths and trials give one job each. + + Two workers never write the same file. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", paths=(1, 1), trials=(2, 2, 1), workers=2) + assert [(q["path"], q["trial"]) for q in s["trials"]] == [(1, 1), (1, 2)] + assert all("error" not in q for q in s["trials"]) + + +@pytest.mark.parametrize( + "kw", + [ + {"trials": (0,)}, + {"trials": (-1,)}, + {"trials": (N_TRIALS + 1,)}, + {"paths": (2,)}, + ], +) +def test_selectors_outside_the_run_are_refused( + tmp_path: Path, kw: dict[str, tuple[int, ...]] +) -> None: + """Trials outside 1..the table's trials and paths the run does not have are refused. + + They are refused before any job starts; the CLI reports a usage error. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="trials|paths"): + _export(syn, tmp_path / "out", **kw) + assert not (tmp_path / "out" / "Path1").exists() + flag, values = next(iter(kw.items())) + with pytest.raises(SystemExit) as e: + main([ + "export-f0", + str(syn["run"]), + str(tmp_path / "o2"), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + f"--{flag}", + *[str(v) for v in values], + ]) + assert e.value.code == 2 + + +@pytest.fixture(scope="module") +def exported(tmp_path_factory: pytest.TempPathFactory) -> tuple[dict[str, Any], Path]: + """Export a synthetic session once (default options). + + Returns + ------- + syn : dict[str, Any] + The synthetic session. + out : Path + The folder the session was exported to. + """ + root = tmp_path_factory.mktemp("bad_options") + syn = write_session(root / "syn", "rigid", n80=200) + _export(syn, root / "out") + return syn, root / "out" + + +@pytest.mark.parametrize( + "kw, cli", + [ + ({"deflate": 10}, ["--deflate", "10"]), + ({"deflate": -1}, ["--deflate", "-1"]), + ({"blur": -1.0}, ["--blur", "-1"]), + ({"blur": float("nan")}, ["--blur", "nan"]), + ({"blur": float("inf")}, ["--blur", "inf"]), + ({"var_fac": "median"}, None), + ({"kernel": "box"}, None), + ({"interp": "nearest"}, None), + ], +) +def test_invalid_options_keep_earlier_files( + exported: tuple[dict[str, Any], Path], kw: dict[str, Any], cli: list[str] | None +) -> None: + """An option every trial would fail on is refused before any trial. + + So a rerun with it leaves the earlier export in place; the CLI reports a + usage error. + """ + syn, out = exported + files = sorted((out / "Path1").glob("trial_*.h5")) + assert len(files) == N_TRIALS + stamps = [f.stat().st_mtime_ns for f in files] + with pytest.raises(ValueError): + _export(syn, out, **kw) + assert [f.stat().st_mtime_ns for f in files] == stamps + if cli is None: # argparse's choices refuse these + return + with pytest.raises(SystemExit) as e: + main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + *cli, + ]) + assert e.value.code == 2 + assert [f.stat().st_mtime_ns for f in files] == stamps + + +def test_ignore_sources(tmp_path: Path) -> None: + """Without sources: zero activity, no sources group, no QC.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", ignore_sources=True) + for q in s["trials"]: + assert q["nSources"] == 0 and np.isnan(q["peakR"]) + with h5py.File(q["file"], "r") as f: + assert not f["activity"][()].any() + assert "sources" not in f + assert not f["mask/footprint_support"][()].any() + + +def test_cli(tmp_path: Path) -> None: + """Giant export-f0 writes the trials and returns 0.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + rc = main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--kernel", + "matched", + "--interp", + "cubic", + "--label", + "syn", + ]) + assert rc == 0 + with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: + assert f.attrs["label"] == "syn" and f.attrs["kernel"] == "matched" + + +def test_movmedian_omitnan() -> None: + """The running median ignores NaN and shrinks at the ends.""" + rng = np.random.default_rng(0) + x = rng.normal(size=(3, 300)) + x[0, 50:60] = np.nan + x[2, :] = np.nan + m = f0_qc.movmedian_omitnan(x, 81) + for i in range(2): + for t in (0, 10, 55, 150, 299): + w = x[i, max(0, t - 40) : t + 41] + assert m[i, t] == pytest.approx(np.median(w[~np.isnan(w)])) + assert np.isnan(m[2]).all() + + +def test_event_residual_and_peaks() -> None: + """The event-triggered residual is 0 when the activity is the movie's signal. + + It is 1 when no activity is removed. + """ + from scipy import sparse + + T = 400 + x = np.zeros((1, T)) + for e in (50, 150, 250, 350): + x[0, e : e + 20] += 10 * np.exp(-np.arange(20) / 4.0) + H = sparse.csr_matrix(np.array([[0.2], [0.5], [0.3]])) + Y = (np.asarray(H @ x).T + 5.0).astype(np.float64) + pk = f0_qc.peak_pixels(H) + assert pk.tolist() == [1] + frac, n = f0_qc.event_residual(H, x, Y, pk) + assert n > 0 and abs(frac) < 1e-9 + frac0, _ = f0_qc.event_residual(H, x, Y + np.asarray(H @ x).T, pk) + assert frac0 == pytest.approx(0.5) # half of the doubled movie left + sl, r = f0_qc.peak_fit(H, x, Y, pk) + assert sl[0] == pytest.approx(1.0) and r[0] == pytest.approx(1.0) + + +def _two_channels(syn: dict[str, Any]) -> None: + """Rewrite the synthetic movies with a second channel. + + The second channel is 2 x the first + 5, interleaved by frame; also set + numChannels 2. + """ + for mf in sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")): + with h5py.File(mf, "r+") as f: + a = f["mov"][()] # (pages, cols, rows) + del f["mov"] + st = np.empty((2 * a.shape[0],) + a.shape[1:], a.dtype) + st[0::2], st[1::2] = a, 2 * a + 5 + f["mov"] = st + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + f["params/numChannels"][...] = 2 + + +def test_written_channels_and_mean_image(tmp_path: Path) -> None: + """The mean image follows the written channels, as movie and activity do. + + The reader indexes all three alike. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + _two_channels(syn) + s = _export(syn, tmp_path / "c2", channels=(2,)) + with h5py.File(s["trials"][0]["file"], "r") as f: + m, mi = f["movie"][()], f["mean_image"][()] + valid = f["mask/valid"][()].astype(bool) + assert m.shape[0] == 1 and mi.shape[0] == 1 + np.testing.assert_allclose(mi[0][valid], np.nanmean(m[0], 0)[valid], rtol=1e-4) + assert int(f.attrs["activityChannel"]) == 1 + s = _export(syn, tmp_path / "c21", channels=(2, 1)) + with h5py.File(s["trials"][0]["file"], "r") as f: + mi = f["mean_image"][()] + np.testing.assert_allclose(mi[0], 2 * mi[1] + 5, rtol=1e-4) + + +def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path: Path) -> None: + """The mean image leaves out the discarded frames and is NaN outside the valid pixels. + + This is as slap2-f0 computes it at inference. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + alf = sorted(syn["moco"].glob("*_ALIGNMENTDATA.h5"))[0] + with h5py.File(alf, "r+") as f: + rne = f["recNegErr"][()] + rne[100:110] = 1.0 # a motion spike: those frames are discarded + f["recNegErr"][...] = rne + stem = alf.name.replace("_ALIGNMENTDATA.h5", "") + mf = syn["moco"] / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" + with h5py.File(mf, "r+") as f: + key = next(iter(f.keys())) + a = f[key][()] # (frames, cols, rows), one channel + a[100:110] += 1000.0 # what a mean over every frame would show + col = a.shape[1] // 2 + a[:150, col, :] = np.nan # a column imaged in a quarter of the frames + f[key][...] = a + s = _export(syn, tmp_path / "out", trials=(1,)) + q = s["trials"][0] + assert "error" not in q + with h5py.File(q["file"], "r") as f: + disc = f["frame/discard"][()].astype(bool) + m, mi = f["movie"][0], f["mean_image"][0] + valid = f["mask/valid"][()].astype(bool) + c0 = int(np.ravel(f.attrs["cropOriginRC"])[1]) + assert disc[100:110].all() + np.testing.assert_allclose(mi[valid], np.nanmean(m, 0)[valid], rtol=1e-4) + assert np.nanmax(mi) < 500 # the bright discarded frames are not in it + assert not valid[:, col - c0].any() and np.isnan(mi[:, col - c0]).all() + + +def test_sources_without_traces_are_refused(tmp_path: Path) -> None: + """Sources without dF_denoised traces would give zero activity. + + The target would keep every event, so the trials are reported, not + written. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["Path1/sources/temporal/dF_denoised"] + s = _export(syn, tmp_path / "out") + for q in s["trials"]: + assert "dF_denoised" in q["error"] + assert not list((tmp_path / "out" / "Path1").glob("trial_*.h5")) + + +@pytest.mark.parametrize("channels", [(0,), (3,), (1, 2)]) +def test_channels_outside_the_movie_are_refused(tmp_path: Path, channels: tuple[int, ...]) -> None: + """Channels are one-based and within numChannels (1 here).""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="channels"): + _export(syn, tmp_path / "out", channels=channels) + with pytest.raises(SystemExit) as e: # the CLI reports it as a usage error + main([ + "export-f0", + str(syn["run"]), + str(tmp_path / "o2"), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--channels", + *[str(c) for c in channels], + ]) + assert e.value.code == 2 + + +# ------------------------------------------------- activity mask, events + + +def _noisy_traces(syn: dict[str, Any], sd: float = 2.0) -> None: + """Give the synthetic run noisy dF_ls (noise SD sd around dF_denoised). + + Also give it an events trace at the denoised trace's jumps. + """ + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + den = g["dF_denoised"][()] # (frames, channels, sources) + rng = np.random.default_rng(5) + g["dF_ls"][...] = den + rng.normal(0, sd, den.shape) + jump = np.diff(den, axis=0, prepend=den[:1]) + g["events"][...] = np.where(jump > 5, jump, 0.0) + + +def _plan_file( + syn: dict[str, Any], unused: tuple[tuple[float, float], ...] = ((8.0, 40.0),) +) -> None: + """Write a minimal SILo plan file for path 1. + + It holds the sources' seeds plus unused seeds without a source (as + giant silo keeps it in source_extraction/silo/plan). + """ + plan = syn["run"] / "source_extraction" / "silo" / "plan" / "path1.h5" + plan.parent.mkdir(parents=True, exist_ok=True) + rc = np.vstack([CENTRES, np.asarray(unused, float)]) + seeds = np.column_stack([np.ones(len(rc)), rc, np.ones(len(rc))]) + pix = np.floor(CENTRES + 0.5).astype(int) + with h5py.File(plan, "w") as f: + g = f.create_group("sources") + g["seeds"] = seeds + g["rows"] = pix[:, 0] + g["cols"] = pix[:, 1] + + +def test_temporal_mask_rule() -> None: + """A crossing masks its frames, the widening after it and the shared frames on both sides. + + Nothing else is masked. + """ + from giant_python.export.f0_mask import MaskRule, temporal_mask + + n200 = 500 + lines200 = np.arange(n200) * 54.0 + ds = np.arange(0, n200 * 54, 134.0) + den = np.zeros((n200, 2)) + den[200:210, 0] = 10.0 # above 2 x 1 for 10 frames + den[300:310, 1] = 1.5 # below the threshold + rule = MaskRule(k=2, margin_px=0, widen_tau=1, share_frames=6) + tm = temporal_mask(den, np.ones(2), lines200, np.zeros(n200, bool), ds, rule, 30) + assert not tm[1].any() + f = np.flatnonzero(tm[0]) + first = int(np.argmin(np.abs(ds - 200 * 54))) - 6 + last = int(np.argmin(np.abs(ds - (209 + 30) * 54))) + 6 + assert f.min() == first and f.max() == last and f.size == last - first + 1 + + +def test_mask_widening_uses_the_activity_channel_decay() -> None: + """The widening's decay constant is the activity channel's, not channel 2's tau2. + + The activity channel's is SILo's tau_full, else tau_s times the + frame rate. + """ + from types import SimpleNamespace + + from giant_python.export.f0_training import _mask_inputs + + class Run: + """A run with only the given params (as SiloRun.param reads them).""" + + def __init__(self, params: dict[str, object]) -> None: + """Keep the params.""" + self.params = params + + def param(self, name: str, default: object = None) -> object: + """Return a param, the default when missing or empty. + + Returns + ------- + object + The named param, or `default` if it is missing, None or an empty string. + """ + v = self.params.get(name, default) + return default if v is None or v == "" else v + + p = SimpleNamespace( + sources=SimpleNamespace(n=0, rejected_rc=np.zeros((0, 2)), unused_seeds=None) + ) + # tau_full overrides tau_s (6 frames, not 0.024 s x 200 Hz = 4.8) + both = { + "analyzeHz": 200.0, + "tau_s": 0.024, + "tau_full": 6.0, + "tau2_s": 0.15, + "tau2_samps": 30.0, + } + m = _mask_inputs(Run(both), p, {}, None) + assert m["tau200"] == 6.0 and m["tau_seconds"] == pytest.approx(0.03) + # tau_s in the run's frames; the recorded constant in seconds + no_full = {"analyzeHz": 100.0, "tau_s": 0.05, "tau2_s": 0.15} + m = _mask_inputs(Run(no_full), p, {}, None) + assert m["tau200"] == pytest.approx(5.0) + assert m["tau_seconds"] == pytest.approx(0.05) + m = _mask_inputs(Run({}), p, {}, None) + assert m["tau200"] == pytest.approx(4.8) + assert m["tau_seconds"] == pytest.approx(0.024) + + +def test_activity_mask_written(tmp_path: Path) -> None: + """mask/activity covers the sources' activity, never pixels far from a footprint. + + It also leaves quiet stretches; spots add to it; the rule and the masked + shares are recorded. + """ + from scipy import ndimage + + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + _plan_file(syn) + rule = MaskRule(k=2, margin_px=1, widen_tau=1, share_frames=6, spots="none") + s = _export(syn, tmp_path / "m", interp="cubic", activity_mask=rule) + s2 = _export( + syn, + tmp_path / "m2", + interp="cubic", + activity_mask=MaskRule(k=2, margin_px=1, spots="seeds"), + ) + for q, q2 in zip(s["trials"], s2["trials"]): + assert "error" not in q + assert 0 < q["activityMaskFractionSupport"] < 1 + assert q["activityMaskFraction"] < q["activityMaskFractionSupport"] + assert q2["activityMaskFraction"] >= q["activityMaskFraction"] + with h5py.File(q["file"], "r") as f: + am = f["mask/activity"][()].astype(bool) + a = f["activity"][0] + sup = f["mask/footprint_support"][()].astype(bool) + assert f["mask/activity"].dtype == np.uint8 + assert f.attrs["activityMaskK"] == 2.0 + assert f.attrs["activityMaskSpots"] == "none" + # SILo's tau_s default (24 ms) at 200 Hz: the activity channel's + assert f.attrs["activityMaskTauSeconds"] == pytest.approx(0.024) + with h5py.File(q2["file"], "r") as f: + assert f.attrs["activityMaskWidenTau"] == 2.0 # the default + assert am.shape == a.shape + big = a > 0.2 * a.max() + assert big.any() and am[big].all() # the events are masked + far = ~ndimage.binary_dilation(sup, iterations=3) + assert not am[:, far].any() # nothing beyond footprint + margin + act = a.reshape(a.shape[0], -1).max(1) > 0 + near = ndimage.binary_dilation(act, np.ones(41, bool)) + if (~near).any(): # quiet stretches stay in the loss + assert not am[~near][:, sup].any() + + +def test_mask_and_event_stats_off_by_default(tmp_path: Path) -> None: + """Without the options neither the mask nor the statistics file.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out") + with h5py.File(s["trials"][0]["file"], "r") as f: + assert "mask/activity" not in f + assert not (tmp_path / "out" / "event_statistics.json").exists() + + +def test_event_statistics(tmp_path: Path) -> None: + """event_statistics.json: events are crossings of k noise SDs. + + SILo's small noise events in its events trace do not count; the file + also holds rate, sizes and the synchrony against chance. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + den = np.zeros(g["dF_denoised"].shape) # (frames, channels, sources) + T = den.shape[0] + kern = np.exp(-np.arange(40) / 4.8) + starts = np.arange(30, T - 60, 100) # well apart: one event each + for a in starts: + den[a : a + 40, 0, :] += 40.0 * kern[: min(40, T - a)][:, None] + rng = np.random.default_rng(3) + g["dF_denoised"][...] = den + g["dF_ls"][...] = den + rng.normal(0, 2.0, den.shape) + tiny = np.zeros_like(den) + tiny[::7] = 0.5 # SILo's small events: not activity + g["events"][...] = tiny + _export(syn, tmp_path / "out", event_stats=True) + j = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) + p = j["paths"][0] + assert p["path"] == 1 and len(p["sources"]) == CENTRES.shape[0] + assert p["thresholdSD"] == 6.0 + for src in p["sources"]: + assert src["noise"] == pytest.approx(2.0, rel=0.15) + assert src["events"] == starts.size + assert src["ratePerMin"] == pytest.approx(starts.size / p["keptMinutes"]) + assert src["sizeRaw"]["q50"] == pytest.approx(40.0) + assert src["sizeDff"]["q50"] == pytest.approx(40.0 / 50) + assert src["ratesPerMin"]["3"] == pytest.approx(src["ratePerMin"]) + sy = p["synchrony"] + assert 0 <= sy["observed"] <= 1 and 0 <= sy["expected"] <= 1 + + +@pytest.mark.parametrize( + "bad", + [{"k": 0}, {"margin_px": -1}, {"share_frames": 1.5}, {"spots": "all"}], +) +def test_invalid_mask_rule_refused(tmp_path: Path, bad: dict[str, Any]) -> None: + """An invalid mask rule is refused before any trial.""" + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="mask"): + _export(syn, tmp_path / "out", activity_mask=MaskRule(**bad)) + + +def test_cli_mask_and_event_stats(tmp_path: Path) -> None: + """Giant export-f0 --activity-mask --event-stats writes both.""" + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + out = tmp_path / "out" + rc = main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--activity-mask", + "--mask-k", + "3", + "--mask-spots", + "none", + "--event-stats", + ]) + assert rc == 0 + with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: + assert "mask/activity" in f and f.attrs["activityMaskK"] == 3.0 + assert (out / "event_statistics.json").exists() + + +def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path: Path) -> None: + """The exact and matched kernels cannot match the movie when 200 Hz frames are wider. + + With 200 Hz frames wider than the movie's (dt200 > dt80) the trials are + reported, not written with interpolated (too smooth) activity; the + MATLAB exporter's kernel still exports. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + ds = f["Path1/frame_info/frame_line_idxs"] + ds[...] = ds[()] * 3 # 200 Hz frames every ~160 lines, dt80 134 + for kernel in ("exact", "matched"): + s = _export(syn, tmp_path / kernel, kernel=kernel) + for q in s["trials"]: + assert "wider than the movie's" in q["error"] + s = _export(syn, tmp_path / "exporter", kernel="exporter") + assert all("error" not in q for q in s["trials"]) + + +def _trial_frames(syn: dict[str, Any]) -> np.ndarray: + """SILo's 200 Hz frames per trial of the synthetic run. + + Returns + ------- + np.ndarray + Integer number of frames of each trial, from Path1/frame_info/trial_num_frames. + """ + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + return np.ravel(f["Path1/frame_info/trial_num_frames"][()]).astype(int) + + +def _set_traces(syn: dict[str, Any], den: np.ndarray, ls: np.ndarray | None = None) -> None: + """Replace dF_denoised (and dF_ls: den + noise SD 2 unless given).""" + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + g["dF_denoised"][...] = den + if ls is None: + rng = np.random.default_rng(4) + ls = np.nan_to_num(den) + rng.normal(0, 2.0, den.shape) + g["dF_ls"][...] = ls + + +def test_event_statistics_per_trial_and_observed_time(tmp_path: Path) -> None: + """An event across a trial boundary counts once in each trial. + + A trial without traces adds no observation time. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + n1, n2 = _trial_frames(syn)[:2] + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = np.zeros(f["Path1/sources/temporal/dF_denoised"].shape) + den[n1 - 3 : n1 + 5, 0, :] = 40.0 # straddles the boundary + den[20:28, 0, :] = 40.0 # one more in trial 1 + den[n1:, 0, 1] = np.nan # source 1: trial 2 not extracted + _set_traces(syn, den) + _export(syn, tmp_path / "out", event_stats=True) + p = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) + s0, s1 = p["paths"][0]["sources"][:2] + assert s0["events"] == 3 # 2 in trial 1, 1 at the start of trial 2 + assert s1["events"] == 2 # trial 2 has no trace for it + assert s1["observedMinutes"] == pytest.approx(s0["observedMinutes"] * n1 / (n1 + n2), rel=0.02) + assert s1["ratePerMin"] == pytest.approx(2 / s1["observedMinutes"]) + + +def test_mask_refuses_active_sources_without_noise(tmp_path: Path) -> None: + """A source with activity but no dF_ls (no noise estimate) would stay unmasked. + + The trial is refused. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = f["Path1/sources/temporal/dF_denoised"][()] + ls = den + 0.0 + ls[:, 0, 0] = np.nan + _set_traces(syn, den, ls) + s = _export(syn, tmp_path / "out", activity_mask=MaskRule()) + for q in s["trials"]: + assert "no noise estimate" in q["error"] and "[0]" in q["error"] + + +def test_mask_fractions_count_finite_samples(tmp_path: Path) -> None: + """The masked shares count only finite samples of the activity channel. + + A valid pixel may miss some frames. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + mf = sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5"))[0] + with h5py.File(mf, "r+") as f: + key = next(iter(f.keys())) + a = f[key][()] # (frames, cols, rows) + a[::5, :, :] = np.where( + np.random.default_rng(1).random(a[::5].shape) < 0.5, np.nan, a[::5] + ) # 10% of the samples missing: every pixel stays valid + f[key][...] = a + s = _export(syn, tmp_path / "out", trials=(1,), activity_mask=MaskRule(k=2)) + q = s["trials"][0] + with h5py.File(q["file"], "r") as f: + am = f["mask/activity"][()].astype(bool) + m = f["movie"][0] + valid = f["mask/valid"][()].astype(bool) + ok = np.isfinite(m) & valid[None] + assert valid.sum() > 0 and (~np.isfinite(m[:, valid])).any() + assert q["activityMaskFraction"] == pytest.approx(am[ok].mean()) + + +def test_event_statistics_unavailable_and_stale_file(tmp_path: Path) -> None: + """An active source without a noise estimate is reported as unavailable, not as zero events. + + A rerun without --event-stats removes the earlier statistics. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = f["Path1/sources/temporal/dF_denoised"][()] + ls = den + np.random.default_rng(2).normal(0, 2.0, den.shape) + ls[:, 0, 0] = np.nan + _set_traces(syn, den, ls) + out = tmp_path / "out" + _export(syn, out, event_stats=True) + j = json.loads((out / "event_statistics.json").read_text()) + s0, s1 = j["paths"][0]["sources"][:2] + assert s0["events"] is None and s0["ratePerMin"] is None + assert "no noise estimate" in s0["unavailable"] + assert s1["events"] > 0 and "unavailable" not in s1 + _export(syn, out) # statistics off: the earlier file is not this run's + assert not (out / "event_statistics.json").exists() + + +def test_mask_seeds_refused_without_a_map(tmp_path: Path) -> None: + """With --mask-spots seeds, a trial whose seeds cannot be placed is refused. + + Such a trial (no across-trial map) is refused rather than written + without them. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + a = f["Path1/frame_info/trial_alignment_affine"][()] + a[..., 1] = np.nan # trial 2 has no map + f["Path1/frame_info/trial_alignment_affine"][...] = a + _plan_file(syn) + s = _export( + syn, + tmp_path / "out", + ignore_sources=True, + activity_mask=MaskRule(spots="seeds"), + ) + by_trial = {q["trial"]: q for q in s["trials"]} + assert "error" not in by_trial[1] + assert "cannot be placed" in by_trial[2]["error"] + s = _export( + syn, + tmp_path / "none", + ignore_sources=True, + activity_mask=MaskRule(spots="none"), + ) + assert all("error" not in q for q in s["trials"]) + + +def test_mask_seeds_refused_without_a_plan_file(tmp_path: Path) -> None: + """Without SILo's plan file the unused seeds are unknown, not absent. + + --mask-spots seeds is refused; the default (no spots) exports. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", activity_mask=MaskRule(spots="seeds")) + for q in s["trials"]: + assert "plan file" in q["error"] + s = _export(syn, tmp_path / "none", activity_mask=MaskRule()) + assert all("error" not in q for q in s["trials"]) + + +def test_event_statistics_without_denoised_traces_or_f0(tmp_path: Path) -> None: + """Without dF_denoised the path is reported as unavailable. + + Without F0 the counts and raw sizes remain and dF/F is null. + """ + from giant_python.export.f0_events import path_statistics + from giant_python.viewer.run import SiloRun + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["Path1/sources/temporal/F0"] + _export(syn, tmp_path / "a", event_stats=True) + j = json.loads((tmp_path / "a" / "event_statistics.json").read_text()) + src = j["paths"][0]["sources"][0] + assert src["events"] > 0 and src["sizeRaw"] is not None + assert src["sizeDff"] is None and src["f0Median"] is None + run = SiloRun(syn["run"]) + run.traces(1).pop("dF_denoised") + p = path_statistics(run, 1) + assert "dF_denoised" in p["unavailable"] and p["sources"] == [] + + +def test_synchrony_counts_only_observed_partners() -> None: + """A partner without a trace around an event neither coincides nor counts towards chance. + + With full traces chance follows the rates. + """ + from giant_python.export.f0_events import synchrony + + T = 1000 + a = np.array([100, 300, 500]) + b = np.array([101, 700]) + full = np.ones((2, T), bool) + r = synchrony([([a, b], full)], 2) + assert r["events"] == 5 and r["observed"] == pytest.approx(2 / 5) + gap = full.copy() + gap[1, :600] = False # b is not observed around a's events + b2 = b[1:] + r2 = synchrony([([a, b2], gap)], 2) + assert r2["events"] == 4 and r2["observed"] == 0.0 + # only b2's event has an observed partner (a, rate 3 x 5 / 1000) + assert r2["expected"] == pytest.approx((3 * 5 / 1000) / 4, rel=1e-6) diff --git a/tests/raster/__init__.py b/tests/raster/__init__.py index a7413461..548691c0 100644 --- a/tests/raster/__init__.py +++ b/tests/raster/__init__.py @@ -1 +1 @@ -"""Tests of raster (multi-ROI) source extraction.""" +"""Tests of raster (multi-ROI) source extraction.""" diff --git a/tests/raster/alignment_synthetic.py b/tests/raster/alignment_synthetic.py index 3baa61cc..e6632680 100644 --- a/tests/raster/alignment_synthetic.py +++ b/tests/raster/alignment_synthetic.py @@ -1,144 +1,180 @@ -"""Synthetic trials for the across-trial alignment tests. - -A port of the scenario of GIAnT-MATLAB's ``TestTrialAlignment.m``, with numpy's -random numbers: a labeled neuron (dendrites with spines, an unscanned band and a -hole) seen through known affine maps and, optionally, smooth bends, with -shot-like noise in two halves per trial. -""" - -from __future__ import annotations - -from collections.abc import Callable - -import numpy as np -import scipy.ndimage as ndimage - -from giant_python.extraction.raster.alignment import interp2_cubic - -SIZE = (180, 260) -N_TRIALS = 6 - - -def neuron( - rng: np.random.Generator, size: tuple[int, int] = SIZE -) -> tuple[np.ndarray, np.ndarray]: - """Mean image of a labeled neuron and its scanned pixels (NaN outside them).""" - h, w = size - rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) - truth = np.full(size, 5.0) - for _ in range(6): - t = np.linspace(0, 1, 400)[:, None] - p0 = rng.random(2) * np.array(size) - ang = rng.random() * np.pi - length = 150 + 100 * rng.random() - along = np.array([np.sin(ang), np.cos(ang)]) - across = np.array([np.cos(ang), -np.sin(ang)]) - wiggle = 8 * np.sin(2 * np.pi * (t * (1 + rng.random()) + rng.random())) - path = p0 + t * length * along + wiggle * across - for q in range(0, path.shape[0], 20): - truth += 30 * np.exp(-((rr - path[q, 0]) ** 2 + (cc - path[q, 1]) ** 2) / (2 * 1.5**2)) - sp = path[q] + (3 + 2 * rng.random()) * across * np.sign(rng.standard_normal()) - truth += (40 + 80 * rng.random()) * np.exp( - -((rr - sp[0]) ** 2 + (cc - sp[1]) ** 2) / (2 * 1.1**2) - ) - scan = np.ones(size, bool) - scan[:, :12] = False - scan[79:100, 119:150] = False - truth[~scan] = np.nan - return truth, scan - - -def trials( - truth: np.ndarray, - scan: np.ndarray, - bends: bool, - rng: np.random.Generator, - n_trials: int = N_TRIALS, - bend_px: float = 0.25, - affine_sd: float = 0.003, -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Trial mean images, their halves, the true fields and the rigid starting maps. - - Mean images ``(trials, rows, cols)``, halves ``(trials, 2, rows, cols)``, - true fields ``(trials, 2, rows, cols)`` (consensus pixel ``x`` is at - ``x + U(x)`` in the trial) and rigid starting maps ``(trials, 2, 3)``. - """ - h, w = truth.shape - rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) - filled = np.where(np.isnan(truth), 5.0, truth) - m = np.full((n_trials, h, w), np.nan) - mh = np.full((n_trials, 2, h, w), np.nan) - u = np.zeros((n_trials, 2, h, w)) - a0 = np.zeros((n_trials, 2, 3)) - for t in range(n_trials): - lin = np.eye(2) + affine_sd * rng.standard_normal((2, 2)) - tr = 0.6 * rng.standard_normal(2) - u_r = (lin[0, 0] - 1) * rr + lin[0, 1] * cc + tr[0] - u_c = lin[1, 0] * rr + (lin[1, 1] - 1) * cc + tr[1] - if bends: - for comp in (0, 1): - b = ndimage.gaussian_filter( - rng.standard_normal((h, w)), 40, mode="nearest", truncate=5 - ) - b = bend_px * b / b.std() - if comp == 0: - u_r = u_r + b - else: - u_c = u_c + b - u[t, 0], u[t, 1] = u_r, u_c - # the consensus point each trial pixel shows: y = x - U(y) - y_r, y_c = rr.ravel().copy(), cc.ravel().copy() - for _ in range(8): - coords = np.vstack([y_r, y_c]) - ur = ndimage.map_coordinates(u_r, coords, order=1, mode="nearest") - uc = ndimage.map_coordinates(u_c, coords, order=1, mode="nearest") - y_r, y_c = rr.ravel() - ur, cc.ravel() - uc - img = interp2_cubic(filled, y_r, y_c) - img = np.where(np.isnan(img), 5.0, img).reshape(h, w) - for half in range(2): - x = img + 0.2 * np.sqrt(np.maximum(img, 0)) * rng.standard_normal((h, w)) - x[~scan] = np.nan # the scan mask is fixed in the trial's frame - mh[t, half] = x - m[t] = mh[t].mean(axis=0) - c0 = (h // 2 - 1, w // 2 - 1) # MATLAB's round(sz/2), zero-based - a0[t] = [[1, 0, np.round(u_r[c0])], [0, 1, np.round(u_c[c0])]] - return m, mh, u, a0 - - -def field_error( - coords: Callable[[int, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]], - u: np.ndarray, - a0: np.ndarray, - truth: np.ndarray, - scan: np.ndarray, -) -> tuple[float, float]: - """RMS error of fitted maps relative to the trials' mean map. - - Weighted by image structure; and the same for the rigid start. - ``coords(t, r, c)`` gives the fitted positions. - """ - n_trials = u.shape[0] - sel = ndimage.binary_erosion(scan, np.ones((5, 5)), border_value=0) - rows, cols = np.nonzero(sel) - est = np.empty((n_trials, rows.size, 2)) - tru = np.empty_like(est) - rig = np.empty_like(est) - for t in range(n_trials): - r_t, c_t = coords(t, rows.astype(float), cols.astype(float)) - est[t] = np.column_stack([r_t - rows, c_t - cols]) - tru[t] = np.column_stack([u[t, 0][sel], u[t, 1][sel]]) - rig[t] = a0[t, :, 2] - sq = np.sqrt(np.fmax(truth, 0)) - g_r, g_c = np.gradient(sq, axis=0), np.gradient(sq, axis=1) - wgt = g_r[sel] ** 2 + g_c[sel] ** 2 - wgt[np.isnan(wgt)] = 0 - - def rel(x: np.ndarray) -> np.ndarray: - """Relative to the trials' mean.""" - return x - x.mean(axis=0) - - def wrms(e: np.ndarray) -> float: - """Structure-weighted RMS over trials and pixels.""" - return np.sqrt(np.sum((e**2).sum(axis=2).mean(axis=0) * wgt) / wgt.sum()) - - return wrms(rel(est) - rel(tru)), wrms(rel(rig) - rel(tru)) +"""Synthetic trials for the across-trial alignment tests. + +A port of the scenario of GIAnT-MATLAB's TestTrialAlignment.m, with numpy's +random numbers: a labeled neuron (dendrites with spines, an unscanned band and a +hole) seen through known affine maps and, optionally, smooth bends, with +shot-like noise in two halves per trial. +""" + +from __future__ import annotations + +from collections.abc import Callable + +import numpy as np +import scipy.ndimage as ndimage + +from giant_python.extraction.raster.alignment import interp2_cubic + +SIZE = (180, 260) +N_TRIALS = 6 + + +def neuron(rng: np.random.Generator, size: tuple[int, int] = SIZE) -> tuple[np.ndarray, np.ndarray]: + """Mean image of a labeled neuron and its scanned pixels (NaN outside them). + + Returns + ------- + truth : np.ndarray + The neuron's mean image, NaN outside the scanned pixels. + scan : np.ndarray + Boolean mask of the scanned pixels. + """ + h, w = size + rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) + truth = np.full(size, 5.0) + for _ in range(6): + t = np.linspace(0, 1, 400)[:, None] + p0 = rng.random(2) * np.array(size) + ang = rng.random() * np.pi + length = 150 + 100 * rng.random() + along = np.array([np.sin(ang), np.cos(ang)]) + across = np.array([np.cos(ang), -np.sin(ang)]) + wiggle = 8 * np.sin(2 * np.pi * (t * (1 + rng.random()) + rng.random())) + path = p0 + t * length * along + wiggle * across + for q in range(0, path.shape[0], 20): + truth += 30 * np.exp(-((rr - path[q, 0]) ** 2 + (cc - path[q, 1]) ** 2) / (2 * 1.5**2)) + sp = path[q] + (3 + 2 * rng.random()) * across * np.sign(rng.standard_normal()) + truth += (40 + 80 * rng.random()) * np.exp( + -((rr - sp[0]) ** 2 + (cc - sp[1]) ** 2) / (2 * 1.1**2) + ) + scan = np.ones(size, bool) + scan[:, :12] = False + scan[79:100, 119:150] = False + truth[~scan] = np.nan + return truth, scan + + +def trials( + truth: np.ndarray, + scan: np.ndarray, + bends: bool, + rng: np.random.Generator, + n_trials: int = N_TRIALS, + bend_px: float = 0.25, + affine_sd: float = 0.003, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Trial mean images, their halves, the true fields and the rigid starting maps. + + Mean images (trials, rows, cols), halves (trials, 2, rows, cols), + true fields (trials, 2, rows, cols) (consensus pixel x is at + x + U(x) in the trial) and rigid starting maps (trials, 2, 3). + + Returns + ------- + m : np.ndarray + Trial mean images (trials, rows, cols). + mh : np.ndarray + Each trial's two halves (trials, 2, rows, cols). + u : np.ndarray + The true fields (trials, 2, rows, cols). + a0 : np.ndarray + The rigid starting maps (trials, 2, 3). + """ + h, w = truth.shape + rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) + filled = np.where(np.isnan(truth), 5.0, truth) + m = np.full((n_trials, h, w), np.nan) + mh = np.full((n_trials, 2, h, w), np.nan) + u = np.zeros((n_trials, 2, h, w)) + a0 = np.zeros((n_trials, 2, 3)) + for t in range(n_trials): + lin = np.eye(2) + affine_sd * rng.standard_normal((2, 2)) + tr = 0.6 * rng.standard_normal(2) + u_r = (lin[0, 0] - 1) * rr + lin[0, 1] * cc + tr[0] + u_c = lin[1, 0] * rr + (lin[1, 1] - 1) * cc + tr[1] + if bends: + for comp in (0, 1): + b = ndimage.gaussian_filter( + rng.standard_normal((h, w)), 40, mode="nearest", truncate=5 + ) + b = bend_px * b / b.std() + if comp == 0: + u_r = u_r + b + else: + u_c = u_c + b + u[t, 0], u[t, 1] = u_r, u_c + # the consensus point each trial pixel shows: y = x - U(y) + y_r, y_c = rr.ravel().copy(), cc.ravel().copy() + for _ in range(8): + coords = np.vstack([y_r, y_c]) + ur = ndimage.map_coordinates(u_r, coords, order=1, mode="nearest") + uc = ndimage.map_coordinates(u_c, coords, order=1, mode="nearest") + y_r, y_c = rr.ravel() - ur, cc.ravel() - uc + img = interp2_cubic(filled, y_r, y_c) + img = np.where(np.isnan(img), 5.0, img).reshape(h, w) + for half in range(2): + x = img + 0.2 * np.sqrt(np.maximum(img, 0)) * rng.standard_normal((h, w)) + x[~scan] = np.nan # the scan mask is fixed in the trial's frame + mh[t, half] = x + m[t] = mh[t].mean(axis=0) + c0 = (h // 2 - 1, w // 2 - 1) # MATLAB's round(sz/2), zero-based + a0[t] = [[1, 0, np.round(u_r[c0])], [0, 1, np.round(u_c[c0])]] + return m, mh, u, a0 + + +def field_error( + coords: Callable[[int, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]], + u: np.ndarray, + a0: np.ndarray, + truth: np.ndarray, + scan: np.ndarray, +) -> tuple[float, float]: + """RMS error of fitted maps relative to the trials' mean map. + + Weighted by image structure; and the same for the rigid start. + coords(t, r, c) gives the fitted positions. + + Returns + ------- + fitted : float + Structure-weighted RMS error of the fitted maps. + rigid : float + The same for the rigid start. + """ + n_trials = u.shape[0] + sel = ndimage.binary_erosion(scan, np.ones((5, 5)), border_value=0) + rows, cols = np.nonzero(sel) + est = np.empty((n_trials, rows.size, 2)) + tru = np.empty_like(est) + rig = np.empty_like(est) + for t in range(n_trials): + r_t, c_t = coords(t, rows.astype(float), cols.astype(float)) + est[t] = np.column_stack([r_t - rows, c_t - cols]) + tru[t] = np.column_stack([u[t, 0][sel], u[t, 1][sel]]) + rig[t] = a0[t, :, 2] + sq = np.sqrt(np.fmax(truth, 0)) + g_r, g_c = np.gradient(sq, axis=0), np.gradient(sq, axis=1) + wgt = g_r[sel] ** 2 + g_c[sel] ** 2 + wgt[np.isnan(wgt)] = 0 + + def rel(x: np.ndarray) -> np.ndarray: + """Relative to the trials' mean. + + Returns + ------- + np.ndarray + x minus its mean over trials. + """ + return x - x.mean(axis=0) + + def wrms(e: np.ndarray) -> float: + """Structure-weighted RMS over trials and pixels. + + Returns + ------- + float + The RMS of e, weighted by image structure. + """ + return np.sqrt(np.sum((e**2).sum(axis=2).mean(axis=0) * wgt) / wgt.sum()) + + return wrms(rel(est) - rel(tru)), wrms(rel(rig) - rel(tru)) diff --git a/tests/raster/data/make_matlab_kinetics.m b/tests/raster/data/make_matlab_kinetics.m index 65a494b8..a7514fc1 100644 --- a/tests/raster/data/make_matlab_kinetics.m +++ b/tests/raster/data/make_matlab_kinetics.m @@ -1,55 +1,55 @@ -function make_matlab_kinetics(out) -% Reference values of islocalmax and sourceKinetics/rejectFastSources for -% GIAnT-Python's tests (GIAnT-MATLAB main 5a0673b, read-only). -% Writes a v7.3 .mat; make_matlab_kinetics_h5.py turns it into the test's -% matlab_kinetics.h5: -% make_matlab_kinetics('kinetics_fixture.mat') (GIAnT-MATLAB dependencies on the path) -% python make_matlab_kinetics_h5.py kinetics_fixture.mat matlab_kinetics.h5 -rng(7); -% islocalmax with plateaus and MinSeparation -Y = randi([0 5], 300, 40); -Y(1:100, :) = Y(1:100, :) + 0.001 * randn(100, 40); -seps = [0 1 2 3 5 9.6]; -M = false(numel(seps), size(Y,1), size(Y,2)); -for i = 1:numel(seps) - M(i, :, :) = islocalmax(Y, 2, 'MinSeparation', seps(i)); -end -% kinetics: trials with sensor-like and fast transients, discards -params = struct('tau_s', 0.024, 'analyzeHz', 200, 'minKineticScore', 0.2); -nS = 10; nT = 600; nTr = 3; -tauF = params.tau_s * params.analyzeHz; -E = cell(nTr, 1); -LS = nan(nTr, nS, nT); -for t = 1:nTr - x = 0.3 * randn(nS, nT) + 0.05 * (1:nT) / nT; - for s = 1:nS - on = find(rand(1, nT) < 0.02); - for p = on - a = 3 + 3 * rand; - if s <= 4 - k = exp(-(0:min(40, nT - p)) / tauF); % sensor kinetics - elseif s <= 7 - k = [1 0.3]; % fast transients - k = k(1:min(2, nT - p + 1)); - else - k = exp(-(0:min(40, nT - p)) / (tauF / 3)); % between - end - x(s, p:p + numel(k) - 1) = x(s, p:p + numel(k) - 1) + a * k; - end - end - discard = rand(1, nT) < 0.05; - discard(100:120) = true; - x(:, discard) = nan; - if t == 2 - x(9, :) = nan; % a source without data in one trial - end - E{t}.dF.ls = cat(3, x, randn(nS, nT)); - LS(t, :, :) = x; -end -E{nTr + 1} = []; % a trial without traces -[score, nEvents] = sourceKinetics(E, params); -sources = struct('R', (1:nS)', 'C', (2:nS + 1)', 'V', ones(nS, 1)); -[~, kept, kin] = rejectFastSources(E, sources, params); -keep = ismember((1:nS)', kept.R); -save(out, 'Y', 'seps', 'M', 'LS', 'score', 'nEvents', 'keep', 'kin', '-v7.3'); -end +function make_matlab_kinetics(out) +% Reference values of islocalmax and sourceKinetics/rejectFastSources for +% GIAnT-Python's tests (GIAnT-MATLAB main 5a0673b, read-only). +% Writes a v7.3 .mat; make_matlab_kinetics_h5.py turns it into the test's +% matlab_kinetics.h5: +% make_matlab_kinetics('kinetics_fixture.mat') (GIAnT-MATLAB dependencies on the path) +% python make_matlab_kinetics_h5.py kinetics_fixture.mat matlab_kinetics.h5 +rng(7); +% islocalmax with plateaus and MinSeparation +Y = randi([0 5], 300, 40); +Y(1:100, :) = Y(1:100, :) + 0.001 * randn(100, 40); +seps = [0 1 2 3 5 9.6]; +M = false(numel(seps), size(Y,1), size(Y,2)); +for i = 1:numel(seps) + M(i, :, :) = islocalmax(Y, 2, 'MinSeparation', seps(i)); +end +% kinetics: trials with sensor-like and fast transients, discards +params = struct('tau_s', 0.024, 'analyzeHz', 200, 'minKineticScore', 0.2); +nS = 10; nT = 600; nTr = 3; +tauF = params.tau_s * params.analyzeHz; +E = cell(nTr, 1); +LS = nan(nTr, nS, nT); +for t = 1:nTr + x = 0.3 * randn(nS, nT) + 0.05 * (1:nT) / nT; + for s = 1:nS + on = find(rand(1, nT) < 0.02); + for p = on + a = 3 + 3 * rand; + if s <= 4 + k = exp(-(0:min(40, nT - p)) / tauF); % sensor kinetics + elseif s <= 7 + k = [1 0.3]; % fast transients + k = k(1:min(2, nT - p + 1)); + else + k = exp(-(0:min(40, nT - p)) / (tauF / 3)); % between + end + x(s, p:p + numel(k) - 1) = x(s, p:p + numel(k) - 1) + a * k; + end + end + discard = rand(1, nT) < 0.05; + discard(100:120) = true; + x(:, discard) = nan; + if t == 2 + x(9, :) = nan; % a source without data in one trial + end + E{t}.dF.ls = cat(3, x, randn(nS, nT)); + LS(t, :, :) = x; +end +E{nTr + 1} = []; % a trial without traces +[score, nEvents] = sourceKinetics(E, params); +sources = struct('R', (1:nS)', 'C', (2:nS + 1)', 'V', ones(nS, 1)); +[~, kept, kin] = rejectFastSources(E, sources, params); +keep = ismember((1:nS)', kept.R); +save(out, 'Y', 'seps', 'M', 'LS', 'score', 'nEvents', 'keep', 'kin', '-v7.3'); +end diff --git a/tests/raster/data/make_matlab_kinetics_h5.py b/tests/raster/data/make_matlab_kinetics_h5.py index fe32962e..548b8267 100644 --- a/tests/raster/data/make_matlab_kinetics_h5.py +++ b/tests/raster/data/make_matlab_kinetics_h5.py @@ -1,42 +1,42 @@ -"""Convert make_matlab_kinetics.m's output into matlab_kinetics.h5. - -usage: python make_matlab_kinetics_h5.py kinetics_fixture.mat OUT.h5 - -The MATLAB script saves a v7.3 .mat (HDF5 with MATLAB's dimensions reversed -and vectors as 2-D arrays). This writes the flat datasets the test reads, -in numpy orientation: ``Y`` (rows, n), ``M`` (separations, rows, n), -``seps``, ``LS`` (trials, sources, frames), ``score``, ``nEvents``, -``keep`` (vectors 1-D). A subset of the islocalmax rows is kept (60 with -noise, 60 of whole numbers) to keep the file small. -""" - -import sys - -import h5py -import numpy as np - - -def main(src: str, dst: str) -> None: - """Read the .mat and write the fixture.""" - with h5py.File(src, "r") as f, h5py.File(dst, "w") as g: - y = f["Y"][()].T - m = f["M"][()].transpose(2, 1, 0).astype(np.uint8) - rows = np.r_[0:60, 100:160] - g.attrs["source"] = "make_matlab_kinetics.m (GIAnT-MATLAB main 5a0673b, MATLAB R2024b)" - g["Y"] = y[rows] - g["M"] = m[:, rows] - g["seps"] = f["seps"][()].ravel() - g.create_dataset( - "LS", - data=f["LS"][()].transpose(2, 1, 0), - compression="gzip", - compression_opts=9, - shuffle=True, - ) - g["score"] = f["score"][()].ravel() - g["nEvents"] = f["nEvents"][()].ravel().astype(np.int64) - g["keep"] = f["keep"][()].ravel().astype(np.uint8) - - -if __name__ == "__main__": - main(sys.argv[1], sys.argv[2]) +"""Convert make_matlab_kinetics.m's output into matlab_kinetics.h5. + +usage: python make_matlab_kinetics_h5.py kinetics_fixture.mat OUT.h5 + +The MATLAB script saves a v7.3 .mat (HDF5 with MATLAB's dimensions reversed +and vectors as 2-D arrays). This writes the flat datasets the test reads, +in numpy orientation: Y (rows, n), M (separations, rows, n), +seps, LS (trials, sources, frames), score, nEvents, +keep (vectors 1-D). A subset of the islocalmax rows is kept (60 with +noise, 60 of whole numbers) to keep the file small. +""" + +import sys + +import h5py +import numpy as np + + +def main(src: str, dst: str) -> None: + """Read the .mat and write the fixture.""" + with h5py.File(src, "r") as f, h5py.File(dst, "w") as g: + y = f["Y"][()].T + m = f["M"][()].transpose(2, 1, 0).astype(np.uint8) + rows = np.r_[0:60, 100:160] + g.attrs["source"] = "make_matlab_kinetics.m (GIAnT-MATLAB main 5a0673b, MATLAB R2024b)" + g["Y"] = y[rows] + g["M"] = m[:, rows] + g["seps"] = f["seps"][()].ravel() + g.create_dataset( + "LS", + data=f["LS"][()].transpose(2, 1, 0), + compression="gzip", + compression_opts=9, + shuffle=True, + ) + g["score"] = f["score"][()].ravel() + g["nEvents"] = f["nEvents"][()].ravel().astype(np.int64) + g["keep"] = f["keep"][()].ravel().astype(np.uint8) + + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2]) diff --git a/tests/raster/data/make_matlab_trial_data.m b/tests/raster/data/make_matlab_trial_data.m index daec87c5..07f36f4a 100644 --- a/tests/raster/data/make_matlab_trial_data.m +++ b/tests/raster/data/make_matlab_trial_data.m @@ -1,81 +1,81 @@ -% MATLAB references for GIAnT-Python tests/raster/test_raster_trial_data.py -% (R2024b; nansvd.m is GIAnT-MATLAB main 5a0673b's dependencies/nansvd.m) -rng(7); -out = struct(); - -% smoothdata's moving mean: even, odd and fractional windows -x = [1 nan 3 4 nan nan 7 8 9 10 nan 12 2 5 nan 1]; -w = [4 5 4.6 5.4 3.2]; -out.mm_x = x; out.mm_w = w; out.mm_y = nan(numel(w), numel(x)); -for k = 1:numel(w) - out.mm_y(k, :) = smoothdata(x, 2, 'movmean', w(k), 'omitmissing'); -end - -% medfilt2 with NaN, and the labeled pixels of loadTrial -A = 10 * rand(9, 11); A(rand(size(A)) < 0.2) = nan; -out.med_in = A; out.med_out = medfilt2(A, [3 3]); -lab = medfilt2(A, [3 3]); -out.labeled = double(~isnan(A) & lab > 3 * prctile(lab(~isnan(lab)), 25)); - -% motion upsampling: interp1 pchip with extrapolation -ds = ceil(3:133.58:3000); mot = cumsum(randn(size(ds))) * 0.3; -lines = ceil(1:53.4333:3050); -out.pchip_x = ds; out.pchip_y = mot; out.pchip_q = lines; -out.pchip_v = interp1(ds, mot, lines, 'pchip', 'extrap'); - -% discarded frames at the extraction's frames -d = rand(1, 37) < 0.2; n = 91; -out.disc_in = double(d); -out.disc_out = double(interp1(1:numel(d), double(d(:)), linspace(1, numel(d), n)) > 0); -out.blocks = round(linspace(1, 5633 + 1, ceil(5633 / 600) + 1)); - -% nansvd and the denoised ROI trace of loadTrial -t = 1:300; -D = (rand(12, 1) + 0.5) * (5 + sin(t / 9)) + 0.4 * randn(12, 300) + 3 * rand(12, 1) * cos(t / 23); -D(rand(size(D)) < 0.05) = nan; D(3, :) = nan; D(:, 40:44) = nan; D(7, 1:150) = nan; -[UU, SS, VV, bg] = nansvd(D, 3, 10, 0.33); -roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; -[~, selPC] = max(roiLikeness); -out.svd_d = D; out.svd_s = diag(SS)'; out.svd_bg = bg; out.svd_recon = UU * SS * VV'; -out.svd_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); -D1 = D(5, :); % a one-pixel ROI: fewer components than requested -[UU, SS, VV, bg] = nansvd(D1, 3, 10, 0.33); -roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; -[~, selPC] = max(roiLikeness); -out.svd1_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); - -% the end of loadTrial (processAllTrials_Async.m, after the block loop): -% discards, aberrantly negative samples, gap filling, variance multiplier -IMsel = 5 + randn(6, 2, 120); Finvsel = 1 + rand(6, 120); -IMsel(2, :, :) = nan; % a pixel without any sample -IMsel(3, 1, 20:75) = nan; % a gap longer than the window -IMsel(4, 2, [1:5 100:120]) = nan; % gaps at both ends -IMsel(5, 1, 60) = -40; % an aberrantly negative sample -IMsel(6, :, 30:33) = nan; -Finvsel(squeeze(isnan(IMsel(:, 1, :)))) = nan; -discardFrames = false(1, 48); discardFrames([10 11 30]) = true; -params.baselineWindow_samps = 16; -out.fin_y_in = IMsel; out.fin_finv_in = Finvsel; out.fin_discard_in = double(discardFrames); -out.fin_window = params.baselineWindow_samps; -if numel(discardFrames) > 1 - discard = interp1(1:numel(discardFrames), double(discardFrames(:)), linspace(1, numel(discardFrames), size(IMsel,3)))>0; -else - discard = repmat(any(discardFrames(:)), 1, size(IMsel,3)); -end -IMsel(:,:,discard) = nan; -IMsel(IMsel<-2*std(IMsel,0,3, 'omitmissing')) = nan; -nans = isnan(IMsel); -nanFill = IMsel; -nanFill(all(nans,3)) = 0; -passes = 0; -while any(isnan(nanFill), 'all') - nanFill = smoothdata(nanFill,3,"movmean",params.baselineWindow_samps, 'omitmissing'); - passes = passes + 1; -end -IMsel(nans) = nanFill(nans); -Finvsel(squeeze(nans(:,1,:))) = 1000*mean(Finvsel,'all', 'omitmissing'); -out.fin_y = IMsel; out.fin_finv = Finvsel; out.fin_discard = double(discard); out.fin_passes = passes; -fprintf('passes %d\n', passes); - -save('matlab_trial_data.mat', '-struct', 'out', '-v7'); -disp(out.mm_y); +% MATLAB references for GIAnT-Python tests/raster/test_raster_trial_data.py +% (R2024b; nansvd.m is GIAnT-MATLAB main 5a0673b's dependencies/nansvd.m) +rng(7); +out = struct(); + +% smoothdata's moving mean: even, odd and fractional windows +x = [1 nan 3 4 nan nan 7 8 9 10 nan 12 2 5 nan 1]; +w = [4 5 4.6 5.4 3.2]; +out.mm_x = x; out.mm_w = w; out.mm_y = nan(numel(w), numel(x)); +for k = 1:numel(w) + out.mm_y(k, :) = smoothdata(x, 2, 'movmean', w(k), 'omitmissing'); +end + +% medfilt2 with NaN, and the labeled pixels of loadTrial +A = 10 * rand(9, 11); A(rand(size(A)) < 0.2) = nan; +out.med_in = A; out.med_out = medfilt2(A, [3 3]); +lab = medfilt2(A, [3 3]); +out.labeled = double(~isnan(A) & lab > 3 * prctile(lab(~isnan(lab)), 25)); + +% motion upsampling: interp1 pchip with extrapolation +ds = ceil(3:133.58:3000); mot = cumsum(randn(size(ds))) * 0.3; +lines = ceil(1:53.4333:3050); +out.pchip_x = ds; out.pchip_y = mot; out.pchip_q = lines; +out.pchip_v = interp1(ds, mot, lines, 'pchip', 'extrap'); + +% discarded frames at the extraction's frames +d = rand(1, 37) < 0.2; n = 91; +out.disc_in = double(d); +out.disc_out = double(interp1(1:numel(d), double(d(:)), linspace(1, numel(d), n)) > 0); +out.blocks = round(linspace(1, 5633 + 1, ceil(5633 / 600) + 1)); + +% nansvd and the denoised ROI trace of loadTrial +t = 1:300; +D = (rand(12, 1) + 0.5) * (5 + sin(t / 9)) + 0.4 * randn(12, 300) + 3 * rand(12, 1) * cos(t / 23); +D(rand(size(D)) < 0.05) = nan; D(3, :) = nan; D(:, 40:44) = nan; D(7, 1:150) = nan; +[UU, SS, VV, bg] = nansvd(D, 3, 10, 0.33); +roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; +[~, selPC] = max(roiLikeness); +out.svd_d = D; out.svd_s = diag(SS)'; out.svd_bg = bg; out.svd_recon = UU * SS * VV'; +out.svd_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); +D1 = D(5, :); % a one-pixel ROI: fewer components than requested +[UU, SS, VV, bg] = nansvd(D1, 3, 10, 0.33); +roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; +[~, selPC] = max(roiLikeness); +out.svd1_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); + +% the end of loadTrial (processAllTrials_Async.m, after the block loop): +% discards, aberrantly negative samples, gap filling, variance multiplier +IMsel = 5 + randn(6, 2, 120); Finvsel = 1 + rand(6, 120); +IMsel(2, :, :) = nan; % a pixel without any sample +IMsel(3, 1, 20:75) = nan; % a gap longer than the window +IMsel(4, 2, [1:5 100:120]) = nan; % gaps at both ends +IMsel(5, 1, 60) = -40; % an aberrantly negative sample +IMsel(6, :, 30:33) = nan; +Finvsel(squeeze(isnan(IMsel(:, 1, :)))) = nan; +discardFrames = false(1, 48); discardFrames([10 11 30]) = true; +params.baselineWindow_samps = 16; +out.fin_y_in = IMsel; out.fin_finv_in = Finvsel; out.fin_discard_in = double(discardFrames); +out.fin_window = params.baselineWindow_samps; +if numel(discardFrames) > 1 + discard = interp1(1:numel(discardFrames), double(discardFrames(:)), linspace(1, numel(discardFrames), size(IMsel,3)))>0; +else + discard = repmat(any(discardFrames(:)), 1, size(IMsel,3)); +end +IMsel(:,:,discard) = nan; +IMsel(IMsel<-2*std(IMsel,0,3, 'omitmissing')) = nan; +nans = isnan(IMsel); +nanFill = IMsel; +nanFill(all(nans,3)) = 0; +passes = 0; +while any(isnan(nanFill), 'all') + nanFill = smoothdata(nanFill,3,"movmean",params.baselineWindow_samps, 'omitmissing'); + passes = passes + 1; +end +IMsel(nans) = nanFill(nans); +Finvsel(squeeze(nans(:,1,:))) = 1000*mean(Finvsel,'all', 'omitmissing'); +out.fin_y = IMsel; out.fin_finv = Finvsel; out.fin_discard = double(discard); out.fin_passes = passes; +fprintf('passes %d\n', passes); + +save('matlab_trial_data.mat', '-struct', 'out', '-v7'); +disp(out.mm_y); diff --git a/tests/raster/test_raster_alignment.py b/tests/raster/test_raster_alignment.py index 072de151..04db23e8 100644 --- a/tests/raster/test_raster_alignment.py +++ b/tests/raster/test_raster_alignment.py @@ -1,339 +1,350 @@ -"""Tests of the across-trial alignment of SiLo's plan stage.""" - -from collections.abc import Callable, Sequence - -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import ( - TrialWarp, - align_trials, - dftregistration_clipped, - interp2_linear, - make_consensus_template, - mask_to_consensus, - matlab_round, - template_samples, - warp_trial_image, - xcorr2_nans, -) - -NAN = np.nan - - -def _scene( - shape: tuple[int, int] = (60, 80), n_blobs: int = 25, seed: int = 0 -) -> Callable[..., np.ndarray]: - """Build a smooth image of Gaussian blobs, with a function to shift it.""" - rng = np.random.default_rng(seed) - centres = rng.uniform([8, 8], [shape[0] - 8, shape[1] - 8], (n_blobs, 2)) - amps = rng.uniform(1, 3, n_blobs) - - def render(shift: Sequence[float] | np.ndarray = (0.0, 0.0)) -> np.ndarray: - """Render the scene moved by ``shift``. - - Pixel p shows scene point p - shift. - """ - rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) - im = np.full(shape, 0.2) - for (r0, c0), a in zip(centres, amps): - im += a * np.exp( - -((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * 2.0**2) - ) - return im - - return render - - -def test_matlab_round_halves_away_from_zero() -> None: - """MATLAB rounds 2.5 to 3 and -2.5 to -3. - - The largest double below a half rounds down. - """ - np.testing.assert_array_equal( - matlab_round([2.5, -2.5, 3.5, 0.5, 0.49999999999999994, -0.2]), - [3, -3, 4, 1, 0, 0], - ) - - -def test_interp2_linear_is_matlabs() -> None: - """Values from MATLAB R2024b's interp2 on the same image. - - A point on a grid row or column ignores the next one (so a NaN there does - not spread), fractional points next to a NaN are NaN, outside is NaN. - """ - v = np.array([[1, 2, 3], [4, NAN, 6], [7, 8, 9], [10, 11, 12]], dtype=float) - rr, cc = np.mgrid[:4, :3].astype(float) - np.testing.assert_array_equal(interp2_linear(v, rr, cc), v) - np.testing.assert_array_equal( - interp2_linear(v, rr + 0.25, cc), - [ - [1.75, NAN, 3.75], - [4.75, NAN, 6.75], - [7.75, 8.75, 9.75], - [NAN, NAN, NAN], - ], - ) - np.testing.assert_array_equal( - interp2_linear(v, rr, cc + 0.5), - [ - [1.5, 2.5, NAN], - [NAN, NAN, NAN], - [7.5, 8.5, NAN], - [10.5, 11.5, NAN], - ], - ) - # the last row and column are inside; just beyond is not - np.testing.assert_array_equal( - interp2_linear(v, [3, 0, 0, 3.0000001], [2, 2, 2.0000001, 0]), - [12, 3, NAN, NAN], - ) - assert np.isnan(interp2_linear(v, NAN, 1.0)) - - -def test_xcorr2_nans_finds_shifts() -> None: - """A frame moved by a known amount against the template. - - The motion is the frame's shift, to a fraction of a pixel, and the - correlation is near 1. NaN borders and a NaN hole do not matter. - """ - render = _scene() - template = render() - template[:3] = NAN - template[20:23, 30:34] = NAN - for shift in [(2.0, -3.0), (0.4, 1.7), (-1.3, 0.25)]: - frame = render(shift) - frame[:, -2:] = NAN - centre = matlab_round(shift) - motion, r = xcorr2_nans(frame, template, centre, 4) - np.testing.assert_allclose(motion, shift, atol=0.08) - assert r > 0.99 - # a search that starts away from the shift still finds it - motion, _ = xcorr2_nans(render((2.0, -3.0)), template, (0, 0), 4) - np.testing.assert_allclose(motion, (2.0, -3.0), atol=0.05) - - -def test_xcorr2_nans_edge_of_search_and_errors() -> None: - """A maximum on the edge of the search is returned whole (no parabola). - - Shapes must agree. - """ - render = _scene() - motion, _ = xcorr2_nans(render((3.0, 0.0)), render(), (0, 0), 2) - np.testing.assert_array_equal(motion, [2.0, 0.0]) - with pytest.raises(ValueError, match="frame is"): - xcorr2_nans(np.zeros((4, 5)), np.zeros((5, 4)), (0, 0), 1) - - -def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: - """Where shifted pixels leave the image the mask is rolled as MATLAB's circshift. - - This is the general path; it must agree with the index lookup on an image - where nothing wraps, and run where it does. - """ - render = _scene((30, 40), 12, seed=3) - template, frame = render(), render((1.0, -1.0)) - motion, r = xcorr2_nans(frame, template, (1, -1), 2) - np.testing.assert_allclose(motion, (1.0, -1.0), atol=0.05) - # a centre beyond the margin makes the valid pixels wrap around - wrapped, _ = xcorr2_nans(frame, template, (9, 0), 2) - assert np.isfinite(wrapped).all() - - -def test_dftregistration_clipped_whole_shifts() -> None: - """A circularly shifted image is registered by minus its shift. - - A shift outside the clip window is not found. - """ - rng = np.random.default_rng(1) - ref = rng.normal(size=(64, 48)) - moved = np.roll(ref, (5, -7), axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) - assert out[2:] == (-5, 7) - assert out[0] < 1e-6 # identical up to the shift - far = np.roll(ref, (20, 0), axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(far), 10) - assert abs(out[2]) <= 5 and abs(out[3]) <= 5 - - -def test_dftregistration_clipped_odd_sizes_as_matlab() -> None: - """On an odd axis MATLAB returns a shift of half the axis as its negative alias. - - MATLAB's midpoint test (``rloc > fix(m/2)`` on the one-based index) does - this: values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 - image moved circularly. - """ - rng = np.random.default_rng(4) - matlab = { - (5, 7): { - (-2, 0): (-3, 0), # the alias of +2 on 5 rows - (2, 0): (-2, 0), - (0, 3): (0, -3), - (0, -3): (0, -4), # the alias of +3 on 7 columns - (1, -2): (-1, 2), - }, - (6, 8): { - (-3, 0): (-3, 0), - (3, 0): (-3, 0), - (0, 4): (0, -4), - (0, -4): (0, -4), - }, - } - for shape, cases in matlab.items(): - ref = rng.normal(size=shape) - for moved_by, expect in cases.items(): - moved = np.roll(ref, moved_by, axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) - assert out[2:] == expect, (shape, moved_by) - - -def test_template_samples() -> None: - """Up to 20 kept trials, evenly spaced as MATLAB's round(linspace(1, n, 20)).""" - keep = np.array([True, False, True, True]) - np.testing.assert_array_equal(template_samples(keep), [0, 2, 3]) - many = template_samples(np.ones(50, bool)) - assert many.size == 20 and many[0] == 0 and many[-1] == 49 - # MATLAB: round(linspace(1, 50, 20)) starts 1 4 6 9 11 - np.testing.assert_array_equal(many[:5] + 1, [1, 4, 6, 9, 11]) - - -def test_consensus_template_of_shifted_copies() -> None: - """Copies of one scene are averaged on the reference. - - One image gives itself on the larger canvas. - """ - render = _scene() - shifts = [(0, 0), (1, 0), (0, -2), (1, 1), (-1, 2)] - stack = np.stack([render(s) for s in shifts]) - stack[:, :2] = NAN - template = make_consensus_template(stack, 5) - assert template.shape == (70, 90) - # the reference is one of the copies: the template shows the scene - # moved by that copy's shift (the parabola fit of a whole shift is off - # by a few thousandths of a pixel) - best = min(np.nanmax(np.abs(template[5:-5, 5:-5] - render(s))) for s in shifts) - assert best < 5e-3 - alone = make_consensus_template(stack[:1], 3) - np.testing.assert_array_equal(alone[3:-3, 3:-3], stack[0]) - assert np.isnan(alone[:3]).all() and np.isnan(alone[:, -3:]).all() - - -def test_consensus_template_without_overlap_is_nan() -> None: - """Images that share no pixels give no template.""" - a = np.full((20, 20), NAN) - b = a.copy() - a[:8] = 1.0 - b[12:] = 1.0 - assert np.isnan(make_consensus_template(np.stack([a, b]), 2)).all() - - -def test_trial_warp_coordinates() -> None: - """Shifts and affine maps; MATLAB's one-based affine round-trips.""" - warp = TrialWarp.from_shifts([[0.5, -1.25], [NAN, NAN]]) - np.testing.assert_array_equal(warp.aligned, [True, False]) - assert warp.n_trials == 2 and warp.is_shift(0) - np.testing.assert_array_equal(warp.shift(0), [0.5, -1.25]) - r_t, c_t = warp.coords(0, np.array([0.0, 3.0]), np.array([2.0, 4.0])) - np.testing.assert_array_equal(r_t, [0.5, 3.5]) - np.testing.assert_array_equal(c_t, [0.75, 2.75]) - # MATLAB: [rT; cT] = A * [r; c; 1] in one-based coordinates - a1 = np.array([[[1.01, 0.02, -0.4], [-0.03, 0.98, 0.7]]]) - affine = TrialWarp.from_matlab(a1) - assert not affine.is_shift(0) - with pytest.raises(ValueError, match="not a shift"): - affine.shift(0) - np.testing.assert_allclose(affine.to_matlab(), a1, atol=1e-15) - r_t, c_t = affine.coords(0, 4.0, 9.0) - expect = a1[0] @ [5.0, 10.0, 1.0] - 1 - np.testing.assert_allclose([r_t, c_t], expect, atol=1e-12) - # a shift is the same in both conventions - np.testing.assert_array_equal( - TrialWarp.from_shifts([[0.5, -1.25]]).to_matlab()[0, :, 2], - [0.5, -1.25], - ) - - -def test_patchwise_warp_is_not_a_shift() -> None: - """A warp with patch centres is not a shift, whatever its affine part. - - It maps through its field (zero displacements: the identity). - """ - nodes = np.array([[0, 0], [5, 1], [2, 9.0]]) - warp = TrialWarp(np.eye(2, 3)[None], nodes=nodes, sigma=3.0) - assert not warp.is_shift(0) and warp.is_patchwise - r, c = warp.coords(0, np.array([1.5, 3.0]), np.array([2.0, 7.0])) - np.testing.assert_allclose(r, [1.5, 3.0], atol=1e-12) - np.testing.assert_allclose(c, [2.0, 7.0], atol=1e-12) - - -def test_warp_trial_image() -> None: - """A whole shift moves the image exactly (NaN where it leaves the trial's image). - - Channels are resampled alike; fractional shifts interpolate. - """ - rng = np.random.default_rng(2) - im = rng.normal(size=(6, 7)) - warp = TrialWarp.from_shifts([[1.0, -2.0], [0.5, 0.0]]) - out = warp_trial_image(im, warp, 0) - np.testing.assert_array_equal(out[:5, 2:], im[1:, :5]) - assert np.isnan(out[5]).all() and np.isnan(out[:, :2]).all() - two = warp_trial_image(np.stack([im, 2 * im], axis=2), warp, 0) - np.testing.assert_array_equal(two[:, :, 0], out) - np.testing.assert_array_equal(two[:, :, 1], 2 * out) - half = warp_trial_image(im, warp, 1) - np.testing.assert_allclose(half[:5], (im[:5] + im[1:]) / 2) - with pytest.raises(ValueError, match="nearest"): - warp_trial_image(im, warp, 0, method="nearest") - - -def test_align_trials_recovers_shifts() -> None: - """Trials that show one scene at known offsets are aligned to each other. - - They agree to within a tenth of a pixel; trials that are not kept, or - without an activity image, are left out. - """ - render = _scene((70, 90), 30, seed=5) - true = np.array([[0.0, 0.0], [1.3, -0.6], [-2.2, 1.9], [0.4, 3.1], [0, 0], [0, 0]]) - m = np.stack([render(s) for s in true]) - m[:, :, :4] = NAN - act = np.ones(m.shape) - act[5] = NAN # no activity image: not aligned - keep = np.array([True, True, True, True, False, True]) - res = align_trials(m, act, keep, max_shift=5) - assert res.template.shape == (80, 100) - np.testing.assert_array_equal(res.samples, [0, 1, 2, 3, 5]) - assert np.isnan(res.shifts[4:]).all() and np.isnan(res.corr[4:]).all() - # shifts are relative to the template's reference trial - rel = res.shifts[:4] - res.shifts[0] - np.testing.assert_allclose(rel, true[:4] - true[0], atol=0.1) - assert (res.corr[:4] > 0.99).all() - with pytest.raises(ValueError, match="no trials"): - align_trials(m, act, np.zeros(6, bool)) - - -def test_mask_to_consensus() -> None: - """A mask drawn on a trial moves by minus the trial's shift. - - The shift is rounded as MATLAB's shiftRoiData (halves away from zero); - pixels leaving the frame are dropped; an unknown or unaligned trial only - crops or pads; an affine map takes the nearest trial pixel - (roisToConsensusFrame). - """ - mask = np.zeros((6, 8), bool) - mask[2, 3] = mask[5, 7] = True - warp = TrialWarp.from_shifts([[1.4, -2.5], [NAN, NAN], [0.0, 0.0], [-0.5, 0.5]]) - out = mask_to_consensus(mask, warp, 0, (6, 8)) - # consensus (r, c) is trial (r + 1.4, c - 2.5): the mask moves by - # round(-1.4) = -1 rows and round(2.5) = 3 columns - assert out.sum() == 1 and out[1, 6] - half = mask_to_consensus(mask, warp, 3, (6, 8)) - assert half.sum() == 1 and half[3, 2] # +1 row, -1 column - np.testing.assert_array_equal(mask_to_consensus(mask, warp, 2, (6, 8)), mask) - for trial in (None, 1): - padded = mask_to_consensus(mask, warp, trial, (7, 7)) - assert padded.shape == (7, 7) and padded.sum() == 1 and padded[2, 3] - # an affine map that is nearly the shift (1, -2) of trial 0 - affine = TrialWarp([[[1.0, 1e-9, 1.0], [0.0, 1.0, -2.0]]]) - assert not affine.is_shift(0) - moved = mask_to_consensus(mask, affine, 0, (6, 8)) - assert moved.sum() == 1 and moved[1, 5] +"""Tests of the across-trial alignment of SiLo's plan stage.""" + +from collections.abc import Callable, Sequence + +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import ( + TrialWarp, + align_trials, + dftregistration_clipped, + interp2_linear, + make_consensus_template, + mask_to_consensus, + matlab_round, + template_samples, + warp_trial_image, + xcorr2_nans, +) + +NAN = np.nan + + +def _scene( + shape: tuple[int, int] = (60, 80), n_blobs: int = 25, seed: int = 0 +) -> Callable[..., np.ndarray]: + """Build a smooth image of Gaussian blobs, with a function to shift it. + + Returns + ------- + Callable + render(shift), the scene image moved by shift. + """ + rng = np.random.default_rng(seed) + centres = rng.uniform([8, 8], [shape[0] - 8, shape[1] - 8], (n_blobs, 2)) + amps = rng.uniform(1, 3, n_blobs) + + def render(shift: Sequence[float] | np.ndarray = (0.0, 0.0)) -> np.ndarray: + """Render the scene moved by shift. + + Pixel p shows scene point p - shift. + + Returns + ------- + np.ndarray + The scene image of shape, moved by shift. + """ + rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) + im = np.full(shape, 0.2) + for (r0, c0), a in zip(centres, amps): + im += a * np.exp( + -((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * 2.0**2) + ) + return im + + return render + + +def test_matlab_round_halves_away_from_zero() -> None: + """MATLAB rounds 2.5 to 3 and -2.5 to -3. + + The largest double below a half rounds down. + """ + np.testing.assert_array_equal( + matlab_round([2.5, -2.5, 3.5, 0.5, 0.49999999999999994, -0.2]), + [3, -3, 4, 1, 0, 0], + ) + + +def test_interp2_linear_is_matlabs() -> None: + """Values from MATLAB R2024b's interp2 on the same image. + + A point on a grid row or column ignores the next one (so a NaN there does + not spread), fractional points next to a NaN are NaN, outside is NaN. + """ + v = np.array([[1, 2, 3], [4, NAN, 6], [7, 8, 9], [10, 11, 12]], dtype=float) + rr, cc = np.mgrid[:4, :3].astype(float) + np.testing.assert_array_equal(interp2_linear(v, rr, cc), v) + np.testing.assert_array_equal( + interp2_linear(v, rr + 0.25, cc), + [ + [1.75, NAN, 3.75], + [4.75, NAN, 6.75], + [7.75, 8.75, 9.75], + [NAN, NAN, NAN], + ], + ) + np.testing.assert_array_equal( + interp2_linear(v, rr, cc + 0.5), + [ + [1.5, 2.5, NAN], + [NAN, NAN, NAN], + [7.5, 8.5, NAN], + [10.5, 11.5, NAN], + ], + ) + # the last row and column are inside; just beyond is not + np.testing.assert_array_equal( + interp2_linear(v, [3, 0, 0, 3.0000001], [2, 2, 2.0000001, 0]), + [12, 3, NAN, NAN], + ) + assert np.isnan(interp2_linear(v, NAN, 1.0)) + + +def test_xcorr2_nans_finds_shifts() -> None: + """A frame moved by a known amount against the template. + + The motion is the frame's shift, to a fraction of a pixel, and the + correlation is near 1. NaN borders and a NaN hole do not matter. + """ + render = _scene() + template = render() + template[:3] = NAN + template[20:23, 30:34] = NAN + for shift in [(2.0, -3.0), (0.4, 1.7), (-1.3, 0.25)]: + frame = render(shift) + frame[:, -2:] = NAN + centre = matlab_round(shift) + motion, r = xcorr2_nans(frame, template, centre, 4) + np.testing.assert_allclose(motion, shift, atol=0.08) + assert r > 0.99 + # a search that starts away from the shift still finds it + motion, _ = xcorr2_nans(render((2.0, -3.0)), template, (0, 0), 4) + np.testing.assert_allclose(motion, (2.0, -3.0), atol=0.05) + + +def test_xcorr2_nans_edge_of_search_and_errors() -> None: + """A maximum on the edge of the search is returned whole (no parabola). + + Shapes must agree. + """ + render = _scene() + motion, _ = xcorr2_nans(render((3.0, 0.0)), render(), (0, 0), 2) + np.testing.assert_array_equal(motion, [2.0, 0.0]) + with pytest.raises(ValueError, match="frame is"): + xcorr2_nans(np.zeros((4, 5)), np.zeros((5, 4)), (0, 0), 1) + + +def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: + """Where shifted pixels leave the image the mask is rolled as MATLAB's circshift. + + This is the general path; it must agree with the index lookup on an image + where nothing wraps, and run where it does. + """ + render = _scene((30, 40), 12, seed=3) + template, frame = render(), render((1.0, -1.0)) + motion, r = xcorr2_nans(frame, template, (1, -1), 2) + np.testing.assert_allclose(motion, (1.0, -1.0), atol=0.05) + # a centre beyond the margin makes the valid pixels wrap around + wrapped, _ = xcorr2_nans(frame, template, (9, 0), 2) + assert np.isfinite(wrapped).all() + + +def test_dftregistration_clipped_whole_shifts() -> None: + """A circularly shifted image is registered by minus its shift. + + A shift outside the clip window is not found. + """ + rng = np.random.default_rng(1) + ref = rng.normal(size=(64, 48)) + moved = np.roll(ref, (5, -7), axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) + assert out[2:] == (-5, 7) + assert out[0] < 1e-6 # identical up to the shift + far = np.roll(ref, (20, 0), axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(far), 10) + assert abs(out[2]) <= 5 and abs(out[3]) <= 5 + + +def test_dftregistration_clipped_odd_sizes_as_matlab() -> None: + """On an odd axis MATLAB returns a shift of half the axis as its negative alias. + + MATLAB's midpoint test (rloc > fix(m/2) on the one-based index) does + this: values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 + image moved circularly. + """ + rng = np.random.default_rng(4) + matlab = { + (5, 7): { + (-2, 0): (-3, 0), # the alias of +2 on 5 rows + (2, 0): (-2, 0), + (0, 3): (0, -3), + (0, -3): (0, -4), # the alias of +3 on 7 columns + (1, -2): (-1, 2), + }, + (6, 8): { + (-3, 0): (-3, 0), + (3, 0): (-3, 0), + (0, 4): (0, -4), + (0, -4): (0, -4), + }, + } + for shape, cases in matlab.items(): + ref = rng.normal(size=shape) + for moved_by, expect in cases.items(): + moved = np.roll(ref, moved_by, axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) + assert out[2:] == expect, (shape, moved_by) + + +def test_template_samples() -> None: + """Up to 20 kept trials, evenly spaced as MATLAB's round(linspace(1, n, 20)).""" + keep = np.array([True, False, True, True]) + np.testing.assert_array_equal(template_samples(keep), [0, 2, 3]) + many = template_samples(np.ones(50, bool)) + assert many.size == 20 and many[0] == 0 and many[-1] == 49 + # MATLAB: round(linspace(1, 50, 20)) starts 1 4 6 9 11 + np.testing.assert_array_equal(many[:5] + 1, [1, 4, 6, 9, 11]) + + +def test_consensus_template_of_shifted_copies() -> None: + """Copies of one scene are averaged on the reference. + + One image gives itself on the larger canvas. + """ + render = _scene() + shifts = [(0, 0), (1, 0), (0, -2), (1, 1), (-1, 2)] + stack = np.stack([render(s) for s in shifts]) + stack[:, :2] = NAN + template = make_consensus_template(stack, 5) + assert template.shape == (70, 90) + # the reference is one of the copies: the template shows the scene + # moved by that copy's shift (the parabola fit of a whole shift is off + # by a few thousandths of a pixel) + best = min(np.nanmax(np.abs(template[5:-5, 5:-5] - render(s))) for s in shifts) + assert best < 5e-3 + alone = make_consensus_template(stack[:1], 3) + np.testing.assert_array_equal(alone[3:-3, 3:-3], stack[0]) + assert np.isnan(alone[:3]).all() and np.isnan(alone[:, -3:]).all() + + +def test_consensus_template_without_overlap_is_nan() -> None: + """Images that share no pixels give no template.""" + a = np.full((20, 20), NAN) + b = a.copy() + a[:8] = 1.0 + b[12:] = 1.0 + assert np.isnan(make_consensus_template(np.stack([a, b]), 2)).all() + + +def test_trial_warp_coordinates() -> None: + """Shifts and affine maps; MATLAB's one-based affine round-trips.""" + warp = TrialWarp.from_shifts([[0.5, -1.25], [NAN, NAN]]) + np.testing.assert_array_equal(warp.aligned, [True, False]) + assert warp.n_trials == 2 and warp.is_shift(0) + np.testing.assert_array_equal(warp.shift(0), [0.5, -1.25]) + r_t, c_t = warp.coords(0, np.array([0.0, 3.0]), np.array([2.0, 4.0])) + np.testing.assert_array_equal(r_t, [0.5, 3.5]) + np.testing.assert_array_equal(c_t, [0.75, 2.75]) + # MATLAB: [rT; cT] = A * [r; c; 1] in one-based coordinates + a1 = np.array([[[1.01, 0.02, -0.4], [-0.03, 0.98, 0.7]]]) + affine = TrialWarp.from_matlab(a1) + assert not affine.is_shift(0) + with pytest.raises(ValueError, match="not a shift"): + affine.shift(0) + np.testing.assert_allclose(affine.to_matlab(), a1, atol=1e-15) + r_t, c_t = affine.coords(0, 4.0, 9.0) + expect = a1[0] @ [5.0, 10.0, 1.0] - 1 + np.testing.assert_allclose([r_t, c_t], expect, atol=1e-12) + # a shift is the same in both conventions + np.testing.assert_array_equal( + TrialWarp.from_shifts([[0.5, -1.25]]).to_matlab()[0, :, 2], + [0.5, -1.25], + ) + + +def test_patchwise_warp_is_not_a_shift() -> None: + """A warp with patch centres is not a shift, whatever its affine part. + + It maps through its field (zero displacements: the identity). + """ + nodes = np.array([[0, 0], [5, 1], [2, 9.0]]) + warp = TrialWarp(np.eye(2, 3)[None], nodes=nodes, sigma=3.0) + assert not warp.is_shift(0) and warp.is_patchwise + r, c = warp.coords(0, np.array([1.5, 3.0]), np.array([2.0, 7.0])) + np.testing.assert_allclose(r, [1.5, 3.0], atol=1e-12) + np.testing.assert_allclose(c, [2.0, 7.0], atol=1e-12) + + +def test_warp_trial_image() -> None: + """A whole shift moves the image exactly (NaN where it leaves the trial's image). + + Channels are resampled alike; fractional shifts interpolate. + """ + rng = np.random.default_rng(2) + im = rng.normal(size=(6, 7)) + warp = TrialWarp.from_shifts([[1.0, -2.0], [0.5, 0.0]]) + out = warp_trial_image(im, warp, 0) + np.testing.assert_array_equal(out[:5, 2:], im[1:, :5]) + assert np.isnan(out[5]).all() and np.isnan(out[:, :2]).all() + two = warp_trial_image(np.stack([im, 2 * im], axis=2), warp, 0) + np.testing.assert_array_equal(two[:, :, 0], out) + np.testing.assert_array_equal(two[:, :, 1], 2 * out) + half = warp_trial_image(im, warp, 1) + np.testing.assert_allclose(half[:5], (im[:5] + im[1:]) / 2) + with pytest.raises(ValueError, match="nearest"): + warp_trial_image(im, warp, 0, method="nearest") + + +def test_align_trials_recovers_shifts() -> None: + """Trials that show one scene at known offsets are aligned to each other. + + They agree to within a tenth of a pixel; trials that are not kept, or + without an activity image, are left out. + """ + render = _scene((70, 90), 30, seed=5) + true = np.array([[0.0, 0.0], [1.3, -0.6], [-2.2, 1.9], [0.4, 3.1], [0, 0], [0, 0]]) + m = np.stack([render(s) for s in true]) + m[:, :, :4] = NAN + act = np.ones(m.shape) + act[5] = NAN # no activity image: not aligned + keep = np.array([True, True, True, True, False, True]) + res = align_trials(m, act, keep, max_shift=5) + assert res.template.shape == (80, 100) + np.testing.assert_array_equal(res.samples, [0, 1, 2, 3, 5]) + assert np.isnan(res.shifts[4:]).all() and np.isnan(res.corr[4:]).all() + # shifts are relative to the template's reference trial + rel = res.shifts[:4] - res.shifts[0] + np.testing.assert_allclose(rel, true[:4] - true[0], atol=0.1) + assert (res.corr[:4] > 0.99).all() + with pytest.raises(ValueError, match="no trials"): + align_trials(m, act, np.zeros(6, bool)) + + +def test_mask_to_consensus() -> None: + """A mask drawn on a trial moves by minus the trial's shift. + + The shift is rounded as MATLAB's shiftRoiData (halves away from zero); + pixels leaving the frame are dropped; an unknown or unaligned trial only + crops or pads; an affine map takes the nearest trial pixel + (roisToConsensusFrame). + """ + mask = np.zeros((6, 8), bool) + mask[2, 3] = mask[5, 7] = True + warp = TrialWarp.from_shifts([[1.4, -2.5], [NAN, NAN], [0.0, 0.0], [-0.5, 0.5]]) + out = mask_to_consensus(mask, warp, 0, (6, 8)) + # consensus (r, c) is trial (r + 1.4, c - 2.5): the mask moves by + # round(-1.4) = -1 rows and round(2.5) = 3 columns + assert out.sum() == 1 and out[1, 6] + half = mask_to_consensus(mask, warp, 3, (6, 8)) + assert half.sum() == 1 and half[3, 2] # +1 row, -1 column + np.testing.assert_array_equal(mask_to_consensus(mask, warp, 2, (6, 8)), mask) + for trial in (None, 1): + padded = mask_to_consensus(mask, warp, trial, (7, 7)) + assert padded.shape == (7, 7) and padded.sum() == 1 and padded[2, 3] + # an affine map that is nearly the shift (1, -2) of trial 0 + affine = TrialWarp([[[1.0, 1e-9, 1.0], [0.0, 1.0, -2.0]]]) + assert not affine.is_shift(0) + moved = mask_to_consensus(mask, affine, 0, (6, 8)) + assert moved.sum() == 1 and moved[1, 5] diff --git a/tests/raster/test_raster_alignment_modes.py b/tests/raster/test_raster_alignment_modes.py index 94ab1699..db1c94f2 100644 --- a/tests/raster/test_raster_alignment_modes.py +++ b/tests/raster/test_raster_alignment_modes.py @@ -1,299 +1,315 @@ -"""Tests of the affine and patchwise across-trial alignments and of their helpers. - -The alignment tests are ports of GIAnT-MATLAB's ``TestTrialAlignment.m``. -""" - -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import ( - CubicInterpolant, - TrialWarp, - align_trials_affine, - align_trials_patchwise, - interp2_cubic, - interp2_linear, - kmeans, - make_patches, - matlab_gradient, - patch_field_apply, - patch_field_matrix, - warp_image_affine, - warp_trial_image, -) -from giant_python.extraction.raster.plan import PlanParams - -from .alignment_synthetic import field_error, neuron, trials - - -def test_cubic_reproduces_quadratics_and_grid_values() -> None: - """Keys' convolution with MATLAB's boundary rows is exact for quadratics. - - Also next to the edges, and returns the image on the grid; NaN outside - the image. - """ - rng = np.random.default_rng(0) - rr, cc = np.mgrid[0:9, 0:11].astype(float) - - def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: - """Evaluate a quadratic surface.""" - return 1 + 0.3 * r - 0.2 * c + 0.05 * r * r - 0.04 * r * c + 0.02 * c**2 - - im = f(rr, cc) - r = rng.uniform(0, 8, 500) - c = rng.uniform(0, 10, 500) - np.testing.assert_allclose(interp2_cubic(im, r, c), f(r, c), atol=1e-12) - np.testing.assert_allclose(interp2_cubic(im, rr, cc), im, atol=1e-12) - out = interp2_cubic(im, np.array([-0.1, 8.1, 3.0]), np.array([1, 1, 10.5])) - assert np.isnan(out).all() - - -def test_cubic_nan_reaches_its_whole_stencil() -> None: - """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN. - - Also a grid point next to it (MATLAB's interp2), unlike linear - interpolation; the cubic warp falls back to linear there. - """ - im = np.arange(80, dtype=float).reshape(8, 10) - im[4, 5] = np.nan - assert np.isnan(interp2_cubic(im, 4.0, 4.0)) # on the grid, next to it - assert np.isnan(interp2_cubic(im, 2.5, 6.5)) # stencil rows 2-5 - assert not np.isnan(interp2_cubic(im, 1.5, 6.5)) - assert interp2_linear(im, 4.0, 4.0) == im[4, 4] - a = np.array([[1.0, 0, 0.3], [0, 1, -0.6]]) - lin = warp_image_affine(im, a, "linear") - cub = warp_image_affine(im, a, "cubic") - np.testing.assert_array_equal(np.isnan(cub), np.isnan(lin)) - - -def test_gradient_is_matlabs() -> None: - """Central differences inside, one-sided differences at the edges.""" - im = np.array([[0.0, 1, 4, 9], [1, 3, 5, 7], [2, 2, 2, 2]]) - g_r, g_c = matlab_gradient(im) - np.testing.assert_array_equal(g_c[0], [1, 2, 4, 5]) - np.testing.assert_array_equal(g_r[:, 0], [1, 1, 1]) - np.testing.assert_array_equal(g_r[1], [1, 0.5, -1, -3.5]) - - -def test_field_reproduces_affine_map() -> None: - """Displacements at the centres that follow an affine map give that map everywhere. - - Also far outside the centres. - """ - rng = np.random.default_rng(1) - nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) - a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) - d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T - cc, rr = np.meshgrid(np.linspace(-50, 550, 61), np.linspace(-50, 350, 41)) - u = patch_field_matrix(nodes, 30, rr, cc)[0] @ d - pts = np.column_stack([rr.ravel(), cc.ravel()]) - u_a = (a[:, :2] @ pts.T + a[:, 2:3] - pts.T).T - assert np.abs(u - u_a).max() < 1e-9 - warp = TrialWarp(a[None], nodes, 30.0, d[None]) - im = rng.random((300, 500)) - out = warp_trial_image(im, warp, 0) - ref = warp_image_affine(im, a) - np.testing.assert_array_equal(np.isnan(out), np.isnan(ref)) - assert np.nanmax(np.abs(out - ref)) < 1e-9 - - -def test_field_apply_matches_field_matrix() -> None: - """Evaluating a bent field without the field matrix gives the same displacements. - - Also with fewer than 3 centres (their mean). - """ - rng = np.random.default_rng(2) - nodes = np.column_stack([rng.random(40) * 200 + 50, rng.random(40) * 400 + 50]) - a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) - d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T - d = d + 0.4 * rng.standard_normal(d.shape) - r, c = rng.random(5000) * 300, rng.random(5000) * 500 - np.testing.assert_allclose( - patch_field_apply(nodes, 25, r, c, d), - patch_field_matrix(nodes, 25, r, c)[0] @ d, - atol=1e-10, - ) - np.testing.assert_allclose( - patch_field_apply(nodes[:2], 25, r, c, d[:2]), - patch_field_matrix(nodes[:2], 25, r, c)[0] @ d[:2], - atol=1e-10, - ) - - -def test_inverse_undoes_bent_field() -> None: - """trialWarpInverse: back to the consensus points to 1e-5 px.""" - rng = np.random.default_rng(3) - nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) - a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) - d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T - d = d + 0.4 * rng.standard_normal(d.shape) - warp = TrialWarp(a[None], nodes, 30.0, d[None]) - r0, c0 = rng.random(1000) * 300, rng.random(1000) * 500 - r_t, c_t = warp.coords(0, r0, c0) - r1, c1 = warp.inverse(0, r_t, c_t) - assert max(np.abs(r1 - r0).max(), np.abs(c1 - c0).max()) < 1e-5 - rigid = TrialWarp.from_shifts([[0.25, -1.5]]) - r2, c2 = rigid.inverse(0, np.array([3.0]), np.array([4.0])) - assert (r2[0], c2[0]) == (2.75, 5.5) - - -def test_matlab_conversion_of_a_field() -> None: - """MATLAB's one-based centres and affine maps convert to zero-based. - - Displacements stay; the map of a point moves with the base. - """ - rng = np.random.default_rng(4) - nodes1 = np.column_stack([rng.random(8) * 50 + 10, rng.random(8) * 80 + 10]) - a1 = np.array([[[1.002, 0.001, 0.4], [0.0, 0.999, -0.3]]]) - d = 0.3 * rng.standard_normal((1, 8, 2)) - warp = TrialWarp.from_matlab(a1, nodes1, 12.0, d) - np.testing.assert_allclose(warp.nodes, nodes1 - 1) - r0 = rng.random(50) * 60 - c0 = rng.random(50) * 90 - r_t, c_t = warp.coords(0, r0, c0) - one = TrialWarp(a1, nodes1, 12.0, d) # read as zero-based: one-based maps - r1, c1 = one.coords(0, r0 + 1, c0 + 1) - np.testing.assert_allclose(r_t, r1 - 1, atol=1e-12) - np.testing.assert_allclose(c_t, c1 - 1, atol=1e-12) - np.testing.assert_allclose(warp.to_matlab(), a1) - - -def test_kmeans_finds_separated_clusters() -> None: - """Three well separated clusters are found from k-means++ starts. - - An empty cluster restarts at the farthest point. - """ - rng = np.random.default_rng(5) - centres = np.array([[0.0, 0], [50, 0], [0, 50]]) - x = np.vstack([c + rng.standard_normal((200, 2)) for c in centres]) - labels, cen = kmeans(x, 3, rng, replicates=3) - found = cen[np.argsort(cen[:, 0] + 2 * cen[:, 1])] - np.testing.assert_allclose(found, centres, atol=0.5) - assert np.bincount(labels).tolist() == [200, 200, 200] - start = np.array([[0.0, 0], [0.5, 0], [1000, 1000]]) - labels, cen = kmeans(x, 3, start=start) - assert np.bincount(labels, minlength=3).min() > 0 - # the farthest point of a singleton is not moved (that would empty it) - pts = np.array([[0.0, 0], [10, 0], [11, 0]]) - labels, cen = kmeans(pts, 3, start=np.array([[5.0, 0], [10.5, 0], [1e3, 0]])) - assert np.isfinite(cen).all() - assert sorted(np.bincount(labels, minlength=3)) == [1, 1, 1] - - -def test_patch_size_is_bounded() -> None: - """A patch needs at least one pixel; one pixel per patch at most.""" - valid = np.zeros((6, 8), bool) - valid[1:4, 2:6] = True - with pytest.raises(ValueError, match="patch_px"): - make_patches(valid, 0.5) - patch, nodes = make_patches(valid, 1) - assert nodes.shape[0] == valid.sum() - assert sorted(patch[valid]) == list(range(1, valid.sum() + 1)) - with pytest.raises(ValueError, match="align_patch_px"): - PlanParams(align_patch_px=0.5) - - -def test_patches_have_their_size() -> None: - """About patch_px pixels each, none under half of it, centred on their pixels.""" - valid = np.zeros((120, 160), bool) - valid[10:100, 20:150] = True - valid[40:60, 60:90] = False - patch, nodes = make_patches(valid, 900) - n = np.bincount(patch[valid], minlength=nodes.shape[0] + 1)[1:] - assert (patch[~valid] == 0).all() and n.min() >= 450 - assert abs(n.size - valid.sum() / 900) <= 2 - rows, cols = np.nonzero(valid) - for k in range(nodes.shape[0]): - sel = patch[rows, cols] == k + 1 - np.testing.assert_allclose(nodes[k], [rows[sel].mean(), cols[sel].mean()], atol=1e-9) - - -@pytest.fixture(scope="module") -def synthetic_neuron() -> tuple[np.ndarray, np.ndarray, np.random.Generator]: - """Build the labeled neuron of MATLAB's test and its scanned pixels.""" - rng = np.random.default_rng(1) - truth, scan = neuron(rng) - return truth, scan, rng - - -def test_affine_recovers_known_maps( - synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], -) -> None: - """The relative maps between trials are recovered to 0.05 px. - - Much better than the rigid start. - """ - truth, scan, rng = synthetic_neuron - m, _, u, a0 = trials(truth, scan, False, rng) - a, info = align_trials_affine(m, a0) - warp = TrialWarp(a) - err, err0 = field_error(warp.coords, u, a0, truth, scan) - assert err < 0.05 and err < err0 / 5 - assert np.all(info.corr > 0.9) - - -def test_patchwise_recovers_bends( - synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], -) -> None: - """Smooth bends (over ~40 px) on top of affine maps are recovered to 0.08 px. - - Much better than the rigid start and beyond an affine fit; no patch under - half the target size. - """ - truth, scan, rng = synthetic_neuron - m, mh, u, a0 = trials(truth, scan, True, rng) - fit, info = align_trials_patchwise(m, a0, mh, 1500) - warp = TrialWarp(fit.affine, fit.nodes, fit.sigma, fit.disp, fit.patch) - err, err0 = field_error(warp.coords, u, a0, truth, scan) - assert err < 0.08 and err < err0 / 3 - assert fit.nodes.shape[0] > 10 and info.n_px.min() >= 750 - a, _ = align_trials_affine(m, a0) - err_a, _ = field_error(TrialWarp(a).coords, u, a0, truth, scan) - assert err < 0.7 * err_a - # the plane is the field's affine part: equal at the plane's points - plane = TrialWarp(fit.affine) - np.testing.assert_allclose(np.mean(fit.affine[:, :, :2], axis=0), np.eye(2), atol=1e-3) - assert np.isfinite(plane.coords(0, 1.0, 1.0)[0]) - - -def test_patchwise_adds_nothing_without_bends( - synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], -) -> None: - """Affine maps only: the patchwise field is as good as the affine fit.""" - truth, scan, rng = synthetic_neuron - m, mh, u, a0 = trials(truth, scan, False, rng) - fit, _ = align_trials_patchwise(m, a0, mh, 1500) - warp = TrialWarp(fit.affine, fit.nodes, fit.sigma, fit.disp) - err, _ = field_error(warp.coords, u, a0, truth, scan) - assert err < 0.05 - - -def test_patchwise_given_patches_and_without_halves() -> None: - """Given its own patches back, the fit is the same. - - Without halves the departures are kept as fitted (weight 1) and the fit - still runs. - """ - rng = np.random.default_rng(7) - truth, scan = neuron(rng, (70, 90)) - m, mh, _, a0 = trials(truth, scan, True, rng, n_trials=3) - fit, info = align_trials_patchwise(m, a0, mh, 600, n_rounds=1) - again, _ = align_trials_patchwise(m, a0, mh, 600, n_rounds=1, patches=(fit.patch, fit.nodes)) - np.testing.assert_array_equal(again.disp, fit.disp) - assert np.all((info.weight >= 0) & (info.weight <= 1)) - plain, plain_info = align_trials_patchwise(m, a0, None, 600, n_rounds=1) - np.testing.assert_array_equal(plain_info.weight, 1.0) - assert np.isnan(plain_info.noise_sd).all() - assert np.isfinite(plain.disp).all() - - -def test_too_few_trials_or_pixels_keep_the_start() -> None: - """With fewer than 2 trials to fit, the maps are the starting ones.""" - m = np.random.default_rng(6).random((2, 30, 40)) - a0 = np.array([np.eye(2, 3), np.full((2, 3), np.nan)]) - a, info = align_trials_affine(m, a0) - np.testing.assert_array_equal(a, a0) - fit, _ = align_trials_patchwise(m, a0) - assert fit.nodes.shape[0] == 0 - np.testing.assert_array_equal(fit.affine, a0) - assert CubicInterpolant(m[0]).shape == (30, 40) +"""Tests of the affine and patchwise across-trial alignments and of their helpers. + +The alignment tests are ports of GIAnT-MATLAB's TestTrialAlignment.m. +""" + +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import ( + CubicInterpolant, + TrialWarp, + align_trials_affine, + align_trials_patchwise, + interp2_cubic, + interp2_linear, + kmeans, + make_patches, + matlab_gradient, + patch_field_apply, + patch_field_matrix, + warp_image_affine, + warp_trial_image, +) +from giant_python.extraction.raster.plan import PlanParams + +from .alignment_synthetic import field_error, neuron, trials + + +def test_cubic_reproduces_quadratics_and_grid_values() -> None: + """Keys' convolution with MATLAB's boundary rows is exact for quadratics. + + Also next to the edges, and returns the image on the grid; NaN outside + the image. + """ + rng = np.random.default_rng(0) + rr, cc = np.mgrid[0:9, 0:11].astype(float) + + def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: + """Evaluate a quadratic surface. + + Returns + ------- + np.ndarray + The surface's values at rows r and columns c. + """ + return 1 + 0.3 * r - 0.2 * c + 0.05 * r * r - 0.04 * r * c + 0.02 * c**2 + + im = f(rr, cc) + r = rng.uniform(0, 8, 500) + c = rng.uniform(0, 10, 500) + np.testing.assert_allclose(interp2_cubic(im, r, c), f(r, c), atol=1e-12) + np.testing.assert_allclose(interp2_cubic(im, rr, cc), im, atol=1e-12) + out = interp2_cubic(im, np.array([-0.1, 8.1, 3.0]), np.array([1, 1, 10.5])) + assert np.isnan(out).all() + + +def test_cubic_nan_reaches_its_whole_stencil() -> None: + """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN. + + Also a grid point next to it (MATLAB's interp2), unlike linear + interpolation; the cubic warp falls back to linear there. + """ + im = np.arange(80, dtype=float).reshape(8, 10) + im[4, 5] = np.nan + assert np.isnan(interp2_cubic(im, 4.0, 4.0)) # on the grid, next to it + assert np.isnan(interp2_cubic(im, 2.5, 6.5)) # stencil rows 2-5 + assert not np.isnan(interp2_cubic(im, 1.5, 6.5)) + assert interp2_linear(im, 4.0, 4.0) == im[4, 4] + a = np.array([[1.0, 0, 0.3], [0, 1, -0.6]]) + lin = warp_image_affine(im, a, "linear") + cub = warp_image_affine(im, a, "cubic") + np.testing.assert_array_equal(np.isnan(cub), np.isnan(lin)) + + +def test_gradient_is_matlabs() -> None: + """Central differences inside, one-sided differences at the edges.""" + im = np.array([[0.0, 1, 4, 9], [1, 3, 5, 7], [2, 2, 2, 2]]) + g_r, g_c = matlab_gradient(im) + np.testing.assert_array_equal(g_c[0], [1, 2, 4, 5]) + np.testing.assert_array_equal(g_r[:, 0], [1, 1, 1]) + np.testing.assert_array_equal(g_r[1], [1, 0.5, -1, -3.5]) + + +def test_field_reproduces_affine_map() -> None: + """Displacements at the centres that follow an affine map give that map everywhere. + + Also far outside the centres. + """ + rng = np.random.default_rng(1) + nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) + a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) + d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T + cc, rr = np.meshgrid(np.linspace(-50, 550, 61), np.linspace(-50, 350, 41)) + u = patch_field_matrix(nodes, 30, rr, cc)[0] @ d + pts = np.column_stack([rr.ravel(), cc.ravel()]) + u_a = (a[:, :2] @ pts.T + a[:, 2:3] - pts.T).T + assert np.abs(u - u_a).max() < 1e-9 + warp = TrialWarp(a[None], nodes, 30.0, d[None]) + im = rng.random((300, 500)) + out = warp_trial_image(im, warp, 0) + ref = warp_image_affine(im, a) + np.testing.assert_array_equal(np.isnan(out), np.isnan(ref)) + assert np.nanmax(np.abs(out - ref)) < 1e-9 + + +def test_field_apply_matches_field_matrix() -> None: + """Evaluating a bent field without the field matrix gives the same displacements. + + Also with fewer than 3 centres (their mean). + """ + rng = np.random.default_rng(2) + nodes = np.column_stack([rng.random(40) * 200 + 50, rng.random(40) * 400 + 50]) + a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) + d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T + d = d + 0.4 * rng.standard_normal(d.shape) + r, c = rng.random(5000) * 300, rng.random(5000) * 500 + np.testing.assert_allclose( + patch_field_apply(nodes, 25, r, c, d), + patch_field_matrix(nodes, 25, r, c)[0] @ d, + atol=1e-10, + ) + np.testing.assert_allclose( + patch_field_apply(nodes[:2], 25, r, c, d[:2]), + patch_field_matrix(nodes[:2], 25, r, c)[0] @ d[:2], + atol=1e-10, + ) + + +def test_inverse_undoes_bent_field() -> None: + """trialWarpInverse: back to the consensus points to 1e-5 px.""" + rng = np.random.default_rng(3) + nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) + a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) + d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T + d = d + 0.4 * rng.standard_normal(d.shape) + warp = TrialWarp(a[None], nodes, 30.0, d[None]) + r0, c0 = rng.random(1000) * 300, rng.random(1000) * 500 + r_t, c_t = warp.coords(0, r0, c0) + r1, c1 = warp.inverse(0, r_t, c_t) + assert max(np.abs(r1 - r0).max(), np.abs(c1 - c0).max()) < 1e-5 + rigid = TrialWarp.from_shifts([[0.25, -1.5]]) + r2, c2 = rigid.inverse(0, np.array([3.0]), np.array([4.0])) + assert (r2[0], c2[0]) == (2.75, 5.5) + + +def test_matlab_conversion_of_a_field() -> None: + """MATLAB's one-based centres and affine maps convert to zero-based. + + Displacements stay; the map of a point moves with the base. + """ + rng = np.random.default_rng(4) + nodes1 = np.column_stack([rng.random(8) * 50 + 10, rng.random(8) * 80 + 10]) + a1 = np.array([[[1.002, 0.001, 0.4], [0.0, 0.999, -0.3]]]) + d = 0.3 * rng.standard_normal((1, 8, 2)) + warp = TrialWarp.from_matlab(a1, nodes1, 12.0, d) + np.testing.assert_allclose(warp.nodes, nodes1 - 1) + r0 = rng.random(50) * 60 + c0 = rng.random(50) * 90 + r_t, c_t = warp.coords(0, r0, c0) + one = TrialWarp(a1, nodes1, 12.0, d) # read as zero-based: one-based maps + r1, c1 = one.coords(0, r0 + 1, c0 + 1) + np.testing.assert_allclose(r_t, r1 - 1, atol=1e-12) + np.testing.assert_allclose(c_t, c1 - 1, atol=1e-12) + np.testing.assert_allclose(warp.to_matlab(), a1) + + +def test_kmeans_finds_separated_clusters() -> None: + """Three well separated clusters are found from k-means++ starts. + + An empty cluster restarts at the farthest point. + """ + rng = np.random.default_rng(5) + centres = np.array([[0.0, 0], [50, 0], [0, 50]]) + x = np.vstack([c + rng.standard_normal((200, 2)) for c in centres]) + labels, cen = kmeans(x, 3, rng, replicates=3) + found = cen[np.argsort(cen[:, 0] + 2 * cen[:, 1])] + np.testing.assert_allclose(found, centres, atol=0.5) + assert np.bincount(labels).tolist() == [200, 200, 200] + start = np.array([[0.0, 0], [0.5, 0], [1000, 1000]]) + labels, cen = kmeans(x, 3, start=start) + assert np.bincount(labels, minlength=3).min() > 0 + # the farthest point of a singleton is not moved (that would empty it) + pts = np.array([[0.0, 0], [10, 0], [11, 0]]) + labels, cen = kmeans(pts, 3, start=np.array([[5.0, 0], [10.5, 0], [1e3, 0]])) + assert np.isfinite(cen).all() + assert sorted(np.bincount(labels, minlength=3)) == [1, 1, 1] + + +def test_patch_size_is_bounded() -> None: + """A patch needs at least one pixel; one pixel per patch at most.""" + valid = np.zeros((6, 8), bool) + valid[1:4, 2:6] = True + with pytest.raises(ValueError, match="patch_px"): + make_patches(valid, 0.5) + patch, nodes = make_patches(valid, 1) + assert nodes.shape[0] == valid.sum() + assert sorted(patch[valid]) == list(range(1, valid.sum() + 1)) + with pytest.raises(ValueError, match="align_patch_px"): + PlanParams(align_patch_px=0.5) + + +def test_patches_have_their_size() -> None: + """About patch_px pixels each, none under half of it, centred on their pixels.""" + valid = np.zeros((120, 160), bool) + valid[10:100, 20:150] = True + valid[40:60, 60:90] = False + patch, nodes = make_patches(valid, 900) + n = np.bincount(patch[valid], minlength=nodes.shape[0] + 1)[1:] + assert (patch[~valid] == 0).all() and n.min() >= 450 + assert abs(n.size - valid.sum() / 900) <= 2 + rows, cols = np.nonzero(valid) + for k in range(nodes.shape[0]): + sel = patch[rows, cols] == k + 1 + np.testing.assert_allclose(nodes[k], [rows[sel].mean(), cols[sel].mean()], atol=1e-9) + + +@pytest.fixture(scope="module") +def synthetic_neuron() -> tuple[np.ndarray, np.ndarray, np.random.Generator]: + """Build the labeled neuron of MATLAB's test and its scanned pixels. + + Returns + ------- + truth : np.ndarray + The neuron's mean image, NaN outside the scanned pixels. + scan : np.ndarray + Boolean mask of the scanned pixels. + rng : np.random.Generator + The random generator, to draw the trials from. + """ + rng = np.random.default_rng(1) + truth, scan = neuron(rng) + return truth, scan, rng + + +def test_affine_recovers_known_maps( + synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], +) -> None: + """The relative maps between trials are recovered to 0.05 px. + + Much better than the rigid start. + """ + truth, scan, rng = synthetic_neuron + m, _, u, a0 = trials(truth, scan, False, rng) + a, info = align_trials_affine(m, a0) + warp = TrialWarp(a) + err, err0 = field_error(warp.coords, u, a0, truth, scan) + assert err < 0.05 and err < err0 / 5 + assert np.all(info.corr > 0.9) + + +def test_patchwise_recovers_bends( + synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], +) -> None: + """Smooth bends (over ~40 px) on top of affine maps are recovered to 0.08 px. + + Much better than the rigid start and beyond an affine fit; no patch under + half the target size. + """ + truth, scan, rng = synthetic_neuron + m, mh, u, a0 = trials(truth, scan, True, rng) + fit, info = align_trials_patchwise(m, a0, mh, 1500) + warp = TrialWarp(fit.affine, fit.nodes, fit.sigma, fit.disp, fit.patch) + err, err0 = field_error(warp.coords, u, a0, truth, scan) + assert err < 0.08 and err < err0 / 3 + assert fit.nodes.shape[0] > 10 and info.n_px.min() >= 750 + a, _ = align_trials_affine(m, a0) + err_a, _ = field_error(TrialWarp(a).coords, u, a0, truth, scan) + assert err < 0.7 * err_a + # the plane is the field's affine part: equal at the plane's points + plane = TrialWarp(fit.affine) + np.testing.assert_allclose(np.mean(fit.affine[:, :, :2], axis=0), np.eye(2), atol=1e-3) + assert np.isfinite(plane.coords(0, 1.0, 1.0)[0]) + + +def test_patchwise_adds_nothing_without_bends( + synthetic_neuron: tuple[np.ndarray, np.ndarray, np.random.Generator], +) -> None: + """Affine maps only: the patchwise field is as good as the affine fit.""" + truth, scan, rng = synthetic_neuron + m, mh, u, a0 = trials(truth, scan, False, rng) + fit, _ = align_trials_patchwise(m, a0, mh, 1500) + warp = TrialWarp(fit.affine, fit.nodes, fit.sigma, fit.disp) + err, _ = field_error(warp.coords, u, a0, truth, scan) + assert err < 0.05 + + +def test_patchwise_given_patches_and_without_halves() -> None: + """Given its own patches back, the fit is the same. + + Without halves the departures are kept as fitted (weight 1) and the fit + still runs. + """ + rng = np.random.default_rng(7) + truth, scan = neuron(rng, (70, 90)) + m, mh, _, a0 = trials(truth, scan, True, rng, n_trials=3) + fit, info = align_trials_patchwise(m, a0, mh, 600, n_rounds=1) + again, _ = align_trials_patchwise(m, a0, mh, 600, n_rounds=1, patches=(fit.patch, fit.nodes)) + np.testing.assert_array_equal(again.disp, fit.disp) + assert np.all((info.weight >= 0) & (info.weight <= 1)) + plain, plain_info = align_trials_patchwise(m, a0, None, 600, n_rounds=1) + np.testing.assert_array_equal(plain_info.weight, 1.0) + assert np.isnan(plain_info.noise_sd).all() + assert np.isfinite(plain.disp).all() + + +def test_too_few_trials_or_pixels_keep_the_start() -> None: + """With fewer than 2 trials to fit, the maps are the starting ones.""" + m = np.random.default_rng(6).random((2, 30, 40)) + a0 = np.array([np.eye(2, 3), np.full((2, 3), np.nan)]) + a, info = align_trials_affine(m, a0) + np.testing.assert_array_equal(a, a0) + fit, _ = align_trials_patchwise(m, a0) + assert fit.nodes.shape[0] == 0 + np.testing.assert_array_equal(fit.affine, a0) + assert CubicInterpolant(m[0]).shape == (30, 40) diff --git a/tests/raster/test_raster_annotations.py b/tests/raster/test_raster_annotations.py index 9717ae91..9cac2716 100644 --- a/tests/raster/test_raster_annotations.py +++ b/tests/raster/test_raster_annotations.py @@ -1,165 +1,171 @@ -"""Tests of reading SILo's annotations.h5 and moving ROIs to the consensus frame. - -MATLAB functions: loadAnnotationsH5, roisToConsensusFrame, shiftRoiData. -""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import TrialWarp -from giant_python.extraction.raster.annotations import ( - PathAnnotations, - UserRoi, - annotation_trial, - read_annotations, - rois_to_consensus, - session_annotations, - soma_mask, -) - -SHAPE = (12, 16) # MATLAB rows x cols of the annotation image - - -def _text(f: h5py.File, path: str, value: str) -> None: - """Write a string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" - f.create_dataset(path, data=np.array([[ord(c)] for c in value], dtype=np.uint16)) - - -def _matlab(f: h5py.File, path: str, value: np.ndarray) -> None: - """Write a numeric array as MATLAB's h5write stores it (dimensions reversed).""" - f.create_dataset(path, data=np.ascontiguousarray(np.asarray(value).T)) - - -def write_annotations(path: Path, zero_indexed: bool | None = True) -> list[np.ndarray]: - """Write a file with two paths in MATLAB's layout and return the masks.""" - masks = [] - with h5py.File(path, "w") as f: - _matlab(f, "row_major", np.uint8([[0]])) - if zero_indexed is not None: - _matlab(f, "coords_zero_indexed", np.uint8([[int(zero_indexed)]])) - _matlab(f, "schema_version", np.uint32([[2]])) - for d, (label, fn) in enumerate([ - ("Soma 1", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz"), - ("spine", ""), - ]): - root = f"Path{d + 1}" - _text(f, f"{root}/dr", "C:\\data\\moco") - if fn: - _text(f, f"{root}/fn", fn) - _matlab(f, f"{root}/n_rois", np.uint32([[2 if d == 0 else 0]])) - if d: - continue - for k, (lab, r0, c0) in enumerate([(label, 2, 3), ("sp2", 6, 9)]): - mask = np.zeros(SHAPE, np.uint8) - mask[r0 : r0 + 3, c0 : c0 + 2] = 1 - masks.append(mask.astype(bool)) - roi = f"{root}/roi_{k + 1:03d}" - _text(f, f"{roi}/type", "circle") - _text(f, f"{roi}/label", lab) - _matlab(f, f"{roi}/mask", mask) - # zero-based [row col] in the file when zero-indexed - center = ( - np.array([[r0 + 1.0, c0 + 0.5]]) - if zero_indexed - else np.array([[c0 + 1.5, r0 + 2.0]]) - ) - _matlab(f, f"{roi}/center", center) - _matlab(f, f"{roi}/radius", np.array([[1.5]])) - return masks - - -@pytest.mark.parametrize("zero_indexed", [True, False]) -def test_read_annotations(tmp_path: Path, zero_indexed: bool) -> None: - """Strings, masks (MATLAB orientation) and geometry are read back.""" - path = tmp_path / "annotations.h5" - masks = write_annotations(path, zero_indexed) - paths = read_annotations(path) - assert len(paths) == 2 - a = paths[0] - assert a.fn == "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz" - assert a.dr == "C:\\data\\moco" - assert [r.label for r in a.rois] == ["Soma 1", "sp2"] - assert [r.type for r in a.rois] == ["circle", "circle"] - np.testing.assert_array_equal(a.rois[0].mask, masks[0]) - # images.roi [x, y], one-based - np.testing.assert_allclose(a.rois[0].center, [4.5, 4.0]) - assert a.rois[0].radius == 1.5 - assert a.rois[0].is_soma and not a.rois[1].is_soma - assert paths[1].fn == "" and paths[1].rois == [] - assert [a.path for a in paths] == [1, 2] - - -def test_annotation_trial() -> None: - """The annotation's file is matched with or without its extension.""" - fns = ["E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", "E1T2DMD1_X.h5"] - assert annotation_trial("E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz", fns) == 0 - assert annotation_trial("E1T2DMD1_X.tif", fns) == 1 - assert annotation_trial("C:\\moco\\E1T2DMD1_X", fns) == 1 - assert annotation_trial("other", fns) is None - assert annotation_trial("", fns) is None - - -def test_rois_to_consensus_shift(tmp_path: Path) -> None: - """Masks move by minus the trial's rounded shift, geometry exactly. - - A trial that is not known or not aligned leaves them in place. - """ - path = tmp_path / "annotations.h5" - masks = write_annotations(path) - ann = read_annotations(path)[0] - fns = ["t1.tif", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif"] - warp = TrialWarp.from_shifts(np.array([[0.0, 0.0], [1.4, -2.0]])) - shape = (14, 15) - moved = rois_to_consensus(ann, fns, warp, shape) - want = np.zeros(shape, bool) - r, c = np.nonzero(masks[0]) - keep = (r - 1 >= 0) & (c + 2 < shape[1]) - want[r[keep] - 1, c[keep] + 2] = True - np.testing.assert_array_equal(moved[0].mask, want) - np.testing.assert_allclose(moved[0].center, ann.rois[0].center + [2, -1.4]) - assert ann.rois[0].mask.shape == SHAPE # the input is unchanged - unaligned = TrialWarp.from_shifts(np.array([[0, 0], [np.nan, np.nan]])) - with pytest.warns(UserWarning, match="not aligned"): - same = rois_to_consensus(ann, fns, unaligned, shape) - np.testing.assert_array_equal(same[0].mask[:12, :15], masks[0][:, :15]) - with pytest.warns(UserWarning, match="not in the trial table"): - rois_to_consensus(ann, ["a.tif", "b.tif"], warp, shape) - - -def test_soma_mask_and_session(tmp_path: Path) -> None: - """Soma masks are the union of the ROIs labelled SOMA. - - A session without a file has no annotations. - """ - rois = [ - UserRoi("soma", "polygon", np.eye(4, dtype=bool)), - UserRoi("Spine", "circle", np.ones((4, 4), bool)), - UserRoi("SOMA2", "circle", np.zeros((0, 0), bool)), - ] - np.testing.assert_array_equal(soma_mask(rois, (3, 5))[:, :3], np.eye(3)) - assert session_annotations(None, 2) == [None, None] - assert session_annotations(tmp_path / "missing.h5", 1) == [None] - path = tmp_path / "annotations.h5" - write_annotations(path) - got = session_annotations(path, 3) - assert isinstance(got[0], PathAnnotations) and got[2] is None - # paths are placed by their numbers, not by their order in the file - with h5py.File(path, "a") as f: - f.move("Path1", "Path3") - got = session_annotations(path, 3) - assert got[0] is None and got[1].path == 2 and got[2].path == 3 - - -def test_text_is_utf16(tmp_path: Path) -> None: - """MATLAB stores text as UTF-16 code units, surrogate pairs included.""" - label = "soma é😀" - codes = np.frombuffer(label.encode("utf-16-le"), dtype=" None: + """Write a string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" + f.create_dataset(path, data=np.array([[ord(c)] for c in value], dtype=np.uint16)) + + +def _matlab(f: h5py.File, path: str, value: np.ndarray) -> None: + """Write a numeric array as MATLAB's h5write stores it (dimensions reversed).""" + f.create_dataset(path, data=np.ascontiguousarray(np.asarray(value).T)) + + +def write_annotations(path: Path, zero_indexed: bool | None = True) -> list[np.ndarray]: + """Write a file with two paths in MATLAB's layout and return the masks. + + Returns + ------- + list[np.ndarray] + The boolean ROI masks written to the first path, in ROI order. + """ + masks = [] + with h5py.File(path, "w") as f: + _matlab(f, "row_major", np.uint8([[0]])) + if zero_indexed is not None: + _matlab(f, "coords_zero_indexed", np.uint8([[int(zero_indexed)]])) + _matlab(f, "schema_version", np.uint32([[2]])) + for d, (label, fn) in enumerate([ + ("Soma 1", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz"), + ("spine", ""), + ]): + root = f"Path{d + 1}" + _text(f, f"{root}/dr", "C:\\data\\moco") + if fn: + _text(f, f"{root}/fn", fn) + _matlab(f, f"{root}/n_rois", np.uint32([[2 if d == 0 else 0]])) + if d: + continue + for k, (lab, r0, c0) in enumerate([(label, 2, 3), ("sp2", 6, 9)]): + mask = np.zeros(SHAPE, np.uint8) + mask[r0 : r0 + 3, c0 : c0 + 2] = 1 + masks.append(mask.astype(bool)) + roi = f"{root}/roi_{k + 1:03d}" + _text(f, f"{roi}/type", "circle") + _text(f, f"{roi}/label", lab) + _matlab(f, f"{roi}/mask", mask) + # zero-based [row col] in the file when zero-indexed + center = ( + np.array([[r0 + 1.0, c0 + 0.5]]) + if zero_indexed + else np.array([[c0 + 1.5, r0 + 2.0]]) + ) + _matlab(f, f"{roi}/center", center) + _matlab(f, f"{roi}/radius", np.array([[1.5]])) + return masks + + +@pytest.mark.parametrize("zero_indexed", [True, False]) +def test_read_annotations(tmp_path: Path, zero_indexed: bool) -> None: + """Strings, masks (MATLAB orientation) and geometry are read back.""" + path = tmp_path / "annotations.h5" + masks = write_annotations(path, zero_indexed) + paths = read_annotations(path) + assert len(paths) == 2 + a = paths[0] + assert a.fn == "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz" + assert a.dr == "C:\\data\\moco" + assert [r.label for r in a.rois] == ["Soma 1", "sp2"] + assert [r.type for r in a.rois] == ["circle", "circle"] + np.testing.assert_array_equal(a.rois[0].mask, masks[0]) + # images.roi [x, y], one-based + np.testing.assert_allclose(a.rois[0].center, [4.5, 4.0]) + assert a.rois[0].radius == 1.5 + assert a.rois[0].is_soma and not a.rois[1].is_soma + assert paths[1].fn == "" and paths[1].rois == [] + assert [a.path for a in paths] == [1, 2] + + +def test_annotation_trial() -> None: + """The annotation's file is matched with or without its extension.""" + fns = ["E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", "E1T2DMD1_X.h5"] + assert annotation_trial("E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz", fns) == 0 + assert annotation_trial("E1T2DMD1_X.tif", fns) == 1 + assert annotation_trial("C:\\moco\\E1T2DMD1_X", fns) == 1 + assert annotation_trial("other", fns) is None + assert annotation_trial("", fns) is None + + +def test_rois_to_consensus_shift(tmp_path: Path) -> None: + """Masks move by minus the trial's rounded shift, geometry exactly. + + A trial that is not known or not aligned leaves them in place. + """ + path = tmp_path / "annotations.h5" + masks = write_annotations(path) + ann = read_annotations(path)[0] + fns = ["t1.tif", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif"] + warp = TrialWarp.from_shifts(np.array([[0.0, 0.0], [1.4, -2.0]])) + shape = (14, 15) + moved = rois_to_consensus(ann, fns, warp, shape) + want = np.zeros(shape, bool) + r, c = np.nonzero(masks[0]) + keep = (r - 1 >= 0) & (c + 2 < shape[1]) + want[r[keep] - 1, c[keep] + 2] = True + np.testing.assert_array_equal(moved[0].mask, want) + np.testing.assert_allclose(moved[0].center, ann.rois[0].center + [2, -1.4]) + assert ann.rois[0].mask.shape == SHAPE # the input is unchanged + unaligned = TrialWarp.from_shifts(np.array([[0, 0], [np.nan, np.nan]])) + with pytest.warns(UserWarning, match="not aligned"): + same = rois_to_consensus(ann, fns, unaligned, shape) + np.testing.assert_array_equal(same[0].mask[:12, :15], masks[0][:, :15]) + with pytest.warns(UserWarning, match="not in the trial table"): + rois_to_consensus(ann, ["a.tif", "b.tif"], warp, shape) + + +def test_soma_mask_and_session(tmp_path: Path) -> None: + """Soma masks are the union of the ROIs labelled SOMA. + + A session without a file has no annotations. + """ + rois = [ + UserRoi("soma", "polygon", np.eye(4, dtype=bool)), + UserRoi("Spine", "circle", np.ones((4, 4), bool)), + UserRoi("SOMA2", "circle", np.zeros((0, 0), bool)), + ] + np.testing.assert_array_equal(soma_mask(rois, (3, 5))[:, :3], np.eye(3)) + assert session_annotations(None, 2) == [None, None] + assert session_annotations(tmp_path / "missing.h5", 1) == [None] + path = tmp_path / "annotations.h5" + write_annotations(path) + got = session_annotations(path, 3) + assert isinstance(got[0], PathAnnotations) and got[2] is None + # paths are placed by their numbers, not by their order in the file + with h5py.File(path, "a") as f: + f.move("Path1", "Path3") + got = session_annotations(path, 3) + assert got[0] is None and got[1].path == 2 and got[2].path == 3 + + +def test_text_is_utf16(tmp_path: Path) -> None: + """MATLAB stores text as UTF-16 code units, surrogate pairs included.""" + label = "soma é😀" + codes = np.frombuffer(label.encode("utf-16-le"), dtype=" np.ndarray: - """Build a stack that is linear in row and column, the same in every frame.""" - r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") - return np.broadcast_to(a + br * r + bc * c, (n_t, n_r, n_c)).copy() - - -def test_baseline_file_names() -> None: - """The file is named from the trial's stem or its movie's name.""" - assert baseline_file("d", "E1T2DMD1").name == "E1T2DMD1_BASELINE-80Hz.h5" - name = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - assert baseline_file("d", name).name == "E1T2DMD1_BASELINE-80Hz.h5" - - -def test_read_network_baseline_orientation(tmp_path: Path) -> None: - """slap2-f0 writes (frame, MATLAB col, MATLAB row). - - Reading gives (frame, row, col). - """ - stack = np.random.default_rng(0).random((4, 3, 5)).astype(np.float32) - path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" - with h5py.File(path, "w") as f: - f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) - f.attrs["checkpoint"] = "x.pt" - values, attrs = read_network_baseline(path) - assert values.shape == (4, 3, 5) - np.testing.assert_allclose(values, stack, rtol=1e-3) - assert attrs["checkpoint"] == "x.pt" - - -def test_read_network_baseline_rejects_other_shapes(tmp_path: Path) -> None: - """A /baseline that is not three-dimensional is refused.""" - path = tmp_path / "b.h5" - with h5py.File(path, "w") as f: - f["baseline"] = np.zeros((4, 3)) - with pytest.raises(ValueError, match="frame, col, row"): - read_network_baseline(path) - - -def test_bilinear_is_exact_on_a_plane() -> None: - """A plane is sampled exactly at sub-pixel positions.""" - stack = _plane(3, 6, 7) - rc = np.array([[0.0, 0.0], [2.5, 3.25], [4.9, 5.1], [5.0, 6.0]]) - values, weight = sample_bilinear(stack, rc) - want = 100 + 10 * rc[:, 0] + 5 * rc[:, 1] - np.testing.assert_allclose(values, np.repeat(want[:, None], 3, 1)) - np.testing.assert_allclose(weight, 1.0) - - -def test_bilinear_renormalizes_over_neighbours_with_values() -> None: - """Neighbours without a value are left out. - - Too little weight left gives NaN. - """ - stack = np.full((2, 4, 4), 7.0) - stack[:, 1, 2] = np.nan - # (1.2, 1.2): the NaN corner (1, 2) carries 0.8 * 0.2 of the weight - values, weight = sample_bilinear(stack, np.array([[1.2, 1.2]])) - np.testing.assert_allclose(values, 7.0) - np.testing.assert_allclose(weight, 1 - 0.16) - # (1.1, 1.9): it carries 0.9 * 0.9 = 0.81 - values, weight = sample_bilinear(stack, np.array([[1.1, 1.9]])) - assert np.isnan(values).all() - np.testing.assert_allclose(weight, 0.19) - values, _ = sample_bilinear(stack, np.array([[1.1, 1.9]]), 0.1) - np.testing.assert_allclose(values, 7.0) - - -def test_bilinear_outside_the_frame() -> None: - """Neighbours outside the stack have no value. - - A whole-pixel position on the last row needs no neighbour beyond it. - """ - stack = _plane(1, 3, 3) - values, weight = sample_bilinear(stack, np.array([[2.0, 1.0], [2.4, 1.0], [-1.0, -1.0]])) - np.testing.assert_allclose(values[0], 100 + 20 + 5) - np.testing.assert_allclose(weight[0], 1.0) - np.testing.assert_allclose(values[1], 125) - np.testing.assert_allclose(weight[1], 0.6) - assert np.isnan(values[2]).all() - assert weight[2] == 0 - - -def test_bilinear_per_frame_nans() -> None: - """A neighbour missing in one frame only is left out of that frame.""" - stack = _plane(3, 3, 3) - stack[1, 1, 1] = np.nan - values, weight = sample_bilinear(stack, np.array([[1.75, 1.0]])) - np.testing.assert_allclose(values[0, [0, 2]], 100 + 17.5 + 5) - np.testing.assert_allclose(values[0, 1], 100 + 20 + 5) - np.testing.assert_allclose(weight, 0.75) - with pytest.raises(ValueError): - sample_bilinear(stack, np.array([[np.nan, 1.0]])) - with pytest.raises(ValueError): - sample_bilinear(stack, np.array([[1.0, 1.0]]), 0.0) - - -def test_interp_frames_linear_in_lines() -> None: - """Linear in line number, NaN samples left out, ends held.""" - src = np.array([10.0, 30.0, 50.0, 70.0]) - vals = np.array([[1.0, 3.0, 5.0, 7.0], [1.0, np.nan, 5.0, 7.0]]) - dst = np.array([0.0, 10.0, 20.0, 45.0, 70.0, 90.0]) - out = interp_frames(vals, src, dst) - np.testing.assert_allclose(out[0], [1, 1, 2, 4.5, 7, 7]) - np.testing.assert_allclose(out[1], [1, 1, 2, 4.5, 7, 7]) - nan_row = interp_frames(np.full((1, 4), np.nan), src, dst) - assert np.isnan(nan_row).all() - one = interp_frames(np.array([[4.0]]), np.array([5.0]), dst) - np.testing.assert_allclose(one, 4.0) - with pytest.raises(ValueError): - interp_frames(vals, src[::-1], dst) - with pytest.raises(ValueError): - interp_frames(vals[:, :3], src, dst) - - -def _registration( - n_r: int = 12, - n_c: int = 14, - lines_80: int = 100, - lines_200: int = 40, - n_lines: int = 8000, -) -> tuple[ - np.ndarray, - np.ndarray, - np.ndarray, - Callable[[ArrayLike, ArrayLike, ArrayLike], np.ndarray], -]: - """Build a synthetic network baseline: a plane times a slow time course. - - Returns the stack (counts), the registered frames' lines, the - extraction frames' lines and the true value as a function of - (row, col, line). - """ - ds = np.arange(1, n_lines, lines_80, dtype=np.float64) - fl = np.arange(1, n_lines, lines_200, dtype=np.float64) - - def truth(r: ArrayLike, c: ArrayLike, line: ArrayLike) -> np.ndarray: - """Return the baseline in counts.""" - return (200 + 8 * r + 3 * c) * (1 + 0.1 * np.sin(line / 2000.0)) - - r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") - stack = truth(r[None], c[None], ds[:, None, None]).astype(np.float32) - return stack, ds, fl, truth - - -def test_map_baseline_space_time_units() -> None: - """Space, time and units of the mapping, against the known field.""" - stack, ds, fl, truth = _registration() - rc = np.array([[3.4, 5.7], [0.0, 0.0], [11.0, 13.0], [6.5, 2.25]]) - mapped = map_baseline(stack, rc, ds, fl, photon_scale=25.0) - assert isinstance(mapped, MappedBaseline) - assert mapped.values.shape == (4, fl.size) - assert not mapped.missing.any() - want = truth(rc[:, :1], rc[:, 1:], fl[None, :]) / 25.0 - inner = fl <= ds[-1] - # linear interpolation of a slow sine: error below 1e-4 relative - np.testing.assert_allclose(mapped.values[:, inner], want[:, inner], 2e-4) - # after the last registered frame: its value - last = truth(rc[:, 0], rc[:, 1], ds[-1]) / 25.0 - tail = np.broadcast_to(last[:, None], mapped.values[:, ~inner].shape) - np.testing.assert_allclose(mapped.values[:, ~inner], tail, 1e-6) - - -def test_map_baseline_missing_pixels_and_fallback() -> None: - """Pixels without a network value are flagged. - - With the data given they get its starting baseline. - """ - stack, ds, fl, _ = _registration() - stack[:, :, :4] = np.nan - rc = np.array([[5.0, 1.0], [5.0, 3.6], [5.0, 3.4], [5.0, 8.0]]) - mapped = map_baseline(stack, rc, ds, fl, 25.0) - # (5, 3.6) has 0.6 of its weight on column 4, (5, 3.4) only 0.4 - np.testing.assert_array_equal(mapped.missing, [True, False, True, False]) - assert np.isnan(mapped.values[mapped.missing]).all() - rng = np.random.default_rng(1) - data = 8 + rng.normal(0, 0.1, (4, fl.size)) - params = SolverParams() - filled = map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data) - np.testing.assert_array_equal(filled.missing, mapped.missing) - miss = mapped.missing - np.testing.assert_allclose(filled.values[miss], initial_baseline(data[miss], params)) - np.testing.assert_allclose(filled.values[~miss], mapped.values[~miss]) - with pytest.raises(ValueError, match="fallback_data"): - map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data[:, :5]) - - -def test_map_baseline_dropped_frames_are_interpolated_over() -> None: - """Dropped registered frames do not enter the time interpolation.""" - stack, ds, fl, truth = _registration() - bad = stack.copy() - drop = np.zeros(ds.size, bool) - drop[20:25] = True - bad[drop] = 1e6 - rc = np.array([[4.0, 4.0]]) - mapped = map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop) - want = truth(4.0, 4.0, fl) - np.testing.assert_allclose(mapped.values[0], want, rtol=5e-3) - kept = map_baseline(stack, rc, ds, fl, 1.0) - none = map_baseline(stack, rc, ds, fl, 1.0, drop_frames=np.zeros_like(drop)) - np.testing.assert_array_equal(kept.values, none.values) - with pytest.raises(ValueError, match="drop_frames"): - map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop[:-1]) - with pytest.raises(ValueError, match="every registered frame"): - map_baseline(bad, rc, ds, fl, 1.0, drop_frames=np.ones_like(drop)) - - -def test_map_baseline_checks_inputs() -> None: - """Mismatched frames and a bad photon scale are refused.""" - stack, ds, fl, _ = _registration() - rc = np.zeros((1, 2)) - with pytest.raises(ValueError, match="registration has"): - map_baseline(stack, rc, ds[:-1], fl, 25.0) - for scale in (0.0, -1.0, np.nan): - with pytest.raises(ValueError, match="photon_scale"): - map_baseline(stack, rc, ds, fl, scale) - - -def test_interp_frames_in_blocks() -> None: - """Interpolating in blocks gives the same rows.""" - rng = np.random.default_rng(11) - vals = rng.random((37, 20)) - src = np.arange(20) * 5.0 - dst = np.linspace(-3, 103, 51) - np.testing.assert_array_equal( - interp_frames(vals, src, dst, block=4), interp_frames(vals, src, dst) - ) +"""Tests of the mapping of the F0 network's baseline onto the extraction. + +The baseline is mapped onto the extraction's pixels, frames and units. +""" + +from collections.abc import Callable +from pathlib import Path + +import h5py +import numpy as np +import pytest +from numpy.typing import ArrayLike + +from giant_python.extraction.raster.baseline_map import ( + MappedBaseline, + baseline_file, + interp_frames, + map_baseline, + read_network_baseline, + sample_bilinear, +) +from giant_python.extraction.raster.solver_baseline import initial_baseline +from giant_python.extraction.raster.solver_setup import SolverParams + + +def _plane( + n_t: int, n_r: int, n_c: int, a: float = 100.0, br: float = 10.0, bc: float = 5.0 +) -> np.ndarray: + """Build a stack that is linear in row and column, the same in every frame. + + Returns + ------- + np.ndarray + The (n_t, n_r, n_c) stack a + br * row + bc * col. + """ + r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") + return np.broadcast_to(a + br * r + bc * c, (n_t, n_r, n_c)).copy() + + +def test_baseline_file_names() -> None: + """The file is named from the trial's stem or its movie's name.""" + assert baseline_file("d", "E1T2DMD1").name == "E1T2DMD1_BASELINE-80Hz.h5" + name = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + assert baseline_file("d", name).name == "E1T2DMD1_BASELINE-80Hz.h5" + + +def test_read_network_baseline_orientation(tmp_path: Path) -> None: + """slap2-f0 writes (frame, MATLAB col, MATLAB row). + + Reading gives (frame, row, col). + """ + stack = np.random.default_rng(0).random((4, 3, 5)).astype(np.float32) + path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" + with h5py.File(path, "w") as f: + f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) + f.attrs["checkpoint"] = "x.pt" + values, attrs = read_network_baseline(path) + assert values.shape == (4, 3, 5) + np.testing.assert_allclose(values, stack, rtol=1e-3) + assert attrs["checkpoint"] == "x.pt" + + +def test_read_network_baseline_rejects_other_shapes(tmp_path: Path) -> None: + """A /baseline that is not three-dimensional is refused.""" + path = tmp_path / "b.h5" + with h5py.File(path, "w") as f: + f["baseline"] = np.zeros((4, 3)) + with pytest.raises(ValueError, match="frame, col, row"): + read_network_baseline(path) + + +def test_bilinear_is_exact_on_a_plane() -> None: + """A plane is sampled exactly at sub-pixel positions.""" + stack = _plane(3, 6, 7) + rc = np.array([[0.0, 0.0], [2.5, 3.25], [4.9, 5.1], [5.0, 6.0]]) + values, weight = sample_bilinear(stack, rc) + want = 100 + 10 * rc[:, 0] + 5 * rc[:, 1] + np.testing.assert_allclose(values, np.repeat(want[:, None], 3, 1)) + np.testing.assert_allclose(weight, 1.0) + + +def test_bilinear_renormalizes_over_neighbours_with_values() -> None: + """Neighbours without a value are left out. + + Too little weight left gives NaN. + """ + stack = np.full((2, 4, 4), 7.0) + stack[:, 1, 2] = np.nan + # (1.2, 1.2): the NaN corner (1, 2) carries 0.8 * 0.2 of the weight + values, weight = sample_bilinear(stack, np.array([[1.2, 1.2]])) + np.testing.assert_allclose(values, 7.0) + np.testing.assert_allclose(weight, 1 - 0.16) + # (1.1, 1.9): it carries 0.9 * 0.9 = 0.81 + values, weight = sample_bilinear(stack, np.array([[1.1, 1.9]])) + assert np.isnan(values).all() + np.testing.assert_allclose(weight, 0.19) + values, _ = sample_bilinear(stack, np.array([[1.1, 1.9]]), 0.1) + np.testing.assert_allclose(values, 7.0) + + +def test_bilinear_outside_the_frame() -> None: + """Neighbours outside the stack have no value. + + A whole-pixel position on the last row needs no neighbour beyond it. + """ + stack = _plane(1, 3, 3) + values, weight = sample_bilinear(stack, np.array([[2.0, 1.0], [2.4, 1.0], [-1.0, -1.0]])) + np.testing.assert_allclose(values[0], 100 + 20 + 5) + np.testing.assert_allclose(weight[0], 1.0) + np.testing.assert_allclose(values[1], 125) + np.testing.assert_allclose(weight[1], 0.6) + assert np.isnan(values[2]).all() + assert weight[2] == 0 + + +def test_bilinear_per_frame_nans() -> None: + """A neighbour missing in one frame only is left out of that frame.""" + stack = _plane(3, 3, 3) + stack[1, 1, 1] = np.nan + values, weight = sample_bilinear(stack, np.array([[1.75, 1.0]])) + np.testing.assert_allclose(values[0, [0, 2]], 100 + 17.5 + 5) + np.testing.assert_allclose(values[0, 1], 100 + 20 + 5) + np.testing.assert_allclose(weight, 0.75) + with pytest.raises(ValueError): + sample_bilinear(stack, np.array([[np.nan, 1.0]])) + with pytest.raises(ValueError): + sample_bilinear(stack, np.array([[1.0, 1.0]]), 0.0) + + +def test_interp_frames_linear_in_lines() -> None: + """Linear in line number, NaN samples left out, ends held.""" + src = np.array([10.0, 30.0, 50.0, 70.0]) + vals = np.array([[1.0, 3.0, 5.0, 7.0], [1.0, np.nan, 5.0, 7.0]]) + dst = np.array([0.0, 10.0, 20.0, 45.0, 70.0, 90.0]) + out = interp_frames(vals, src, dst) + np.testing.assert_allclose(out[0], [1, 1, 2, 4.5, 7, 7]) + np.testing.assert_allclose(out[1], [1, 1, 2, 4.5, 7, 7]) + nan_row = interp_frames(np.full((1, 4), np.nan), src, dst) + assert np.isnan(nan_row).all() + one = interp_frames(np.array([[4.0]]), np.array([5.0]), dst) + np.testing.assert_allclose(one, 4.0) + with pytest.raises(ValueError): + interp_frames(vals, src[::-1], dst) + with pytest.raises(ValueError): + interp_frames(vals[:, :3], src, dst) + + +def _registration( + n_r: int = 12, + n_c: int = 14, + lines_80: int = 100, + lines_200: int = 40, + n_lines: int = 8000, +) -> tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + Callable[[ArrayLike, ArrayLike, ArrayLike], np.ndarray], +]: + """Build a synthetic network baseline: a plane times a slow time course. + + Returns the stack (counts), the registered frames' lines, the + extraction frames' lines and the true value as a function of + (row, col, line). + + Returns + ------- + stack : np.ndarray + The baseline stack (counts). + ds : np.ndarray + The registered frames' lines. + fl : np.ndarray + The extraction frames' lines. + truth : Callable + The true value as a function of (row, col, line). + """ + ds = np.arange(1, n_lines, lines_80, dtype=np.float64) + fl = np.arange(1, n_lines, lines_200, dtype=np.float64) + + def truth(r: ArrayLike, c: ArrayLike, line: ArrayLike) -> np.ndarray: + """Return the baseline in counts. + + Returns + ------- + np.ndarray + The baseline at (r, c, line), in counts. + """ + return (200 + 8 * r + 3 * c) * (1 + 0.1 * np.sin(line / 2000.0)) + + r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") + stack = truth(r[None], c[None], ds[:, None, None]).astype(np.float32) + return stack, ds, fl, truth + + +def test_map_baseline_space_time_units() -> None: + """Space, time and units of the mapping, against the known field.""" + stack, ds, fl, truth = _registration() + rc = np.array([[3.4, 5.7], [0.0, 0.0], [11.0, 13.0], [6.5, 2.25]]) + mapped = map_baseline(stack, rc, ds, fl, photon_scale=25.0) + assert isinstance(mapped, MappedBaseline) + assert mapped.values.shape == (4, fl.size) + assert not mapped.missing.any() + want = truth(rc[:, :1], rc[:, 1:], fl[None, :]) / 25.0 + inner = fl <= ds[-1] + # linear interpolation of a slow sine: error below 1e-4 relative + np.testing.assert_allclose(mapped.values[:, inner], want[:, inner], 2e-4) + # after the last registered frame: its value + last = truth(rc[:, 0], rc[:, 1], ds[-1]) / 25.0 + tail = np.broadcast_to(last[:, None], mapped.values[:, ~inner].shape) + np.testing.assert_allclose(mapped.values[:, ~inner], tail, 1e-6) + + +def test_map_baseline_missing_pixels_and_fallback() -> None: + """Pixels without a network value are flagged. + + With the data given they get its starting baseline. + """ + stack, ds, fl, _ = _registration() + stack[:, :, :4] = np.nan + rc = np.array([[5.0, 1.0], [5.0, 3.6], [5.0, 3.4], [5.0, 8.0]]) + mapped = map_baseline(stack, rc, ds, fl, 25.0) + # (5, 3.6) has 0.6 of its weight on column 4, (5, 3.4) only 0.4 + np.testing.assert_array_equal(mapped.missing, [True, False, True, False]) + assert np.isnan(mapped.values[mapped.missing]).all() + rng = np.random.default_rng(1) + data = 8 + rng.normal(0, 0.1, (4, fl.size)) + params = SolverParams() + filled = map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data) + np.testing.assert_array_equal(filled.missing, mapped.missing) + miss = mapped.missing + np.testing.assert_allclose(filled.values[miss], initial_baseline(data[miss], params)) + np.testing.assert_allclose(filled.values[~miss], mapped.values[~miss]) + with pytest.raises(ValueError, match="fallback_data"): + map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data[:, :5]) + + +def test_map_baseline_dropped_frames_are_interpolated_over() -> None: + """Dropped registered frames do not enter the time interpolation.""" + stack, ds, fl, truth = _registration() + bad = stack.copy() + drop = np.zeros(ds.size, bool) + drop[20:25] = True + bad[drop] = 1e6 + rc = np.array([[4.0, 4.0]]) + mapped = map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop) + want = truth(4.0, 4.0, fl) + np.testing.assert_allclose(mapped.values[0], want, rtol=5e-3) + kept = map_baseline(stack, rc, ds, fl, 1.0) + none = map_baseline(stack, rc, ds, fl, 1.0, drop_frames=np.zeros_like(drop)) + np.testing.assert_array_equal(kept.values, none.values) + with pytest.raises(ValueError, match="drop_frames"): + map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop[:-1]) + with pytest.raises(ValueError, match="every registered frame"): + map_baseline(bad, rc, ds, fl, 1.0, drop_frames=np.ones_like(drop)) + + +def test_map_baseline_checks_inputs() -> None: + """Mismatched frames and a bad photon scale are refused.""" + stack, ds, fl, _ = _registration() + rc = np.zeros((1, 2)) + with pytest.raises(ValueError, match="registration has"): + map_baseline(stack, rc, ds[:-1], fl, 25.0) + for scale in (0.0, -1.0, np.nan): + with pytest.raises(ValueError, match="photon_scale"): + map_baseline(stack, rc, ds, fl, scale) + + +def test_interp_frames_in_blocks() -> None: + """Interpolating in blocks gives the same rows.""" + rng = np.random.default_rng(11) + vals = rng.random((37, 20)) + src = np.arange(20) * 5.0 + dst = np.linspace(-3, 103, 51) + np.testing.assert_array_equal( + interp_frames(vals, src, dst, block=4), interp_frames(vals, src, dst) + ) diff --git a/tests/raster/test_raster_container.py b/tests/raster/test_raster_container.py index 82ba0b48..576b6839 100644 --- a/tests/raster/test_raster_container.py +++ b/tests/raster/test_raster_container.py @@ -1,320 +1,337 @@ -"""Tests of the container: one trial-path's inputs of source extraction.""" - -from pathlib import Path -from typing import NoReturn - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.container import ( - FORMAT_VERSION, - crop_of, - read_container, - read_subproblem, - settings_hash, - write_container, -) -from giant_python.extraction.raster.trial_data import ( - TrialData, - TrialLoadParams, -) - -SHAPE = (12, 15) # consensus frame - - -def make_trial( - n_frames: int = 40, seed: int = 0 -) -> tuple[TrialData, np.ndarray, list[np.ndarray], list[np.ndarray], np.ndarray]: - """Make a small trial with two blobs of selected pixels and three sources. - - Returns the trial, the sources and each subproblem's pixels and - sources: the two blobs' subproblems share the pixels of column 7. - """ - rng = np.random.default_rng(seed) - sel = np.zeros(SHAPE, dtype=bool) - sel[2:7, 3:8] = True - sel[4:10, 7:12] = True - cols, rows = np.nonzero(sel.T) # column-major, as find(selPix) - pixel_rc = np.stack([rows, cols], 1) - n_px = rows.size - trial = TrialData( - y=rng.standard_normal((2, n_px, n_frames)).astype(np.float32), - finv=(1 + rng.random((n_px, n_frames))).astype(np.float32), - frame_lines=np.ceil(np.arange(n_frames) * 53.4 + 1).astype(np.int64), - motion_r=rng.standard_normal(n_frames), - motion_c=rng.standard_normal(n_frames), - discard=rng.random(n_frames) < 0.1, - global_f=rng.random((2, n_frames)), - roi_f=rng.random((3, 2, n_frames)), - roi_fsvd=rng.random((3, 2, n_frames)), - pixel_rc=pixel_rc, - trial_rc=pixel_rc + np.array([0.25, -0.5]), - photon_scale=25.0, - ) - trial.roi_f[1] = np.nan # a ROI without data - sources_rc = np.array([[4, 5], [6, 9], [8, 10]]) - in_a = (rows < 7) & (cols < 8) - in_b = (rows >= 4) & (cols >= 7) - pixels = [np.flatnonzero(in_a), np.flatnonzero(in_b)] - return trial, sources_rc, pixels, [np.array([0]), np.array([1, 2])], sel - - -@pytest.mark.parametrize("compression", ["lzf", "gzip", None]) -def test_round_trip_is_exact(tmp_path: Path, compression: str | None) -> None: - """Everything written is read back unchanged, whole or by subproblem.""" - trial, sources_rc, pixels, sources, sel = make_trial() - params = {"loader": TrialLoadParams(), "lambda": 0.9, "k": np.arange(3.0)} - path = write_container( - tmp_path / "trial.h5", - trial, - sources_rc, - pixels, - sources, - SHAPE, - params, - {"dat": "a_DMD1-TRIAL000002.dat", "path": 1, "trial": 2}, - compression=compression, - chunk_pixels=4, - ) - assert path.exists() and not list(tmp_path.glob("*.partial")) - c = read_container(path) - for name in ( - "y", - "finv", - "frame_lines", - "discard", - "motion_r", - "motion_c", - "pixel_rc", - "trial_rc", - "global_f", - "roi_f", - "roi_fsvd", - ): - got, want = getattr(c, name), getattr(trial, name) - np.testing.assert_array_equal(got, want) - assert got.dtype == want.dtype or name == "pixel_rc" - np.testing.assert_array_equal(c.sources_rc, sources_rc) - assert c.consensus_shape == SHAPE and c.photon_scale == 25.0 - assert c.n_subproblems == 2 and not c.baseline_filled - assert c.params["lambda"] == 0.9 and c.params["k"] == [0.0, 1.0, 2.0] - assert c.params["loader"]["analyze_hz"] == 200.0 - assert c.source == {"dat": "a_DMD1-TRIAL000002.dat", "path": 1, "trial": 2} - assert c.settings_hash == settings_hash(params) and c.code_version - shell = read_container(path, data=False) - assert shell.y is None and shell.finv is None - with pytest.raises(ValueError, match="without its data"): - shell.subproblem(0) - with h5py.File(path, "r") as f: - from_file = [read_subproblem(f, k) for k in range(2)] - for k in range(2): - for sp in (c.subproblem(k), read_subproblem(path, k), from_file[k]): - np.testing.assert_array_equal(sp.y, trial.y[:, pixels[k]]) - np.testing.assert_array_equal(sp.finv, trial.finv[pixels[k]]) - assert sp.y.dtype == np.float32 and sp.y.shape[0] == 2 - np.testing.assert_array_equal(sp.pixels, pixels[k]) - np.testing.assert_array_equal(sp.sources, sources[k]) - # the crop is the bounding box of the pixels; sel's true - # elements in column-major order are the rows of y - rc = trial.pixel_rc[pixels[k]] - assert (sp.row0, sp.col0) == tuple(rc.min(0)) - box = sel[ - sp.row0 : sp.row0 + sp.sel.shape[0], - sp.col0 : sp.col0 + sp.sel.shape[1], - ] - assert not (sp.sel & ~box).any() # within the selected map - cols, rows = np.nonzero(sp.sel.T) - np.testing.assert_array_equal(np.stack([rows + sp.row0, cols + sp.col0], 1), rc) - np.testing.assert_array_equal( - sp.sources_rc, sources_rc[sources[k]] - [sp.row0, sp.col0] - ) - # overlapping subproblems share pixels: the data are stored once - shared = np.intersect1d(pixels[0], pixels[1]) - assert shared.size == 3 - with h5py.File(path, "r") as f: - assert f["data/y"].shape == trial.y.shape - assert f["data/y"].chunks == (1, 4, trial.y.shape[2]) - assert f["data/y"].compression == compression - assert f.attrs["format_version"] == FORMAT_VERSION - - -def test_baseline_is_reserved_and_can_be_filled(tmp_path: Path) -> None: - """The F0 network's baseline has empty, resizable datasets.""" - trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) - n_px = trial.y.shape[1] - with h5py.File(path, "r+") as f: - g = f["baseline"] - assert g["values"].shape == (n_px, 0) - assert g["values"].maxshape == (n_px, None) - assert g["frame_lines"].shape == (0,) and g.attrs["filled"] == 0 - assert g["values"].id.get_storage_size() == 0 # nothing stored - g["values"].resize((n_px, 16)) - g["frame_lines"].resize((16,)) - assert np.isnan(g["values"][()]).all() # unwritten: NaN - g["values"][...] = 1.5 - g["frame_lines"][...] = np.arange(16) * 133.0 + 1 - g.attrs["filled"] = 1 - c = read_container(path, data=False) - assert c.baseline_filled - np.testing.assert_array_equal( # the data are untouched - read_subproblem(path, 1).y, trial.y[:, pixels[1]] - ) - - -def test_settings_hash_ignores_key_order_only() -> None: - """The same settings hash alike however they are ordered or typed.""" - a = {"lambda": 0.9, "loader": TrialLoadParams(), "k": np.array([1.0, 2.0])} - b = { - "k": [1.0, 2.0], - "loader": { - "block_frames": 600, - "nan_thresh": 0.33, - "baseline_window_s": 4.0, - "photon_scale": np.float64(25.0), - "activity_channel": np.int64(1), - "analyze_hz": 200.0, - }, - "lambda": 0.9, - } - assert settings_hash(a) == settings_hash(b) - assert len(settings_hash(a)) == 64 - assert settings_hash(a) != settings_hash({**a, "lambda": 1.0}) - assert settings_hash({}) != settings_hash({"lambda": 0.9}) - - -def test_subproblem_lists_are_checked(tmp_path: Path) -> None: - """Index lists must match, increase and stay inside their lists.""" - trial, sources_rc, pixels, sources, _ = make_trial() - path = tmp_path / "trial.h5" - cases = [ - (pixels[:1], sources, "one source list"), - ([pixels[0][::-1], pixels[1]], sources, "pixels must increase"), - ([pixels[0], pixels[1] + 1000], sources, "pixels outside"), - (pixels, [np.array([0]), np.array([1, 3])], "sources outside"), - (pixels, [np.array([0]), np.array([2, 1])], "sources must increase"), - # fractions are not cut to the index below them - ([np.array([-0.5, 3.0]), pixels[1]], sources, "pixels must be whole"), - ([pixels[0] + 0.25, pixels[1]], sources, "pixels must be whole"), - (pixels, [[np.nan], [1, 2]], "sources must be whole"), - (pixels, [[True], [1, 2]], "sources must be whole"), - ] - for pix, src, message in cases: - with pytest.raises(ValueError, match=message): - write_container(path, trial, sources_rc, pix, src, SHAPE) - assert not path.exists() - # whole numbers held as floating point are indices - as_float = [v.astype(np.float64) for v in pixels] - write_container(path, trial, sources_rc, as_float, sources, SHAPE) - np.testing.assert_array_equal(read_container(path, data=False).subproblem_pixels[1], pixels[1]) - write_container(path, trial, sources_rc, pixels, sources, SHAPE) - # the same indices are refused in memory and from the file - whole = read_container(path) - for k in (2, -1): - for source in (path, whole): - with pytest.raises(IndexError, match="not one of 2"): - read_subproblem(source, k) - - -def test_empty_grouping_and_foreign_files(tmp_path: Path) -> None: - """A container may hold no subproblems, or an empty one. - - Other HDF5 files and newer formats are refused. - """ - trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container(tmp_path / "none.h5", trial, sources_rc[:0], [], [], SHAPE) - c = read_container(path) - assert c.n_subproblems == 0 and c.crops.shape == (0, 4) - assert c.sources_rc.shape == (0, 2) - empty = [np.zeros(0, int), pixels[1]] - path = write_container(tmp_path / "empty.h5", trial, sources_rc, empty, [[], [1, 2]], SHAPE) - sp = read_subproblem(path, 0) - assert sp.y.shape == (2, 0, trial.y.shape[2]) and sp.sel.shape == (0, 0) - assert sp.sources_rc.shape == (0, 2) - np.testing.assert_array_equal(crop_of(trial.pixel_rc[:0]), [0, 0, 0, 0]) - np.testing.assert_array_equal(read_subproblem(path, 1).y, trial.y[:, pixels[1]]) - other = tmp_path / "other.h5" - with h5py.File(other, "w") as f: - f["data"] = np.arange(3) - with pytest.raises(ValueError, match="not a SILo container"): - read_container(other) - with h5py.File(path, "r+") as f: - f.attrs["format_version"] = FORMAT_VERSION + 1 - with pytest.raises(ValueError, match="container format"): - read_subproblem(path, 0) - - -@pytest.mark.parametrize("compression", ["lzf", None]) -def test_trial_without_selected_pixels_round_trips( - tmp_path: Path, compression: str | None -) -> None: - """A path without sources has no selected pixels. - - Its container holds the frames and traces, and empty data. - """ - full, *_ = make_trial() - n_f = full.frame_lines.size - trial = TrialData( - y=np.zeros((2, 0, n_f), np.float32), - finv=np.zeros((0, n_f), np.float32), - frame_lines=full.frame_lines, - motion_r=full.motion_r, - motion_c=full.motion_c, - discard=full.discard, - global_f=full.global_f, - roi_f=np.zeros((0, 2, n_f)), - roi_fsvd=np.zeros((0, 2, n_f)), - pixel_rc=np.zeros((0, 2), np.int64), - trial_rc=np.zeros((0, 2)), - photon_scale=25.0, - ) - path = write_container( - tmp_path / "empty.h5", - trial, - np.zeros((0, 2), int), - [], - [], - SHAPE, - compression=compression, - ) - c = read_container(path) - assert c.y.shape == (2, 0, n_f) and c.finv.shape == (0, n_f) - assert c.pixel_rc.shape == (0, 2) and c.roi_f.shape == (0, 2, n_f) - assert c.n_subproblems == 0 and not c.baseline_filled - np.testing.assert_array_equal(c.global_f, full.global_f) - np.testing.assert_array_equal(c.frame_lines, full.frame_lines) - with h5py.File(path, "r") as f: - assert f["baseline/values"].shape == (0, 0) - with pytest.raises(IndexError, match="not one of 0"): - read_subproblem(path, 0) - - -def test_interrupted_write_leaves_the_old_container( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A failed write keeps an existing container and no partial file under its name.""" - trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) - before = path.read_bytes() - from giant_python.extraction.raster import container - - def fail(*args: object, **kwargs: object) -> NoReturn: - """Stand in for a failure late in the write.""" - raise OSError("disk full") - - monkeypatch.setattr(container, "_reserve_baseline", fail) - other, *rest = make_trial(seed=1) - with pytest.raises(OSError, match="disk full"): - write_container(path, other, *rest[:3], SHAPE) - assert path.read_bytes() == before - assert not list(tmp_path.glob("*.partial")) - np.testing.assert_array_equal(read_container(path).y, trial.y) - # the write completes but the file cannot take its name (a folder has - # it): the temporary file is removed too - monkeypatch.undo() - taken = tmp_path / "taken.h5" - taken.mkdir() - with pytest.raises(OSError): - write_container(taken, other, *rest[:3], SHAPE) - assert taken.is_dir() and not list(tmp_path.glob("*.partial")) +"""Tests of the container: one trial-path's inputs of source extraction.""" + +from pathlib import Path +from typing import NoReturn + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.container import ( + FORMAT_VERSION, + crop_of, + read_container, + read_subproblem, + settings_hash, + write_container, +) +from giant_python.extraction.raster.trial_data import ( + TrialData, + TrialLoadParams, +) + +SHAPE = (12, 15) # consensus frame + + +def make_trial( + n_frames: int = 40, seed: int = 0 +) -> tuple[TrialData, np.ndarray, list[np.ndarray], list[np.ndarray], np.ndarray]: + """Make a small trial with two blobs of selected pixels and three sources. + + Returns the trial, the sources and each subproblem's pixels and + sources: the two blobs' subproblems share the pixels of column 7. + + Returns + ------- + trial : TrialData + The trial. + sources_rc : np.ndarray + (3, 2) row/column positions of the sources. + pixels : list of np.ndarray + Each subproblem's pixels, as indices into the trial's selected pixels. + sources : list of np.ndarray + Each subproblem's source indices. + sel : np.ndarray + Boolean mask of the selected pixels in the consensus frame. + """ + rng = np.random.default_rng(seed) + sel = np.zeros(SHAPE, dtype=bool) + sel[2:7, 3:8] = True + sel[4:10, 7:12] = True + cols, rows = np.nonzero(sel.T) # column-major, as find(selPix) + pixel_rc = np.stack([rows, cols], 1) + n_px = rows.size + trial = TrialData( + y=rng.standard_normal((2, n_px, n_frames)).astype(np.float32), + finv=(1 + rng.random((n_px, n_frames))).astype(np.float32), + frame_lines=np.ceil(np.arange(n_frames) * 53.4 + 1).astype(np.int64), + motion_r=rng.standard_normal(n_frames), + motion_c=rng.standard_normal(n_frames), + discard=rng.random(n_frames) < 0.1, + global_f=rng.random((2, n_frames)), + roi_f=rng.random((3, 2, n_frames)), + roi_fsvd=rng.random((3, 2, n_frames)), + pixel_rc=pixel_rc, + trial_rc=pixel_rc + np.array([0.25, -0.5]), + photon_scale=25.0, + ) + trial.roi_f[1] = np.nan # a ROI without data + sources_rc = np.array([[4, 5], [6, 9], [8, 10]]) + in_a = (rows < 7) & (cols < 8) + in_b = (rows >= 4) & (cols >= 7) + pixels = [np.flatnonzero(in_a), np.flatnonzero(in_b)] + return trial, sources_rc, pixels, [np.array([0]), np.array([1, 2])], sel + + +@pytest.mark.parametrize("compression", ["lzf", "gzip", None]) +def test_round_trip_is_exact(tmp_path: Path, compression: str | None) -> None: + """Everything written is read back unchanged, whole or by subproblem.""" + trial, sources_rc, pixels, sources, sel = make_trial() + params = {"loader": TrialLoadParams(), "lambda": 0.9, "k": np.arange(3.0)} + path = write_container( + tmp_path / "trial.h5", + trial, + sources_rc, + pixels, + sources, + SHAPE, + params, + {"dat": "a_DMD1-TRIAL000002.dat", "path": 1, "trial": 2}, + compression=compression, + chunk_pixels=4, + ) + assert path.exists() and not list(tmp_path.glob("*.partial")) + c = read_container(path) + for name in ( + "y", + "finv", + "frame_lines", + "discard", + "motion_r", + "motion_c", + "pixel_rc", + "trial_rc", + "global_f", + "roi_f", + "roi_fsvd", + ): + got, want = getattr(c, name), getattr(trial, name) + np.testing.assert_array_equal(got, want) + assert got.dtype == want.dtype or name == "pixel_rc" + np.testing.assert_array_equal(c.sources_rc, sources_rc) + assert c.consensus_shape == SHAPE and c.photon_scale == 25.0 + assert c.n_subproblems == 2 and not c.baseline_filled + assert c.params["lambda"] == 0.9 and c.params["k"] == [0.0, 1.0, 2.0] + assert c.params["loader"]["analyze_hz"] == 200.0 + assert c.source == {"dat": "a_DMD1-TRIAL000002.dat", "path": 1, "trial": 2} + assert c.settings_hash == settings_hash(params) and c.code_version + shell = read_container(path, data=False) + assert shell.y is None and shell.finv is None + with pytest.raises(ValueError, match="without its data"): + shell.subproblem(0) + with h5py.File(path, "r") as f: + from_file = [read_subproblem(f, k) for k in range(2)] + for k in range(2): + for sp in (c.subproblem(k), read_subproblem(path, k), from_file[k]): + np.testing.assert_array_equal(sp.y, trial.y[:, pixels[k]]) + np.testing.assert_array_equal(sp.finv, trial.finv[pixels[k]]) + assert sp.y.dtype == np.float32 and sp.y.shape[0] == 2 + np.testing.assert_array_equal(sp.pixels, pixels[k]) + np.testing.assert_array_equal(sp.sources, sources[k]) + # the crop is the bounding box of the pixels; sel's true + # elements in column-major order are the rows of y + rc = trial.pixel_rc[pixels[k]] + assert (sp.row0, sp.col0) == tuple(rc.min(0)) + box = sel[ + sp.row0 : sp.row0 + sp.sel.shape[0], + sp.col0 : sp.col0 + sp.sel.shape[1], + ] + assert not (sp.sel & ~box).any() # within the selected map + cols, rows = np.nonzero(sp.sel.T) + np.testing.assert_array_equal(np.stack([rows + sp.row0, cols + sp.col0], 1), rc) + np.testing.assert_array_equal( + sp.sources_rc, sources_rc[sources[k]] - [sp.row0, sp.col0] + ) + # overlapping subproblems share pixels: the data are stored once + shared = np.intersect1d(pixels[0], pixels[1]) + assert shared.size == 3 + with h5py.File(path, "r") as f: + assert f["data/y"].shape == trial.y.shape + assert f["data/y"].chunks == (1, 4, trial.y.shape[2]) + assert f["data/y"].compression == compression + assert f.attrs["format_version"] == FORMAT_VERSION + + +def test_baseline_is_reserved_and_can_be_filled(tmp_path: Path) -> None: + """The F0 network's baseline has empty, resizable datasets.""" + trial, sources_rc, pixels, sources, _ = make_trial() + path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) + n_px = trial.y.shape[1] + with h5py.File(path, "r+") as f: + g = f["baseline"] + assert g["values"].shape == (n_px, 0) + assert g["values"].maxshape == (n_px, None) + assert g["frame_lines"].shape == (0,) and g.attrs["filled"] == 0 + assert g["values"].id.get_storage_size() == 0 # nothing stored + g["values"].resize((n_px, 16)) + g["frame_lines"].resize((16,)) + assert np.isnan(g["values"][()]).all() # unwritten: NaN + g["values"][...] = 1.5 + g["frame_lines"][...] = np.arange(16) * 133.0 + 1 + g.attrs["filled"] = 1 + c = read_container(path, data=False) + assert c.baseline_filled + np.testing.assert_array_equal( # the data are untouched + read_subproblem(path, 1).y, trial.y[:, pixels[1]] + ) + + +def test_settings_hash_ignores_key_order_only() -> None: + """The same settings hash alike however they are ordered or typed.""" + a = {"lambda": 0.9, "loader": TrialLoadParams(), "k": np.array([1.0, 2.0])} + b = { + "k": [1.0, 2.0], + "loader": { + "block_frames": 600, + "nan_thresh": 0.33, + "baseline_window_s": 4.0, + "photon_scale": np.float64(25.0), + "activity_channel": np.int64(1), + "analyze_hz": 200.0, + }, + "lambda": 0.9, + } + assert settings_hash(a) == settings_hash(b) + assert len(settings_hash(a)) == 64 + assert settings_hash(a) != settings_hash({**a, "lambda": 1.0}) + assert settings_hash({}) != settings_hash({"lambda": 0.9}) + + +def test_subproblem_lists_are_checked(tmp_path: Path) -> None: + """Index lists must match, increase and stay inside their lists.""" + trial, sources_rc, pixels, sources, _ = make_trial() + path = tmp_path / "trial.h5" + cases = [ + (pixels[:1], sources, "one source list"), + ([pixels[0][::-1], pixels[1]], sources, "pixels must increase"), + ([pixels[0], pixels[1] + 1000], sources, "pixels outside"), + (pixels, [np.array([0]), np.array([1, 3])], "sources outside"), + (pixels, [np.array([0]), np.array([2, 1])], "sources must increase"), + # fractions are not cut to the index below them + ([np.array([-0.5, 3.0]), pixels[1]], sources, "pixels must be whole"), + ([pixels[0] + 0.25, pixels[1]], sources, "pixels must be whole"), + (pixels, [[np.nan], [1, 2]], "sources must be whole"), + (pixels, [[True], [1, 2]], "sources must be whole"), + ] + for pix, src, message in cases: + with pytest.raises(ValueError, match=message): + write_container(path, trial, sources_rc, pix, src, SHAPE) + assert not path.exists() + # whole numbers held as floating point are indices + as_float = [v.astype(np.float64) for v in pixels] + write_container(path, trial, sources_rc, as_float, sources, SHAPE) + np.testing.assert_array_equal(read_container(path, data=False).subproblem_pixels[1], pixels[1]) + write_container(path, trial, sources_rc, pixels, sources, SHAPE) + # the same indices are refused in memory and from the file + whole = read_container(path) + for k in (2, -1): + for source in (path, whole): + with pytest.raises(IndexError, match="not one of 2"): + read_subproblem(source, k) + + +def test_empty_grouping_and_foreign_files(tmp_path: Path) -> None: + """A container may hold no subproblems, or an empty one. + + Other HDF5 files and newer formats are refused. + """ + trial, sources_rc, pixels, sources, _ = make_trial() + path = write_container(tmp_path / "none.h5", trial, sources_rc[:0], [], [], SHAPE) + c = read_container(path) + assert c.n_subproblems == 0 and c.crops.shape == (0, 4) + assert c.sources_rc.shape == (0, 2) + empty = [np.zeros(0, int), pixels[1]] + path = write_container(tmp_path / "empty.h5", trial, sources_rc, empty, [[], [1, 2]], SHAPE) + sp = read_subproblem(path, 0) + assert sp.y.shape == (2, 0, trial.y.shape[2]) and sp.sel.shape == (0, 0) + assert sp.sources_rc.shape == (0, 2) + np.testing.assert_array_equal(crop_of(trial.pixel_rc[:0]), [0, 0, 0, 0]) + np.testing.assert_array_equal(read_subproblem(path, 1).y, trial.y[:, pixels[1]]) + other = tmp_path / "other.h5" + with h5py.File(other, "w") as f: + f["data"] = np.arange(3) + with pytest.raises(ValueError, match="not a SILo container"): + read_container(other) + with h5py.File(path, "r+") as f: + f.attrs["format_version"] = FORMAT_VERSION + 1 + with pytest.raises(ValueError, match="container format"): + read_subproblem(path, 0) + + +@pytest.mark.parametrize("compression", ["lzf", None]) +def test_trial_without_selected_pixels_round_trips(tmp_path: Path, compression: str | None) -> None: + """A path without sources has no selected pixels. + + Its container holds the frames and traces, and empty data. + """ + full, *_ = make_trial() + n_f = full.frame_lines.size + trial = TrialData( + y=np.zeros((2, 0, n_f), np.float32), + finv=np.zeros((0, n_f), np.float32), + frame_lines=full.frame_lines, + motion_r=full.motion_r, + motion_c=full.motion_c, + discard=full.discard, + global_f=full.global_f, + roi_f=np.zeros((0, 2, n_f)), + roi_fsvd=np.zeros((0, 2, n_f)), + pixel_rc=np.zeros((0, 2), np.int64), + trial_rc=np.zeros((0, 2)), + photon_scale=25.0, + ) + path = write_container( + tmp_path / "empty.h5", + trial, + np.zeros((0, 2), int), + [], + [], + SHAPE, + compression=compression, + ) + c = read_container(path) + assert c.y.shape == (2, 0, n_f) and c.finv.shape == (0, n_f) + assert c.pixel_rc.shape == (0, 2) and c.roi_f.shape == (0, 2, n_f) + assert c.n_subproblems == 0 and not c.baseline_filled + np.testing.assert_array_equal(c.global_f, full.global_f) + np.testing.assert_array_equal(c.frame_lines, full.frame_lines) + with h5py.File(path, "r") as f: + assert f["baseline/values"].shape == (0, 0) + with pytest.raises(IndexError, match="not one of 0"): + read_subproblem(path, 0) + + +def test_interrupted_write_leaves_the_old_container( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed write keeps an existing container and no partial file under its name.""" + trial, sources_rc, pixels, sources, _ = make_trial() + path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) + before = path.read_bytes() + from giant_python.extraction.raster import container + + def fail(*args: object, **kwargs: object) -> NoReturn: + """Stand in for a failure late in the write. + + Raises + ------ + OSError + Always, to simulate a full disk. + """ + raise OSError("disk full") + + monkeypatch.setattr(container, "_reserve_baseline", fail) + other, *rest = make_trial(seed=1) + with pytest.raises(OSError, match="disk full"): + write_container(path, other, *rest[:3], SHAPE) + assert path.read_bytes() == before + assert not list(tmp_path.glob("*.partial")) + np.testing.assert_array_equal(read_container(path).y, trial.y) + # the write completes but the file cannot take its name (a folder has + # it): the temporary file is removed too + monkeypatch.undo() + taken = tmp_path / "taken.h5" + taken.mkdir() + with pytest.raises(OSError): + write_container(taken, other, *rest[:3], SHAPE) + assert taken.is_dir() and not list(tmp_path.glob("*.partial")) diff --git a/tests/raster/test_raster_f0_images.py b/tests/raster/test_raster_f0_images.py index cc6e2fda..a32c9397 100644 --- a/tests/raster/test_raster_f0_images.py +++ b/tests/raster/test_raster_f0_images.py @@ -1,305 +1,330 @@ -"""Tests of SILo's per-trial F0 images (``f0_im_trim_s``). - -Covers the frames they average, the solver's per-subproblem image, results -files, assembly over subproblems and the summaries (GIAnT-MATLAB's spine-size -branch). -""" - -import argparse -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import numpy.typing as npt -import pytest - -from giant_python.cli_silo import params_from_args -from giant_python.extraction.raster.results import ( - TrialOutcome, - TrialRecord, - _same, - read_results, - write_results, -) -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - assemble_results, - solve_subproblem, -) -from giant_python.extraction.raster.solver_setup import Subproblem, f0_image_frames -from giant_python.extraction.raster.summary import PathResult, write_summaries -from giant_python.models.params import SiloParams -from giant_python.spine.summary_io import RunSummary - -from .test_raster_solver import ( - PARAMS, - _placed, - _result, - fixture, # noqa: F401 (a pytest fixture) -) -from .test_raster_summary import N_TRIALS, C, H, W, alignment, make_plan -from .test_raster_summary import outcome as summary_outcome - - -def test_f0_image_frames_trim_the_kept_frames() -> None: - """Kept frames less the trim at each end. - - All kept frames when the trim leaves none; no trim keeps every kept frame. - """ - discard = np.zeros(20, bool) - discard[[5, 6]] = True - fr = f0_image_frames(discard, 0.02, 200.0) # 4 frames each end - want = ~discard - want[:4] = want[16:] = False - np.testing.assert_array_equal(fr, want) - np.testing.assert_array_equal(f0_image_frames(discard, 0.0, 200), ~discard) - # a trial too short for the trim is averaged whole (its kept frames) - np.testing.assert_array_equal(f0_image_frames(discard, 1.0, 200), ~discard) - assert not f0_image_frames(np.ones(5, bool), 0.0, 200).any() - # half a frame rounds up (MATLAB's round, the spine readout's trim) - fr = f0_image_frames(np.zeros(20, bool), 0.0125, 200.0) # 2.5 frames - assert fr[3:17].all() and not fr[:3].any() and not fr[17:].any() - - -def test_solver_averages_its_final_baseline( - fixture: tuple[Subproblem, dict[str, np.ndarray]], # noqa: F811 -) -> None: - """The F0 image is the final baseline averaged over the given frames. - - The final baseline is as kept with keep_baseline; averaged per channel and - pixel. - """ - sub, _ = fixture - n_t = sub.y.shape[2] - frames = np.zeros(n_t, bool) - frames[n_t // 5 : 4 * n_t // 5] = True - frames[::7] = False - r = solve_subproblem( - replace(sub, f0_frames=frames), - PARAMS, - SolverOptions(keep_baseline=True), - ) - assert r.f0_image.shape == (sub.y.shape[0], sub.y.shape[1]) - np.testing.assert_allclose(r.f0_image, r.baseline[:, :, frames].mean(axis=2), rtol=1e-12) - assert solve_subproblem(sub, PARAMS).f0_image is None - with pytest.raises(ValueError, match="f0_frames has"): - solve_subproblem(replace(sub, f0_frames=frames[:-1]), PARAMS) - - -def _with_image(result: SubproblemResult, image: npt.ArrayLike) -> SubproblemResult: - """Return ``result`` with an F0 image.""" - return replace(result, f0_image=np.asarray(image, float)) - - -def test_assembly_averages_shared_pixels() -> None: - """Pixels held by several subproblems get the mean of their images. - - In movie units; pixels held by none are NaN; without an image in every - subproblem there is none. - """ - subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - b = _with_image(_result(2, 2, 6, 2.0), [[10, 20], [30, 40]]) - t = assemble_results(subs, [a, b], 6, 5, photon_scale=25.0) - want = np.full((2, 6), np.nan) - want[:, [0, 1]] = [[1, 2], [4, 5]] - want[:, 2] = [10, 30] - want[:, 4] = [(3 + 20) / 2, (6 + 40) / 2] - np.testing.assert_allclose(t.f0_image, 25.0 * want) - t2 = assemble_results(subs, [a, _result(2, 2, 6, 2.0)], 6, 5, photon_scale=25.0) - assert t2.f0_image is None - with pytest.raises(ValueError, match="f0_image is"): - assemble_results(subs, [a, _with_image(b, [[1, 2, 3]])], 6, 5, photon_scale=25.0) - - -def _record(n_t: int = 6) -> TrialRecord: - """Build a trial record of ``n_t`` frames.""" - return TrialRecord( - frame_lines=np.arange(n_t) + 1, - discard=np.zeros(n_t, bool), - global_f=np.zeros((2, n_t)), - roi_f=np.zeros((0, 2, n_t)), - roi_fsvd=np.zeros((0, 2, n_t)), - ) - - -def test_results_files_keep_the_image(tmp_path: Path) -> None: - """The image goes into the results file and back. - - A result without one reads back without one, and the two do not count as - equal. - """ - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - b = _result(3, 1, 6, 1.0) - attrs = {"n_subproblems": 2, "n_pixels": 6, "n_sources": 5} - path = write_results( - tmp_path / "r.h5", - _record(), - {0: (np.array([0, 1, 4]), np.array([2]), a), 1: ([2, 3, 5], [0], b)}, - attrs, - ) - back = read_results(path).results - np.testing.assert_array_equal(back[0][2].f0_image, a.f0_image) - assert back[1][2].f0_image is None - with h5py.File(path) as f: - assert "f0_image" in f["subproblems/0"] - assert "f0_image" not in f["subproblems/1"] - assert _same(back[0], (np.array([0, 1, 4]), np.array([2]), a)) - assert not _same(back[0], (np.array([0, 1, 4]), np.array([2]), b)) - - -def _f0_outcome(t: int, n_px: int, scale: float) -> TrialOutcome: - """Build the summary tests' trial outcome with an F0 image. - - The analysis channel ``c`` of pixel ``p`` holds ``scale * (100 c + p + 1)``. - """ - out = summary_outcome(t, n_px) - img = scale * (100.0 * np.arange(C)[:, None] + np.arange(n_px)[None, :] + 1) - out.activity.f0_image = img - return out - - -def test_summaries_hold_the_f0_images(tmp_path: Path) -> None: - """The summaries hold the per-trial F0 images and the user ROIs' F0. - - The per-trial F0 images (file channel order, NaN outside the selected - pixels and for trials without one), their mean over trials and the user - ROIs' F0 with coverage, in MATLAB's layout, read back by the spine - readout's reader. - """ - plan = make_plan() - n_px = plan.n_pixels - result = PathResult( - plan=plan, - trials=[None, _f0_outcome(1, n_px, 1.0), _f0_outcome(2, n_px, 2.0)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=["spine01", "soma"], - roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], - ) - params = SiloParams(activity_channel=2).to_matlab(C, 80.0, 1, "a", "b") - exp = tmp_path / "experiment_summary.h5" - per = tmp_path / "per_trial_summary.h5" - write_summaries(exp, per, [result], params, N_TRIALS, C, 2) - rows, cols = plan.selected_pixels() - # activity channel 2 is analysis channel 0 - want = np.full((N_TRIALS, H, W, C), np.nan) - for t, scale in ((1, 1.0), (2, 2.0)): - want[t, rows, cols, 1] = scale * (np.arange(n_px) + 1) - want[t, rows, cols, 0] = scale * (100 + np.arange(n_px) + 1) - with h5py.File(per) as f: - g = f["Path1"] - raw = g["visualizations/per_trial_F0_im"] - assert raw.dtype == np.float32 - assert raw.shape == g["visualizations/per_trial_mean_im"].shape - np.testing.assert_allclose(raw[()].T[:, :, 0].transpose(0, 2, 3, 1), want) - roi = g["user_rois/per_trial_F0"][()].T # rois, channels, trials - cov = g["user_rois/per_trial_F0_coverage"][()].T # rois, trials - with h5py.File(exp) as f: - f0_im = f["Path1/visualizations/F0_im"][()].T[:, 0] # C, H, W - with np.errstate(invalid="ignore"): - mean = np.nanmean(want[1:], axis=0).transpose(2, 0, 1) - np.testing.assert_allclose(f0_im, mean) - eye = np.eye(H, W, dtype=bool) - for r, mask in enumerate((eye, np.ones((H, W), bool))): - for t in range(N_TRIALS): - vals = want[t][mask] # pixels, channels - if t == 0: - assert np.isnan(roi[r, :, t]).all() and cov[r, t] == 0 - continue - np.testing.assert_allclose(roi[r, :, t], np.nanmean(vals, 0)) - assert cov[r, t] == pytest.approx(np.isfinite(vals[:, 1]).mean()) - run = RunSummary(tmp_path) - for c in range(C): - np.testing.assert_allclose(run.per_trial_images(1, "per_trial_F0_im", c), want[..., c]) - - -def test_no_f0_images_without_them(tmp_path: Path) -> None: - """Trials without F0 images give no F0 datasets.""" - plan = make_plan() - n_px = plan.n_pixels - result = PathResult( - plan=plan, - trials=[None, summary_outcome(1, n_px), summary_outcome(2, n_px)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=["spine01", "soma"], - roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], - ) - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0) - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], params, N_TRIALS, C, 1) - with h5py.File(per) as f, h5py.File(exp) as g: - assert "per_trial_F0_im" not in f["Path1/visualizations"] - assert "per_trial_F0" not in f.get("Path1/user_rois", {}) - assert "F0_im" not in g["Path1/visualizations"] - assert "F0imTrim_s" not in g["params"] - - -def test_trial_outcome_carries_the_image() -> None: - """A trial's processed activity keeps the assembled F0 image.""" - from giant_python.extraction.raster.results import trial_outcome - - class File: - """A results file in memory.""" - - def __init__(self, results: dict, attrs: dict) -> None: - """Hold the parts :func:`trial_outcome` reads.""" - self.record = _record() - self.results = results - self.attrs = attrs - - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - attrs = dict( - n_subproblems=1, - n_pixels=3, - n_sources=1, - photon_scale=2.0, - container="c", - container_hash="h", - ) - out = trial_outcome( - [File({0: (np.arange(3), np.array([0]), a)}, attrs)], - replace(PARAMS), - ) - assert isinstance(out, TrialOutcome) - np.testing.assert_allclose(out.activity.f0_image, 2.0 * a.f0_image) - - -def test_settings_and_options() -> None: - """The trim is a solve-stage setting recorded only when F0 images are made. - - Results files made without them stay current then; the command line turns - them off or sets the trim, not both. - """ - assert "f0_im_trim_s" not in SiloParams(f0_im_trim_s=None).stage_settings("solve") - assert SiloParams().stage_settings("solve")["f0_im_trim_s"] == 1.0 - assert SiloParams().to_matlab(2, 80.0)["F0imTrim_s"] == 1.0 - with pytest.raises(ValueError, match="f0_im_trim_s"): - SiloParams(f0_im_trim_s=-1.0) - - def args(**kw: object) -> argparse.Namespace: - """Build a namespace with the F0-image options.""" - return argparse.Namespace(**{"f0_im_trim_s": None, "no_f0_images": False, **kw}) - - assert params_from_args(args()).f0_im_trim_s == 1.0 - assert params_from_args(args(no_f0_images=True)).f0_im_trim_s is None - assert params_from_args(args(f0_im_trim_s=0.5)).f0_im_trim_s == 0.5 - with pytest.raises(ValueError, match="not both"): - params_from_args(args(f0_im_trim_s=0.5, no_f0_images=True)) - - -def test_results_without_images_assemble_without(tmp_path: Path) -> None: - """Results of a run without F0 images give a trial without an image. - - Also for older files. - """ - r = SubproblemResult( - footprints=np.ones((2, 1)), - events=np.zeros((2, 1, 6)), - ls=np.zeros((2, 1, 6)), - f0=np.ones((2, 1, 6)), - snr=np.ones(1), - ) - t = assemble_results([_placed([0, 1], [0], 6)], [r], 2, 1, 25.0) - assert t.f0_image is None +"""Tests of SILo's per-trial F0 images (f0_im_trim_s). + +Covers the frames they average, the solver's per-subproblem image, results +files, assembly over subproblems and the summaries (GIAnT-MATLAB's spine-size +branch). +""" + +import argparse +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import numpy.typing as npt +import pytest + +from giant_python.cli_silo import params_from_args +from giant_python.extraction.raster.results import ( + TrialOutcome, + TrialRecord, + _same, + read_results, + write_results, +) +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + assemble_results, + solve_subproblem, +) +from giant_python.extraction.raster.solver_setup import Subproblem, f0_image_frames +from giant_python.extraction.raster.summary import PathResult, write_summaries +from giant_python.models.params import SiloParams +from giant_python.spine.summary_io import RunSummary + +from .test_raster_solver import ( + PARAMS, + _placed, + _result, + fixture, # noqa: F401 (a pytest fixture) +) +from .test_raster_summary import N_TRIALS, C, H, W, alignment, make_plan +from .test_raster_summary import outcome as summary_outcome + + +def test_f0_image_frames_trim_the_kept_frames() -> None: + """Kept frames less the trim at each end. + + All kept frames when the trim leaves none; no trim keeps every kept frame. + """ + discard = np.zeros(20, bool) + discard[[5, 6]] = True + fr = f0_image_frames(discard, 0.02, 200.0) # 4 frames each end + want = ~discard + want[:4] = want[16:] = False + np.testing.assert_array_equal(fr, want) + np.testing.assert_array_equal(f0_image_frames(discard, 0.0, 200), ~discard) + # a trial too short for the trim is averaged whole (its kept frames) + np.testing.assert_array_equal(f0_image_frames(discard, 1.0, 200), ~discard) + assert not f0_image_frames(np.ones(5, bool), 0.0, 200).any() + # half a frame rounds up (MATLAB's round, the spine readout's trim) + fr = f0_image_frames(np.zeros(20, bool), 0.0125, 200.0) # 2.5 frames + assert fr[3:17].all() and not fr[:3].any() and not fr[17:].any() + + +def test_solver_averages_its_final_baseline( + fixture: tuple[Subproblem, dict[str, np.ndarray]], # noqa: F811 +) -> None: + """The F0 image is the final baseline averaged over the given frames. + + The final baseline is as kept with keep_baseline; averaged per channel and + pixel. + """ + sub, _ = fixture + n_t = sub.y.shape[2] + frames = np.zeros(n_t, bool) + frames[n_t // 5 : 4 * n_t // 5] = True + frames[::7] = False + r = solve_subproblem( + replace(sub, f0_frames=frames), + PARAMS, + SolverOptions(keep_baseline=True), + ) + assert r.f0_image.shape == (sub.y.shape[0], sub.y.shape[1]) + np.testing.assert_allclose(r.f0_image, r.baseline[:, :, frames].mean(axis=2), rtol=1e-12) + assert solve_subproblem(sub, PARAMS).f0_image is None + with pytest.raises(ValueError, match="f0_frames has"): + solve_subproblem(replace(sub, f0_frames=frames[:-1]), PARAMS) + + +def _with_image(result: SubproblemResult, image: npt.ArrayLike) -> SubproblemResult: + """Return result with an F0 image. + + Returns + ------- + SubproblemResult + A copy of result whose f0_image is image as a float array. + """ + return replace(result, f0_image=np.asarray(image, float)) + + +def test_assembly_averages_shared_pixels() -> None: + """Pixels held by several subproblems get the mean of their images. + + In movie units; pixels held by none are NaN; without an image in every + subproblem there is none. + """ + subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + b = _with_image(_result(2, 2, 6, 2.0), [[10, 20], [30, 40]]) + t = assemble_results(subs, [a, b], 6, 5, photon_scale=25.0) + want = np.full((2, 6), np.nan) + want[:, [0, 1]] = [[1, 2], [4, 5]] + want[:, 2] = [10, 30] + want[:, 4] = [(3 + 20) / 2, (6 + 40) / 2] + np.testing.assert_allclose(t.f0_image, 25.0 * want) + t2 = assemble_results(subs, [a, _result(2, 2, 6, 2.0)], 6, 5, photon_scale=25.0) + assert t2.f0_image is None + with pytest.raises(ValueError, match="f0_image is"): + assemble_results(subs, [a, _with_image(b, [[1, 2, 3]])], 6, 5, photon_scale=25.0) + + +def _record(n_t: int = 6) -> TrialRecord: + """Build a trial record of n_t frames. + + Returns + ------- + TrialRecord + A record of n_t frames with zero fluorescence, no ROIs and no discarded frames. + """ + return TrialRecord( + frame_lines=np.arange(n_t) + 1, + discard=np.zeros(n_t, bool), + global_f=np.zeros((2, n_t)), + roi_f=np.zeros((0, 2, n_t)), + roi_fsvd=np.zeros((0, 2, n_t)), + ) + + +def test_results_files_keep_the_image(tmp_path: Path) -> None: + """The image goes into the results file and back. + + A result without one reads back without one, and the two do not count as + equal. + """ + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + b = _result(3, 1, 6, 1.0) + attrs = {"n_subproblems": 2, "n_pixels": 6, "n_sources": 5} + path = write_results( + tmp_path / "r.h5", + _record(), + {0: (np.array([0, 1, 4]), np.array([2]), a), 1: ([2, 3, 5], [0], b)}, + attrs, + ) + back = read_results(path).results + np.testing.assert_array_equal(back[0][2].f0_image, a.f0_image) + assert back[1][2].f0_image is None + with h5py.File(path) as f: + assert "f0_image" in f["subproblems/0"] + assert "f0_image" not in f["subproblems/1"] + assert _same(back[0], (np.array([0, 1, 4]), np.array([2]), a)) + assert not _same(back[0], (np.array([0, 1, 4]), np.array([2]), b)) + + +def _f0_outcome(t: int, n_px: int, scale: float) -> TrialOutcome: + """Build the summary tests' trial outcome with an F0 image. + + The analysis channel c of pixel p holds scale * (100 c + p + 1). + + Returns + ------- + TrialOutcome + The summary tests' outcome for trial t and n_px pixels, with that F0 image + set on its activity. + """ + out = summary_outcome(t, n_px) + img = scale * (100.0 * np.arange(C)[:, None] + np.arange(n_px)[None, :] + 1) + out.activity.f0_image = img + return out + + +def test_summaries_hold_the_f0_images(tmp_path: Path) -> None: + """The summaries hold the per-trial F0 images and the user ROIs' F0. + + The per-trial F0 images (file channel order, NaN outside the selected + pixels and for trials without one), their mean over trials and the user + ROIs' F0 with coverage, in MATLAB's layout, read back by the spine + readout's reader. + """ + plan = make_plan() + n_px = plan.n_pixels + result = PathResult( + plan=plan, + trials=[None, _f0_outcome(1, n_px, 1.0), _f0_outcome(2, n_px, 2.0)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=["spine01", "soma"], + roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], + ) + params = SiloParams(activity_channel=2).to_matlab(C, 80.0, 1, "a", "b") + exp = tmp_path / "experiment_summary.h5" + per = tmp_path / "per_trial_summary.h5" + write_summaries(exp, per, [result], params, N_TRIALS, C, 2) + rows, cols = plan.selected_pixels() + # activity channel 2 is analysis channel 0 + want = np.full((N_TRIALS, H, W, C), np.nan) + for t, scale in ((1, 1.0), (2, 2.0)): + want[t, rows, cols, 1] = scale * (np.arange(n_px) + 1) + want[t, rows, cols, 0] = scale * (100 + np.arange(n_px) + 1) + with h5py.File(per) as f: + g = f["Path1"] + raw = g["visualizations/per_trial_F0_im"] + assert raw.dtype == np.float32 + assert raw.shape == g["visualizations/per_trial_mean_im"].shape + np.testing.assert_allclose(raw[()].T[:, :, 0].transpose(0, 2, 3, 1), want) + roi = g["user_rois/per_trial_F0"][()].T # rois, channels, trials + cov = g["user_rois/per_trial_F0_coverage"][()].T # rois, trials + with h5py.File(exp) as f: + f0_im = f["Path1/visualizations/F0_im"][()].T[:, 0] # C, H, W + with np.errstate(invalid="ignore"): + mean = np.nanmean(want[1:], axis=0).transpose(2, 0, 1) + np.testing.assert_allclose(f0_im, mean) + eye = np.eye(H, W, dtype=bool) + for r, mask in enumerate((eye, np.ones((H, W), bool))): + for t in range(N_TRIALS): + vals = want[t][mask] # pixels, channels + if t == 0: + assert np.isnan(roi[r, :, t]).all() and cov[r, t] == 0 + continue + np.testing.assert_allclose(roi[r, :, t], np.nanmean(vals, 0)) + assert cov[r, t] == pytest.approx(np.isfinite(vals[:, 1]).mean()) + run = RunSummary(tmp_path) + for c in range(C): + np.testing.assert_allclose(run.per_trial_images(1, "per_trial_F0_im", c), want[..., c]) + + +def test_no_f0_images_without_them(tmp_path: Path) -> None: + """Trials without F0 images give no F0 datasets.""" + plan = make_plan() + n_px = plan.n_pixels + result = PathResult( + plan=plan, + trials=[None, summary_outcome(1, n_px), summary_outcome(2, n_px)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=["spine01", "soma"], + roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], + ) + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0) + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], params, N_TRIALS, C, 1) + with h5py.File(per) as f, h5py.File(exp) as g: + assert "per_trial_F0_im" not in f["Path1/visualizations"] + assert "per_trial_F0" not in f.get("Path1/user_rois", {}) + assert "F0_im" not in g["Path1/visualizations"] + assert "F0imTrim_s" not in g["params"] + + +def test_trial_outcome_carries_the_image() -> None: + """A trial's processed activity keeps the assembled F0 image.""" + from giant_python.extraction.raster.results import trial_outcome + + class File: + """A results file in memory.""" + + def __init__(self, results: dict, attrs: dict) -> None: + """Hold the parts :func:`trial_outcome` reads.""" + self.record = _record() + self.results = results + self.attrs = attrs + + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + attrs = dict( + n_subproblems=1, + n_pixels=3, + n_sources=1, + photon_scale=2.0, + container="c", + container_hash="h", + ) + out = trial_outcome( + [File({0: (np.arange(3), np.array([0]), a)}, attrs)], + replace(PARAMS), + ) + assert isinstance(out, TrialOutcome) + np.testing.assert_allclose(out.activity.f0_image, 2.0 * a.f0_image) + + +def test_settings_and_options() -> None: + """The trim is a solve-stage setting recorded only when F0 images are made. + + Results files made without them stay current then; the command line turns + them off or sets the trim, not both. + """ + assert "f0_im_trim_s" not in SiloParams(f0_im_trim_s=None).stage_settings("solve") + assert SiloParams().stage_settings("solve")["f0_im_trim_s"] == 1.0 + assert SiloParams().to_matlab(2, 80.0)["F0imTrim_s"] == 1.0 + with pytest.raises(ValueError, match="f0_im_trim_s"): + SiloParams(f0_im_trim_s=-1.0) + + def args(**kw: object) -> argparse.Namespace: + """Build a namespace with the F0-image options. + + Returns + ------- + argparse.Namespace + The options f0_im_trim_s (None) and no_f0_images (False), overridden by + kw. + """ + return argparse.Namespace(**{"f0_im_trim_s": None, "no_f0_images": False, **kw}) + + assert params_from_args(args()).f0_im_trim_s == 1.0 + assert params_from_args(args(no_f0_images=True)).f0_im_trim_s is None + assert params_from_args(args(f0_im_trim_s=0.5)).f0_im_trim_s == 0.5 + with pytest.raises(ValueError, match="not both"): + params_from_args(args(f0_im_trim_s=0.5, no_f0_images=True)) + + +def test_results_without_images_assemble_without(tmp_path: Path) -> None: + """Results of a run without F0 images give a trial without an image. + + Also for older files. + """ + r = SubproblemResult( + footprints=np.ones((2, 1)), + events=np.zeros((2, 1, 6)), + ls=np.zeros((2, 1, 6)), + f0=np.ones((2, 1, 6)), + snr=np.ones(1), + ) + t = assemble_results([_placed([0, 1], [0], 6)], [r], 2, 1, 25.0) + assert t.f0_image is None diff --git a/tests/raster/test_raster_kinetics.py b/tests/raster/test_raster_kinetics.py index fde32118..54da33c1 100644 --- a/tests/raster/test_raster_kinetics.py +++ b/tests/raster/test_raster_kinetics.py @@ -1,144 +1,150 @@ -"""Tests of the kinetics test (sourceKinetics, rejectFastSources). - -``data/matlab_kinetics.h5`` holds GIAnT-MATLAB's results (main 5a0673b, -MATLAB R2024b) on the inputs of ``data/make_matlab_kinetics.m`` (converted -by ``data/make_matlab_kinetics_h5.py``): rows with -and without runs of equal values for ``islocalmax``, and three trials of -ten sources (four with the sensor's kinetics, three with one-frame -transients, three in between; discarded frames; a source without data in -one trial; a trial without traces). -""" - -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.kinetics import ( - islocalmax, - movmean_omitnan, - reject_fast_sources, - source_kinetics, -) - -DATA = Path(__file__).parent / "data" / "matlab_kinetics.h5" - - -@pytest.fixture(scope="module") -def ref() -> dict[str, Any]: - """MATLAB's inputs and results.""" - with h5py.File(DATA, "r") as f: - return {k: f[k][()] for k in f} - - -def test_islocalmax_matches_matlab(ref: dict[str, Any]) -> None: - """Maxima, runs of equal values and MinSeparation as MATLAB's.""" - for i, sep in enumerate(ref["seps"]): - got = islocalmax(ref["Y"], sep) - np.testing.assert_array_equal(got, ref["M"][i].astype(bool)) - - -def test_islocalmax_rules() -> None: - """Ends are never maxima; a run's centre is marked. - - A closer, more prominent maximum replaces the last one kept. - """ - y = np.array([5.0, 1, 3, 3, 3, 3, 1, 0, 4, 0, 2, 9]) - assert np.flatnonzero(islocalmax(y)).tolist() == [3, 8] - # 3 (run 2..5) and 8 are 3 apart from the run's end; 8 is more prominent - assert np.flatnonzero(islocalmax(y, 4)).tolist() == [8] - assert np.flatnonzero(islocalmax(y, 3)).tolist() == [3, 8] - assert not islocalmax(np.array([1.0, 2.0])).any() - two = np.stack([y, y[::-1]]) - np.testing.assert_array_equal(islocalmax(two)[1], islocalmax(y[::-1])) - - -def test_kinetics_scores_match_matlab(ref: dict[str, Any]) -> None: - """Scores and event counts of sourceKinetics; the sources kept.""" - traces = list(ref["LS"]) + [None] - score, n_events = source_kinetics(traces, 0.024, 200.0) - np.testing.assert_allclose(score, ref["score"], rtol=1e-12) - np.testing.assert_array_equal(n_events, ref["nEvents"]) - test = reject_fast_sources(traces, 10, 0.024, 200.0, 0.2) - np.testing.assert_array_equal(test.keep, ref["keep"].astype(bool)) - assert test.kept_score.size == test.keep.sum() - np.testing.assert_array_equal(test.rejected, np.flatnonzero(~test.keep)) - - -def test_movmean_omitnan() -> None: - """Window placement of MATLAB's movmean (even and odd), NaN left out.""" - x = np.array([[1.0, np.nan, 3, 4, 5, 6]]) - np.testing.assert_allclose(movmean_omitnan(x, 3)[0], [1, 2, 3.5, 4, 5, 5.5]) - # even window: two before, one after - np.testing.assert_allclose(movmean_omitnan(x, 4)[0], [1, 2, 8 / 3, 4, 4.5, 5]) - assert np.isnan(movmean_omitnan(np.full((1, 4), np.nan), 3)).all() - - -def test_source_minutes(ref: dict[str, Any]) -> None: - """Minutes of each source's frames that were not discarded, over the trials with traces. - - This gives the rate the evidence test compares. - """ - from giant_python.extraction.raster.kinetics import ( - source_minutes, - weak_sources, - ) - - np.testing.assert_allclose(source_minutes([np.zeros((2, 1200)), None], 2, 200.0), [0.1, 0.1]) - traces = [np.array(t, dtype=np.float64) for t in ref["LS"]] - n = traces[0].shape[0] - expect = source_minutes(traces, n, 200.0) - lost = np.isfinite(traces[0][2, :100]).sum() - traces[0][2, :100] = np.nan # source 2 loses frames of trial 1 - expect[2] -= lost / 200.0 / 60.0 - minutes = source_minutes(traces + [None, np.zeros((0, 0))], n, 200.0) - np.testing.assert_allclose(minutes, expect) - _, n_events = source_kinetics(traces, 0.024, 200.0) - rate = n_events / minutes - cut = float(np.median(rate)) - np.testing.assert_array_equal(weak_sources(np.ones(n), rate, min_event_rate=cut), rate < cut) - # a recording twice as long with the same events has half the rate - twice = source_minutes(traces + traces, n, 200.0) - np.testing.assert_allclose(twice, 2 * minutes) - - -def test_kinetics_edge_cases() -> None: - """No traces, a short time constant and threshold 0 keep everything.""" - score, n = source_kinetics([None], 0.024, 200.0) - assert score.size == 0 and n.size == 0 - rng = np.random.default_rng(0) - trace = rng.standard_normal((3, 400)) - score, n = source_kinetics([trace], 0.005, 200.0) # tau 1 frame - assert np.isnan(score).all() and (n == 0).all() - test = reject_fast_sources([None], 4, 0.024, 200.0, 0.2) - assert test.keep.all() and np.isnan(test.score).all() - test = reject_fast_sources([trace], 3, 0.024, 200.0, 0.0) - assert test.keep.all() - - -def test_weak_sources_and_mean_snr() -> None: - """The evidence test's criteria, each off at 0.""" - from giant_python.extraction.raster.kinetics import ( - mean_snr, - weak_sources, - ) - - snr = mean_snr([np.array([1.0, np.nan, 3.0]), None, np.array([3.0, np.nan, 5.0])], 3) - np.testing.assert_allclose(snr, [2.0, np.nan, 4.0]) - # only NaN is left out, as the summary's mean SNR - assert mean_snr([np.array([1.0]), np.array([np.inf])], 1)[0] == np.inf - rates = np.array([0.0, 9.0, 2.0]) - np.testing.assert_array_equal(weak_sources(snr, rates), [False, False, False]) - np.testing.assert_array_equal(weak_sources(snr, rates, min_snr=3.0), [True, False, False]) - np.testing.assert_array_equal(weak_sources(snr, rates, min_event_rate=3.0), [True, False, True]) - # a source without a rate (no valid frame) is not judged by it - np.testing.assert_array_equal( - weak_sources(snr, [np.nan, 9.0, 2.0], min_event_rate=3.0), - [False, False, True], - ) - with pytest.raises(ValueError): - weak_sources(snr, rates, min_event_rate=-1.0) - with pytest.raises(ValueError): - weak_sources(snr, rates, min_snr=-1.0) +"""Tests of the kinetics test (sourceKinetics, rejectFastSources). + +data/matlab_kinetics.h5 holds GIAnT-MATLAB's results (main 5a0673b, +MATLAB R2024b) on the inputs of data/make_matlab_kinetics.m (converted +by data/make_matlab_kinetics_h5.py): rows with +and without runs of equal values for islocalmax, and three trials of +ten sources (four with the sensor's kinetics, three with one-frame +transients, three in between; discarded frames; a source without data in +one trial; a trial without traces). +""" + +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.kinetics import ( + islocalmax, + movmean_omitnan, + reject_fast_sources, + source_kinetics, +) + +DATA = Path(__file__).parent / "data" / "matlab_kinetics.h5" + + +@pytest.fixture(scope="module") +def ref() -> dict[str, Any]: + """MATLAB's inputs and results. + + Returns + ------- + dict[str, Any] + Every dataset of the reference file, by name. + """ + with h5py.File(DATA, "r") as f: + return {k: f[k][()] for k in f} + + +def test_islocalmax_matches_matlab(ref: dict[str, Any]) -> None: + """Maxima, runs of equal values and MinSeparation as MATLAB's.""" + for i, sep in enumerate(ref["seps"]): + got = islocalmax(ref["Y"], sep) + np.testing.assert_array_equal(got, ref["M"][i].astype(bool)) + + +def test_islocalmax_rules() -> None: + """Ends are never maxima; a run's centre is marked. + + A closer, more prominent maximum replaces the last one kept. + """ + y = np.array([5.0, 1, 3, 3, 3, 3, 1, 0, 4, 0, 2, 9]) + assert np.flatnonzero(islocalmax(y)).tolist() == [3, 8] + # 3 (run 2..5) and 8 are 3 apart from the run's end; 8 is more prominent + assert np.flatnonzero(islocalmax(y, 4)).tolist() == [8] + assert np.flatnonzero(islocalmax(y, 3)).tolist() == [3, 8] + assert not islocalmax(np.array([1.0, 2.0])).any() + two = np.stack([y, y[::-1]]) + np.testing.assert_array_equal(islocalmax(two)[1], islocalmax(y[::-1])) + + +def test_kinetics_scores_match_matlab(ref: dict[str, Any]) -> None: + """Scores and event counts of sourceKinetics; the sources kept.""" + traces = list(ref["LS"]) + [None] + score, n_events = source_kinetics(traces, 0.024, 200.0) + np.testing.assert_allclose(score, ref["score"], rtol=1e-12) + np.testing.assert_array_equal(n_events, ref["nEvents"]) + test = reject_fast_sources(traces, 10, 0.024, 200.0, 0.2) + np.testing.assert_array_equal(test.keep, ref["keep"].astype(bool)) + assert test.kept_score.size == test.keep.sum() + np.testing.assert_array_equal(test.rejected, np.flatnonzero(~test.keep)) + + +def test_movmean_omitnan() -> None: + """Window placement of MATLAB's movmean (even and odd), NaN left out.""" + x = np.array([[1.0, np.nan, 3, 4, 5, 6]]) + np.testing.assert_allclose(movmean_omitnan(x, 3)[0], [1, 2, 3.5, 4, 5, 5.5]) + # even window: two before, one after + np.testing.assert_allclose(movmean_omitnan(x, 4)[0], [1, 2, 8 / 3, 4, 4.5, 5]) + assert np.isnan(movmean_omitnan(np.full((1, 4), np.nan), 3)).all() + + +def test_source_minutes(ref: dict[str, Any]) -> None: + """Minutes of each source's frames that were not discarded, over the trials with traces. + + This gives the rate the evidence test compares. + """ + from giant_python.extraction.raster.kinetics import ( + source_minutes, + weak_sources, + ) + + np.testing.assert_allclose(source_minutes([np.zeros((2, 1200)), None], 2, 200.0), [0.1, 0.1]) + traces = [np.array(t, dtype=np.float64) for t in ref["LS"]] + n = traces[0].shape[0] + expect = source_minutes(traces, n, 200.0) + lost = np.isfinite(traces[0][2, :100]).sum() + traces[0][2, :100] = np.nan # source 2 loses frames of trial 1 + expect[2] -= lost / 200.0 / 60.0 + minutes = source_minutes(traces + [None, np.zeros((0, 0))], n, 200.0) + np.testing.assert_allclose(minutes, expect) + _, n_events = source_kinetics(traces, 0.024, 200.0) + rate = n_events / minutes + cut = float(np.median(rate)) + np.testing.assert_array_equal(weak_sources(np.ones(n), rate, min_event_rate=cut), rate < cut) + # a recording twice as long with the same events has half the rate + twice = source_minutes(traces + traces, n, 200.0) + np.testing.assert_allclose(twice, 2 * minutes) + + +def test_kinetics_edge_cases() -> None: + """No traces, a short time constant and threshold 0 keep everything.""" + score, n = source_kinetics([None], 0.024, 200.0) + assert score.size == 0 and n.size == 0 + rng = np.random.default_rng(0) + trace = rng.standard_normal((3, 400)) + score, n = source_kinetics([trace], 0.005, 200.0) # tau 1 frame + assert np.isnan(score).all() and (n == 0).all() + test = reject_fast_sources([None], 4, 0.024, 200.0, 0.2) + assert test.keep.all() and np.isnan(test.score).all() + test = reject_fast_sources([trace], 3, 0.024, 200.0, 0.0) + assert test.keep.all() + + +def test_weak_sources_and_mean_snr() -> None: + """The evidence test's criteria, each off at 0.""" + from giant_python.extraction.raster.kinetics import ( + mean_snr, + weak_sources, + ) + + snr = mean_snr([np.array([1.0, np.nan, 3.0]), None, np.array([3.0, np.nan, 5.0])], 3) + np.testing.assert_allclose(snr, [2.0, np.nan, 4.0]) + # only NaN is left out, as the summary's mean SNR + assert mean_snr([np.array([1.0]), np.array([np.inf])], 1)[0] == np.inf + rates = np.array([0.0, 9.0, 2.0]) + np.testing.assert_array_equal(weak_sources(snr, rates), [False, False, False]) + np.testing.assert_array_equal(weak_sources(snr, rates, min_snr=3.0), [True, False, False]) + np.testing.assert_array_equal(weak_sources(snr, rates, min_event_rate=3.0), [True, False, True]) + # a source without a rate (no valid frame) is not judged by it + np.testing.assert_array_equal( + weak_sources(snr, [np.nan, 9.0, 2.0], min_event_rate=3.0), + [False, False, True], + ) + with pytest.raises(ValueError): + weak_sources(snr, rates, min_event_rate=-1.0) + with pytest.raises(ValueError): + weak_sources(snr, rates, min_snr=-1.0) diff --git a/tests/raster/test_raster_localization.py b/tests/raster/test_raster_localization.py index bee03e7e..429b856a 100644 --- a/tests/raster/test_raster_localization.py +++ b/tests/raster/test_raster_localization.py @@ -1,242 +1,260 @@ -"""Tests of the multi-ROI (raster) SiLo localization port and its options.""" - -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.localization import ( - RasterLocalizationParams, - activity_score, - gauss_filter, - localize_sources, - matlab_prctile, - movmean_nan, - movmedian_nan, -) - -FIXTURE = Path(__file__).parent / "data" / "matlab_localization.h5" - - -def _fixture() -> tuple[np.ndarray, np.ndarray, np.ndarray, dict[str, dict[str, Any]]]: - """Read the synthetic trial and GIAnT-MATLAB's results on it. - - HDF5 holds MATLAB's (rows, cols, frames) arrays as (frames, cols, rows). - """ - with h5py.File(FIXTURE, "r") as f: - movie = f["movie"][()].transpose(0, 2, 1) - vf = f["var_factor"][()].transpose(0, 2, 1) - base = f["baseline"][()].transpose(0, 2, 1) - ref = {} - for kind in ("movmedian", "external"): - g = f["matlab"][kind] - ref[kind] = dict( - act_im=g["act_im"][()].T, - summary=g["summary"][()].T, - peaks={th: np.atleast_2d(g[f"peaks_{th}"][()].T) for th in (3, 5, 8)}, - ) - return movie, vf, base, ref - - -def _seed_offsets(py: np.ndarray, ml: np.ndarray) -> np.ndarray: - """Distance from each MATLAB seed (1-based) to the nearest Python seed.""" - if ml.size == 0 or py.size == 0: - return np.array([]) - d = np.hypot(ml[:, 1:2] - 1 - py[None, :, 1], ml[:, 2:3] - 1 - py[None, :, 2]) - return d.min(1) - - -@pytest.mark.parametrize("kind", ["movmedian", "external"]) -def test_matches_matlab(kind: str) -> None: - """Activity image, summary and seeds agree with GIAnT-MATLAB.""" - movie, vf, base, ref = _fixture() - r = localize_sources( - movie, - vf, - RasterLocalizationParams(), - base if kind == "external" else None, - ) - want = ref[kind] - assert np.array_equal(np.isnan(r.act_im), np.isnan(want["act_im"])) - ok = np.isfinite(want["act_im"]) - scale = np.max(np.abs(want["act_im"][ok])) - assert np.max(np.abs(r.act_im[ok] - want["act_im"][ok])) < 1e-3 * scale - ok = np.isfinite(want["summary"]) - assert np.corrcoef(r.summary[ok], want["summary"][ok])[0, 1] > 0.99999 - from giant_python.extraction.raster.peaks import get_act_im_peaks - - # the optimizers differ (lsqcurvefit vs least_squares), so marginal seeds - # among many can differ; the strong ones agree - py = get_act_im_peaks(r.summary, 8) - ml = want["peaks"][8] - assert abs(py.shape[0] - ml.shape[0]) <= 1 - assert np.mean(_seed_offsets(py, ml) < 0.1) >= 0.9 - - -def test_peak_port_on_matlab_summary() -> None: - """Seeds from MATLAB's own summary image agree with MATLAB's seeds.""" - from giant_python.extraction.raster.peaks import get_act_im_peaks - - _, _, _, ref = _fixture() - for kind in ("movmedian", "external"): - for th, near in ((5, 0.8), (8, 0.9)): - ml = ref[kind]["peaks"][th] - py = get_act_im_peaks(ref[kind]["summary"], th) - assert abs(py.shape[0] - ml.shape[0]) <= max(1, 0.1 * ml.shape[0]) - assert np.mean(_seed_offsets(py, ml) < 0.25) >= near - - -def test_moving_windows_match_matlab() -> None: - """Smoothdata movmean/movmedian with 'omitnan' and an even window.""" - x = np.array([1, np.nan, 3, 4, np.nan, 6, 7, 8, 9, 10], np.float32) - mean = movmean_nan(x[:, None], 4).ravel() - med = movmedian_nan(x[:, None], 4).ravel() - np.testing.assert_allclose(mean, [1, 2, 8 / 3, 3.5, 13 / 3, 17 / 3, 7, 7.5, 8.5, 9], rtol=1e-6) - np.testing.assert_allclose(med, [1, 2, 3, 3.5, 4, 6, 7, 7.5, 8.5, 9]) - assert matlab_prctile(np.array([3, 1, 4, 1, 5, 9, 2, 6.0]), 90) == (pytest.approx(8.1)) - - -def test_no_surround_is_the_gaussian_alone() -> None: - """surround=False: the spatial filter is the Gaussian, without the DoG.""" - rng = np.random.default_rng(0) - z = rng.standard_normal((40, 30, 32)).astype(np.float32) - nans = np.zeros(z.shape, bool) - p0 = RasterLocalizationParams(surround=False) - sk, _ = activity_score(z.copy(), nans, p0) - # the same score by hand: exponential filter, Gaussian, maxima squared - from giant_python.extraction.raster.localization import temporal_filter - - g = gauss_filter(temporal_filter(z.copy(), p0.tau_frames), p0.sigma_px) - sk_with, _ = activity_score(z.copy(), nans, RasterLocalizationParams()) - assert not np.allclose(sk, sk_with) - last = g.shape[0] - int(np.ceil(1.5 * p0.tau_frames)) - from scipy import ndimage - - want = np.zeros(g.shape[1:]) - for fr in range(1, last): - mx = ndimage.maximum_filter(g[fr], 3, mode="constant", cval=0) - is_max = (g[fr] == mx) & (g[fr] > g[fr - 1]) & (g[fr] >= g[fr + 1]) - want[is_max] += g[fr][is_max].astype(float) ** 2 - want /= 300 + (last - 1) - # the 3x3 maximum at the border sees MATLAB's zero padding in both - np.testing.assert_allclose(sk, want, rtol=1e-5, atol=1e-9) - - -def test_soft_threshold_ignores_noise_maxima() -> None: - """Maxima below soft_th add nothing; a strong event still scores.""" - rng = np.random.default_rng(1) - z = rng.standard_normal((300, 24, 24)).astype(np.float32) - nans = np.zeros(z.shape, bool) - p = RasterLocalizationParams(score="soft_threshold", soft_th=2.0) - sk_noise, sd = activity_score(z.copy(), nans, p) - sk_sq, _ = activity_score(z.copy(), nans, RasterLocalizationParams()) - assert sd > 0 - assert np.mean(sk_noise == 0) > 0.2 and np.mean(sk_sq == 0) < 0.05 - z[150:153, 12, 12] += 40 - sk_ev, _ = activity_score(z.copy(), nans, p, sd) - assert np.unravel_index(np.argmax(sk_ev), sk_ev.shape) == (12, 12) - - -def test_params_validation() -> None: - """Unknown option values are rejected.""" - with pytest.raises(ValueError): - RasterLocalizationParams(null="signflip") - with pytest.raises(ValueError): - RasterLocalizationParams(score="energy") - with pytest.raises(ValueError): - RasterLocalizationParams(null_draws=0) - for bad in (2.0, True): # would fail in range() or count as 1 - with pytest.raises(ValueError): - RasterLocalizationParams(null_draws=bad) - assert RasterLocalizationParams(null_draws=np.int64(3)).null_draws == 3 - with pytest.raises(ValueError): - RasterLocalizationParams(soft_th=-1) - - -def test_external_baseline_shape_checked() -> None: - """An external baseline must have the movie's shape.""" - movie = np.ones((50, 10, 10), np.float32) - with pytest.raises(ValueError): - localize_sources(movie, None, baseline=np.ones((50, 10, 9))) - - -def test_var_factor_shape_checked() -> None: - """The variance factor must have the movie's shape. - - A transposed one of the same size, or a single frame, is rejected rather - than reshaped. - """ - movie = np.ones((50, 10, 12), np.float32) - for vf in (np.ones((50, 12, 10)), np.ones((10, 12))): - with pytest.raises(ValueError, match="var_factor"): - localize_sources(movie, vf) - - -def test_no_variance_floor_needs_an_external_baseline() -> None: - """Without the floor, an external baseline is required. - - The moving median's low bias at low counts would blow up dim pixels' - Z-scores. - """ - movie = np.ones((50, 10, 10), np.float32) - p = RasterLocalizationParams(variance_floor=False) - with pytest.raises(ValueError, match="external baseline"): - localize_sources(movie, None, p) - - -def test_moving_mean_keeps_precision_on_long_recordings() -> None: - """Prefix sums in float64: no drift over a long float32 recording.""" - x = np.full((24000, 2), 1.1, np.float32) - out = movmean_nan(x, 8) - np.testing.assert_allclose(out[-50:], np.float32(1.1), rtol=1e-6) - - -def test_no_floor_with_a_uniform_external_baseline() -> None: - """A spatially uniform baseline still gives a finite activity image without the floor. - - Uniform here means no pixel above the 90th percentile of brightness. - """ - rng = np.random.default_rng(3) - base = np.full((600, 20, 20), 9.0, np.float32) - movie = (base + 3 * rng.standard_normal(base.shape)).astype(np.float32) - p = RasterLocalizationParams(variance_floor=False) - loc = localize_sources(movie, None, p, base, find_peaks=False) - assert np.isfinite(loc.act_im[loc.valid]).all() - assert loc.info["Vk"] > 0 - - -def test_no_valid_pixels_keeps_find_peaks_false() -> None: - """The early return for a trial without valid pixels honours ``find_peaks``. - - Peaks are None when seeding was not requested. - """ - movie = np.full((50, 10, 10), np.nan, np.float32) - with pytest.warns(UserWarning): - loc = localize_sources(movie, find_peaks=False) - assert loc.peaks is None - with pytest.warns(UserWarning): - assert localize_sources(movie).peaks.shape == (0, 4) - - -def test_pixels_mostly_missing_leave_the_variance_model() -> None: - """Valid pixels missing more than 40% of frames do not change Vb. - - As MATLAB (``varIM(nanFrac > 0.4) = nan``). - """ - rng = np.random.default_rng(5) - t = 600 - movie = (20 + 3 * rng.standard_normal((t, 20, 20))).astype(np.float32) - gone = rng.random(t) < 0.45 - p = RasterLocalizationParams(nan_thresh=0.5) - vb = [] - for scale in (0.1, 30.0): # those pixels' noise: tiny, or huge - m = movie.copy() - block = 20 + scale * rng.standard_normal((t, 5, 5)) - m[:, :5, :5] = block.astype(np.float32) - m[gone, :5, :5] = np.nan - loc = localize_sources(m, None, p, find_peaks=False) - assert loc.valid[:5, :5].all() - vb.append(loc.info["Vb"]) - assert vb[0] == vb[1] +"""Tests of the multi-ROI (raster) SiLo localization port and its options.""" + +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.localization import ( + RasterLocalizationParams, + activity_score, + gauss_filter, + localize_sources, + matlab_prctile, + movmean_nan, + movmedian_nan, +) + +FIXTURE = Path(__file__).parent / "data" / "matlab_localization.h5" + + +def _fixture() -> tuple[np.ndarray, np.ndarray, np.ndarray, dict[str, dict[str, Any]]]: + """Read the synthetic trial and GIAnT-MATLAB's results on it. + + HDF5 holds MATLAB's (rows, cols, frames) arrays as (frames, cols, rows). + + Returns + ------- + movie : np.ndarray + Synthetic movie, transposed to (frames, rows, cols). + vf : np.ndarray + Variance-factor array, same layout as movie. + base : np.ndarray + Baseline array, same layout as movie. + ref : dict[str, dict[str, Any]] + MATLAB results keyed by "movmedian" and "external", each holding act_im, + summary and peaks (a dict of seed arrays keyed by threshold 3, 5 and 8). + """ + with h5py.File(FIXTURE, "r") as f: + movie = f["movie"][()].transpose(0, 2, 1) + vf = f["var_factor"][()].transpose(0, 2, 1) + base = f["baseline"][()].transpose(0, 2, 1) + ref = {} + for kind in ("movmedian", "external"): + g = f["matlab"][kind] + ref[kind] = dict( + act_im=g["act_im"][()].T, + summary=g["summary"][()].T, + peaks={th: np.atleast_2d(g[f"peaks_{th}"][()].T) for th in (3, 5, 8)}, + ) + return movie, vf, base, ref + + +def _seed_offsets(py: np.ndarray, ml: np.ndarray) -> np.ndarray: + """Distance from each MATLAB seed (1-based) to the nearest Python seed. + + Returns + ------- + np.ndarray + One distance per MATLAB seed, or an empty array when either seed set is empty. + """ + if ml.size == 0 or py.size == 0: + return np.array([]) + d = np.hypot(ml[:, 1:2] - 1 - py[None, :, 1], ml[:, 2:3] - 1 - py[None, :, 2]) + return d.min(1) + + +@pytest.mark.parametrize("kind", ["movmedian", "external"]) +def test_matches_matlab(kind: str) -> None: + """Activity image, summary and seeds agree with GIAnT-MATLAB.""" + movie, vf, base, ref = _fixture() + r = localize_sources( + movie, + vf, + RasterLocalizationParams(), + base if kind == "external" else None, + ) + want = ref[kind] + assert np.array_equal(np.isnan(r.act_im), np.isnan(want["act_im"])) + ok = np.isfinite(want["act_im"]) + scale = np.max(np.abs(want["act_im"][ok])) + assert np.max(np.abs(r.act_im[ok] - want["act_im"][ok])) < 1e-3 * scale + ok = np.isfinite(want["summary"]) + assert np.corrcoef(r.summary[ok], want["summary"][ok])[0, 1] > 0.99999 + from giant_python.extraction.raster.peaks import get_act_im_peaks + + # the optimizers differ (lsqcurvefit vs least_squares), so marginal seeds + # among many can differ; the strong ones agree + py = get_act_im_peaks(r.summary, 8) + ml = want["peaks"][8] + assert abs(py.shape[0] - ml.shape[0]) <= 1 + assert np.mean(_seed_offsets(py, ml) < 0.1) >= 0.9 + + +def test_peak_port_on_matlab_summary() -> None: + """Seeds from MATLAB's own summary image agree with MATLAB's seeds.""" + from giant_python.extraction.raster.peaks import get_act_im_peaks + + _, _, _, ref = _fixture() + for kind in ("movmedian", "external"): + for th, near in ((5, 0.8), (8, 0.9)): + ml = ref[kind]["peaks"][th] + py = get_act_im_peaks(ref[kind]["summary"], th) + assert abs(py.shape[0] - ml.shape[0]) <= max(1, 0.1 * ml.shape[0]) + assert np.mean(_seed_offsets(py, ml) < 0.25) >= near + + +def test_moving_windows_match_matlab() -> None: + """Smoothdata movmean/movmedian with 'omitnan' and an even window.""" + x = np.array([1, np.nan, 3, 4, np.nan, 6, 7, 8, 9, 10], np.float32) + mean = movmean_nan(x[:, None], 4).ravel() + med = movmedian_nan(x[:, None], 4).ravel() + np.testing.assert_allclose(mean, [1, 2, 8 / 3, 3.5, 13 / 3, 17 / 3, 7, 7.5, 8.5, 9], rtol=1e-6) + np.testing.assert_allclose(med, [1, 2, 3, 3.5, 4, 6, 7, 7.5, 8.5, 9]) + assert matlab_prctile(np.array([3, 1, 4, 1, 5, 9, 2, 6.0]), 90) == (pytest.approx(8.1)) + + +def test_no_surround_is_the_gaussian_alone() -> None: + """surround=False: the spatial filter is the Gaussian, without the DoG.""" + rng = np.random.default_rng(0) + z = rng.standard_normal((40, 30, 32)).astype(np.float32) + nans = np.zeros(z.shape, bool) + p0 = RasterLocalizationParams(surround=False) + sk, _ = activity_score(z.copy(), nans, p0) + # the same score by hand: exponential filter, Gaussian, maxima squared + from giant_python.extraction.raster.localization import temporal_filter + + g = gauss_filter(temporal_filter(z.copy(), p0.tau_frames), p0.sigma_px) + sk_with, _ = activity_score(z.copy(), nans, RasterLocalizationParams()) + assert not np.allclose(sk, sk_with) + last = g.shape[0] - int(np.ceil(1.5 * p0.tau_frames)) + from scipy import ndimage + + want = np.zeros(g.shape[1:]) + for fr in range(1, last): + mx = ndimage.maximum_filter(g[fr], 3, mode="constant", cval=0) + is_max = (g[fr] == mx) & (g[fr] > g[fr - 1]) & (g[fr] >= g[fr + 1]) + want[is_max] += g[fr][is_max].astype(float) ** 2 + want /= 300 + (last - 1) + # the 3x3 maximum at the border sees MATLAB's zero padding in both + np.testing.assert_allclose(sk, want, rtol=1e-5, atol=1e-9) + + +def test_soft_threshold_ignores_noise_maxima() -> None: + """Maxima below soft_th add nothing; a strong event still scores.""" + rng = np.random.default_rng(1) + z = rng.standard_normal((300, 24, 24)).astype(np.float32) + nans = np.zeros(z.shape, bool) + p = RasterLocalizationParams(score="soft_threshold", soft_th=2.0) + sk_noise, sd = activity_score(z.copy(), nans, p) + sk_sq, _ = activity_score(z.copy(), nans, RasterLocalizationParams()) + assert sd > 0 + assert np.mean(sk_noise == 0) > 0.2 and np.mean(sk_sq == 0) < 0.05 + z[150:153, 12, 12] += 40 + sk_ev, _ = activity_score(z.copy(), nans, p, sd) + assert np.unravel_index(np.argmax(sk_ev), sk_ev.shape) == (12, 12) + + +def test_params_validation() -> None: + """Unknown option values are rejected.""" + with pytest.raises(ValueError): + RasterLocalizationParams(null="signflip") + with pytest.raises(ValueError): + RasterLocalizationParams(score="energy") + with pytest.raises(ValueError): + RasterLocalizationParams(null_draws=0) + for bad in (2.0, True): # would fail in range() or count as 1 + with pytest.raises(ValueError): + RasterLocalizationParams(null_draws=bad) + assert RasterLocalizationParams(null_draws=np.int64(3)).null_draws == 3 + with pytest.raises(ValueError): + RasterLocalizationParams(soft_th=-1) + + +def test_external_baseline_shape_checked() -> None: + """An external baseline must have the movie's shape.""" + movie = np.ones((50, 10, 10), np.float32) + with pytest.raises(ValueError): + localize_sources(movie, None, baseline=np.ones((50, 10, 9))) + + +def test_var_factor_shape_checked() -> None: + """The variance factor must have the movie's shape. + + A transposed one of the same size, or a single frame, is rejected rather + than reshaped. + """ + movie = np.ones((50, 10, 12), np.float32) + for vf in (np.ones((50, 12, 10)), np.ones((10, 12))): + with pytest.raises(ValueError, match="var_factor"): + localize_sources(movie, vf) + + +def test_no_variance_floor_needs_an_external_baseline() -> None: + """Without the floor, an external baseline is required. + + The moving median's low bias at low counts would blow up dim pixels' + Z-scores. + """ + movie = np.ones((50, 10, 10), np.float32) + p = RasterLocalizationParams(variance_floor=False) + with pytest.raises(ValueError, match="external baseline"): + localize_sources(movie, None, p) + + +def test_moving_mean_keeps_precision_on_long_recordings() -> None: + """Prefix sums in float64: no drift over a long float32 recording.""" + x = np.full((24000, 2), 1.1, np.float32) + out = movmean_nan(x, 8) + np.testing.assert_allclose(out[-50:], np.float32(1.1), rtol=1e-6) + + +def test_no_floor_with_a_uniform_external_baseline() -> None: + """A spatially uniform baseline still gives a finite activity image without the floor. + + Uniform here means no pixel above the 90th percentile of brightness. + """ + rng = np.random.default_rng(3) + base = np.full((600, 20, 20), 9.0, np.float32) + movie = (base + 3 * rng.standard_normal(base.shape)).astype(np.float32) + p = RasterLocalizationParams(variance_floor=False) + loc = localize_sources(movie, None, p, base, find_peaks=False) + assert np.isfinite(loc.act_im[loc.valid]).all() + assert loc.info["Vk"] > 0 + + +def test_no_valid_pixels_keeps_find_peaks_false() -> None: + """The early return for a trial without valid pixels honours find_peaks. + + Peaks are None when seeding was not requested. + """ + movie = np.full((50, 10, 10), np.nan, np.float32) + with pytest.warns(UserWarning): + loc = localize_sources(movie, find_peaks=False) + assert loc.peaks is None + with pytest.warns(UserWarning): + assert localize_sources(movie).peaks.shape == (0, 4) + + +def test_pixels_mostly_missing_leave_the_variance_model() -> None: + """Valid pixels missing more than 40% of frames do not change Vb. + + As MATLAB (varIM(nanFrac > 0.4) = nan). + """ + rng = np.random.default_rng(5) + t = 600 + movie = (20 + 3 * rng.standard_normal((t, 20, 20))).astype(np.float32) + gone = rng.random(t) < 0.45 + p = RasterLocalizationParams(nan_thresh=0.5) + vb = [] + for scale in (0.1, 30.0): # those pixels' noise: tiny, or huge + m = movie.copy() + block = 20 + scale * rng.standard_normal((t, 5, 5)) + m[:, :5, :5] = block.astype(np.float32) + m[gone, :5, :5] = np.nan + loc = localize_sources(m, None, p, find_peaks=False) + assert loc.valid[:5, :5].all() + vb.append(loc.info["Vb"]) + assert vb[0] == vb[1] diff --git a/tests/raster/test_raster_null.py b/tests/raster/test_raster_null.py index 32e7c2b0..f1d1e512 100644 --- a/tests/raster/test_raster_null.py +++ b/tests/raster/test_raster_null.py @@ -1,498 +1,536 @@ -"""Tests of the bootstrap null of the raster SiLo activity image.""" - -from collections.abc import Callable - -import numpy as np -import pytest - -from giant_python.extraction.raster.localization import ( - RasterLocalizationParams, - localize_sources, -) -from giant_python.extraction.raster.null import ( - _brightness_bins, - _calibration_maps, - noise_model, - null_movie, - spatial_kernel, - temporal_kernel, -) - - -def _gradient_movie( - rng: np.random.Generator, - t: int = 1500, - rows: int = 40, - cols: int = 90, - gain: float = 8.0, - margin: int = 0, - photons: np.ndarray | None = None, -) -> tuple[np.ndarray, np.ndarray, dict, np.ndarray]: - """Pure photon noise with brightness 0.03-30 photons across the columns. - - Brightness is the given photons per column, if any. The noise is filtered - as image formation does (correlations in time and space); with a margin of - unimaged (NaN) pixels around it, as SLAP2 frames have. - """ - if photons is None: - photons = np.exp(np.linspace(np.log(0.03), np.log(30), cols)) - b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) - base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) - noise["W2"] = float( - (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() - ) - vidx = np.arange(rows * cols) - nans = np.zeros((t, rows, cols), bool) - flat = base.reshape(t, -1) - ones = np.ones_like(flat) - z = null_movie(flat, ones, ones, nans, vidx, noise, seed=3) - movie = base + z # std = 1: z is the noise in counts - if margin: - pad = ((0, 0), (margin, margin), (margin, margin)) - movie = np.pad(movie, pad, constant_values=np.nan) - base = np.pad(base, pad, constant_values=np.nan) - return movie.astype(np.float32), base, noise, photons - - -def test_kernels_give_the_correlations() -> None: - """The fitted kernels' autocorrelations are the requested ones.""" - k = temporal_kernel(0.6, 0.25) - ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() - assert abs(ac[1] - 0.6) < 0.01 and abs(ac[2] - 0.25) < 0.01 - s = spatial_kernel(0.36) - assert abs((s[0] * s[1] + s[1] * s[2]) / (s**2).sum() - 0.36) < 1e-9 - assert np.isclose(k.sum(), 1) and np.isclose(s.sum(), 1) - - -def test_noise_model_recovers_gain_and_correlations() -> None: - """A null movie's measured model is the model it was drawn with.""" - rng = np.random.default_rng(0) - movie, base, noise, _ = _gradient_movie(rng) - t = movie.shape[0] - resid = (movie - base).reshape(t, -1) - m = noise_model( - resid, - base.reshape(t, -1), - np.ones_like(resid), - np.arange(resid.shape[1]), - movie.shape[1:], - ) - assert abs(m["gain"] / noise["gain"] - 1) < 0.05 - np.testing.assert_allclose(m["rho"], [0.6, 0.25, 0.23, 0.37], atol=0.03) - assert 1.0 <= m["q"] < 1.3 - - -def test_null_mean_is_the_baseline_and_skew_is_poisson() -> None: - """Null noise has the baseline's mean, gain x b variance, Poisson skew.""" - rng = np.random.default_rng(1) - movie, base, noise, photons = _gradient_movie(rng, t=3000, cols=6) - r = movie - base - sd_frame = np.sqrt(noise["gain"] * base[0, 0]) - assert np.all(np.abs(r.mean((0, 1))) < 0.1 * sd_frame) - var = r.var((0, 1)) - np.testing.assert_allclose(var / (noise["gain"] * base[0, 0]), 1, rtol=0.1) - skew = (r**3).mean((0, 1)) / var**1.5 - w2 = noise["W2"] - w3 = (noise["kt"] ** 3).sum() * (noise["kr"] ** 3).sum() * (noise["kc"] ** 3).sum() - want = w3 / w2**1.5 / np.sqrt(photons * w2) - np.testing.assert_allclose(skew[:3], want[:3], rtol=0.25) - - -def _tail(x: np.ndarray) -> tuple[float, float]: - """Median and (99.5th percentile - median) of an image's pixels.""" - x = x[np.isfinite(x)] - m = np.median(x) - return m, np.quantile(x, 0.995) - m - - -def test_bootstrap_calibrates_dim_and_bright_pixels() -> None: - """The calibrated image has the same centre and tail at every brightness. - - On a trial of pure photon noise, the calibrated image has the same centre - and upper tail at every brightness; uncalibrated, dim pixels' tail is - heavier. - """ - rng = np.random.default_rng(2) - movie, base, _, photons = _gradient_movie(rng, rows=80, margin=6) - p_raw = RasterLocalizationParams(variance_floor=False) - p_cal = RasterLocalizationParams( - variance_floor=False, null="bootstrap", null_seed=11, null_draws=2 - ) - raw = localize_sources(movie, None, p_raw, base, find_peaks=False) - cal = localize_sources(movie, None, p_cal, base, find_peaks=False) - inner = (slice(6 + 2, -6 - 2), slice(6 + 2, -6 - 2)) - a_raw, a_cal = raw.act_im[inner], cal.act_im[inner] - cols = photons[2:-2] - dim, bright = cols < 0.3, cols > 3 - assert _tail(a_raw[:, dim])[1] > 1.3 * _tail(a_raw[:, bright])[1] - for sel in (dim, bright): - m, t = _tail(a_cal[:, sel]) - assert abs(m) < 0.3 - assert 0.7 * 2.576 < t < 1.3 * 2.576 - info = cal.info["null"] - assert info["s0"][0] > 1.3 * info["s0"][-1] - - -def _ar1(rng: np.random.Generator, t: int, n: int, rho: float = 0.6) -> np.ndarray: - """Independent AR(1) series (one per column) with lag-1 correlation.""" - e = rng.standard_normal((t, n)) - r = np.empty((t, n)) - r[0] = e[0] - for k in range(1, t): - r[k] = rho * r[k - 1] + np.sqrt(1 - rho**2) * e[k] - return r - - -@pytest.mark.parametrize( - "kept", - [ - lambda t: (t // 3) % 2 == 0, # blocks of 3 kept, 3 discarded - lambda t: t % 3 != 2, # 0, 1, 3, 4, 6, 7...: lag 2 spans a gap - ], -) -def test_lag_correlations_use_recorded_frame_indices( - kept: Callable[[np.ndarray], np.ndarray], -) -> None: - """Lags are counted in recorded frames. - - Pairs are matched by their original indices, also across a discarded - frame between them, and never across a gap that changes the lag. - """ - rng = np.random.default_rng(4) - t, n = 3000, 400 - r = _ar1(rng, t, n) - base = np.full((t, n), 4.0) - frames = np.flatnonzero(kept(np.arange(t))) - m = noise_model(r, base, np.ones_like(r), np.arange(n), (20, 20), frames) - np.testing.assert_allclose(m["rho"][:2], [0.6, 0.36], atol=0.03) - - -def test_null_variance_around_discarded_frames() -> None: - """Discarded frames (NaN baseline, as an external baseline gives) keep their latent noise. - - The frames next to them get the full variance. - """ - t, rows, cols, gain = 4000, 20, 20, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) - noise["W2"] = float( - (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() - ) - disc = np.arange(t) % 8 == 0 - base = np.full((t, rows * cols), 2.0 * gain, np.float32) - base[disc] = np.nan - ones = np.ones_like(base) - nans = np.zeros((t, rows, cols), bool) - nans[disc] = True - z = null_movie(base, ones, ones, nans, np.arange(rows * cols), noise, seed=7) - assert np.isnan(z[disc]).all() - inner = z[:, 2:-2, 2:-2] - phase = np.arange(t) % 8 - var_next = inner[(phase == 1) | (phase == 7)].var() - var_far = inner[(phase >= 3) & (phase <= 5)].var() - assert abs(var_next / var_far - 1) < 0.03 - assert abs(var_far / (gain * 2.0 * gain) - 1) < 0.05 # gain x b - - -def test_null_variance_next_to_bright_structures() -> None: - """Every pixel keeps the variance gain x b next to bright structures. - - Where brightness changes across the spatial kernel, every pixel keeps the - variance gain x b, and the measured model is still the drawn one. - """ - t, rows, cols, gain = 3000, 30, 30, 8.0 - photons = np.where((np.arange(cols) // 3) % 2 == 0, 30.0, 0.3) - b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) - base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) - noise["W2"] = float( - (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() - ) - flat = base.reshape(t, -1) - ones = np.ones_like(flat) - vidx = np.arange(rows * cols) - z = null_movie(flat, ones, ones, np.zeros(base.shape, bool), vidx, noise, seed=5) - inner = (slice(None), slice(2, -2), slice(2, -2)) - var = z[inner].var(0) - np.testing.assert_allclose((var / (gain * b[2:-2, 2:-2])).mean(0), 1, rtol=0.1) - m = noise_model(z.reshape(t, -1), flat, ones, vidx, (rows, cols), np.arange(1000)) - np.testing.assert_allclose(m["rho"][:3], [0.6, 0.25, 0.23], atol=0.03) - - -def test_bootstrap_on_a_uniform_baseline() -> None: - """A trial of one brightness is calibrated with a single bin.""" - rng = np.random.default_rng(6) - t, rows, cols = 1200, 30, 30 - base = np.full((t, rows, cols), 16.0, np.float32) - movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) - p = RasterLocalizationParams(variance_floor=False, null="bootstrap") - loc = localize_sources(movie, None, p, base, find_peaks=False) - assert np.isfinite(loc.act_im[loc.valid]).all() - assert loc.info["null"]["m0"].size == 1 - - -def test_temporal_kernel_stays_finite_for_negative_lag2() -> None: - """A negative lag-2 correlation whose best unconstrained taps sum to 0 gives a finite kernel. - - The taps are ``[-0.4, -0.1, 0, 1, 0, -0.1, -0.4]``. - """ - k = temporal_kernel(0.08 / 1.34, -0.2 / 1.34) - assert np.isfinite(k).all() and np.isclose(k.sum(), 1) - assert np.abs(k).max() < 2.0 - ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() - np.testing.assert_allclose(ac[1:3], [0.08 / 1.34, -0.2 / 1.34], atol=0.02) - for t1, t2 in ((0.7, 0.37), (0.6, 0.25), (0.3, 0.05)): - k = temporal_kernel(t1, t2) # measured SLAP2 values: unchanged fits - ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() - assert abs(ac[1] - t1) < 0.02 and abs(ac[2] - t2) < 0.02 - - -def test_null_variance_follows_a_fast_changing_baseline() -> None: - """Each frame keeps the variance gain x b where the baseline changes fast. - - Where the baseline changes within the temporal kernel (here every 2 - frames, 30 or 0.3 photons), each frame keeps the variance gain x b. - """ - t, rows, cols, gain = 4000, 12, 12, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) - noise["W2"] = float( - (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() - ) - bright = (np.arange(t) // 2) % 2 == 0 - b_t = np.where(bright, 30.0, 0.3) * gain - base = np.repeat(b_t[:, None], rows * cols, 1).astype(np.float32) - ones = np.ones_like(base) - z = null_movie( - base, - ones, - ones, - np.zeros((t, rows, cols), bool), - np.arange(rows * cols), - noise, - seed=8, - ) - inner = z[:, 2:-2, 2:-2] - for sel in (bright, ~bright): - ratio = inner[sel].var() / (gain * b_t[sel][0]) - assert abs(ratio - 1) < 0.1 - - -def test_calibration_of_zero_brightness_is_the_dimmest_bin() -> None: - """Pixels with zero or negative baseline take the dimmest bin's centre and scale. - - They do not take the middle bin's; NaN brightness takes the middle. - """ - centre = np.log([0.1, 1.0, 10.0]) - m0, s0 = np.array([1.0, 2.0, 3.0]), np.array([10.0, 20.0, 30.0]) - photons = np.array([0.0, -1.0, np.nan, 0.01, 1.0, 100.0]) - m, s = _calibration_maps(photons, centre, m0, s0) - np.testing.assert_array_equal(m, [1, 1, 2, 1, 2, 3]) - np.testing.assert_array_equal(s, [10, 10, 20, 10, 20, 30]) - - -def test_null_has_no_noise_at_zero_baselines() -> None: - """A zero-baseline pixel next to bright ones gets no null noise. - - Its variance gain x b is 0; it does not get its neighbours' mixed in. - """ - t, rows, cols, gain = 2000, 16, 16, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) - noise["W2"] = float( - (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() - ) - photons = np.where((np.arange(cols) // 2) % 2 == 0, 20.0, 0.0) - b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) - base = np.broadcast_to(b[None], (t, rows, cols)).reshape(t, -1) - base = base.astype(np.float32) - ones = np.ones_like(base) - z = null_movie( - base, - ones, - ones, - np.zeros((t, rows, cols), bool), - np.arange(rows * cols), - noise, - seed=9, - ) - var = z.var(0) - assert np.all(var[:, photons == 0] == 0) - bright = var[2:-2][:, photons > 0][:, 1:-1] / (gain * 20.0 * gain) - np.testing.assert_allclose(bright.mean(), 1, rtol=0.1) - - -def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch: pytest.MonkeyPatch) -> None: - """The data's variance follows the per-frame variance factor. - - So the noise model and the null movies get it unsmoothed (the Z-score - keeps MATLAB's smoothed one). - """ - import giant_python.extraction.raster.null as null_mod - - rng = np.random.default_rng(10) - t, rows, cols = 800, 24, 24 - vf = np.where(np.arange(t) % 2 == 0, 1.0, 3.0)[:, None, None] - vf = np.broadcast_to(vf, (t, rows, cols)).astype(np.float32) - base = np.full((t, rows, cols), 40.0, np.float32) - movie = base + np.sqrt(4 * base * vf) * rng.standard_normal(base.shape) - seen = {} - real_model, real_movie = null_mod.noise_model, null_mod.null_movie - - def spy_model( - resid: np.ndarray, baseline: np.ndarray, var_factor: np.ndarray, *a: object, **k: object - ) -> dict: - """Record the variance factor given to the noise model.""" - seen["model"] = np.array(var_factor) - return real_model(resid, baseline, var_factor, *a, **k) - - def spy_movie( - baseline: np.ndarray, var_factor: np.ndarray, *a: object, **k: object - ) -> np.ndarray: - """Record the variance factor given to the null movie.""" - seen["movie"] = np.array(var_factor) - return real_movie(baseline, var_factor, *a, **k) - - monkeypatch.setattr(null_mod, "noise_model", spy_model) - monkeypatch.setattr(null_mod, "null_movie", spy_movie) - p = RasterLocalizationParams(null="bootstrap") - localize_sources(movie.astype(np.float32), vf, p, base, find_peaks=False) - for key in ("model", "movie"): - got = seen[key] - assert set(np.unique(got[np.isfinite(got)])) == {1.0, 3.0} - - -def test_bins_hold_enough_null_values() -> None: - """A small field of view gets fewer brightness bins. - - So no bin's 99.5th percentile rests on a few dozen values. - """ - rng = np.random.default_rng(11) - movie, base, _, _ = _gradient_movie(rng, t=1200, rows=12, cols=30) - p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) - loc = localize_sources(movie, None, p, base, find_peaks=False) - n_ok = 8 * 26 # pixels away from the edges, at most - assert loc.info["null"]["m0"].size <= max(1, n_ok // 500) - - -def test_bins_keep_the_minimum_with_tied_brightness() -> None: - """Ties collapse equal-count edges. - - A few pixels below a tied block would form a bin of their own. Bins merge - until each holds 500 null values, and tied pixels are never split. - """ - rng = np.random.default_rng(12) - lp = np.concatenate([ - np.full(3, -3.0), # a few darker pixels - np.zeros(2000), # half the pixels at one brightness - rng.uniform(0.1, 3.0, 2000), - ]) - bins, counts = _brightness_bins(lp, draws=1) - assert counts.size > 1 and counts.min() >= 500 - np.testing.assert_array_equal(counts, np.bincount(bins)) - for k in range(counts.size - 1): # contiguous in brightness, no split - assert lp[bins == k].max() < lp[bins == k + 1].min() - assert bins[0] == bins[3] # the darker pixels joined the tied block - bins2, counts2 = _brightness_bins(lp, draws=2) # counts are values - assert counts2.min() >= 500 and counts2.size >= counts.size - - -def test_tied_brightness_end_to_end() -> None: - """Half the columns at one brightness and two darker ones. - - Every bin of the calibration has at least 500 null values, so the dimmest - bin's 99.5th percentile is not set by a single maximum. - """ - rng = np.random.default_rng(13) - cols = 60 - photons = np.r_[[0.05, 0.05], np.full(30, 0.5), np.linspace(1, 30, cols - 32)] - movie, base, _, _ = _gradient_movie(rng, t=1200, rows=40, cols=cols, photons=photons) - p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) - info = localize_sources(movie, None, p, base, find_peaks=False).info - counts = info["null"]["counts"] - assert counts.size >= 2 and counts.min() >= 500 - assert counts[0] * (1 - 0.995) >= 2.5 # several values above the q99.5 - - -@pytest.mark.parametrize("t", [1, 5]) -def test_trial_too_short_for_the_null_is_left_out(t: int) -> None: - """A trial of a few frames is left out of localization with a warning. - - No pixel has enough frames for the noise model; the trial is left out as - a trial without valid pixels, instead of failing SILo. - """ - rng = np.random.default_rng(9) - base = np.full((t, 30, 30), 16.0, np.float32) - movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) - p = RasterLocalizationParams(null="bootstrap") - with pytest.warns(UserWarning, match="left out of localization"): - loc = localize_sources(movie, None, p, base, find_peaks=True) - assert not loc.valid.any() - assert np.isnan(loc.act_im).all() and np.isnan(loc.summary).all() - assert loc.peaks.shape == (0, 4) - - -def test_noise_model_raises_null_unavailable() -> None: - """The noise model's refusal is a NullUnavailable (a ValueError).""" - from giant_python.extraction.raster.null import NullUnavailable - - rng = np.random.default_rng(1) - r = rng.standard_normal((3, 400)).astype(np.float32) - b = np.full_like(r, 10.0) - with pytest.raises(NullUnavailable, match="too few imaged pixels"): - noise_model(r, b, np.ones_like(r), np.arange(400), (20, 20)) - assert issubclass(NullUnavailable, ValueError) - - -def test_trial_without_calibration_pixels_is_left_out() -> None: - """A trial whose null calibration has no eligible pixel is left out of localization. - - Its noise model can be measured, but its null calibration has no eligible - pixel (a 2-pixel-wide imaged stripe: no pixel has a full 3 x 3 - neighbourhood); it is left out as a trial without valid pixels. - """ - from giant_python.extraction.raster.null import noise_model - - rng = np.random.default_rng(4) - t, rows, cols = 400, 20, 60 - base = np.full((t, rows, cols), np.nan, np.float32) - base[:, 9:11, 5:55] = np.linspace(4.0, 40.0, 50)[None, None, :] - movie = (base + 2 * rng.standard_normal(base.shape)).astype(np.float32) - vidx = np.flatnonzero(np.isfinite(base[0]).ravel()) - flat_m = movie.reshape(t, -1)[:, vidx] - flat_b = base.reshape(t, -1)[:, vidx] - noise_model(flat_m - flat_b, flat_b, np.ones_like(flat_b), vidx, (rows, cols)) - p = RasterLocalizationParams(null="bootstrap") - with pytest.warns(UserWarning, match="null calibration"): - loc = localize_sources(movie, None, p, base, find_peaks=True) - assert not loc.valid.any() - assert np.isnan(loc.act_im).all() and np.isnan(loc.summary).all() - assert loc.peaks.shape == (0, 4) +"""Tests of the bootstrap null of the raster SiLo activity image.""" + +from collections.abc import Callable + +import numpy as np +import pytest + +from giant_python.extraction.raster.localization import ( + RasterLocalizationParams, + localize_sources, +) +from giant_python.extraction.raster.null import ( + _brightness_bins, + _calibration_maps, + noise_model, + null_movie, + spatial_kernel, + temporal_kernel, +) + + +def _gradient_movie( + rng: np.random.Generator, + t: int = 1500, + rows: int = 40, + cols: int = 90, + gain: float = 8.0, + margin: int = 0, + photons: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray, dict, np.ndarray]: + """Pure photon noise with brightness 0.03-30 photons across the columns. + + Brightness is the given photons per column, if any. The noise is filtered + as image formation does (correlations in time and space); with a margin of + unimaged (NaN) pixels around it, as SLAP2 frames have. + + Returns + ------- + movie : np.ndarray + The float32 noisy movie, shape (t, rows + 2 * margin, cols + 2 * margin). + base : np.ndarray + The noise-free baseline movie of the same shape (NaN in the margin). + noise : dict + The noise model the movie was drawn with (gain, kernels kt, kr, kc, + q and W2). + photons : np.ndarray + The brightness in photons of each column. + """ + if photons is None: + photons = np.exp(np.linspace(np.log(0.03), np.log(30), cols)) + b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) + base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) + noise = dict( + gain=gain, + kt=temporal_kernel(0.6, 0.25), + kr=spatial_kernel(0.23), + kc=spatial_kernel(0.37), + q=1.0, + ) + noise["W2"] = float( + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() + ) + vidx = np.arange(rows * cols) + nans = np.zeros((t, rows, cols), bool) + flat = base.reshape(t, -1) + ones = np.ones_like(flat) + z = null_movie(flat, ones, ones, nans, vidx, noise, seed=3) + movie = base + z # std = 1: z is the noise in counts + if margin: + pad = ((0, 0), (margin, margin), (margin, margin)) + movie = np.pad(movie, pad, constant_values=np.nan) + base = np.pad(base, pad, constant_values=np.nan) + return movie.astype(np.float32), base, noise, photons + + +def test_kernels_give_the_correlations() -> None: + """The fitted kernels' autocorrelations are the requested ones.""" + k = temporal_kernel(0.6, 0.25) + ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() + assert abs(ac[1] - 0.6) < 0.01 and abs(ac[2] - 0.25) < 0.01 + s = spatial_kernel(0.36) + assert abs((s[0] * s[1] + s[1] * s[2]) / (s**2).sum() - 0.36) < 1e-9 + assert np.isclose(k.sum(), 1) and np.isclose(s.sum(), 1) + + +def test_noise_model_recovers_gain_and_correlations() -> None: + """A null movie's measured model is the model it was drawn with.""" + rng = np.random.default_rng(0) + movie, base, noise, _ = _gradient_movie(rng) + t = movie.shape[0] + resid = (movie - base).reshape(t, -1) + m = noise_model( + resid, + base.reshape(t, -1), + np.ones_like(resid), + np.arange(resid.shape[1]), + movie.shape[1:], + ) + assert abs(m["gain"] / noise["gain"] - 1) < 0.05 + np.testing.assert_allclose(m["rho"], [0.6, 0.25, 0.23, 0.37], atol=0.03) + assert 1.0 <= m["q"] < 1.3 + + +def test_null_mean_is_the_baseline_and_skew_is_poisson() -> None: + """Null noise has the baseline's mean, gain x b variance, Poisson skew.""" + rng = np.random.default_rng(1) + movie, base, noise, photons = _gradient_movie(rng, t=3000, cols=6) + r = movie - base + sd_frame = np.sqrt(noise["gain"] * base[0, 0]) + assert np.all(np.abs(r.mean((0, 1))) < 0.1 * sd_frame) + var = r.var((0, 1)) + np.testing.assert_allclose(var / (noise["gain"] * base[0, 0]), 1, rtol=0.1) + skew = (r**3).mean((0, 1)) / var**1.5 + w2 = noise["W2"] + w3 = (noise["kt"] ** 3).sum() * (noise["kr"] ** 3).sum() * (noise["kc"] ** 3).sum() + want = w3 / w2**1.5 / np.sqrt(photons * w2) + np.testing.assert_allclose(skew[:3], want[:3], rtol=0.25) + + +def _tail(x: np.ndarray) -> tuple[float, float]: + """Median and (99.5th percentile - median) of an image's pixels. + + Returns + ------- + median : float + Median of the image's finite pixels. + tail : float + The 99.5th percentile of those pixels minus their median. + """ + x = x[np.isfinite(x)] + m = np.median(x) + return m, np.quantile(x, 0.995) - m + + +def test_bootstrap_calibrates_dim_and_bright_pixels() -> None: + """The calibrated image has the same centre and tail at every brightness. + + On a trial of pure photon noise, the calibrated image has the same centre + and upper tail at every brightness; uncalibrated, dim pixels' tail is + heavier. + """ + rng = np.random.default_rng(2) + movie, base, _, photons = _gradient_movie(rng, rows=80, margin=6) + p_raw = RasterLocalizationParams(variance_floor=False) + p_cal = RasterLocalizationParams( + variance_floor=False, null="bootstrap", null_seed=11, null_draws=2 + ) + raw = localize_sources(movie, None, p_raw, base, find_peaks=False) + cal = localize_sources(movie, None, p_cal, base, find_peaks=False) + inner = (slice(6 + 2, -6 - 2), slice(6 + 2, -6 - 2)) + a_raw, a_cal = raw.act_im[inner], cal.act_im[inner] + cols = photons[2:-2] + dim, bright = cols < 0.3, cols > 3 + assert _tail(a_raw[:, dim])[1] > 1.3 * _tail(a_raw[:, bright])[1] + for sel in (dim, bright): + m, t = _tail(a_cal[:, sel]) + assert abs(m) < 0.3 + assert 0.7 * 2.576 < t < 1.3 * 2.576 + info = cal.info["null"] + assert info["s0"][0] > 1.3 * info["s0"][-1] + + +def _ar1(rng: np.random.Generator, t: int, n: int, rho: float = 0.6) -> np.ndarray: + """Independent AR(1) series (one per column) with lag-1 correlation. + + Returns + ------- + np.ndarray + The series, shape (t, n), each column unit-variance AR(1) with coefficient rho. + """ + e = rng.standard_normal((t, n)) + r = np.empty((t, n)) + r[0] = e[0] + for k in range(1, t): + r[k] = rho * r[k - 1] + np.sqrt(1 - rho**2) * e[k] + return r + + +@pytest.mark.parametrize( + "kept", + [ + lambda t: (t // 3) % 2 == 0, # blocks of 3 kept, 3 discarded + lambda t: t % 3 != 2, # 0, 1, 3, 4, 6, 7...: lag 2 spans a gap + ], +) +def test_lag_correlations_use_recorded_frame_indices( + kept: Callable[[np.ndarray], np.ndarray], +) -> None: + """Lags are counted in recorded frames. + + Pairs are matched by their original indices, also across a discarded + frame between them, and never across a gap that changes the lag. + """ + rng = np.random.default_rng(4) + t, n = 3000, 400 + r = _ar1(rng, t, n) + base = np.full((t, n), 4.0) + frames = np.flatnonzero(kept(np.arange(t))) + m = noise_model(r, base, np.ones_like(r), np.arange(n), (20, 20), frames) + np.testing.assert_allclose(m["rho"][:2], [0.6, 0.36], atol=0.03) + + +def test_null_variance_around_discarded_frames() -> None: + """Discarded frames (NaN baseline, as an external baseline gives) keep their latent noise. + + The frames next to them get the full variance. + """ + t, rows, cols, gain = 4000, 20, 20, 8.0 + noise = dict( + gain=gain, + kt=temporal_kernel(0.6, 0.25), + kr=spatial_kernel(0.23), + kc=spatial_kernel(0.37), + q=1.0, + ) + noise["W2"] = float( + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() + ) + disc = np.arange(t) % 8 == 0 + base = np.full((t, rows * cols), 2.0 * gain, np.float32) + base[disc] = np.nan + ones = np.ones_like(base) + nans = np.zeros((t, rows, cols), bool) + nans[disc] = True + z = null_movie(base, ones, ones, nans, np.arange(rows * cols), noise, seed=7) + assert np.isnan(z[disc]).all() + inner = z[:, 2:-2, 2:-2] + phase = np.arange(t) % 8 + var_next = inner[(phase == 1) | (phase == 7)].var() + var_far = inner[(phase >= 3) & (phase <= 5)].var() + assert abs(var_next / var_far - 1) < 0.03 + assert abs(var_far / (gain * 2.0 * gain) - 1) < 0.05 # gain x b + + +def test_null_variance_next_to_bright_structures() -> None: + """Every pixel keeps the variance gain x b next to bright structures. + + Where brightness changes across the spatial kernel, every pixel keeps the + variance gain x b, and the measured model is still the drawn one. + """ + t, rows, cols, gain = 3000, 30, 30, 8.0 + photons = np.where((np.arange(cols) // 3) % 2 == 0, 30.0, 0.3) + b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) + base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) + noise = dict( + gain=gain, + kt=temporal_kernel(0.6, 0.25), + kr=spatial_kernel(0.23), + kc=spatial_kernel(0.37), + q=1.0, + ) + noise["W2"] = float( + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() + ) + flat = base.reshape(t, -1) + ones = np.ones_like(flat) + vidx = np.arange(rows * cols) + z = null_movie(flat, ones, ones, np.zeros(base.shape, bool), vidx, noise, seed=5) + inner = (slice(None), slice(2, -2), slice(2, -2)) + var = z[inner].var(0) + np.testing.assert_allclose((var / (gain * b[2:-2, 2:-2])).mean(0), 1, rtol=0.1) + m = noise_model(z.reshape(t, -1), flat, ones, vidx, (rows, cols), np.arange(1000)) + np.testing.assert_allclose(m["rho"][:3], [0.6, 0.25, 0.23], atol=0.03) + + +def test_bootstrap_on_a_uniform_baseline() -> None: + """A trial of one brightness is calibrated with a single bin.""" + rng = np.random.default_rng(6) + t, rows, cols = 1200, 30, 30 + base = np.full((t, rows, cols), 16.0, np.float32) + movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) + p = RasterLocalizationParams(variance_floor=False, null="bootstrap") + loc = localize_sources(movie, None, p, base, find_peaks=False) + assert np.isfinite(loc.act_im[loc.valid]).all() + assert loc.info["null"]["m0"].size == 1 + + +def test_temporal_kernel_stays_finite_for_negative_lag2() -> None: + """A negative lag-2 correlation whose best unconstrained taps sum to 0 gives a finite kernel. + + The taps are [-0.4, -0.1, 0, 1, 0, -0.1, -0.4]. + """ + k = temporal_kernel(0.08 / 1.34, -0.2 / 1.34) + assert np.isfinite(k).all() and np.isclose(k.sum(), 1) + assert np.abs(k).max() < 2.0 + ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() + np.testing.assert_allclose(ac[1:3], [0.08 / 1.34, -0.2 / 1.34], atol=0.02) + for t1, t2 in ((0.7, 0.37), (0.6, 0.25), (0.3, 0.05)): + k = temporal_kernel(t1, t2) # measured SLAP2 values: unchanged fits + ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() + assert abs(ac[1] - t1) < 0.02 and abs(ac[2] - t2) < 0.02 + + +def test_null_variance_follows_a_fast_changing_baseline() -> None: + """Each frame keeps the variance gain x b where the baseline changes fast. + + Where the baseline changes within the temporal kernel (here every 2 + frames, 30 or 0.3 photons), each frame keeps the variance gain x b. + """ + t, rows, cols, gain = 4000, 12, 12, 8.0 + noise = dict( + gain=gain, + kt=temporal_kernel(0.6, 0.25), + kr=spatial_kernel(0.23), + kc=spatial_kernel(0.37), + q=1.0, + ) + noise["W2"] = float( + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() + ) + bright = (np.arange(t) // 2) % 2 == 0 + b_t = np.where(bright, 30.0, 0.3) * gain + base = np.repeat(b_t[:, None], rows * cols, 1).astype(np.float32) + ones = np.ones_like(base) + z = null_movie( + base, + ones, + ones, + np.zeros((t, rows, cols), bool), + np.arange(rows * cols), + noise, + seed=8, + ) + inner = z[:, 2:-2, 2:-2] + for sel in (bright, ~bright): + ratio = inner[sel].var() / (gain * b_t[sel][0]) + assert abs(ratio - 1) < 0.1 + + +def test_calibration_of_zero_brightness_is_the_dimmest_bin() -> None: + """Pixels with zero or negative baseline take the dimmest bin's centre and scale. + + They do not take the middle bin's; NaN brightness takes the middle. + """ + centre = np.log([0.1, 1.0, 10.0]) + m0, s0 = np.array([1.0, 2.0, 3.0]), np.array([10.0, 20.0, 30.0]) + photons = np.array([0.0, -1.0, np.nan, 0.01, 1.0, 100.0]) + m, s = _calibration_maps(photons, centre, m0, s0) + np.testing.assert_array_equal(m, [1, 1, 2, 1, 2, 3]) + np.testing.assert_array_equal(s, [10, 10, 20, 10, 20, 30]) + + +def test_null_has_no_noise_at_zero_baselines() -> None: + """A zero-baseline pixel next to bright ones gets no null noise. + + Its variance gain x b is 0; it does not get its neighbours' mixed in. + """ + t, rows, cols, gain = 2000, 16, 16, 8.0 + noise = dict( + gain=gain, + kt=temporal_kernel(0.6, 0.25), + kr=spatial_kernel(0.23), + kc=spatial_kernel(0.37), + q=1.0, + ) + noise["W2"] = float( + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() + ) + photons = np.where((np.arange(cols) // 2) % 2 == 0, 20.0, 0.0) + b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) + base = np.broadcast_to(b[None], (t, rows, cols)).reshape(t, -1) + base = base.astype(np.float32) + ones = np.ones_like(base) + z = null_movie( + base, + ones, + ones, + np.zeros((t, rows, cols), bool), + np.arange(rows * cols), + noise, + seed=9, + ) + var = z.var(0) + assert np.all(var[:, photons == 0] == 0) + bright = var[2:-2][:, photons > 0][:, 1:-1] / (gain * 20.0 * gain) + np.testing.assert_allclose(bright.mean(), 1, rtol=0.1) + + +def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch: pytest.MonkeyPatch) -> None: + """The data's variance follows the per-frame variance factor. + + So the noise model and the null movies get it unsmoothed (the Z-score + keeps MATLAB's smoothed one). + """ + import giant_python.extraction.raster.null as null_mod + + rng = np.random.default_rng(10) + t, rows, cols = 800, 24, 24 + vf = np.where(np.arange(t) % 2 == 0, 1.0, 3.0)[:, None, None] + vf = np.broadcast_to(vf, (t, rows, cols)).astype(np.float32) + base = np.full((t, rows, cols), 40.0, np.float32) + movie = base + np.sqrt(4 * base * vf) * rng.standard_normal(base.shape) + seen = {} + real_model, real_movie = null_mod.noise_model, null_mod.null_movie + + def spy_model( + resid: np.ndarray, baseline: np.ndarray, var_factor: np.ndarray, *a: object, **k: object + ) -> dict: + """Record the variance factor given to the noise model. + + Returns + ------- + dict + The result of the real noise_model called with the same arguments. + """ + seen["model"] = np.array(var_factor) + return real_model(resid, baseline, var_factor, *a, **k) + + def spy_movie( + baseline: np.ndarray, var_factor: np.ndarray, *a: object, **k: object + ) -> np.ndarray: + """Record the variance factor given to the null movie. + + Returns + ------- + np.ndarray + The result of the real null_movie called with the same arguments. + """ + seen["movie"] = np.array(var_factor) + return real_movie(baseline, var_factor, *a, **k) + + monkeypatch.setattr(null_mod, "noise_model", spy_model) + monkeypatch.setattr(null_mod, "null_movie", spy_movie) + p = RasterLocalizationParams(null="bootstrap") + localize_sources(movie.astype(np.float32), vf, p, base, find_peaks=False) + for key in ("model", "movie"): + got = seen[key] + assert set(np.unique(got[np.isfinite(got)])) == {1.0, 3.0} + + +def test_bins_hold_enough_null_values() -> None: + """A small field of view gets fewer brightness bins. + + So no bin's 99.5th percentile rests on a few dozen values. + """ + rng = np.random.default_rng(11) + movie, base, _, _ = _gradient_movie(rng, t=1200, rows=12, cols=30) + p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) + loc = localize_sources(movie, None, p, base, find_peaks=False) + n_ok = 8 * 26 # pixels away from the edges, at most + assert loc.info["null"]["m0"].size <= max(1, n_ok // 500) + + +def test_bins_keep_the_minimum_with_tied_brightness() -> None: + """Ties collapse equal-count edges. + + A few pixels below a tied block would form a bin of their own. Bins merge + until each holds 500 null values, and tied pixels are never split. + """ + rng = np.random.default_rng(12) + lp = np.concatenate([ + np.full(3, -3.0), # a few darker pixels + np.zeros(2000), # half the pixels at one brightness + rng.uniform(0.1, 3.0, 2000), + ]) + bins, counts = _brightness_bins(lp, draws=1) + assert counts.size > 1 and counts.min() >= 500 + np.testing.assert_array_equal(counts, np.bincount(bins)) + for k in range(counts.size - 1): # contiguous in brightness, no split + assert lp[bins == k].max() < lp[bins == k + 1].min() + assert bins[0] == bins[3] # the darker pixels joined the tied block + bins2, counts2 = _brightness_bins(lp, draws=2) # counts are values + assert counts2.min() >= 500 and counts2.size >= counts.size + + +def test_tied_brightness_end_to_end() -> None: + """Half the columns at one brightness and two darker ones. + + Every bin of the calibration has at least 500 null values, so the dimmest + bin's 99.5th percentile is not set by a single maximum. + """ + rng = np.random.default_rng(13) + cols = 60 + photons = np.r_[[0.05, 0.05], np.full(30, 0.5), np.linspace(1, 30, cols - 32)] + movie, base, _, _ = _gradient_movie(rng, t=1200, rows=40, cols=cols, photons=photons) + p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) + info = localize_sources(movie, None, p, base, find_peaks=False).info + counts = info["null"]["counts"] + assert counts.size >= 2 and counts.min() >= 500 + assert counts[0] * (1 - 0.995) >= 2.5 # several values above the q99.5 + + +@pytest.mark.parametrize("t", [1, 5]) +def test_trial_too_short_for_the_null_is_left_out(t: int) -> None: + """A trial of a few frames is left out of localization with a warning. + + No pixel has enough frames for the noise model; the trial is left out as + a trial without valid pixels, instead of failing SILo. + """ + rng = np.random.default_rng(9) + base = np.full((t, 30, 30), 16.0, np.float32) + movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) + p = RasterLocalizationParams(null="bootstrap") + with pytest.warns(UserWarning, match="left out of localization"): + loc = localize_sources(movie, None, p, base, find_peaks=True) + assert not loc.valid.any() + assert np.isnan(loc.act_im).all() and np.isnan(loc.summary).all() + assert loc.peaks.shape == (0, 4) + + +def test_noise_model_raises_null_unavailable() -> None: + """The noise model's refusal is a NullUnavailable (a ValueError).""" + from giant_python.extraction.raster.null import NullUnavailable + + rng = np.random.default_rng(1) + r = rng.standard_normal((3, 400)).astype(np.float32) + b = np.full_like(r, 10.0) + with pytest.raises(NullUnavailable, match="too few imaged pixels"): + noise_model(r, b, np.ones_like(r), np.arange(400), (20, 20)) + assert issubclass(NullUnavailable, ValueError) + + +def test_trial_without_calibration_pixels_is_left_out() -> None: + """A trial whose null calibration has no eligible pixel is left out of localization. + + Its noise model can be measured, but its null calibration has no eligible + pixel (a 2-pixel-wide imaged stripe: no pixel has a full 3 x 3 + neighbourhood); it is left out as a trial without valid pixels. + """ + from giant_python.extraction.raster.null import noise_model + + rng = np.random.default_rng(4) + t, rows, cols = 400, 20, 60 + base = np.full((t, rows, cols), np.nan, np.float32) + base[:, 9:11, 5:55] = np.linspace(4.0, 40.0, 50)[None, None, :] + movie = (base + 2 * rng.standard_normal(base.shape)).astype(np.float32) + vidx = np.flatnonzero(np.isfinite(base[0]).ravel()) + flat_m = movie.reshape(t, -1)[:, vidx] + flat_b = base.reshape(t, -1)[:, vidx] + noise_model(flat_m - flat_b, flat_b, np.ones_like(flat_b), vidx, (rows, cols)) + p = RasterLocalizationParams(null="bootstrap") + with pytest.warns(UserWarning, match="null calibration"): + loc = localize_sources(movie, None, p, base, find_peaks=True) + assert not loc.valid.any() + assert np.isnan(loc.act_im).all() and np.isnan(loc.summary).all() + assert loc.peaks.shape == (0, 4) diff --git a/tests/raster/test_raster_peaks.py b/tests/raster/test_raster_peaks.py index ddcd253c..31759ff3 100644 --- a/tests/raster/test_raster_peaks.py +++ b/tests/raster/test_raster_peaks.py @@ -1,273 +1,310 @@ -"""Tests of the getActImPeaks port (raster SiLo seeds).""" - -from typing import Any - -import numpy as np -import pytest -from scipy.optimize import OptimizeResult - -from giant_python.extraction.raster.peaks import ( - _eval_budget, - _IntegratedGaussians, - _WindowedGaussians, - get_act_im_peaks, - ordfilt3x3, -) - - -def test_ordfilt_matches_matlab() -> None: - """MATLAB ordfilt2(A, 9 or 8, ones(3)): zero padding, NaN windows.""" - a = np.array([[np.nan, 1, -2], [2, 3, -1], [-5, np.nan, 4]]) - nan = np.nan - np.testing.assert_array_equal( - ordfilt3x3(a, 9), [[nan, nan, 3], [nan, nan, nan], [nan, nan, nan]] - ) - np.testing.assert_array_equal( - ordfilt3x3(a, 8), [[nan, nan, 1], [nan, nan, nan], [nan, nan, nan]] - ) - np.testing.assert_array_equal(ordfilt3x3(np.array([[-1.0, -2], [-3, -4]]), 9), np.zeros((2, 2))) - - -def test_jacobian_matches_finite_differences() -> None: - """The analytical Jacobian of the integrated Gaussians is right.""" - yy, xx = np.mgrid[1:12, 1:14] - model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) - theta = np.array([3.0, 1.5, 5.2, 7.7, 4.1, 9.3, 1.1, 0.8]) - jac = model.jacobian(theta) - eps = 1e-6 - num = np.column_stack([ - (model.value(theta + eps * e) - model.value(theta - eps * e)) / (2 * eps) - for e in np.eye(theta.size) - ]) - np.testing.assert_allclose(jac, num, rtol=1e-5, atol=1e-8) - # the value-only path (no derivatives) is the Jacobian path's value - a, (vy, _, _), (vx, _, _) = model.parts(theta) - np.testing.assert_array_equal(model.value(theta), (vy * vx) @ a) - - -def test_finds_separated_gaussians() -> None: - """Two blobs on noise are found at their centres (0-based).""" - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:40, :50] - img = 0.05 * rng.standard_normal((40, 50)) - for r, c in ((10.3, 12.6), (28.0, 35.4)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - img[:, :2] = np.nan - pk = get_act_im_peaks(img, 8) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) - - -def test_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: - """A LAPACK SVD failure in the default solver retries with lsmr.""" - import giant_python.extraction.raster.peaks as peaks - - calls = [] - real = peaks.least_squares - - def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy - """least_squares whose default (SVD) solver always fails.""" - calls.append(kwargs.get("tr_solver")) - if kwargs.get("tr_solver") is None: - raise np.linalg.LinAlgError("SVD did not converge") - return real(*args, **kwargs) - - monkeypatch.setattr(peaks, "least_squares", flaky) - yy, xx = np.mgrid[1:16, 1:16] - model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) - data = model.value(np.array([3.0, 7.4, 8.2, 1.2])) - theta = peaks._fit( - np.array([[2.0, 7.0, 8.0, 1.0]]), - yy.ravel() + 0.0, - xx.ravel() + 0.0, - data, - np.array([[0.0, 5.5, 6.5, 0.2]]), - np.array([[np.inf, 8.5, 9.5, 5.0]]), - ) - assert calls == [None, "lsmr"] - np.testing.assert_allclose(theta[0], [3.0, 7.4, 8.2, 1.2], atol=1e-3) - - -def test_exclusion_mask_and_empty() -> None: - """No seeds inside the exclusion mask; none in pure noise.""" - rng = np.random.default_rng(1) - yy, xx = np.mgrid[:30, :30] - img = 0.05 * rng.standard_normal((30, 30)) - img += 4 * np.exp(-((yy - 15) ** 2 + (xx - 15) ** 2) / 2) - mask = np.zeros((30, 30), bool) - mask[12:19, 12:19] = True - assert get_act_im_peaks(img, 8, mask).shape[0] == 0 - assert get_act_im_peaks(rng.standard_normal((30, 30)), 8).shape == (0, 4) - - -def test_no_fitted_centre_inside_the_exclusion_mask() -> None: - """A source whose centre is just inside the mask is dropped. - - It seeds on its unmasked flank, and its fit moves back into the mask: it - is dropped. A source clear of the mask is kept. - """ - rng = np.random.default_rng(2) - yy, xx = np.mgrid[:30, :40] - img = 0.05 * rng.standard_normal((30, 40)) - for r, c in ((15.0, 15.2), (15.0, 30.0)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - mask = np.zeros((30, 40), bool) - mask[:, 15:20] = True # the first source's centre and right flank - pk = get_act_im_peaks(img, 8, mask) - assert pk.shape[0] == 1 - np.testing.assert_allclose(pk[0, 1:3], [15.0, 30.0], atol=0.15) - unmasked = get_act_im_peaks(img, 8) - assert unmasked.shape[0] == 2 - - -def test_eval_budget_matches_matlab_iterations() -> None: - """MATLAB's 5000 evaluations with finite differences allow (5000 - 1) // (n + 1) iterations. - - The budget here allows as many steps (one evaluation each, plus the - start), down to one step at n = 2500. - """ - for n in (4, 40, 400, 2500, 4998): - assert _eval_budget(n) - 1 == (5000 - 1) // (n + 1) - assert _eval_budget(2500) == 2 # one step (was 1: none) - assert _eval_budget(5000) == 1 # MATLAB cannot take a step either - - -def test_rounding_is_matlabs() -> None: - """Halves round away from zero as in MATLAB (numpy rounds them to even). - - So a centre at exactly k + 0.5 lands on MATLAB's pixel. - """ - from giant_python.extraction.raster.peaks import _rounded_index - - theta = np.array([[1.0, 4.5, 2.5, 0.35], [1.0, 3.5, 7.49, 0.35]]) - iy, ix = _rounded_index(theta, (10, 10)) # 1-based in, 0-based out - np.testing.assert_array_equal(iy, [4, 3]) # MATLAB 5 and 4 - np.testing.assert_array_equal(ix, [2, 6]) # MATLAB 3 and 7 - - -def _windowed( - shape: tuple[int, int], starts: np.ndarray, window: int, rows: np.ndarray | None = None -) -> tuple[_WindowedGaussians, np.ndarray, np.ndarray]: - """Build a windowed model on a gap-free image, and the edges it uses.""" - cols, rws = np.nonzero(np.ones(shape, bool).T) - idx = np.full(shape, -1, np.int64) - idx[rws, cols] = np.arange(rws.size) - edges = (rws + 0.5, rws + 1.5, cols + 0.5, cols + 1.5) - rows = np.arange(rws.size) if rows is None else rows - model = _WindowedGaussians(idx, edges, np.asarray(starts), window, rows) - return model, rws[rows] + 1.0, cols[rows] + 1.0 - - -def test_windowed_model_is_the_integrated_model_within_its_window() -> None: - """With windows covering the image, the windowed model is the dense one. - - Positions are offsets from the start pixels; its Jacobian, dense and - sparse, matches finite differences. - """ - starts = np.array([[4, 6], [9, 3]]) # 0-based start pixels - theta = np.array([[3.0, 5.4, 7.2, 0.7], [1.5, 9.8, 4.1, 1.1]]) - model, ys, xs = _windowed((12, 14), starts, 20) - x = np.concatenate([ - theta[:, 0], - theta[:, 1] - starts[:, 0] - 1, - theta[:, 2] - starts[:, 1] - 1, - theta[:, 3], - ]) - dense = _IntegratedGaussians(ys, xs).value(theta.ravel(order="F")) - np.testing.assert_allclose(model.value(x), dense, rtol=1e-12) - eps = 1e-6 - num = np.column_stack([ - (model.value(x + eps * e) - model.value(x - eps * e)) / (2 * eps) for e in np.eye(x.size) - ]) - np.testing.assert_allclose(model.jacobian(x, True), num, atol=1e-7) - np.testing.assert_allclose(model.jacobian(x, False).toarray(), num, atol=1e-7) - # a narrow window leaves the peak out of pixels beyond it - narrow, ys, xs = _windowed((12, 14), starts[:1], 2) - far = (np.abs(ys - 5) > 2) | (np.abs(xs - 7) > 2) - assert np.all(narrow.value(x[[0, 2, 4, 6]])[far] == 0) - - -@pytest.mark.parametrize("dense_max", [400, 0]) -@pytest.mark.parametrize("merge_px", [0.0, 1.5]) -def test_local_fit_finds_separated_gaussians( - merge_px: float, dense_max: int, monkeypatch: pytest.MonkeyPatch -) -> None: - """The local fit finds the blobs the MATLAB fit finds, at their centres. - - With the dense (SVD) solver of small fits and with the sparse (lsmr) one - of large fits. - """ - import giant_python.extraction.raster.peaks as peaks - - monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:40, :50] - img = 0.05 * rng.standard_normal((40, 50)) - for r, c in ((10.3, 12.6), (28.0, 35.4)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - img[:, :2] = np.nan - pk = get_act_im_peaks(img, 8, fit="local", merge_px=merge_px) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) - - -def _split_prone_image() -> np.ndarray: - """Two sources as activity images show them. - - A peak narrower than a pixel on a wider base, on unit noise. - """ - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:30, :30] - img = rng.standard_normal((30, 30)) - for r, c in ((10.5, 12.0), (20.2, 8.4)): - d2 = (yy - r) ** 2 + (xx - c) ** 2 - img += 40 * np.exp(-d2 / (2 * 0.45**2)) + 6 * np.exp(-d2 / 5.12) - return img - - -def test_local_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: - """A LAPACK SVD failure in a local fit's dense solver retries with the sparse one. - - And the seeds are found. - """ - import giant_python.extraction.raster.peaks as peaks - - calls = [] - real = peaks.least_squares - - def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy - """least_squares whose dense (SVD) solver always fails.""" - calls.append(kwargs.get("tr_solver")) - if kwargs.get("tr_solver") == "exact": - raise np.linalg.LinAlgError("SVD did not converge") - return real(*args, **kwargs) - - monkeypatch.setattr(peaks, "least_squares", flaky) - pk = get_act_im_peaks(_split_prone_image(), 3, fit="local", merge_px=1.5) - assert calls[:2] == ["exact", "lsmr"] - assert pk.shape[0] == 2 - - -@pytest.mark.parametrize("fit", ["matlab", "local"]) -def test_merge_keeps_one_seed_per_split_peak(fit: str) -> None: - """MATLAB's rule fits each source as several peaks less than 1.5 px apart. - - merge_px 1.5 keeps one per source, at the source. - """ - img = _split_prone_image() - assert get_act_im_peaks(img, 3, fit=fit).shape[0] > 2 - pk = get_act_im_peaks(img, 3, fit=fit, merge_px=1.5) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.5, 12.0], [20.2, 8.4]], atol=0.5) - - -def test_seed_fit_options_are_checked() -> None: - """Unknown fits and negative merge distances raise.""" - img = _split_prone_image() - with pytest.raises(ValueError): - get_act_im_peaks(img, 3, fit="other") - with pytest.raises(ValueError): - get_act_im_peaks(img, 3, merge_px=-1) +"""Tests of the getActImPeaks port (raster SiLo seeds).""" + +from typing import Any + +import numpy as np +import pytest +from scipy.optimize import OptimizeResult + +from giant_python.extraction.raster.peaks import ( + _eval_budget, + _IntegratedGaussians, + _WindowedGaussians, + get_act_im_peaks, + ordfilt3x3, +) + + +def test_ordfilt_matches_matlab() -> None: + """MATLAB ordfilt2(A, 9 or 8, ones(3)): zero padding, NaN windows.""" + a = np.array([[np.nan, 1, -2], [2, 3, -1], [-5, np.nan, 4]]) + nan = np.nan + np.testing.assert_array_equal( + ordfilt3x3(a, 9), [[nan, nan, 3], [nan, nan, nan], [nan, nan, nan]] + ) + np.testing.assert_array_equal( + ordfilt3x3(a, 8), [[nan, nan, 1], [nan, nan, nan], [nan, nan, nan]] + ) + np.testing.assert_array_equal(ordfilt3x3(np.array([[-1.0, -2], [-3, -4]]), 9), np.zeros((2, 2))) + + +def test_jacobian_matches_finite_differences() -> None: + """The analytical Jacobian of the integrated Gaussians is right.""" + yy, xx = np.mgrid[1:12, 1:14] + model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) + theta = np.array([3.0, 1.5, 5.2, 7.7, 4.1, 9.3, 1.1, 0.8]) + jac = model.jacobian(theta) + eps = 1e-6 + num = np.column_stack([ + (model.value(theta + eps * e) - model.value(theta - eps * e)) / (2 * eps) + for e in np.eye(theta.size) + ]) + np.testing.assert_allclose(jac, num, rtol=1e-5, atol=1e-8) + # the value-only path (no derivatives) is the Jacobian path's value + a, (vy, _, _), (vx, _, _) = model.parts(theta) + np.testing.assert_array_equal(model.value(theta), (vy * vx) @ a) + + +def test_finds_separated_gaussians() -> None: + """Two blobs on noise are found at their centres (0-based).""" + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:40, :50] + img = 0.05 * rng.standard_normal((40, 50)) + for r, c in ((10.3, 12.6), (28.0, 35.4)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + img[:, :2] = np.nan + pk = get_act_im_peaks(img, 8) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) + + +def test_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: + """A LAPACK SVD failure in the default solver retries with lsmr.""" + import giant_python.extraction.raster.peaks as peaks + + calls = [] + real = peaks.least_squares + + def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy + """least_squares whose default (SVD) solver always fails. + + Returns + ------- + OptimizeResult + The result of the real least_squares when tr_solver is given. + + Raises + ------ + numpy.linalg.LinAlgError + If the default solver (no tr_solver) is used. + """ + calls.append(kwargs.get("tr_solver")) + if kwargs.get("tr_solver") is None: + raise np.linalg.LinAlgError("SVD did not converge") + return real(*args, **kwargs) + + monkeypatch.setattr(peaks, "least_squares", flaky) + yy, xx = np.mgrid[1:16, 1:16] + model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) + data = model.value(np.array([3.0, 7.4, 8.2, 1.2])) + theta = peaks._fit( + np.array([[2.0, 7.0, 8.0, 1.0]]), + yy.ravel() + 0.0, + xx.ravel() + 0.0, + data, + np.array([[0.0, 5.5, 6.5, 0.2]]), + np.array([[np.inf, 8.5, 9.5, 5.0]]), + ) + assert calls == [None, "lsmr"] + np.testing.assert_allclose(theta[0], [3.0, 7.4, 8.2, 1.2], atol=1e-3) + + +def test_exclusion_mask_and_empty() -> None: + """No seeds inside the exclusion mask; none in pure noise.""" + rng = np.random.default_rng(1) + yy, xx = np.mgrid[:30, :30] + img = 0.05 * rng.standard_normal((30, 30)) + img += 4 * np.exp(-((yy - 15) ** 2 + (xx - 15) ** 2) / 2) + mask = np.zeros((30, 30), bool) + mask[12:19, 12:19] = True + assert get_act_im_peaks(img, 8, mask).shape[0] == 0 + assert get_act_im_peaks(rng.standard_normal((30, 30)), 8).shape == (0, 4) + + +def test_no_fitted_centre_inside_the_exclusion_mask() -> None: + """A source whose centre is just inside the mask is dropped. + + It seeds on its unmasked flank, and its fit moves back into the mask: it + is dropped. A source clear of the mask is kept. + """ + rng = np.random.default_rng(2) + yy, xx = np.mgrid[:30, :40] + img = 0.05 * rng.standard_normal((30, 40)) + for r, c in ((15.0, 15.2), (15.0, 30.0)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + mask = np.zeros((30, 40), bool) + mask[:, 15:20] = True # the first source's centre and right flank + pk = get_act_im_peaks(img, 8, mask) + assert pk.shape[0] == 1 + np.testing.assert_allclose(pk[0, 1:3], [15.0, 30.0], atol=0.15) + unmasked = get_act_im_peaks(img, 8) + assert unmasked.shape[0] == 2 + + +def test_eval_budget_matches_matlab_iterations() -> None: + """MATLAB's 5000 evaluations with finite differences allow (5000 - 1) // (n + 1) iterations. + + The budget here allows as many steps (one evaluation each, plus the + start), down to one step at n = 2500. + """ + for n in (4, 40, 400, 2500, 4998): + assert _eval_budget(n) - 1 == (5000 - 1) // (n + 1) + assert _eval_budget(2500) == 2 # one step (was 1: none) + assert _eval_budget(5000) == 1 # MATLAB cannot take a step either + + +def test_rounding_is_matlabs() -> None: + """Halves round away from zero as in MATLAB (numpy rounds them to even). + + So a centre at exactly k + 0.5 lands on MATLAB's pixel. + """ + from giant_python.extraction.raster.peaks import _rounded_index + + theta = np.array([[1.0, 4.5, 2.5, 0.35], [1.0, 3.5, 7.49, 0.35]]) + iy, ix = _rounded_index(theta, (10, 10)) # 1-based in, 0-based out + np.testing.assert_array_equal(iy, [4, 3]) # MATLAB 5 and 4 + np.testing.assert_array_equal(ix, [2, 6]) # MATLAB 3 and 7 + + +def _windowed( + shape: tuple[int, int], starts: np.ndarray, window: int, rows: np.ndarray | None = None +) -> tuple[_WindowedGaussians, np.ndarray, np.ndarray]: + """Build a windowed model on a gap-free image, and the edges it uses. + + Returns + ------- + model : _WindowedGaussians + The windowed model over the pixels in rows. + ys : np.ndarray + Row coordinates (1-based) of those pixels. + xs : np.ndarray + Column coordinates (1-based) of those pixels. + """ + cols, rws = np.nonzero(np.ones(shape, bool).T) + idx = np.full(shape, -1, np.int64) + idx[rws, cols] = np.arange(rws.size) + edges = (rws + 0.5, rws + 1.5, cols + 0.5, cols + 1.5) + rows = np.arange(rws.size) if rows is None else rows + model = _WindowedGaussians(idx, edges, np.asarray(starts), window, rows) + return model, rws[rows] + 1.0, cols[rows] + 1.0 + + +def test_windowed_model_is_the_integrated_model_within_its_window() -> None: + """With windows covering the image, the windowed model is the dense one. + + Positions are offsets from the start pixels; its Jacobian, dense and + sparse, matches finite differences. + """ + starts = np.array([[4, 6], [9, 3]]) # 0-based start pixels + theta = np.array([[3.0, 5.4, 7.2, 0.7], [1.5, 9.8, 4.1, 1.1]]) + model, ys, xs = _windowed((12, 14), starts, 20) + x = np.concatenate([ + theta[:, 0], + theta[:, 1] - starts[:, 0] - 1, + theta[:, 2] - starts[:, 1] - 1, + theta[:, 3], + ]) + dense = _IntegratedGaussians(ys, xs).value(theta.ravel(order="F")) + np.testing.assert_allclose(model.value(x), dense, rtol=1e-12) + eps = 1e-6 + num = np.column_stack([ + (model.value(x + eps * e) - model.value(x - eps * e)) / (2 * eps) for e in np.eye(x.size) + ]) + np.testing.assert_allclose(model.jacobian(x, True), num, atol=1e-7) + np.testing.assert_allclose(model.jacobian(x, False).toarray(), num, atol=1e-7) + # a narrow window leaves the peak out of pixels beyond it + narrow, ys, xs = _windowed((12, 14), starts[:1], 2) + far = (np.abs(ys - 5) > 2) | (np.abs(xs - 7) > 2) + assert np.all(narrow.value(x[[0, 2, 4, 6]])[far] == 0) + + +@pytest.mark.parametrize("dense_max", [400, 0]) +@pytest.mark.parametrize("merge_px", [0.0, 1.5]) +def test_local_fit_finds_separated_gaussians( + merge_px: float, dense_max: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """The local fit finds the blobs the MATLAB fit finds, at their centres. + + With the dense (SVD) solver of small fits and with the sparse (lsmr) one + of large fits. + """ + import giant_python.extraction.raster.peaks as peaks + + monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:40, :50] + img = 0.05 * rng.standard_normal((40, 50)) + for r, c in ((10.3, 12.6), (28.0, 35.4)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + img[:, :2] = np.nan + pk = get_act_im_peaks(img, 8, fit="local", merge_px=merge_px) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) + + +def _split_prone_image() -> np.ndarray: + """Two sources as activity images show them. + + A peak narrower than a pixel on a wider base, on unit noise. + + Returns + ------- + np.ndarray + A 30 x 30 image with two such sources. + """ + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:30, :30] + img = rng.standard_normal((30, 30)) + for r, c in ((10.5, 12.0), (20.2, 8.4)): + d2 = (yy - r) ** 2 + (xx - c) ** 2 + img += 40 * np.exp(-d2 / (2 * 0.45**2)) + 6 * np.exp(-d2 / 5.12) + return img + + +def test_local_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: + """A LAPACK SVD failure in a local fit's dense solver retries with the sparse one. + + And the seeds are found. + """ + import giant_python.extraction.raster.peaks as peaks + + calls = [] + real = peaks.least_squares + + def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy + """least_squares whose dense (SVD) solver always fails. + + Returns + ------- + OptimizeResult + The result of the real least_squares when the dense solver is not requested. + + Raises + ------ + numpy.linalg.LinAlgError + If the dense solver (tr_solver="exact") is used. + """ + calls.append(kwargs.get("tr_solver")) + if kwargs.get("tr_solver") == "exact": + raise np.linalg.LinAlgError("SVD did not converge") + return real(*args, **kwargs) + + monkeypatch.setattr(peaks, "least_squares", flaky) + pk = get_act_im_peaks(_split_prone_image(), 3, fit="local", merge_px=1.5) + assert calls[:2] == ["exact", "lsmr"] + assert pk.shape[0] == 2 + + +@pytest.mark.parametrize("fit", ["matlab", "local"]) +def test_merge_keeps_one_seed_per_split_peak(fit: str) -> None: + """MATLAB's rule fits each source as several peaks less than 1.5 px apart. + + merge_px 1.5 keeps one per source, at the source. + """ + img = _split_prone_image() + assert get_act_im_peaks(img, 3, fit=fit).shape[0] > 2 + pk = get_act_im_peaks(img, 3, fit=fit, merge_px=1.5) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.5, 12.0], [20.2, 8.4]], atol=0.5) + + +def test_seed_fit_options_are_checked() -> None: + """Unknown fits and negative merge distances raise.""" + img = _split_prone_image() + with pytest.raises(ValueError): + get_act_im_peaks(img, 3, fit="other") + with pytest.raises(ValueError): + get_act_im_peaks(img, 3, merge_px=-1) diff --git a/tests/raster/test_raster_plan.py b/tests/raster/test_raster_plan.py index 07edb5d1..49aa782c 100644 --- a/tests/raster/test_raster_plan.py +++ b/tests/raster/test_raster_plan.py @@ -1,598 +1,643 @@ -"""Tests of SiLo's path-level plan (alignment, sources, pixels, groups).""" - -from collections.abc import Sequence -from pathlib import Path - -import h5py -import numpy as np -import pytest -from scipy.special import erf - -from giant_python.extraction.raster.plan import ( - ExtractionPlan, - PlanParams, - TrialImages, - combined_activity_image, - group_sources, - plan_path, - read_plan, - write_plan, -) -from giant_python.extraction.raster.seeding import disk_strel - -FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" -NAN = np.nan - -# sources of the synthetic path (scene coordinates): four apart, and a pair -# four pixels from each other -SOURCES = np.array([[14, 16], [14, 60], [40, 30], [52, 70], [30, 50], [30, 54]], dtype=float) -SHIFTS = np.array([[0, 0], [1, -1], [-1, 2], [2, 1], [0, -2]], dtype=float) - - -def _blobs( - shape: tuple[int, int], - centres: np.ndarray, - amps: np.ndarray, - sigma: float, - shift: Sequence[float] | np.ndarray, -) -> np.ndarray: - """Gaussian blobs at ``centres + shift``.""" - rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) - im = np.zeros(shape) - for (r0, c0), a in zip(centres, amps): - im += a * np.exp(-((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * sigma**2)) - return im - - -def _peaks( - shape: tuple[int, int], - centres: np.ndarray, - amp: float, - sigma: float, - shift: Sequence[float] | np.ndarray, -) -> np.ndarray: - """Narrow peaks at ``centres + shift``: Gaussians integrated over each pixel. - - This is the model that seeding fits (activity images are sharper than - the PSF, and a sampled Gaussian would leave residual peaks). - """ - - def axis(n: int, mu: float) -> np.ndarray: - """Integral of the Gaussian over each of n pixels.""" - edges = (np.arange(n + 1) - 0.5 - mu) / (np.sqrt(2) * sigma) - return np.sqrt(np.pi / 2) * sigma * np.diff(erf(edges)) - - im = np.zeros(shape) - for r0, c0 in centres: - im += amp * np.outer(axis(shape[0], r0 + shift[0]), axis(shape[1], c0 + shift[1])) - return im - - -def _synthetic_trials(shape: tuple[int, int] = (64, 84), seed: int = 0) -> list[TrialImages]: - """Five trials of one scene at SHIFTS. - - With an imaged region, two channels, and activity images that peak at - SOURCES. - """ - rng = np.random.default_rng(seed) - scene_c = rng.uniform([6, 6], [shape[0] - 6, shape[1] - 6], (40, 2)) - scene_a = rng.uniform(50, 150, 40) - imaged = np.zeros(shape, bool) - imaged[4:60, 5:80] = True - trials = [] - for shift in SHIFTS: - mean = 20 + _blobs(shape, scene_c, scene_a, 2.0, shift) - act = _peaks(shape, SOURCES, 0.05, 0.6, shift) - act += 0.0005 * np.abs(rng.normal(size=shape)) - mean[~imaged] = NAN - act[~imaged] = NAN - trials.append( - TrialImages( - np.stack([mean, 0.5 * mean], axis=2), - act, - peaks=np.array([[1.0, 2.0, 3.0, 0.4]]), - discard=np.array([False, True, False]), - ) - ) - return trials - - -@pytest.fixture(scope="module") -def synthetic_plan() -> tuple[ExtractionPlan, dict]: - """Plan the synthetic path, and keep its intermediates.""" - details = {} - plan = plan_path(_synthetic_trials(), params=PlanParams(peak_th=12.0), details=details) - return plan, details - - -def test_plan_params() -> None: - """Radii follow MATLAB; options are validated. - - selRadius = ceil(2 dXY); zones of ceil(1.5 sigma + (validKernel - 1) / 2): - MATLAB's 3 x 3 gives ceil(1.5 sigma + 1), the default 5 x 5 one more. - """ - p = PlanParams() - assert p.valid_kernel == 5 - assert p.sel_radius == 6 and p.zone_radius == 4 - assert PlanParams(valid_kernel=3).zone_radius == 3 - assert PlanParams(d_xy=2.2, sigma_px=2.0).sel_radius == 5 - assert PlanParams(sigma_px=2.0, valid_kernel=3).zone_radius == 4 - with pytest.raises(ValueError, match="inter_trial_alignment"): - PlanParams(inter_trial_alignment="elastic") - with pytest.raises(ValueError, match="peak_method"): - PlanParams(peak_method="blobs") - with pytest.raises(ValueError, match="d_xy"): - PlanParams(d_xy=0) - - -def test_group_sources_zones_and_order() -> None: - """Sources whose zones (5 x 5 squares for radius 3) touch form a group. - - Groups come in MATLAB's order, by the first pixel of their zone column - by column; pixels are the group's disks within the selected pixels. - """ - sel = np.ones((40, 60), bool) - sel[:, 30] = False - # (row, col): b and c touch through adjacent zones (5 columns apart); - # a is 6 columns from b: its own group; d lies in an earlier column - rows = np.array([20, 20, 20, 8]) - cols = np.array([20, 26, 31, 10]) - groups = group_sources(rows, cols, sel, zone_radius=3, sel_radius=6) - assert [g.sources.tolist() for g in groups] == [[3], [0], [1, 2]] - disk = disk_strel(6) - first = groups[0] - assert (first.row0, first.col0) == (3, 5) - np.testing.assert_array_equal(first.sel, disk) - np.testing.assert_array_equal(first.sources_rc, [[5, 5]]) - pair = groups[2] - assert (pair.row0, pair.col0) == (15, 21) - assert pair.sel.shape == (11, 16) - np.testing.assert_array_equal(pair.sources_rc, [[5, 5], [5, 10]]) - assert not pair.sel[:, 30 - 21].any() # the unselected column - # the pixel lists address the selected-pixel list (column-major) - cc, rr = np.nonzero(sel.T) - for g in groups: - assert (np.diff(g.pixels) > 0).all() - crop = np.zeros(g.sel.shape, bool) - crop[rr[g.pixels] - g.row0, cc[g.pixels] - g.col0] = True - np.testing.assert_array_equal(crop, g.sel) - assert group_sources(rows[:0], cols[:0], sel, 3, 6) == [] - with pytest.raises(ValueError, match="no selected pixels"): - group_sources(rows, cols, np.zeros_like(sel), 3, 6) - - -def test_combined_activity_image() -> None: - """The trials' mean (NaN where any trial is NaN), scaled and median-subtracted. - - Scaled to a maximum of 10 to 100, minus its 5 x 5 NaN-median. - """ - rng = np.random.default_rng(1) - act = rng.uniform(0.001, 0.002, (3, 12, 14)) - act[:, 6, 7] = 0.04 - act[1, 0, 0] = NAN - im, med, nan_frac = combined_activity_image(act, 0.33) - assert np.isnan(im[0, 0]) and nan_frac[0, 0] == pytest.approx(1 / 3) - scaled = act.mean(axis=0) / 1e-3 - np.testing.assert_allclose(im[6, 7] + med[6, 7], 40.0) - np.testing.assert_allclose(med[3, 3], np.median(scaled[1:6, 1:6]), rtol=1e-12) - empty = combined_activity_image(act[:0], 0.33) - assert all(np.isnan(x).all() for x in empty) - - -def test_plan_of_a_synthetic_path(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: - """Shifts, valid trials, sources, selected pixels and groups of a path. - - The path has known sources. - """ - plan, details = synthetic_plan - assert plan.shape == (64, 84) and plan.n_trials == 5 - np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) - np.testing.assert_array_equal(plan.aligned_trials, np.arange(5)) - assert (plan.corr > 0.99).all() and plan.corr_thresh <= 0.9 - # shifts are relative to the template's reference trial - np.testing.assert_allclose(plan.shifts - plan.shifts[0], SHIFTS - SHIFTS[0], atol=0.1) - assert plan.n_sources == 6 - # each source is where it was put, in every trial's own frame - for t in range(5): - r_t, c_t = plan.warp.coords(t, plan.source_rows, plan.source_cols) - found = np.column_stack([r_t, c_t]) - expect = SOURCES + SHIFTS[t] - apart = np.abs(found[:, None] - expect[None]).max(axis=2) - # a source is the nearest pixel of its seed (half a pixel off) - assert (apart.min(axis=0) < 0.7).all() - assert (apart.min(axis=1) < 0.7).all() - # selected pixels: valid pixels within the disks; the union is sel - assert plan.sel.sum() == plan.n_pixels - assert not (plan.sel & ~plan.px_always_valid).any() - union = np.zeros(plan.shape, bool) - for k in range(plan.n_sources): - mask = plan.source_mask(k) - assert mask[plan.source_rows[k], plan.source_cols[k]] - assert mask.sum() == plan.source_pixels[k].size - union |= mask - np.testing.assert_array_equal(union, plan.sel) - rows, cols = plan.selected_pixels() - assert (np.diff(rows + cols * plan.shape[0]) > 0).all() - # five groups: the pair shares one; every source is in exactly one - assert sorted(g.sources.size for g in plan.groups) == [1, 1, 1, 1, 2] - np.testing.assert_array_equal( - np.sort(np.concatenate([g.sources for g in plan.groups])), - np.arange(6), - ) - for g in plan.groups: - members = np.zeros(plan.shape, bool) - for k in g.sources: - members |= plan.source_mask(k) - crop = members[g.row0 : g.row0 + g.sel.shape[0], g.col0 : g.col0 + g.sel.shape[1]] - np.testing.assert_array_equal(crop, g.sel) - assert members.sum() == g.sel.sum() == g.pixels.size - np.testing.assert_array_equal( - g.sources_rc, - np.column_stack([ - plan.source_rows[g.sources] - g.row0, - plan.source_cols[g.sources] - g.col0, - ]), - ) - # images: the mean of the aligned trials, NaN ignored - assert plan.mean_im.shape == (64, 84, 2) - np.testing.assert_allclose( - plan.mean_im[30, 40], np.nanmean(plan.mean_aligned[:, 30, 40], axis=0) - ) - assert details["keep_sources"].all() and details["rows"].size == 6 - assert details["med_im"].shape == plan.shape - - -def test_plan_leaves_out_bad_and_missing_trials() -> None: - """Bad and missing trials are not valid; sources are seeded from the rest. - - Not valid: a trial that was not localized, one that is not kept, one - without an activity image and one that does not match the others. - """ - trials = _synthetic_trials() - shape = trials[0].act_im.shape - noise = np.random.default_rng(7).uniform(10, 30, shape) - noise[np.isnan(trials[0].act_im)] = NAN # nothing like the scene - odd = TrialImages(np.stack([noise, noise], axis=2), trials[0].act_im) - blank = TrialImages(trials[1].mean_im, np.full(shape, NAN)) - everything = trials + [None, odd, blank, trials[2]] - keep = np.ones(len(everything), bool) - keep[8] = False - plan = plan_path(everything, params=PlanParams(peak_th=12.0), keep_trials=keep) - np.testing.assert_array_equal(plan.keep_trials, keep & (np.arange(9) != 5)) - np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) - np.testing.assert_array_equal(plan.aligned_trials, [0, 1, 2, 3, 4, 6]) - assert plan.corr[6] < plan.corr_thresh < 0.9 - assert np.isnan(plan.shifts[[5, 7, 8]]).all() - assert np.isnan(plan.act_aligned[[5, 7, 8]]).all() - assert plan.n_sources == 6 - assert plan.trial_peaks[5] is None and plan.trial_peaks[0] is not None - with pytest.raises(ValueError, match="no trials"): - plan_path([None, None]) - - -def test_plan_soma_mask_and_given_seeds() -> None: - """No source is seeded in the soma mask (smaller masks sit top left). - - Given seeds replace the seeding; modes that are not ported are refused. - """ - trials = _synthetic_trials() - soma = np.zeros((40, 45), bool) - soma[:25, :30] = True # covers the source at (14, 16) - plan = plan_path(trials, soma, PlanParams(peak_th=12.0)) - assert plan.n_sources == 5 - assert plan.soma_mask.shape == plan.shape and plan.soma_mask.sum() == 750 - assert not plan.soma_mask[plan.source_rows, plan.source_cols].any() - seeds = np.array([[3.0, 20.2, 30.6, 0.5], [2.0, 20.4, 31.4, 0.5], [1.0, 2.0, 2.0, 0.5]]) - given = plan_path(trials, seeds=seeds) - # the first two round to one pixel; the last is outside the imaged area - np.testing.assert_array_equal(given.source_rows, [20]) - np.testing.assert_array_equal(given.source_cols, [31]) - np.testing.assert_array_equal(given.seeds, seeds) - # the same mask drawn on trial 3, whose image is the scene moved by - # SHIFTS[3]: it lands on the same sources of the consensus frame - drawn = np.zeros(plan.shape, bool) - rr, cc = np.nonzero(plan.soma_mask) - move = np.round(plan.shifts[3]).astype(int) - drawn[rr + move[0], cc + move[1]] = True - moved = plan_path(trials, drawn, PlanParams(peak_th=12.0), soma_mask_trial=3) - np.testing.assert_array_equal(moved.soma_mask, plan.soma_mask) - np.testing.assert_array_equal(moved.source_rows, plan.source_rows) - with pytest.warns(UserWarning, match="not aligned"): - loose = plan_path(trials + [None], drawn, PlanParams(peak_th=12.0), soma_mask_trial=5) - np.testing.assert_array_equal(loose.soma_mask, drawn) - with pytest.raises(ValueError, match="soma_mask"): - plan_path(trials, np.zeros((100, 100), bool)) - with pytest.raises(NotImplementedError, match="WMF"): - plan_path(trials, params=PlanParams(peak_method="wmf")) - - -def test_plan_of_trials_of_different_sizes(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: - """Trials of different sizes share one canvas (top left, NaN beyond), as in MATLAB. - - Their mean images must have the same channels. - """ - plan, _ = synthetic_plan - trials = _synthetic_trials() - # nothing is imaged in the rows and columns cut off here - trials[4] = TrialImages(trials[4].mean_im[:60, :80], trials[4].act_im[:60, :80]) - small = plan_path(trials, params=PlanParams(peak_th=12.0)) - assert small.shape == plan.shape - np.testing.assert_array_equal(small.shifts, plan.shifts) - np.testing.assert_array_equal(small.act_im, plan.act_im) - np.testing.assert_array_equal(small.source_rows, plan.source_rows) - np.testing.assert_array_equal(small.sel, plan.sel) - trials[1] = TrialImages(trials[1].mean_im[:, :, :1], trials[1].act_im) - with pytest.raises(ValueError, match="channels"): - plan_path(trials) - - -def test_plan_with_a_trial_without_images(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: - """A kept trial whose images are all NaN does not enter the template. - - Nothing was imaged often enough in it, so the other trials are planned - as without it; in MATLAB it would leave the path without sources. - """ - plan, _ = synthetic_plan - trials = _synthetic_trials() - shape = trials[0].act_im.shape - blank = TrialImages(np.full(shape + (2,), NAN), np.full(shape, NAN)) - with_blank = plan_path(trials[:2] + [blank] + trials[2:], params=PlanParams(peak_th=12.0)) - rest = [0, 1, 3, 4, 5] - assert with_blank.keep_trials.all() - np.testing.assert_array_equal(with_blank.template_trials, rest) - np.testing.assert_array_equal(with_blank.valid_trials, rest) - np.testing.assert_array_equal(with_blank.shifts[rest], plan.shifts) - assert np.isnan(with_blank.shifts[2]).all() - np.testing.assert_array_equal(with_blank.act_im, plan.act_im) - np.testing.assert_array_equal(with_blank.source_rows, plan.source_rows) - np.testing.assert_array_equal(with_blank.source_cols, plan.source_cols) - with pytest.raises(ValueError, match="mean image"): - plan_path([blank, blank]) - - -def test_plan_without_sources() -> None: - """A path whose activity images hold nothing above threshold has no sources. - - It has no sources, pixels or groups, and still writes and reads. - """ - trials = _synthetic_trials() - plan = plan_path(trials, params=PlanParams(peak_th=1e6)) - assert plan.n_sources == 0 and plan.n_pixels == 0 and plan.groups == [] - assert plan.seeds.shape == (0, 4) - - -def _assert_plans_equal(a: ExtractionPlan, b: ExtractionPlan) -> None: - """Every field of two plans is equal (NaN equal to NaN).""" - assert a.params == b.params - assert a.corr_thresh == b.corr_thresh - for name in ( - "keep_trials", - "template", - "template_trials", - "shifts", - "corr", - "act_valid_pix", - "valid_trials", - "mean_ims", - "act_ims", - "mean_aligned", - "act_aligned", - "mean_im", - "act_im", - "soma_mask", - "px_always_valid", - "seeds", - "source_rows", - "source_cols", - "source_values", - "sel", - ): - x, y = getattr(a, name), getattr(b, name) - assert x.dtype.kind == y.dtype.kind, name - np.testing.assert_array_equal(x, y, err_msg=name) - np.testing.assert_array_equal(a.warp.affine, b.warp.affine) - np.testing.assert_array_equal(a.warp.nodes, b.warp.nodes) - np.testing.assert_array_equal(a.warp.disp, b.warp.disp) - assert len(a.source_pixels) == len(b.source_pixels) - for x, y in zip(a.source_pixels, b.source_pixels): - np.testing.assert_array_equal(x, y) - assert len(a.groups) == len(b.groups) - for x, y in zip(a.groups, b.groups): - assert (x.row0, x.col0) == (y.row0, y.col0) - for name in ("sources", "pixels", "sel", "sources_rc"): - np.testing.assert_array_equal(getattr(x, name), getattr(y, name)) - for x, y in zip(a.trial_peaks + a.trial_discard, b.trial_peaks + b.trial_discard): - assert (x is None) == (y is None) - if x is not None: - np.testing.assert_array_equal(x, y) - - -def test_write_and_read_plan(tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict]) -> None: - """A plan survives the file; several paths share a file by group. - - A file that is not a plan, or a newer version, is refused. - """ - plan, _ = synthetic_plan - fn = tmp_path / "extraction_plan.h5" - write_plan(fn, plan) - back = read_plan(fn) - _assert_plans_equal(plan, back) - assert back.trial_discard[0].dtype == bool - # an empty plan, written next to it as a second imaging path - empty = plan_path(_synthetic_trials()[:2] + [None], params=PlanParams(peak_th=1e6)) - write_plan(fn, plan, group="DMD1") - write_plan(fn, empty, group="DMD2") - write_plan(fn, empty, group="DMD2") # replaces the group - _assert_plans_equal(read_plan(fn, "DMD1"), plan) - _assert_plans_equal(read_plan(fn, "DMD2"), empty) - with h5py.File(fn, "r+") as f: - f["DMD2"].attrs["version"] = 99 - f.create_group("other") - with pytest.raises(ValueError, match="version 99"): - read_plan(fn, "DMD2") - with pytest.raises(ValueError, match="does not hold"): - read_plan(fn, "other") - - -def _matlab_case(case: str) -> tuple[list[TrialImages | None], PlanParams, dict]: - """Read the inputs of one fixture case and MATLAB's results on them. - - The fixture holds a 72 x 96 window of five trials of one imaging path - (780125) and what ``SILo.m`` and ``extractTrial.m`` (GIAnT-MATLAB main - 5a0673b) compute from it, in Python's orientation and zero-based. - """ - with h5py.File(FIXTURE, "r") as f: - mean = f["inputs/mean_ims"][()].astype(np.float64) - act = f["inputs/act_ims"][()] - g = f["matlab"][case] - ref = {k: g[k][()] for k in g} - ref.update({k: g.attrs[k] for k in g.attrs}) - a = f["inputs"].attrs - params = PlanParams( - nan_thresh=float(a["nanThresh"]), - peak_th=float(ref["peakth"]), - min_peak_distance=int(a["minPeakDistance"]), - d_xy=float(a["dXY"]), - sigma_px=float(a["sigma_px"]), - # MATLAB's algorithm (the defaults are the local fit, merging, - # the 5 x 5 support and the patchwise alignment) - seed_fit="matlab", - seed_merge_px=0.0, - valid_kernel=3, - inter_trial_alignment="rigid", - ) - keep = ref["keep_trials"].astype(bool) - trials = [TrialImages(mean[t], act[t]) if keep[t] else None for t in range(keep.size)] - return trials, params, ref - - -def _lists(ref: dict, name: str) -> list[np.ndarray]: - """Index lists of the fixture (``_index`` and ``_ptr``).""" - index, ptr = ref[f"{name}_index"], ref[f"{name}_ptr"] - return [index[a:b] for a, b in zip(ptr[:-1], ptr[1:])] - - -@pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_plan_matches_matlab(case: str) -> None: - """Every step but the Gaussian fit of the seeds reproduces MATLAB. - - The template, shifts, valid trials, aligned and combined images to - rounding error; given MATLAB's seeds, the sources, their pixels and the - subproblems exactly. - """ - trials, params, ref = _matlab_case(case) - details = {} - plan = plan_path(trials, params=params, seeds=ref["seeds"], details=details) - close = dict(rtol=0, atol=1e-9) - np.testing.assert_allclose(plan.template, ref["template"], **close) - np.testing.assert_array_equal(plan.template_trials, ref["template_trials"]) - np.testing.assert_allclose(plan.shifts, ref["shifts"], **close) - np.testing.assert_allclose(plan.corr, ref["corr"], **close) - assert plan.corr_thresh == pytest.approx(ref["corr_thresh"], abs=1e-12) - np.testing.assert_allclose(plan.act_valid_pix, ref["act_valid_pix"], **close) - np.testing.assert_array_equal(plan.valid_trials, ref["valid_trials"]) - np.testing.assert_allclose(plan.act_aligned, ref["act_aligned"], **close) - np.testing.assert_allclose(plan.act_im, ref["act_im"], **close) - if "mean_aligned" in ref: - np.testing.assert_allclose(plan.mean_aligned, ref["mean_aligned"], rtol=1e-12, atol=1e-9) - np.testing.assert_allclose(plan.mean_im, ref["mean_im"], rtol=1e-12, atol=1e-9) - np.testing.assert_allclose(details["med_im"], ref["med_im"], **close) - # from MATLAB's seeds on: exact - np.testing.assert_array_equal(details["keep_sources"], ref["keep_sources"].astype(bool)) - np.testing.assert_array_equal(plan.source_rows, ref["source_rows"]) - np.testing.assert_array_equal(plan.source_cols, ref["source_cols"]) - np.testing.assert_array_equal(plan.source_values, ref["source_values"]) - np.testing.assert_array_equal(plan.px_always_valid, ref["px_always_valid"].astype(bool)) - np.testing.assert_array_equal(plan.sel, ref["sel"].astype(bool)) - for mine, matlab in zip(plan.source_pixels, _lists(ref, "source_pixel")): - np.testing.assert_array_equal(mine, matlab) - assert len(plan.groups) == ref["group_rows"].shape[0] - for g, src, pix, rows, cols in zip( - plan.groups, - _lists(ref, "group_source"), - _lists(ref, "group_pixel"), - ref["group_rows"], - ref["group_cols"], - ): - np.testing.assert_array_equal(g.sources, src) - np.testing.assert_array_equal(g.pixels, pix) - assert (g.row0, g.row0 + g.sel.shape[0] - 1) == tuple(rows) - assert (g.col0, g.col0 + g.sel.shape[1] - 1) == tuple(cols) - - -@pytest.mark.parametrize("case, same_pixel", [("all_trials", 0.85), ("one_trial_out", 1.0)]) -def test_own_seeds_are_close_to_matlabs(case: str, same_pixel: float) -> None: - """Seeding with this package's fit gives nearly MATLAB's sources. - - The seeds are fit on MATLAB's combined activity image. They are not - identical: the Gaussian fit is ill-conditioned for peaks narrower than a - pixel and MATLAB's lsqcurvefit stops on a tolerance or on its evaluation - limit, so where it ends depends on the optimizer (at a threshold of 3 SDs - MATLAB finds 21 sources in this window and this package 20). - """ - trials, params, ref = _matlab_case(case) - plan = plan_path(trials, params=params) - matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) - mine = np.column_stack([plan.source_rows, plan.source_cols]) - apart = np.abs(matlab[:, None] - mine[None]).max(axis=2) - assert abs(len(mine) - len(matlab)) <= 1 - assert (apart.min(axis=1) == 0).mean() >= same_pixel - assert (apart.min(axis=1) <= 1).all() and (apart.min(axis=0) <= 1).all() - - -@pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_default_seeding_on_matlabs_window(case: str) -> None: - """The default seeding on MATLAB's combined activity image is close to MATLAB's. - - The default seeding uses local fits, merging residual peaks within - 1.5 px: every MATLAB source is within 1 px of a source here, and every - source here within 1 px of a MATLAB source; only sources next to another - are merged (all trials: 16 of MATLAB's 21). Without merging the local fit - gives MATLAB's count. - """ - import dataclasses - - trials, params, ref = _matlab_case(case) - matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) - plan = plan_path( - trials, - params=dataclasses.replace( - params, - seed_fit=PlanParams.seed_fit, - seed_merge_px=PlanParams.seed_merge_px, - ), - ) - mine = np.column_stack([plan.source_rows, plan.source_cols]) - apart = np.abs(matlab[:, None] - mine[None]).max(axis=2) - assert len(mine) <= len(matlab) - assert (apart.min(axis=1) <= 1).all() and (apart.min(axis=0) <= 1).all() - unmerged = plan_path( - trials, - params=dataclasses.replace(params, seed_fit="local", seed_merge_px=0), - ) - assert abs(unmerged.n_sources - len(matlab)) <= 1 - - -def test_plans_written_before_the_seed_options_read_as_matlabs( - tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict] -) -> None: - """A plan file without the seed fields reads back with MATLAB's seed fit. - - Such a file was written before the fields existed; it reads back with - MATLAB's seed fit and no merging, the settings it was made with; a - current plan keeps its own. - """ - import json - - import h5py - - plan, _ = synthetic_plan - fn = tmp_path / "plan.h5" - write_plan(fn, plan) - assert read_plan(fn).params.seed_fit == plan.params.seed_fit - with h5py.File(fn, "r+") as f: - saved = json.loads(f.attrs["params"]) # a one-path plan: the root - del saved["seed_fit"], saved["seed_merge_px"] - f.attrs["params"] = json.dumps(saved) - old = read_plan(fn).params - assert (old.seed_fit, old.seed_merge_px) == ("matlab", 0.0) +"""Tests of SiLo's path-level plan (alignment, sources, pixels, groups).""" + +from collections.abc import Sequence +from pathlib import Path + +import h5py +import numpy as np +import pytest +from scipy.special import erf + +from giant_python.extraction.raster.plan import ( + ExtractionPlan, + PlanParams, + TrialImages, + combined_activity_image, + group_sources, + plan_path, + read_plan, + write_plan, +) +from giant_python.extraction.raster.seeding import disk_strel + +FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" +NAN = np.nan + +# sources of the synthetic path (scene coordinates): four apart, and a pair +# four pixels from each other +SOURCES = np.array([[14, 16], [14, 60], [40, 30], [52, 70], [30, 50], [30, 54]], dtype=float) +SHIFTS = np.array([[0, 0], [1, -1], [-1, 2], [2, 1], [0, -2]], dtype=float) + + +def _blobs( + shape: tuple[int, int], + centres: np.ndarray, + amps: np.ndarray, + sigma: float, + shift: Sequence[float] | np.ndarray, +) -> np.ndarray: + """Gaussian blobs at centres + shift. + + Returns + ------- + np.ndarray + The image of shape: the blobs' sum, each of amplitude from amps. + """ + rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) + im = np.zeros(shape) + for (r0, c0), a in zip(centres, amps): + im += a * np.exp(-((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * sigma**2)) + return im + + +def _peaks( + shape: tuple[int, int], + centres: np.ndarray, + amp: float, + sigma: float, + shift: Sequence[float] | np.ndarray, +) -> np.ndarray: + """Narrow peaks at centres + shift: Gaussians integrated over each pixel. + + This is the model that seeding fits (activity images are sharper than + the PSF, and a sampled Gaussian would leave residual peaks). + + Returns + ------- + np.ndarray + The image of shape: the peaks' sum, each of amplitude amp. + """ + + def axis(n: int, mu: float) -> np.ndarray: + """Integral of the Gaussian over each of n pixels. + + Returns + ------- + np.ndarray + The n integrals, for a Gaussian centred on mu. + """ + edges = (np.arange(n + 1) - 0.5 - mu) / (np.sqrt(2) * sigma) + return np.sqrt(np.pi / 2) * sigma * np.diff(erf(edges)) + + im = np.zeros(shape) + for r0, c0 in centres: + im += amp * np.outer(axis(shape[0], r0 + shift[0]), axis(shape[1], c0 + shift[1])) + return im + + +def _synthetic_trials(shape: tuple[int, int] = (64, 84), seed: int = 0) -> list[TrialImages]: + """Five trials of one scene at SHIFTS. + + With an imaged region, two channels, and activity images that peak at + SOURCES. + + Returns + ------- + list + The five TrialImages, one per shift in SHIFTS. + """ + rng = np.random.default_rng(seed) + scene_c = rng.uniform([6, 6], [shape[0] - 6, shape[1] - 6], (40, 2)) + scene_a = rng.uniform(50, 150, 40) + imaged = np.zeros(shape, bool) + imaged[4:60, 5:80] = True + trials = [] + for shift in SHIFTS: + mean = 20 + _blobs(shape, scene_c, scene_a, 2.0, shift) + act = _peaks(shape, SOURCES, 0.05, 0.6, shift) + act += 0.0005 * np.abs(rng.normal(size=shape)) + mean[~imaged] = NAN + act[~imaged] = NAN + trials.append( + TrialImages( + np.stack([mean, 0.5 * mean], axis=2), + act, + peaks=np.array([[1.0, 2.0, 3.0, 0.4]]), + discard=np.array([False, True, False]), + ) + ) + return trials + + +@pytest.fixture(scope="module") +def synthetic_plan() -> tuple[ExtractionPlan, dict]: + """Plan the synthetic path, and keep its intermediates. + + Returns + ------- + plan : ExtractionPlan + The plan of the synthetic trials. + details : dict + The intermediates plan_path records. + """ + details = {} + plan = plan_path(_synthetic_trials(), params=PlanParams(peak_th=12.0), details=details) + return plan, details + + +def test_plan_params() -> None: + """Radii follow MATLAB; options are validated. + + selRadius = ceil(2 dXY); zones of ceil(1.5 sigma + (validKernel - 1) / 2): + MATLAB's 3 x 3 gives ceil(1.5 sigma + 1), the default 5 x 5 one more. + """ + p = PlanParams() + assert p.valid_kernel == 5 + assert p.sel_radius == 6 and p.zone_radius == 4 + assert PlanParams(valid_kernel=3).zone_radius == 3 + assert PlanParams(d_xy=2.2, sigma_px=2.0).sel_radius == 5 + assert PlanParams(sigma_px=2.0, valid_kernel=3).zone_radius == 4 + with pytest.raises(ValueError, match="inter_trial_alignment"): + PlanParams(inter_trial_alignment="elastic") + with pytest.raises(ValueError, match="peak_method"): + PlanParams(peak_method="blobs") + with pytest.raises(ValueError, match="d_xy"): + PlanParams(d_xy=0) + + +def test_group_sources_zones_and_order() -> None: + """Sources whose zones (5 x 5 squares for radius 3) touch form a group. + + Groups come in MATLAB's order, by the first pixel of their zone column + by column; pixels are the group's disks within the selected pixels. + """ + sel = np.ones((40, 60), bool) + sel[:, 30] = False + # (row, col): b and c touch through adjacent zones (5 columns apart); + # a is 6 columns from b: its own group; d lies in an earlier column + rows = np.array([20, 20, 20, 8]) + cols = np.array([20, 26, 31, 10]) + groups = group_sources(rows, cols, sel, zone_radius=3, sel_radius=6) + assert [g.sources.tolist() for g in groups] == [[3], [0], [1, 2]] + disk = disk_strel(6) + first = groups[0] + assert (first.row0, first.col0) == (3, 5) + np.testing.assert_array_equal(first.sel, disk) + np.testing.assert_array_equal(first.sources_rc, [[5, 5]]) + pair = groups[2] + assert (pair.row0, pair.col0) == (15, 21) + assert pair.sel.shape == (11, 16) + np.testing.assert_array_equal(pair.sources_rc, [[5, 5], [5, 10]]) + assert not pair.sel[:, 30 - 21].any() # the unselected column + # the pixel lists address the selected-pixel list (column-major) + cc, rr = np.nonzero(sel.T) + for g in groups: + assert (np.diff(g.pixels) > 0).all() + crop = np.zeros(g.sel.shape, bool) + crop[rr[g.pixels] - g.row0, cc[g.pixels] - g.col0] = True + np.testing.assert_array_equal(crop, g.sel) + assert group_sources(rows[:0], cols[:0], sel, 3, 6) == [] + with pytest.raises(ValueError, match="no selected pixels"): + group_sources(rows, cols, np.zeros_like(sel), 3, 6) + + +def test_combined_activity_image() -> None: + """The trials' mean (NaN where any trial is NaN), scaled and median-subtracted. + + Scaled to a maximum of 10 to 100, minus its 5 x 5 NaN-median. + """ + rng = np.random.default_rng(1) + act = rng.uniform(0.001, 0.002, (3, 12, 14)) + act[:, 6, 7] = 0.04 + act[1, 0, 0] = NAN + im, med, nan_frac = combined_activity_image(act, 0.33) + assert np.isnan(im[0, 0]) and nan_frac[0, 0] == pytest.approx(1 / 3) + scaled = act.mean(axis=0) / 1e-3 + np.testing.assert_allclose(im[6, 7] + med[6, 7], 40.0) + np.testing.assert_allclose(med[3, 3], np.median(scaled[1:6, 1:6]), rtol=1e-12) + empty = combined_activity_image(act[:0], 0.33) + assert all(np.isnan(x).all() for x in empty) + + +def test_plan_of_a_synthetic_path(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """Shifts, valid trials, sources, selected pixels and groups of a path. + + The path has known sources. + """ + plan, details = synthetic_plan + assert plan.shape == (64, 84) and plan.n_trials == 5 + np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) + np.testing.assert_array_equal(plan.aligned_trials, np.arange(5)) + assert (plan.corr > 0.99).all() and plan.corr_thresh <= 0.9 + # shifts are relative to the template's reference trial + np.testing.assert_allclose(plan.shifts - plan.shifts[0], SHIFTS - SHIFTS[0], atol=0.1) + assert plan.n_sources == 6 + # each source is where it was put, in every trial's own frame + for t in range(5): + r_t, c_t = plan.warp.coords(t, plan.source_rows, plan.source_cols) + found = np.column_stack([r_t, c_t]) + expect = SOURCES + SHIFTS[t] + apart = np.abs(found[:, None] - expect[None]).max(axis=2) + # a source is the nearest pixel of its seed (half a pixel off) + assert (apart.min(axis=0) < 0.7).all() + assert (apart.min(axis=1) < 0.7).all() + # selected pixels: valid pixels within the disks; the union is sel + assert plan.sel.sum() == plan.n_pixels + assert not (plan.sel & ~plan.px_always_valid).any() + union = np.zeros(plan.shape, bool) + for k in range(plan.n_sources): + mask = plan.source_mask(k) + assert mask[plan.source_rows[k], plan.source_cols[k]] + assert mask.sum() == plan.source_pixels[k].size + union |= mask + np.testing.assert_array_equal(union, plan.sel) + rows, cols = plan.selected_pixels() + assert (np.diff(rows + cols * plan.shape[0]) > 0).all() + # five groups: the pair shares one; every source is in exactly one + assert sorted(g.sources.size for g in plan.groups) == [1, 1, 1, 1, 2] + np.testing.assert_array_equal( + np.sort(np.concatenate([g.sources for g in plan.groups])), + np.arange(6), + ) + for g in plan.groups: + members = np.zeros(plan.shape, bool) + for k in g.sources: + members |= plan.source_mask(k) + crop = members[g.row0 : g.row0 + g.sel.shape[0], g.col0 : g.col0 + g.sel.shape[1]] + np.testing.assert_array_equal(crop, g.sel) + assert members.sum() == g.sel.sum() == g.pixels.size + np.testing.assert_array_equal( + g.sources_rc, + np.column_stack([ + plan.source_rows[g.sources] - g.row0, + plan.source_cols[g.sources] - g.col0, + ]), + ) + # images: the mean of the aligned trials, NaN ignored + assert plan.mean_im.shape == (64, 84, 2) + np.testing.assert_allclose( + plan.mean_im[30, 40], np.nanmean(plan.mean_aligned[:, 30, 40], axis=0) + ) + assert details["keep_sources"].all() and details["rows"].size == 6 + assert details["med_im"].shape == plan.shape + + +def test_plan_leaves_out_bad_and_missing_trials() -> None: + """Bad and missing trials are not valid; sources are seeded from the rest. + + Not valid: a trial that was not localized, one that is not kept, one + without an activity image and one that does not match the others. + """ + trials = _synthetic_trials() + shape = trials[0].act_im.shape + noise = np.random.default_rng(7).uniform(10, 30, shape) + noise[np.isnan(trials[0].act_im)] = NAN # nothing like the scene + odd = TrialImages(np.stack([noise, noise], axis=2), trials[0].act_im) + blank = TrialImages(trials[1].mean_im, np.full(shape, NAN)) + everything = trials + [None, odd, blank, trials[2]] + keep = np.ones(len(everything), bool) + keep[8] = False + plan = plan_path(everything, params=PlanParams(peak_th=12.0), keep_trials=keep) + np.testing.assert_array_equal(plan.keep_trials, keep & (np.arange(9) != 5)) + np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) + np.testing.assert_array_equal(plan.aligned_trials, [0, 1, 2, 3, 4, 6]) + assert plan.corr[6] < plan.corr_thresh < 0.9 + assert np.isnan(plan.shifts[[5, 7, 8]]).all() + assert np.isnan(plan.act_aligned[[5, 7, 8]]).all() + assert plan.n_sources == 6 + assert plan.trial_peaks[5] is None and plan.trial_peaks[0] is not None + with pytest.raises(ValueError, match="no trials"): + plan_path([None, None]) + + +def test_plan_soma_mask_and_given_seeds() -> None: + """No source is seeded in the soma mask (smaller masks sit top left). + + Given seeds replace the seeding; modes that are not ported are refused. + """ + trials = _synthetic_trials() + soma = np.zeros((40, 45), bool) + soma[:25, :30] = True # covers the source at (14, 16) + plan = plan_path(trials, soma, PlanParams(peak_th=12.0)) + assert plan.n_sources == 5 + assert plan.soma_mask.shape == plan.shape and plan.soma_mask.sum() == 750 + assert not plan.soma_mask[plan.source_rows, plan.source_cols].any() + seeds = np.array([[3.0, 20.2, 30.6, 0.5], [2.0, 20.4, 31.4, 0.5], [1.0, 2.0, 2.0, 0.5]]) + given = plan_path(trials, seeds=seeds) + # the first two round to one pixel; the last is outside the imaged area + np.testing.assert_array_equal(given.source_rows, [20]) + np.testing.assert_array_equal(given.source_cols, [31]) + np.testing.assert_array_equal(given.seeds, seeds) + # the same mask drawn on trial 3, whose image is the scene moved by + # SHIFTS[3]: it lands on the same sources of the consensus frame + drawn = np.zeros(plan.shape, bool) + rr, cc = np.nonzero(plan.soma_mask) + move = np.round(plan.shifts[3]).astype(int) + drawn[rr + move[0], cc + move[1]] = True + moved = plan_path(trials, drawn, PlanParams(peak_th=12.0), soma_mask_trial=3) + np.testing.assert_array_equal(moved.soma_mask, plan.soma_mask) + np.testing.assert_array_equal(moved.source_rows, plan.source_rows) + with pytest.warns(UserWarning, match="not aligned"): + loose = plan_path(trials + [None], drawn, PlanParams(peak_th=12.0), soma_mask_trial=5) + np.testing.assert_array_equal(loose.soma_mask, drawn) + with pytest.raises(ValueError, match="soma_mask"): + plan_path(trials, np.zeros((100, 100), bool)) + with pytest.raises(NotImplementedError, match="WMF"): + plan_path(trials, params=PlanParams(peak_method="wmf")) + + +def test_plan_of_trials_of_different_sizes(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """Trials of different sizes share one canvas (top left, NaN beyond), as in MATLAB. + + Their mean images must have the same channels. + """ + plan, _ = synthetic_plan + trials = _synthetic_trials() + # nothing is imaged in the rows and columns cut off here + trials[4] = TrialImages(trials[4].mean_im[:60, :80], trials[4].act_im[:60, :80]) + small = plan_path(trials, params=PlanParams(peak_th=12.0)) + assert small.shape == plan.shape + np.testing.assert_array_equal(small.shifts, plan.shifts) + np.testing.assert_array_equal(small.act_im, plan.act_im) + np.testing.assert_array_equal(small.source_rows, plan.source_rows) + np.testing.assert_array_equal(small.sel, plan.sel) + trials[1] = TrialImages(trials[1].mean_im[:, :, :1], trials[1].act_im) + with pytest.raises(ValueError, match="channels"): + plan_path(trials) + + +def test_plan_with_a_trial_without_images(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """A kept trial whose images are all NaN does not enter the template. + + Nothing was imaged often enough in it, so the other trials are planned + as without it; in MATLAB it would leave the path without sources. + """ + plan, _ = synthetic_plan + trials = _synthetic_trials() + shape = trials[0].act_im.shape + blank = TrialImages(np.full(shape + (2,), NAN), np.full(shape, NAN)) + with_blank = plan_path(trials[:2] + [blank] + trials[2:], params=PlanParams(peak_th=12.0)) + rest = [0, 1, 3, 4, 5] + assert with_blank.keep_trials.all() + np.testing.assert_array_equal(with_blank.template_trials, rest) + np.testing.assert_array_equal(with_blank.valid_trials, rest) + np.testing.assert_array_equal(with_blank.shifts[rest], plan.shifts) + assert np.isnan(with_blank.shifts[2]).all() + np.testing.assert_array_equal(with_blank.act_im, plan.act_im) + np.testing.assert_array_equal(with_blank.source_rows, plan.source_rows) + np.testing.assert_array_equal(with_blank.source_cols, plan.source_cols) + with pytest.raises(ValueError, match="mean image"): + plan_path([blank, blank]) + + +def test_plan_without_sources() -> None: + """A path whose activity images hold nothing above threshold has no sources. + + It has no sources, pixels or groups, and still writes and reads. + """ + trials = _synthetic_trials() + plan = plan_path(trials, params=PlanParams(peak_th=1e6)) + assert plan.n_sources == 0 and plan.n_pixels == 0 and plan.groups == [] + assert plan.seeds.shape == (0, 4) + + +def _assert_plans_equal(a: ExtractionPlan, b: ExtractionPlan) -> None: + """Every field of two plans is equal (NaN equal to NaN).""" + assert a.params == b.params + assert a.corr_thresh == b.corr_thresh + for name in ( + "keep_trials", + "template", + "template_trials", + "shifts", + "corr", + "act_valid_pix", + "valid_trials", + "mean_ims", + "act_ims", + "mean_aligned", + "act_aligned", + "mean_im", + "act_im", + "soma_mask", + "px_always_valid", + "seeds", + "source_rows", + "source_cols", + "source_values", + "sel", + ): + x, y = getattr(a, name), getattr(b, name) + assert x.dtype.kind == y.dtype.kind, name + np.testing.assert_array_equal(x, y, err_msg=name) + np.testing.assert_array_equal(a.warp.affine, b.warp.affine) + np.testing.assert_array_equal(a.warp.nodes, b.warp.nodes) + np.testing.assert_array_equal(a.warp.disp, b.warp.disp) + assert len(a.source_pixels) == len(b.source_pixels) + for x, y in zip(a.source_pixels, b.source_pixels): + np.testing.assert_array_equal(x, y) + assert len(a.groups) == len(b.groups) + for x, y in zip(a.groups, b.groups): + assert (x.row0, x.col0) == (y.row0, y.col0) + for name in ("sources", "pixels", "sel", "sources_rc"): + np.testing.assert_array_equal(getattr(x, name), getattr(y, name)) + for x, y in zip(a.trial_peaks + a.trial_discard, b.trial_peaks + b.trial_discard): + assert (x is None) == (y is None) + if x is not None: + np.testing.assert_array_equal(x, y) + + +def test_write_and_read_plan(tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """A plan survives the file; several paths share a file by group. + + A file that is not a plan, or a newer version, is refused. + """ + plan, _ = synthetic_plan + fn = tmp_path / "extraction_plan.h5" + write_plan(fn, plan) + back = read_plan(fn) + _assert_plans_equal(plan, back) + assert back.trial_discard[0].dtype == bool + # an empty plan, written next to it as a second imaging path + empty = plan_path(_synthetic_trials()[:2] + [None], params=PlanParams(peak_th=1e6)) + write_plan(fn, plan, group="DMD1") + write_plan(fn, empty, group="DMD2") + write_plan(fn, empty, group="DMD2") # replaces the group + _assert_plans_equal(read_plan(fn, "DMD1"), plan) + _assert_plans_equal(read_plan(fn, "DMD2"), empty) + with h5py.File(fn, "r+") as f: + f["DMD2"].attrs["version"] = 99 + f.create_group("other") + with pytest.raises(ValueError, match="version 99"): + read_plan(fn, "DMD2") + with pytest.raises(ValueError, match="does not hold"): + read_plan(fn, "other") + + +def _matlab_case(case: str) -> tuple[list[TrialImages | None], PlanParams, dict]: + """Read the inputs of one fixture case and MATLAB's results on them. + + The fixture holds a 72 x 96 window of five trials of one imaging path + (780125) and what SILo.m and extractTrial.m (GIAnT-MATLAB main + 5a0673b) compute from it, in Python's orientation and zero-based. + + Returns + ------- + trials : list + The case's trials as TrialImages; None for a trial MATLAB left out. + params : PlanParams + The plan parameters of MATLAB's algorithm. + ref : dict + MATLAB's results (and attributes) for the case. + """ + with h5py.File(FIXTURE, "r") as f: + mean = f["inputs/mean_ims"][()].astype(np.float64) + act = f["inputs/act_ims"][()] + g = f["matlab"][case] + ref = {k: g[k][()] for k in g} + ref.update({k: g.attrs[k] for k in g.attrs}) + a = f["inputs"].attrs + params = PlanParams( + nan_thresh=float(a["nanThresh"]), + peak_th=float(ref["peakth"]), + min_peak_distance=int(a["minPeakDistance"]), + d_xy=float(a["dXY"]), + sigma_px=float(a["sigma_px"]), + # MATLAB's algorithm (the defaults are the local fit, merging, + # the 5 x 5 support and the patchwise alignment) + seed_fit="matlab", + seed_merge_px=0.0, + valid_kernel=3, + inter_trial_alignment="rigid", + ) + keep = ref["keep_trials"].astype(bool) + trials = [TrialImages(mean[t], act[t]) if keep[t] else None for t in range(keep.size)] + return trials, params, ref + + +def _lists(ref: dict, name: str) -> list[np.ndarray]: + """Index lists of the fixture (_index and _ptr). + + Returns + ------- + list + One index array per list, split from _index at the offsets _ptr. + """ + index, ptr = ref[f"{name}_index"], ref[f"{name}_ptr"] + return [index[a:b] for a, b in zip(ptr[:-1], ptr[1:])] + + +@pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) +def test_plan_matches_matlab(case: str) -> None: + """Every step but the Gaussian fit of the seeds reproduces MATLAB. + + The template, shifts, valid trials, aligned and combined images to + rounding error; given MATLAB's seeds, the sources, their pixels and the + subproblems exactly. + """ + trials, params, ref = _matlab_case(case) + details = {} + plan = plan_path(trials, params=params, seeds=ref["seeds"], details=details) + close = dict(rtol=0, atol=1e-9) + np.testing.assert_allclose(plan.template, ref["template"], **close) + np.testing.assert_array_equal(plan.template_trials, ref["template_trials"]) + np.testing.assert_allclose(plan.shifts, ref["shifts"], **close) + np.testing.assert_allclose(plan.corr, ref["corr"], **close) + assert plan.corr_thresh == pytest.approx(ref["corr_thresh"], abs=1e-12) + np.testing.assert_allclose(plan.act_valid_pix, ref["act_valid_pix"], **close) + np.testing.assert_array_equal(plan.valid_trials, ref["valid_trials"]) + np.testing.assert_allclose(plan.act_aligned, ref["act_aligned"], **close) + np.testing.assert_allclose(plan.act_im, ref["act_im"], **close) + if "mean_aligned" in ref: + np.testing.assert_allclose(plan.mean_aligned, ref["mean_aligned"], rtol=1e-12, atol=1e-9) + np.testing.assert_allclose(plan.mean_im, ref["mean_im"], rtol=1e-12, atol=1e-9) + np.testing.assert_allclose(details["med_im"], ref["med_im"], **close) + # from MATLAB's seeds on: exact + np.testing.assert_array_equal(details["keep_sources"], ref["keep_sources"].astype(bool)) + np.testing.assert_array_equal(plan.source_rows, ref["source_rows"]) + np.testing.assert_array_equal(plan.source_cols, ref["source_cols"]) + np.testing.assert_array_equal(plan.source_values, ref["source_values"]) + np.testing.assert_array_equal(plan.px_always_valid, ref["px_always_valid"].astype(bool)) + np.testing.assert_array_equal(plan.sel, ref["sel"].astype(bool)) + for mine, matlab in zip(plan.source_pixels, _lists(ref, "source_pixel")): + np.testing.assert_array_equal(mine, matlab) + assert len(plan.groups) == ref["group_rows"].shape[0] + for g, src, pix, rows, cols in zip( + plan.groups, + _lists(ref, "group_source"), + _lists(ref, "group_pixel"), + ref["group_rows"], + ref["group_cols"], + ): + np.testing.assert_array_equal(g.sources, src) + np.testing.assert_array_equal(g.pixels, pix) + assert (g.row0, g.row0 + g.sel.shape[0] - 1) == tuple(rows) + assert (g.col0, g.col0 + g.sel.shape[1] - 1) == tuple(cols) + + +@pytest.mark.parametrize("case, same_pixel", [("all_trials", 0.85), ("one_trial_out", 1.0)]) +def test_own_seeds_are_close_to_matlabs(case: str, same_pixel: float) -> None: + """Seeding with this package's fit gives nearly MATLAB's sources. + + The seeds are fit on MATLAB's combined activity image. They are not + identical: the Gaussian fit is ill-conditioned for peaks narrower than a + pixel and MATLAB's lsqcurvefit stops on a tolerance or on its evaluation + limit, so where it ends depends on the optimizer (at a threshold of 3 SDs + MATLAB finds 21 sources in this window and this package 20). + """ + trials, params, ref = _matlab_case(case) + plan = plan_path(trials, params=params) + matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) + mine = np.column_stack([plan.source_rows, plan.source_cols]) + apart = np.abs(matlab[:, None] - mine[None]).max(axis=2) + assert abs(len(mine) - len(matlab)) <= 1 + assert (apart.min(axis=1) == 0).mean() >= same_pixel + assert (apart.min(axis=1) <= 1).all() and (apart.min(axis=0) <= 1).all() + + +@pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) +def test_default_seeding_on_matlabs_window(case: str) -> None: + """The default seeding on MATLAB's combined activity image is close to MATLAB's. + + The default seeding uses local fits, merging residual peaks within + 1.5 px: every MATLAB source is within 1 px of a source here, and every + source here within 1 px of a MATLAB source; only sources next to another + are merged (all trials: 16 of MATLAB's 21). Without merging the local fit + gives MATLAB's count. + """ + import dataclasses + + trials, params, ref = _matlab_case(case) + matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) + plan = plan_path( + trials, + params=dataclasses.replace( + params, + seed_fit=PlanParams.seed_fit, + seed_merge_px=PlanParams.seed_merge_px, + ), + ) + mine = np.column_stack([plan.source_rows, plan.source_cols]) + apart = np.abs(matlab[:, None] - mine[None]).max(axis=2) + assert len(mine) <= len(matlab) + assert (apart.min(axis=1) <= 1).all() and (apart.min(axis=0) <= 1).all() + unmerged = plan_path( + trials, + params=dataclasses.replace(params, seed_fit="local", seed_merge_px=0), + ) + assert abs(unmerged.n_sources - len(matlab)) <= 1 + + +def test_plans_written_before_the_seed_options_read_as_matlabs( + tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict] +) -> None: + """A plan file without the seed fields reads back with MATLAB's seed fit. + + Such a file was written before the fields existed; it reads back with + MATLAB's seed fit and no merging, the settings it was made with; a + current plan keeps its own. + """ + import json + + import h5py + + plan, _ = synthetic_plan + fn = tmp_path / "plan.h5" + write_plan(fn, plan) + assert read_plan(fn).params.seed_fit == plan.params.seed_fit + with h5py.File(fn, "r+") as f: + saved = json.loads(f.attrs["params"]) # a one-path plan: the root + del saved["seed_fit"], saved["seed_merge_px"] + f.attrs["params"] = json.dumps(saved) + old = read_plan(fn).params + assert (old.seed_fit, old.seed_merge_px) == ("matlab", 0.0) diff --git a/tests/raster/test_raster_refit.py b/tests/raster/test_raster_refit.py index 875d9c27..02f736c9 100644 --- a/tests/raster/test_raster_refit.py +++ b/tests/raster/test_raster_refit.py @@ -1,330 +1,351 @@ -"""Tests of the ground-truth refit test of the subproblem solver.""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.refit_test import ( - RefitTruth, - blur_error, - by_size, - draw_refit_data, - drift_error, - edge_error, - find_events, - refit_test, - scale_error, - score_refit, - shared_component, - summarize, -) -from giant_python.extraction.raster.solver import ( - SolverOptions, - solve_subproblem, -) -from giant_python.extraction.raster.solver_baseline import source_f0 -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -# MATLAB's 3 x 3 support, which the MATLAB subproblem's thresholds below -# were set with (the default is 5 x 5) -PARAMS = SolverParams(valid_kernel=3) - - -def test_find_events() -> None: - """Peaks above 2% of the largest are events. - - They are at least the lag after the previous peak (kept or not), away from - the trial's ends. - """ - x = np.zeros(60) - x[[2, 10, 14, 17, 30, 31, 44, 55]] = [5, 4, 3, 6, 0.05, 2, 1, 9] - # frame 2 is within 5 of the start; 14 and 17 follow a peak within the - # lag of 5; 30 is below 2% of 9, and not a maximum next to 31; 55 is - # within lag + 3 of the end - assert find_events(x, 5).tolist() == [10, 31, 44] - assert find_events(x, 3).tolist() == [10, 14, 17, 31, 44] - assert find_events(np.zeros(30), 5).size == 0 - # a plateau counts once, at its last frame - y = np.zeros(40) - y[[20, 21]] = 3.0 - assert find_events(y, 5).tolist() == [21] - - -def _truth(x: np.ndarray, h: np.ndarray | None = None) -> RefitTruth: - """Build a truth with the given activity, flat baseline and F0.""" - n_src, n_t = x.shape - if h is None: - h = np.array([[0.5], [0.3], [0.2]])[:, :n_src] - return RefitTruth( - h=h, - x=x, - b=np.full((h.shape[0], n_t), 2.0), - f0=np.full((n_src, n_t), 4.0), - z=np.zeros((h.shape[0], n_t)), - ) - - -def test_score_refit_of_a_perfect_and_a_scaled_refit() -> None: - """A refit equal to the truth recovers everything. - - A refit at half the size and with one event missing is scored as such. - """ - k = np.exp(-np.arange(12) / 4.8) - x = np.zeros((1, 120)) - for t, a in ((20, 2.0), (60, 8.0), (95, 1.0)): - x[0, t : t + 12] += a * k - truth = _truth(x) - f0, ls = truth.f0, x.copy() - src, ev = score_refit(truth, x, f0, ls, 4.8) - assert src[0]["recovered"] == pytest.approx(1.0) - assert src[0]["slope"] == pytest.approx(1.0) - assert src[0]["f0_ratio"] == src[0]["f0_ratio_active"] == 1.0 - assert src[0]["baseline"] == pytest.approx(2.0) - assert src[0]["peak_h"] == 0.5 - assert [e["found"] for e in ev] == [True] * 3 - assert [e["size"] for e in ev] == pytest.approx([1.0, 4.0, 0.5]) - for e in ev: - assert e["refit_mass"] == pytest.approx(e["true_mass"]) - - half = 0.5 * x - half[0, 90:] = 0 # the last event is missed - src, ev = score_refit(truth, half, 1.1 * f0, 2 * ls, 4.8) - assert src[0]["f0_ratio"] == pytest.approx(1.1) - assert src[0]["ls_recovered"] == pytest.approx(2.0) - assert [e["found"] for e in ev] == [True, True, False] - assert ev[0]["refit_mass"] == pytest.approx(0.5 * ev[0]["true_mass"]) - rows = by_size(ev) - assert [(r["size_from"], r["n"]) for r in rows] == [ - (0.5, 1), - (1.0, 1), - (4.0, 1), - ] - assert rows[0]["share_found"] == 0 and np.isnan(rows[0]["recovered_found"]) - assert rows[1]["recovered_found"] == pytest.approx(0.5) - summary = summarize(src, ev) - assert summary["n_sources"] == 1 and summary["n_events"] == 3 - assert 0.3 < summary["pooled"] < 0.5 - - -def test_score_refit_of_a_silent_source() -> None: - """A source without true activity has no events and NaN recovery.""" - truth = _truth(np.zeros((1, 50))) - src, ev = score_refit(truth, np.zeros((1, 50)), truth.f0, truth.x, 4.8) - assert ev == [] and np.isnan(src[0]["recovered"]) - assert np.isnan(src[0]["f0_ratio_active"]) - assert np.isnan(summarize(src, ev)["pooled"]) - - -def test_refit_test_on_a_real_subproblem() -> None: - """The refit of data redrawn from a real subproblem's fit recovers the events it finds. - - The subproblem is a dim one, 5 s long, most events below one unit; the same - seed gives the same data. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - r = refit_test([sub], PARAMS, SolverOptions(), seed=3, keep_truths=True) - s = r.summary - assert s["n_sources"] == 2 and s["n_events"] >= 20 - assert len(r.sources) == 2 and len(r.events) == s["n_events"] - assert all(row["subproblem"] == 0 for row in r.sources + r.events) - assert 0.3 < s["recovered"] < 1.2 and 0.3 < s["pooled"] < 1.2 - assert 1.0 < s["f0_ratio"] < 1.3 - found = np.mean([e["found"] for e in r.events]) - assert found > 0.25 - many = [row for row in r.by_size if row["n"] >= 10] - assert many and all(0.6 < row["recovered_found"] < 1.2 for row in many) - truth = r.truths[0] - assert truth.z.shape == sub.finv.shape and truth.z.min() >= 0 - # the redrawn data have the truth's mean - mean = truth.b + truth.h @ truth.x - assert truth.z.mean() == pytest.approx(mean.mean(), rel=0.02) - again = refit_test([sub], PARAMS, seed=3, keep_truths=True) - assert np.array_equal(again.truths[0].z, truth.z) - assert refit_test([sub], PARAMS, seed=4).truths == [] - # the truth of a redraw needs its baseline - fit = solve_subproblem(sub, PARAMS) - with pytest.raises(ValueError, match="keep_baseline"): - draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0)) - - -def _crop_truth(n_t: int = 40) -> tuple[Subproblem, RefitTruth]: - """Build a truth on a 4 x 5 crop with a baseline that varies over pixels.""" - sel = np.ones((4, 5), bool) - sub = Subproblem( - y=np.ones((1, 20, n_t)), - finv=np.ones((20, n_t)), - sel=sel, - sources_rc=np.array([[1, 2]]), - ) - b = np.outer(np.arange(1.0, 21.0), np.ones(n_t)) - truth = RefitTruth( - h=np.full((20, 1), 0.05), - x=np.zeros((1, n_t)), - b=b, - f0=np.full((1, n_t), 4.0), - z=np.zeros((20, n_t)), - ) - return sub, truth - - -def test_baseline_errors() -> None: - """Scale, drift, trial-edge and blur errors of the true baseline.""" - sub, truth = _crop_truth() - rng = np.random.default_rng(0) - b = truth.b - np.testing.assert_allclose(scale_error(-0.05)(truth, sub, rng), 0.95 * b) - d = drift_error(0.1)(truth, sub, rng) - np.testing.assert_allclose(d[:, 0], 0.95 * b[:, 0]) - np.testing.assert_allclose(d[:, -1], 1.05 * b[:, -1]) - np.testing.assert_allclose(d.mean(1), b.mean(1)) - e = edge_error(0.03, 5)(truth, sub, rng) - np.testing.assert_allclose(e[:, :5], 1.03 * b[:, :5]) - np.testing.assert_allclose(e[:, -5:], 1.03 * b[:, -5:]) - np.testing.assert_allclose(e[:, 5:-5], b[:, 5:-5]) - # a flat baseline stays flat when blurred, edges included - flat = RefitTruth(truth.h, truth.x, np.full_like(b, 3.0), truth.f0, b) - np.testing.assert_allclose(blur_error(1.0)(flat, sub, rng), 3.0) - blurred = blur_error(1.0)(truth, sub, rng) - assert blurred.shape == b.shape - assert np.ptp(blurred[:, 0]) < np.ptp(b[:, 0]) - np.testing.assert_allclose(blurred.mean(), b.mean(), rtol=0.05) - - -def test_shared_component() -> None: - """A shared fast change of the given root mean square. - - It is the same for every pixel, reproducible from its generator. - """ - sub, truth = _crop_truth(n_t=4000) - change = shared_component(0.02) - b1 = change(truth.b, sub, np.random.default_rng(5)) - course = b1 / truth.b - 1 - np.testing.assert_allclose(course, course[:1].repeat(20, 0)) - assert np.sqrt(np.mean(course[0] ** 2)) == pytest.approx(0.02) - # smoothed: neighbouring frames are correlated - assert np.corrcoef(course[0, :-1], course[0, 1:])[0, 1] > 0.6 - b2 = change(truth.b, sub, np.random.default_rng(5)) - np.testing.assert_array_equal(b1, b2) - - -def test_refit_test_with_a_given_baseline() -> None: - """The refit can get the true baseline, or one with an error. - - The truth's baseline can carry a shared change that the given one lacks; - the truth fits can be passed in. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - opt = SolverOptions(keep_baseline=True) - fit = solve_subproblem(sub, PARAMS, opt) - fixed = replace(PARAMS, baseline_mode="fixed") - exact = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - given_baseline=scale_error(0.0), - keep_truths=True, - ) - plain = refit_test([sub], PARAMS, opt, seed=2, keep_truths=True) - # the same draws whatever the refit gets - np.testing.assert_array_equal(exact.truths[0].z, plain.truths[0].z) - high = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - given_baseline=scale_error(0.1), - ) - assert high.summary["pooled"] < exact.summary["pooled"] - assert high.summary["f0_ratio"] > exact.summary["f0_ratio"] + 0.01 - shared = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - truth_baseline=shared_component(0.05), - keep_truths=True, - ) - tr = shared.truths[0] - np.testing.assert_array_equal(tr.b_fit, fit.baseline[0]) - assert not np.allclose(tr.b, tr.b_fit) - np.testing.assert_allclose(tr.f0, source_f0(tr.h, tr.b)) - with pytest.raises(ValueError, match="fits for"): - refit_test([sub], PARAMS, opt, fits=[fit, fit]) - - -def test_edge_error_scales_overlapping_ends_once() -> None: - """In a trial shorter than both windows, every frame is scaled once.""" - sub, truth = _crop_truth(n_t=10) - b = edge_error(0.1, 6)(truth, sub, np.random.default_rng(0)) - np.testing.assert_allclose(b, 1.1 * truth.b) - - -def test_refit_keeps_the_subproblems_own_baseline() -> None: - """Without a given_baseline the refit keeps each subproblem's own baseline. - - It keeps the external baseline, so network modes can be refitted. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - opt = SolverOptions(keep_baseline=True) - fit = solve_subproblem(sub, PARAMS, opt) - own = replace(sub, baseline=fit.baseline[0], _coords=None) - gain = replace(PARAMS, baseline_mode="gain") - r = refit_test([own], gain, opt, seed=1) - assert r.summary["n_sources"] == 2 - with pytest.raises(ValueError, match="Subproblem.baseline"): - refit_test([sub], gain, opt, seed=1) - - -def test_truth_baseline_gets_a_copy() -> None: - """An in-place change of the true baseline leaves the fit unchanged.""" - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - fit = solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) - before = fit.baseline.copy() - - def in_place(b: np.ndarray, sub: Subproblem, rng: np.random.Generator) -> np.ndarray: - """Scale the given array itself.""" - b *= 1.5 - return b - - tr = draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0), truth_baseline=in_place) - np.testing.assert_array_equal(fit.baseline, before) - np.testing.assert_array_equal(tr.b_fit, before[0]) - np.testing.assert_allclose(tr.b, 1.5 * before[0]) +"""Tests of the ground-truth refit test of the subproblem solver.""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.refit_test import ( + RefitTruth, + blur_error, + by_size, + draw_refit_data, + drift_error, + edge_error, + find_events, + refit_test, + scale_error, + score_refit, + shared_component, + summarize, +) +from giant_python.extraction.raster.solver import ( + SolverOptions, + solve_subproblem, +) +from giant_python.extraction.raster.solver_baseline import source_f0 +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +# MATLAB's 3 x 3 support, which the MATLAB subproblem's thresholds below +# were set with (the default is 5 x 5) +PARAMS = SolverParams(valid_kernel=3) + + +def test_find_events() -> None: + """Peaks above 2% of the largest are events. + + They are at least the lag after the previous peak (kept or not), away from + the trial's ends. + """ + x = np.zeros(60) + x[[2, 10, 14, 17, 30, 31, 44, 55]] = [5, 4, 3, 6, 0.05, 2, 1, 9] + # frame 2 is within 5 of the start; 14 and 17 follow a peak within the + # lag of 5; 30 is below 2% of 9, and not a maximum next to 31; 55 is + # within lag + 3 of the end + assert find_events(x, 5).tolist() == [10, 31, 44] + assert find_events(x, 3).tolist() == [10, 14, 17, 31, 44] + assert find_events(np.zeros(30), 5).size == 0 + # a plateau counts once, at its last frame + y = np.zeros(40) + y[[20, 21]] = 3.0 + assert find_events(y, 5).tolist() == [21] + + +def _truth(x: np.ndarray, h: np.ndarray | None = None) -> RefitTruth: + """Build a truth with the given activity, flat baseline and F0. + + Returns + ------- + RefitTruth + The truth with activity x, the weights h (a default if None), a flat baseline of + 2, a flat F0 of 4 and zero data. + """ + n_src, n_t = x.shape + if h is None: + h = np.array([[0.5], [0.3], [0.2]])[:, :n_src] + return RefitTruth( + h=h, + x=x, + b=np.full((h.shape[0], n_t), 2.0), + f0=np.full((n_src, n_t), 4.0), + z=np.zeros((h.shape[0], n_t)), + ) + + +def test_score_refit_of_a_perfect_and_a_scaled_refit() -> None: + """A refit equal to the truth recovers everything. + + A refit at half the size and with one event missing is scored as such. + """ + k = np.exp(-np.arange(12) / 4.8) + x = np.zeros((1, 120)) + for t, a in ((20, 2.0), (60, 8.0), (95, 1.0)): + x[0, t : t + 12] += a * k + truth = _truth(x) + f0, ls = truth.f0, x.copy() + src, ev = score_refit(truth, x, f0, ls, 4.8) + assert src[0]["recovered"] == pytest.approx(1.0) + assert src[0]["slope"] == pytest.approx(1.0) + assert src[0]["f0_ratio"] == src[0]["f0_ratio_active"] == 1.0 + assert src[0]["baseline"] == pytest.approx(2.0) + assert src[0]["peak_h"] == 0.5 + assert [e["found"] for e in ev] == [True] * 3 + assert [e["size"] for e in ev] == pytest.approx([1.0, 4.0, 0.5]) + for e in ev: + assert e["refit_mass"] == pytest.approx(e["true_mass"]) + + half = 0.5 * x + half[0, 90:] = 0 # the last event is missed + src, ev = score_refit(truth, half, 1.1 * f0, 2 * ls, 4.8) + assert src[0]["f0_ratio"] == pytest.approx(1.1) + assert src[0]["ls_recovered"] == pytest.approx(2.0) + assert [e["found"] for e in ev] == [True, True, False] + assert ev[0]["refit_mass"] == pytest.approx(0.5 * ev[0]["true_mass"]) + rows = by_size(ev) + assert [(r["size_from"], r["n"]) for r in rows] == [ + (0.5, 1), + (1.0, 1), + (4.0, 1), + ] + assert rows[0]["share_found"] == 0 and np.isnan(rows[0]["recovered_found"]) + assert rows[1]["recovered_found"] == pytest.approx(0.5) + summary = summarize(src, ev) + assert summary["n_sources"] == 1 and summary["n_events"] == 3 + assert 0.3 < summary["pooled"] < 0.5 + + +def test_score_refit_of_a_silent_source() -> None: + """A source without true activity has no events and NaN recovery.""" + truth = _truth(np.zeros((1, 50))) + src, ev = score_refit(truth, np.zeros((1, 50)), truth.f0, truth.x, 4.8) + assert ev == [] and np.isnan(src[0]["recovered"]) + assert np.isnan(src[0]["f0_ratio_active"]) + assert np.isnan(summarize(src, ev)["pooled"]) + + +def test_refit_test_on_a_real_subproblem() -> None: + """The refit of data redrawn from a real subproblem's fit recovers the events it finds. + + The subproblem is a dim one, 5 s long, most events below one unit; the same + seed gives the same data. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + r = refit_test([sub], PARAMS, SolverOptions(), seed=3, keep_truths=True) + s = r.summary + assert s["n_sources"] == 2 and s["n_events"] >= 20 + assert len(r.sources) == 2 and len(r.events) == s["n_events"] + assert all(row["subproblem"] == 0 for row in r.sources + r.events) + assert 0.3 < s["recovered"] < 1.2 and 0.3 < s["pooled"] < 1.2 + assert 1.0 < s["f0_ratio"] < 1.3 + found = np.mean([e["found"] for e in r.events]) + assert found > 0.25 + many = [row for row in r.by_size if row["n"] >= 10] + assert many and all(0.6 < row["recovered_found"] < 1.2 for row in many) + truth = r.truths[0] + assert truth.z.shape == sub.finv.shape and truth.z.min() >= 0 + # the redrawn data have the truth's mean + mean = truth.b + truth.h @ truth.x + assert truth.z.mean() == pytest.approx(mean.mean(), rel=0.02) + again = refit_test([sub], PARAMS, seed=3, keep_truths=True) + assert np.array_equal(again.truths[0].z, truth.z) + assert refit_test([sub], PARAMS, seed=4).truths == [] + # the truth of a redraw needs its baseline + fit = solve_subproblem(sub, PARAMS) + with pytest.raises(ValueError, match="keep_baseline"): + draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0)) + + +def _crop_truth(n_t: int = 40) -> tuple[Subproblem, RefitTruth]: + """Build a truth on a 4 x 5 crop with a baseline that varies over pixels. + + Returns + ------- + sub : Subproblem + The crop's subproblem, with one source. + truth : RefitTruth + The truth, with a baseline that varies over pixels. + """ + sel = np.ones((4, 5), bool) + sub = Subproblem( + y=np.ones((1, 20, n_t)), + finv=np.ones((20, n_t)), + sel=sel, + sources_rc=np.array([[1, 2]]), + ) + b = np.outer(np.arange(1.0, 21.0), np.ones(n_t)) + truth = RefitTruth( + h=np.full((20, 1), 0.05), + x=np.zeros((1, n_t)), + b=b, + f0=np.full((1, n_t), 4.0), + z=np.zeros((20, n_t)), + ) + return sub, truth + + +def test_baseline_errors() -> None: + """Scale, drift, trial-edge and blur errors of the true baseline.""" + sub, truth = _crop_truth() + rng = np.random.default_rng(0) + b = truth.b + np.testing.assert_allclose(scale_error(-0.05)(truth, sub, rng), 0.95 * b) + d = drift_error(0.1)(truth, sub, rng) + np.testing.assert_allclose(d[:, 0], 0.95 * b[:, 0]) + np.testing.assert_allclose(d[:, -1], 1.05 * b[:, -1]) + np.testing.assert_allclose(d.mean(1), b.mean(1)) + e = edge_error(0.03, 5)(truth, sub, rng) + np.testing.assert_allclose(e[:, :5], 1.03 * b[:, :5]) + np.testing.assert_allclose(e[:, -5:], 1.03 * b[:, -5:]) + np.testing.assert_allclose(e[:, 5:-5], b[:, 5:-5]) + # a flat baseline stays flat when blurred, edges included + flat = RefitTruth(truth.h, truth.x, np.full_like(b, 3.0), truth.f0, b) + np.testing.assert_allclose(blur_error(1.0)(flat, sub, rng), 3.0) + blurred = blur_error(1.0)(truth, sub, rng) + assert blurred.shape == b.shape + assert np.ptp(blurred[:, 0]) < np.ptp(b[:, 0]) + np.testing.assert_allclose(blurred.mean(), b.mean(), rtol=0.05) + + +def test_shared_component() -> None: + """A shared fast change of the given root mean square. + + It is the same for every pixel, reproducible from its generator. + """ + sub, truth = _crop_truth(n_t=4000) + change = shared_component(0.02) + b1 = change(truth.b, sub, np.random.default_rng(5)) + course = b1 / truth.b - 1 + np.testing.assert_allclose(course, course[:1].repeat(20, 0)) + assert np.sqrt(np.mean(course[0] ** 2)) == pytest.approx(0.02) + # smoothed: neighbouring frames are correlated + assert np.corrcoef(course[0, :-1], course[0, 1:])[0, 1] > 0.6 + b2 = change(truth.b, sub, np.random.default_rng(5)) + np.testing.assert_array_equal(b1, b2) + + +def test_refit_test_with_a_given_baseline() -> None: + """The refit can get the true baseline, or one with an error. + + The truth's baseline can carry a shared change that the given one lacks; + the truth fits can be passed in. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + opt = SolverOptions(keep_baseline=True) + fit = solve_subproblem(sub, PARAMS, opt) + fixed = replace(PARAMS, baseline_mode="fixed") + exact = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + given_baseline=scale_error(0.0), + keep_truths=True, + ) + plain = refit_test([sub], PARAMS, opt, seed=2, keep_truths=True) + # the same draws whatever the refit gets + np.testing.assert_array_equal(exact.truths[0].z, plain.truths[0].z) + high = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + given_baseline=scale_error(0.1), + ) + assert high.summary["pooled"] < exact.summary["pooled"] + assert high.summary["f0_ratio"] > exact.summary["f0_ratio"] + 0.01 + shared = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + truth_baseline=shared_component(0.05), + keep_truths=True, + ) + tr = shared.truths[0] + np.testing.assert_array_equal(tr.b_fit, fit.baseline[0]) + assert not np.allclose(tr.b, tr.b_fit) + np.testing.assert_allclose(tr.f0, source_f0(tr.h, tr.b)) + with pytest.raises(ValueError, match="fits for"): + refit_test([sub], PARAMS, opt, fits=[fit, fit]) + + +def test_edge_error_scales_overlapping_ends_once() -> None: + """In a trial shorter than both windows, every frame is scaled once.""" + sub, truth = _crop_truth(n_t=10) + b = edge_error(0.1, 6)(truth, sub, np.random.default_rng(0)) + np.testing.assert_allclose(b, 1.1 * truth.b) + + +def test_refit_keeps_the_subproblems_own_baseline() -> None: + """Without a given_baseline the refit keeps each subproblem's own baseline. + + It keeps the external baseline, so network modes can be refitted. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + opt = SolverOptions(keep_baseline=True) + fit = solve_subproblem(sub, PARAMS, opt) + own = replace(sub, baseline=fit.baseline[0], _coords=None) + gain = replace(PARAMS, baseline_mode="gain") + r = refit_test([own], gain, opt, seed=1) + assert r.summary["n_sources"] == 2 + with pytest.raises(ValueError, match="Subproblem.baseline"): + refit_test([sub], gain, opt, seed=1) + + +def test_truth_baseline_gets_a_copy() -> None: + """An in-place change of the true baseline leaves the fit unchanged.""" + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + fit = solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) + before = fit.baseline.copy() + + def in_place(b: np.ndarray, sub: Subproblem, rng: np.random.Generator) -> np.ndarray: + """Scale the given array itself. + + Returns + ------- + np.ndarray + The same array b, scaled by 1.5 in place. + """ + b *= 1.5 + return b + + tr = draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0), truth_baseline=in_place) + np.testing.assert_array_equal(fit.baseline, before) + np.testing.assert_array_equal(tr.b_fit, before[0]) + np.testing.assert_allclose(tr.b, 1.5 * before[0]) diff --git a/tests/raster/test_raster_results.py b/tests/raster/test_raster_results.py index f9ddf4d7..557d4aee 100644 --- a/tests/raster/test_raster_results.py +++ b/tests/raster/test_raster_results.py @@ -1,216 +1,235 @@ -"""Tests of results files. - -Solved subproblems of a trial-path, written by the solve stage and assembled -by the collect stage. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.extraction.raster.results import ( - TrialRecord, - read_results, - subproblem_results, - trial_outcome, - write_results, -) -from giant_python.extraction.raster.solver import ( - SubproblemResult, - assemble_results, - process_result, -) -from giant_python.extraction.raster.solver_setup import SolverParams - -N_PX, N_SRC, N_T = 9, 4, 50 - - -def record(seed: int = 0) -> TrialRecord: - """Build a trial's record.""" - rng = np.random.default_rng(seed) - return TrialRecord( - frame_lines=np.arange(1, N_T + 1) * 40, - discard=rng.random(N_T) < 0.1, - global_f=rng.random((2, N_T)), - roi_f=rng.random((3, 2, N_T)), - roi_fsvd=rng.random((3, 2, N_T)), - ) - - -def solved(seed: int = 1) -> dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]]: - """Three subproblems' placements and results.""" - rng = np.random.default_rng(seed) - placements = [ - (np.array([0, 1, 2, 3]), np.array([0])), - (np.array([3, 4, 5]), np.array([1, 2])), - (np.array([6, 7, 8]), np.array([3])), - ] - out = {} - for k, (pix, src) in enumerate(placements): - n_s = src.size - out[k] = ( - pix, - src, - SubproblemResult( - footprints=rng.random((pix.size, n_s)), - events=rng.random((2, n_s, N_T)), - ls=rng.random((2, n_s, N_T)), - f0=rng.random((2, n_s, N_T)), - snr=rng.random(n_s), - info={"activity1": {"iterations": k, "seconds": 0.1}}, - ), - ) - return out - - -def attrs(**kw: str | float) -> dict[str, str | float]: - """Build a results file's attributes.""" - a = dict( - settings_hash="h", - container="path1_trial0001.h5", - container_hash="c", - path=1, - trial=1, - n_subproblems=3, - n_pixels=N_PX, - n_sources=N_SRC, - photon_scale=25.0, - extracted=1, - ) - a.update(kw) - return a - - -def test_round_trip(tmp_path: Path) -> None: - """The record, every result and the attributes come back.""" - rec, res = record(), solved() - write_results(tmp_path / "r.h5", rec, res, attrs()) - back = read_results(tmp_path / "r.h5") - for name in ("frame_lines", "discard", "global_f", "roi_f", "roi_fsvd"): - np.testing.assert_array_equal(getattr(back.record, name), getattr(rec, name)) - assert sorted(back.results) == [0, 1, 2] - for k, (pix, src, r) in res.items(): - bp, bs, br = back.results[k] - np.testing.assert_array_equal(bp, pix) - np.testing.assert_array_equal(bs, src) - for name in ("footprints", "events", "ls", "f0", "snr"): - np.testing.assert_array_equal(getattr(br, name), getattr(r, name)) - assert br.info == r.info - assert back.attrs["container"] == "path1_trial0001.h5" - assert back.attrs["n_subproblems"] == 3 - light = read_results(tmp_path / "r.h5", data=False) - assert light.results == {0: None, 1: None, 2: None} - assert not list(tmp_path.glob("*.partial")) - - -def test_assembly_does_not_depend_on_the_split(tmp_path: Path) -> None: - """One file or one per subproblem: the same trial. - - Equal to assembleResults and processResult of the results. - """ - rec, res = record(), solved() - p = SolverParams() - write_results(tmp_path / "all.h5", rec, res, attrs()) - whole = trial_outcome([read_results(tmp_path / "all.h5")], p) - parts = [] - for k in res: - f = tmp_path / f"s{k}.h5" - write_results(f, rec, {k: res[k]}, attrs()) - parts.append(read_results(f)) - split = trial_outcome(parts[::-1], p) - - class Place: - """What assemble_results reads of a subproblem.""" - - def __init__(self, pix: np.ndarray, src: np.ndarray) -> None: - """Placement only.""" - self.pixels, self.sources = pix, src - - direct = process_result( - assemble_results( - [Place(pix, src) for pix, src, _ in res.values()], - [r for _, _, r in res.values()], - N_PX, - N_SRC, - 25.0, - ), - p, - rec.discard, - ) - for got in (whole, split): - for name in ("footprints", "events", "denoised", "ls", "f0", "snr"): - np.testing.assert_array_equal(getattr(got.activity, name), getattr(direct, name)) - np.testing.assert_array_equal(got.record.global_f, rec.global_f) - - -def test_incomplete_or_conflicting_results_raise(tmp_path: Path) -> None: - """Incomplete or conflicting results are errors. - - A missing subproblem, two different results of one, and files of two - containers are errors. - """ - rec, res = record(), solved() - p = SolverParams() - write_results(tmp_path / "a.h5", rec, {0: res[0], 1: res[1]}, attrs()) - with pytest.raises(ValueError, match="no results"): - trial_outcome([read_results(tmp_path / "a.h5")], p) - other = solved(seed=5) - write_results(tmp_path / "b.h5", rec, {1: other[1], 2: res[2]}, attrs()) - with pytest.raises(ValueError, match="two different results"): - trial_outcome( - [read_results(tmp_path / "a.h5"), read_results(tmp_path / "b.h5")], - p, - ) - write_results(tmp_path / "c.h5", rec, {2: res[2]}, attrs(container_hash="other")) - with pytest.raises(ValueError, match="different containers"): - trial_outcome( - [read_results(tmp_path / "a.h5"), read_results(tmp_path / "c.h5")], - p, - ) - with pytest.raises(ValueError): - trial_outcome([], p) - # the same results placed elsewhere - moved = dict(res) - moved[2] = (res[2][0] + 0, np.array([2]), res[2][2]) - write_results(tmp_path / "d.h5", rec, {2: res[2]}, attrs()) - write_results(tmp_path / "e.h5", rec, {2: moved[2]}, attrs()) - write_results(tmp_path / "f.h5", rec, {0: res[0], 1: res[1]}, attrs()) - with pytest.raises(ValueError, match="two different results"): - trial_outcome([read_results(tmp_path / n) for n in ("f.h5", "d.h5", "e.h5")], p) - # parts solved with different settings - write_results(tmp_path / "g.h5", rec, {2: res[2]}, attrs(solve_settings="lam 0.5")) - write_results( - tmp_path / "h.h5", - rec, - {0: res[0], 1: res[1]}, - attrs(solve_settings="lam 0.9"), - ) - with pytest.raises(ValueError, match="different settings"): - trial_outcome([read_results(tmp_path / n) for n in ("g.h5", "h.h5")], p) - - -def test_trial_not_extracted(tmp_path: Path) -> None: - """A trial too short to extract has its record and no sources.""" - rec = record() - write_results(tmp_path / "s.h5", rec, {}, attrs(extracted=0)) - out = trial_outcome([read_results(tmp_path / "s.h5")], SolverParams()) - assert out.activity is None - assert out.record.n_frames == N_T - - -def test_subproblem_results() -> None: - """Placements of solved subproblems, with their container indices.""" - - class Sub: - """A subproblem's placement.""" - - def __init__(self, k: int) -> None: - """Pixels and sources of subproblem ``k``.""" - self.pixels, self.sources = np.array([k]), np.array([k]) - - res = subproblem_results([Sub(4), Sub(7)], ["a", "b"], [4, 7]) - assert sorted(res) == [4, 7] and res[7][2] == "b" - assert sorted(subproblem_results([Sub(0)], ["a"])) == [0] - with pytest.raises(ValueError): - subproblem_results([Sub(0)], ["a", "b"]) +"""Tests of results files. + +Solved subproblems of a trial-path, written by the solve stage and assembled +by the collect stage. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.extraction.raster.results import ( + TrialRecord, + read_results, + subproblem_results, + trial_outcome, + write_results, +) +from giant_python.extraction.raster.solver import ( + SubproblemResult, + assemble_results, + process_result, +) +from giant_python.extraction.raster.solver_setup import SolverParams + +N_PX, N_SRC, N_T = 9, 4, 50 + + +def record(seed: int = 0) -> TrialRecord: + """Build a trial's record. + + Returns + ------- + TrialRecord + A record of random frame lines, discard flags and N_T-frame traces, drawn from seed. + """ + rng = np.random.default_rng(seed) + return TrialRecord( + frame_lines=np.arange(1, N_T + 1) * 40, + discard=rng.random(N_T) < 0.1, + global_f=rng.random((2, N_T)), + roi_f=rng.random((3, 2, N_T)), + roi_fsvd=rng.random((3, 2, N_T)), + ) + + +def solved(seed: int = 1) -> dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]]: + """Three subproblems' placements and results. + + Returns + ------- + dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + For each subproblem index, its pixel indices, its source indices and its random result. + """ + rng = np.random.default_rng(seed) + placements = [ + (np.array([0, 1, 2, 3]), np.array([0])), + (np.array([3, 4, 5]), np.array([1, 2])), + (np.array([6, 7, 8]), np.array([3])), + ] + out = {} + for k, (pix, src) in enumerate(placements): + n_s = src.size + out[k] = ( + pix, + src, + SubproblemResult( + footprints=rng.random((pix.size, n_s)), + events=rng.random((2, n_s, N_T)), + ls=rng.random((2, n_s, N_T)), + f0=rng.random((2, n_s, N_T)), + snr=rng.random(n_s), + info={"activity1": {"iterations": k, "seconds": 0.1}}, + ), + ) + return out + + +def attrs(**kw: str | float) -> dict[str, str | float]: + """Build a results file's attributes. + + Returns + ------- + dict[str, str or float] + Default attributes (settings hash, container, path, trial, subproblem, pixel and + source counts, photon scale) updated with the keyword overrides. + """ + a = dict( + settings_hash="h", + container="path1_trial0001.h5", + container_hash="c", + path=1, + trial=1, + n_subproblems=3, + n_pixels=N_PX, + n_sources=N_SRC, + photon_scale=25.0, + extracted=1, + ) + a.update(kw) + return a + + +def test_round_trip(tmp_path: Path) -> None: + """The record, every result and the attributes come back.""" + rec, res = record(), solved() + write_results(tmp_path / "r.h5", rec, res, attrs()) + back = read_results(tmp_path / "r.h5") + for name in ("frame_lines", "discard", "global_f", "roi_f", "roi_fsvd"): + np.testing.assert_array_equal(getattr(back.record, name), getattr(rec, name)) + assert sorted(back.results) == [0, 1, 2] + for k, (pix, src, r) in res.items(): + bp, bs, br = back.results[k] + np.testing.assert_array_equal(bp, pix) + np.testing.assert_array_equal(bs, src) + for name in ("footprints", "events", "ls", "f0", "snr"): + np.testing.assert_array_equal(getattr(br, name), getattr(r, name)) + assert br.info == r.info + assert back.attrs["container"] == "path1_trial0001.h5" + assert back.attrs["n_subproblems"] == 3 + light = read_results(tmp_path / "r.h5", data=False) + assert light.results == {0: None, 1: None, 2: None} + assert not list(tmp_path.glob("*.partial")) + + +def test_assembly_does_not_depend_on_the_split(tmp_path: Path) -> None: + """One file or one per subproblem: the same trial. + + Equal to assembleResults and processResult of the results. + """ + rec, res = record(), solved() + p = SolverParams() + write_results(tmp_path / "all.h5", rec, res, attrs()) + whole = trial_outcome([read_results(tmp_path / "all.h5")], p) + parts = [] + for k in res: + f = tmp_path / f"s{k}.h5" + write_results(f, rec, {k: res[k]}, attrs()) + parts.append(read_results(f)) + split = trial_outcome(parts[::-1], p) + + class Place: + """What assemble_results reads of a subproblem.""" + + def __init__(self, pix: np.ndarray, src: np.ndarray) -> None: + """Placement only.""" + self.pixels, self.sources = pix, src + + direct = process_result( + assemble_results( + [Place(pix, src) for pix, src, _ in res.values()], + [r for _, _, r in res.values()], + N_PX, + N_SRC, + 25.0, + ), + p, + rec.discard, + ) + for got in (whole, split): + for name in ("footprints", "events", "denoised", "ls", "f0", "snr"): + np.testing.assert_array_equal(getattr(got.activity, name), getattr(direct, name)) + np.testing.assert_array_equal(got.record.global_f, rec.global_f) + + +def test_incomplete_or_conflicting_results_raise(tmp_path: Path) -> None: + """Incomplete or conflicting results are errors. + + A missing subproblem, two different results of one, and files of two + containers are errors. + """ + rec, res = record(), solved() + p = SolverParams() + write_results(tmp_path / "a.h5", rec, {0: res[0], 1: res[1]}, attrs()) + with pytest.raises(ValueError, match="no results"): + trial_outcome([read_results(tmp_path / "a.h5")], p) + other = solved(seed=5) + write_results(tmp_path / "b.h5", rec, {1: other[1], 2: res[2]}, attrs()) + with pytest.raises(ValueError, match="two different results"): + trial_outcome( + [read_results(tmp_path / "a.h5"), read_results(tmp_path / "b.h5")], + p, + ) + write_results(tmp_path / "c.h5", rec, {2: res[2]}, attrs(container_hash="other")) + with pytest.raises(ValueError, match="different containers"): + trial_outcome( + [read_results(tmp_path / "a.h5"), read_results(tmp_path / "c.h5")], + p, + ) + with pytest.raises(ValueError): + trial_outcome([], p) + # the same results placed elsewhere + moved = dict(res) + moved[2] = (res[2][0] + 0, np.array([2]), res[2][2]) + write_results(tmp_path / "d.h5", rec, {2: res[2]}, attrs()) + write_results(tmp_path / "e.h5", rec, {2: moved[2]}, attrs()) + write_results(tmp_path / "f.h5", rec, {0: res[0], 1: res[1]}, attrs()) + with pytest.raises(ValueError, match="two different results"): + trial_outcome([read_results(tmp_path / n) for n in ("f.h5", "d.h5", "e.h5")], p) + # parts solved with different settings + write_results(tmp_path / "g.h5", rec, {2: res[2]}, attrs(solve_settings="lam 0.5")) + write_results( + tmp_path / "h.h5", + rec, + {0: res[0], 1: res[1]}, + attrs(solve_settings="lam 0.9"), + ) + with pytest.raises(ValueError, match="different settings"): + trial_outcome([read_results(tmp_path / n) for n in ("g.h5", "h.h5")], p) + + +def test_trial_not_extracted(tmp_path: Path) -> None: + """A trial too short to extract has its record and no sources.""" + rec = record() + write_results(tmp_path / "s.h5", rec, {}, attrs(extracted=0)) + out = trial_outcome([read_results(tmp_path / "s.h5")], SolverParams()) + assert out.activity is None + assert out.record.n_frames == N_T + + +def test_subproblem_results() -> None: + """Placements of solved subproblems, with their container indices.""" + + class Sub: + """A subproblem's placement.""" + + def __init__(self, k: int) -> None: + """Pixels and sources of subproblem k.""" + self.pixels, self.sources = np.array([k]), np.array([k]) + + res = subproblem_results([Sub(4), Sub(7)], ["a", "b"], [4, 7]) + assert sorted(res) == [4, 7] and res[7][2] == "b" + assert sorted(subproblem_results([Sub(0)], ["a"])) == [0] + with pytest.raises(ValueError): + subproblem_results([Sub(0)], ["a", "b"]) diff --git a/tests/raster/test_raster_seed_acceptance.py b/tests/raster/test_raster_seed_acceptance.py index 111c1402..02fd87bc 100644 --- a/tests/raster/test_raster_seed_acceptance.py +++ b/tests/raster/test_raster_seed_acceptance.py @@ -1,464 +1,477 @@ -"""Tests of the seed threshold set from the combined image's null. - -That is ``seed_acceptance='null'`` (GIAnT-Python#51); also tests of the null -images that carry it from the localize stage to the plan stage. -""" - -from pathlib import Path - -import numpy as np -import pytest -from scipy import ndimage - -from giant_python.extraction.raster.peaks import get_act_im_peaks, ordfilt3x3 -from giant_python.extraction.raster.plan import ( - PlanParams, - TrialImages, - combined_activity_image, - combined_null_image, - plan_path, -) -from giant_python.extraction.raster.seeding import ( - candidate_statistic, - null_background, - null_threshold, - seed_sources, -) -from giant_python.extraction.raster.stage_files import ( - read_localization, - write_localization, -) -from giant_python.models.params import SiloParams - - -def _noise_field( - rng: np.random.Generator, shape: tuple[int, int] = (120, 140), sigma: float = 1.3 -) -> np.ndarray: - """Smoothed Gaussian noise: a stand-in for a null activity image.""" - return ndimage.gaussian_filter(rng.standard_normal(shape), sigma) - - -def test_candidate_statistic_is_the_seeding_rule() -> None: - """Maxima whose second-largest neighbour exceeds a threshold are the candidates. - - They are exactly get_act_im_peaks' candidates. - """ - rng = np.random.default_rng(0) - im = _noise_field(rng) - im[:3] = np.nan - excl = np.zeros(im.shape, bool) - excl[50:60, 50:60] = True - rc, value = candidate_statistic(im, excl) - th = np.quantile(value, 0.9) - explored = im * ~excl - with np.errstate(invalid="ignore"): - cand = (ordfilt3x3(explored, 8) > th) & (explored == ordfilt3x3(explored, 9)) - mine = np.zeros(im.shape, bool) - mine[tuple(rc[value > th].T)] = True - np.testing.assert_array_equal(mine, cand) - assert not excl[tuple(rc.T)].any() - - -def test_null_threshold_gives_the_expected_false_seeds() -> None: - """A null threshold gives about the requested false candidates per field. - - A threshold set on one null field for 2 false candidates per field is - crossed about twice per field on independent fields of the same noise; a - lax target is read off the null, a strict one extrapolated. - """ - rng = np.random.default_rng(1) - fields = [_noise_field(rng) for _ in range(41)] - (mu, sd), th, info = null_threshold(np.stack(fields[:4]), 2.0) - assert info["extrapolated"] and info["draws"] == 4 - counts = [np.sum((candidate_statistic(f)[1] - mu) / sd > th) for f in fields[4:]] - assert 1.0 < np.mean(counts) < 4.0 - _, th_lax, info_lax = null_threshold(fields[0], 200.0) - assert not info_lax["extrapolated"] - assert np.sum((candidate_statistic(fields[0])[1] - mu) / sd > th_lax) <= 210 - _, th_strict, _ = null_threshold(fields[0], 0.1) - assert th_strict > th_lax - with pytest.raises(ValueError): - null_threshold(fields[0], 0.0) - with pytest.raises(ValueError): - null_threshold(np.zeros((20, 20)), 1.0) - - -def test_background_override() -> None: - """The image's own median and robust SD as the background reproduce MATLAB's threshold. - - A doubled scale with half the threshold does too. - """ - rng = np.random.default_rng(2) - im = _noise_field(rng, (60, 60)) * 0.2 - for r, c in ((15, 15), (30, 44), (45, 20)): - im[r - 2 : r + 3, c - 2 : c + 3] += 3 * np.exp( - -np.add.outer(np.arange(-2, 3) ** 2, np.arange(-2, 3) ** 2) / 2 - ) - v = im[np.isfinite(im)] - mu = np.median(v) - sd = np.median(np.abs(v - mu)) / 0.6741891400433162 - ref = get_act_im_peaks(im, 5.0, fit="local") - same = get_act_im_peaks(im, 5.0, fit="local", background=(mu, sd)) - half = get_act_im_peaks(im, 2.5, fit="local", background=(mu, 2 * sd)) - np.testing.assert_allclose(same, ref) - np.testing.assert_allclose(half, ref) - assert ref.shape[0] == 3 - with pytest.raises(ValueError): - get_act_im_peaks(im, 5.0, background=(0.0, 0.0)) - - -def test_seed_sources_with_the_null() -> None: - """acceptance='null' seeds at the null's threshold and reports it. - - It needs the null image. - """ - rng = np.random.default_rng(3) - im = _noise_field(rng, (80, 80)) - g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) - im[37:44, 37:44] += 3.0 * g # a source well above the noise (SD ~0.2) - null = np.stack([_noise_field(rng, (80, 80)) for _ in range(2)]) - info = {} - seeds = seed_sources( - im, - 99.0, - fit="local", - acceptance="null", - null_im=null, - false_per_field=1.0, - info=info, - ) - bg, th, _ = null_threshold(null, 1.0) - np.testing.assert_allclose(seeds, get_act_im_peaks(im, th, fit="local", background=bg)) - assert info["peak_th"] == pytest.approx(th) and info["draws"] == 2 - assert np.hypot(*(seeds[:, 1:3] - 40).T).min() < 1.0 - with pytest.raises(ValueError): - seed_sources(im, 3.0, acceptance="null") - with pytest.raises(ValueError): - seed_sources(im, 3.0, acceptance="robust") - info = {} - seed_sources(im, 3.0, fit="local", info=info) - assert info == {"peak_th": 3.0, "background": None} - - -def test_combined_null_is_combined_like_the_image() -> None: - """Null images equal to the activity images combine to the combined activity image. - - Same scale, mask and median subtraction. - """ - rng = np.random.default_rng(4) - act = np.stack([np.abs(_noise_field(rng, (30, 40))) * 50 for _ in range(4)]) - act[1, :2] = np.nan - im, _, _ = combined_activity_image(act, 0.33) - null = combined_null_image(act[:, None], act, 0.33) - assert null.shape == (1, 30, 40) - np.testing.assert_allclose(null[0], im, equal_nan=True) - - -def _trials( - rng: np.random.Generator, - n: int = 3, - shape: tuple[int, int] = (48, 52), - null: bool = True, -) -> list[TrialImages]: - """Trials of one structured mean image with noise activity images.""" - base = ndimage.gaussian_filter(rng.random(shape), 2) * 100 + 10 - out = [] - for _ in range(n): - act = np.abs(_noise_field(rng, shape)) - act[20, 20] += 5 - nul = np.abs(_noise_field(rng, shape))[None] if null else None - out.append(TrialImages(base[..., None] + rng.random(shape + (1,)), act, null_im=nul)) - return out - - -def test_plan_with_null_acceptance() -> None: - """The plan seeds with the trials' null images and reports the threshold. - - Without null images it refuses. - """ - rng = np.random.default_rng(5) - trials = _trials(rng) - det = {} - p = PlanParams( - seed_acceptance="null", - seed_false_per_field=2.0, - inter_trial_alignment="rigid", - ) - plan = plan_path(trials, params=p, details=det) - assert det["null_im"].shape == (1,) + plan.shape - assert det["seed_info"]["draws"] == 1 and det["seed_info"]["background"] - det0 = {} - plan_path(trials, params=PlanParams(inter_trial_alignment="rigid"), details=det0) - assert det0["seed_info"]["background"] is None and "null_im" not in det0 - with pytest.raises(ValueError, match="null images"): - plan_path(_trials(rng, null=False), params=p) - with pytest.raises(ValueError): - PlanParams(seed_acceptance="robust") - with pytest.raises(ValueError): - PlanParams(seed_false_per_field=0) - - -def test_null_images_round_trip(tmp_path: Path) -> None: - """Localization files keep the null images when given.""" - rng = np.random.default_rng(6) - act = rng.random((6, 7)) - null = rng.random((2, 6, 7)).astype(np.float32) - path = tmp_path / "loc.h5" - write_localization( - path, - rng.random((6, 7, 1)), - act, - act, - np.zeros(5, bool), - None, - {}, - None, - null, - ) - rec = read_localization(path) - np.testing.assert_array_equal(rec.null_im, null) - assert rec.attrs["null_im"] == 1 - np.testing.assert_array_equal(rec.trial_images().null_im, null) - write_localization(path, rng.random((6, 7, 1)), act, act, np.zeros(5, bool), None, {}) - assert read_localization(path).null_im is None - - -def test_silo_params_null_acceptance() -> None: - """The localization keeps null images exactly when the seeding needs them (unless set). - - Both need the bootstrap null; defaults leave the stage hashes and MATLAB's - fields alone. - """ - default = SiloParams() - assert default.seed_acceptance == "image" - assert default.localization_keep_null is False - net = SiloParams(baseline_source="network", seed_acceptance="null") - assert net.localization_keep_null is True - assert net.plan_params().seed_acceptance == "null" - assert "localization_keep_null" in net.stage_settings("localize") - assert "seed_acceptance" in net.stage_settings("plan") - assert "localization_keep_null" not in SiloParams(baseline_source="network").stage_settings( - "localize" - ) - m = net.to_matlab(2, 80.0) - assert m["seedAcceptance"] == "null" and m["localizationKeepNull"] - assert "seedAcceptance" not in default.to_matlab(2, 80.0) - keep = SiloParams(baseline_source="network", localization_keep_null=True) - assert keep.seed_acceptance == "image" and keep.localization_keep_null - for bad in ( - dict(seed_acceptance="null"), # no bootstrap null - dict( - baseline_source="network", - seed_acceptance="null", - localization_keep_null=False, - ), - dict(baseline_source="network", seed_false_per_field=-1.0), - dict(baseline_source="network", seed_acceptance="robust"), - ): - with pytest.raises(ValueError): - SiloParams(**bad) - - -def test_silo_params_evidence_test() -> None: - """The evidence test is off by default with MATLAB's baseline. - - It is on with the network's (min_source_event_rate 2 per minute) and - reaches only the collect stage's settings when on. - """ - default = SiloParams() - assert default.min_source_snr == 0 and default.min_source_event_rate == 0 - assert "min_source_snr" not in default.stage_settings("collect") - assert "min_source_event_rate" not in default.stage_settings("collect") - net = SiloParams(baseline_source="network") - assert net.min_source_snr == 0 and net.min_source_event_rate == 2.0 - assert net.stage_settings("collect")["min_source_event_rate"] == 2.0 - assert "min_source_event_rate" not in net.stage_settings("plan") - on = SiloParams(min_source_snr=2.0, min_source_event_rate=1.5) - assert on.stage_settings("collect")["min_source_snr"] == 2.0 - assert on.to_matlab(2, 80.0)["minSourceSNR"] == 2.0 - assert on.to_matlab(2, 80.0)["minSourceEventRate"] == 1.5 - for bad in (dict(min_source_snr=-1.0), dict(min_source_event_rate=-1)): - with pytest.raises(ValueError): - SiloParams(**bad) - - -def test_seed_heights() -> None: - """A source's seed height: the second-largest 3 x 3 value around its pixel. - - In robust SDs above the image's median (NaN left out). - """ - from giant_python.extraction.raster.peaks import _MAD_SCALE - from giant_python.extraction.raster.seeding import seed_heights - - rng = np.random.default_rng(3) - im = rng.standard_normal((40, 50)) - mu = np.median(im) - sigma = np.median(np.abs(im - mu)) / _MAD_SCALE - im[10, 10], im[10, 11] = 50.0, 9.0 * sigma + mu # second largest: 9 SDs - im[0, 0], im[0, 1], im[1, 0], im[1, 1] = 40.0, 30.0, np.nan, np.nan - h = seed_heights(im, np.array([10, 0, 25]), np.array([10, 0, 30])) - # the planted values barely move the image's median and MAD - vals = im[np.isfinite(im)] - mu = np.median(vals) - sigma = np.median(np.abs(vals - mu)) / _MAD_SCALE - win = np.sort(im[24:27, 29:32].ravel()) - np.testing.assert_allclose( - h, [(im[10, 11] - mu) / sigma, (30.0 - mu) / sigma, (win[-2] - mu) / sigma] - ) - assert np.isnan(seed_heights(np.full((5, 5), np.nan), [2], [2])).all() - assert np.isnan(seed_heights(np.ones((5, 5)), [2], [2])).all() - - -def test_silo_params_evidence_margin() -> None: - """The evidence test judges sources seeded below peak_th + 2 by default. - - The margin enters the collect hash and the params struct only when the - test is on, so MATLAB's settings keep both. - """ - m = SiloParams() - assert m.evidence_margin == 2.0 and not m.evidence_test - assert "evidence_margin" not in m.stage_settings("collect") - assert "evidenceMargin" not in m.to_matlab(2, 80.0) - net = SiloParams(baseline_source="network") - assert net.evidence_test and net.evidence_judge_below == 5.0 - assert net.stage_settings("collect")["evidence_margin"] == 2.0 - assert net.to_matlab(2, 80.0)["evidenceMargin"] == 2.0 - every = SiloParams(baseline_source="network", evidence_margin=None) - assert every.evidence_judge_below is None - assert every.to_matlab(2, 80.0)["evidenceMargin"] == np.inf - assert every.stage_settings("collect") != net.stage_settings("collect") - with pytest.raises(ValueError): - SiloParams(evidence_margin=-1.0) - # the null seed thresholds do not count in the image's robust SDs - # above peak_th: the evidence test then judges every source - for mode in ("null", "null_sd"): - p = SiloParams(baseline_source="network", seed_acceptance=mode) - assert p.evidence_test and p.evidence_judge_below is None - - -def test_null_sd_acceptance() -> None: - """acceptance='null_sd' counts peak_th in robust SDs of the null. - - The plan and SiloParams accept it with the null images. - """ - rng = np.random.default_rng(7) - im = _noise_field(rng, (80, 80)) - g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) - im[37:44, 37:44] += 3.0 * g - null = 2.0 * _noise_field(rng, (80, 80))[None] - info = {} - seeds = seed_sources(im, 4.0, fit="local", acceptance="null_sd", null_im=null, info=info) - bg = null_background(null) - np.testing.assert_allclose(seeds, get_act_im_peaks(im, 4.0, fit="local", background=bg)) - assert info["background"] == pytest.approx(bg) - with pytest.raises(ValueError): - seed_sources(im, 4.0, acceptance="null_sd") - det = {} - plan_path( - _trials(np.random.default_rng(8)), - params=PlanParams(seed_acceptance="null_sd", inter_trial_alignment="rigid"), - details=det, - ) - assert det["null_im"].shape[0] == 1 and det["seed_info"]["background"] - p = SiloParams(baseline_source="network", seed_acceptance="null_sd") - assert p.localization_keep_null and p.plan_params().seed_acceptance == ("null_sd") - - -def test_amplitude_rule_pixel_keeps_sharp_peaks() -> None: - """The 'pixel' amplitude rule keeps sharp peaks that MATLAB's test drops. - - MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a sharp - peak whose own pixel is well above the threshold; 'pixel' keeps it, and - drops a peak whose own pixel is below. - """ - from giant_python.extraction.raster.peaks import _finish - - theta = np.array([[0.9, 10.0, 10.0, 0.3], [0.1, 20.0, 20.0, 0.3]]) - excl = np.zeros((30, 30), bool) - assert _finish(theta, 0.22, excl, False).shape[0] == 0 - kept = _finish(theta, 0.22, excl, False, "pixel") - np.testing.assert_allclose(kept[:, 1:3], [[9.0, 9.0]]) - with pytest.raises(ValueError): - get_act_im_peaks(np.zeros((10, 10)), 3.0, amplitude_rule="area") - with pytest.raises(ValueError): - PlanParams(seed_amplitude_rule="area") - p = SiloParams(seed_amplitude_rule="pixel") - assert p.plan_params().seed_amplitude_rule == "pixel" - assert "seed_amplitude_rule" in p.stage_settings("plan") - assert "seed_amplitude_rule" not in SiloParams().stage_settings("plan") - - -def test_null_images_from_localization_and_empty_plans() -> None: - """The in-memory adapter carries the localization's null images. - - A plan without valid trials has no seeds in the null modes too. - """ - from types import SimpleNamespace - - rng = np.random.default_rng(9) - null = rng.random((1, 6, 7)) - loc = SimpleNamespace(act_im=rng.random((6, 7)), peaks=None, info={"null": {"null_im": null}}) - trial = SimpleNamespace(mean_im=rng.random((6, 7, 1)), discard=np.zeros(4, bool), half_ims=None) - np.testing.assert_array_equal(TrialImages.from_localization(loc, trial).null_im, null) - loc.info = {} - assert TrialImages.from_localization(loc, trial).null_im is None - blank = [ - TrialImages(t.mean_im, np.full(t.act_im.shape, np.nan), null_im=t.null_im) - for t in _trials(np.random.default_rng(10)) - ] - plan = plan_path( - blank, - params=PlanParams(seed_acceptance="null", inter_trial_alignment="rigid"), - ) - assert plan.valid_trials.size == 0 and plan.seeds.shape == (0, 4) - - -def test_trial_null_seeds_are_independent() -> None: - """With kept null images every trial-path draws its own null movies. - - Distinct seeds, apart by more than a trial's draws; the default - calibration's seed is not used for them. - """ - from giant_python.pipeline.silo import trial_null_seed - - seeds = {trial_null_seed(0, d, t) for d in range(3) for t in range(200)} - assert len(seeds) == 600 - s = sorted(seeds) - assert min(np.diff(s)) >= 1000 and min(s) > 0 - assert trial_null_seed(7, 0, 0) == trial_null_seed(0, 0, 0) + 7 - - -def test_pixel_rule_uses_the_fits_pixel_edges() -> None: - """Beside a gap in the imaged columns the fits' pixel is wider. - - The 'pixel' rule integrates the same wider pixel. - """ - from giant_python.extraction.raster.peaks import _finish, _pixel_bounds - - finite = np.ones((20, 20), bool) - finite[:, 11:14] = False # a gap of 3 columns right of column 10 - (ylo, yhi), (xlo, xhi) = _pixel_bounds(finite) - np.testing.assert_allclose([ylo[5], yhi[5]], [5.5, 6.5]) - assert xhi[10] - xlo[10] == pytest.approx(2.5) # midpoint to column 15 - theta = np.array([[0.3, 10.0, 11.4, 0.6]]) # 1-based centre in col 11 - excl = np.zeros((20, 20), bool) - unit = _finish(theta, 0.22, excl, False, "pixel") - wide = _finish(theta, 0.22, excl, False, "pixel", 0.0, ((ylo, yhi), (xlo, xhi))) - assert unit.shape[0] == 0 and wide.shape[0] == 1 - - -def test_trial_null_seeds_leave_room_for_many_draws() -> None: - """With more draws than the default block, blocks widen. - - So no two trial-paths share a seed. - """ - from giant_python.pipeline.silo import trial_null_seed - - draws = 2500 - used = set() - for d in range(2): - for t in range(4): - s0 = trial_null_seed(0, d, t, draws) - block = set(range(s0, s0 + draws)) - assert not block & used - used |= block +"""Tests of the seed threshold set from the combined image's null. + +That is seed_acceptance='null' (GIAnT-Python#51); also tests of the null +images that carry it from the localize stage to the plan stage. +""" + +from pathlib import Path + +import numpy as np +import pytest +from scipy import ndimage + +from giant_python.extraction.raster.peaks import get_act_im_peaks, ordfilt3x3 +from giant_python.extraction.raster.plan import ( + PlanParams, + TrialImages, + combined_activity_image, + combined_null_image, + plan_path, +) +from giant_python.extraction.raster.seeding import ( + candidate_statistic, + null_background, + null_threshold, + seed_sources, +) +from giant_python.extraction.raster.stage_files import ( + read_localization, + write_localization, +) +from giant_python.models.params import SiloParams + + +def _noise_field( + rng: np.random.Generator, shape: tuple[int, int] = (120, 140), sigma: float = 1.3 +) -> np.ndarray: + """Smoothed Gaussian noise: a stand-in for a null activity image. + + Returns + ------- + np.ndarray + The noise image of the given shape. + """ + return ndimage.gaussian_filter(rng.standard_normal(shape), sigma) + + +def test_candidate_statistic_is_the_seeding_rule() -> None: + """Maxima whose second-largest neighbour exceeds a threshold are the candidates. + + They are exactly get_act_im_peaks' candidates. + """ + rng = np.random.default_rng(0) + im = _noise_field(rng) + im[:3] = np.nan + excl = np.zeros(im.shape, bool) + excl[50:60, 50:60] = True + rc, value = candidate_statistic(im, excl) + th = np.quantile(value, 0.9) + explored = im * ~excl + with np.errstate(invalid="ignore"): + cand = (ordfilt3x3(explored, 8) > th) & (explored == ordfilt3x3(explored, 9)) + mine = np.zeros(im.shape, bool) + mine[tuple(rc[value > th].T)] = True + np.testing.assert_array_equal(mine, cand) + assert not excl[tuple(rc.T)].any() + + +def test_null_threshold_gives_the_expected_false_seeds() -> None: + """A null threshold gives about the requested false candidates per field. + + A threshold set on one null field for 2 false candidates per field is + crossed about twice per field on independent fields of the same noise; a + lax target is read off the null, a strict one extrapolated. + """ + rng = np.random.default_rng(1) + fields = [_noise_field(rng) for _ in range(41)] + (mu, sd), th, info = null_threshold(np.stack(fields[:4]), 2.0) + assert info["extrapolated"] and info["draws"] == 4 + counts = [np.sum((candidate_statistic(f)[1] - mu) / sd > th) for f in fields[4:]] + assert 1.0 < np.mean(counts) < 4.0 + _, th_lax, info_lax = null_threshold(fields[0], 200.0) + assert not info_lax["extrapolated"] + assert np.sum((candidate_statistic(fields[0])[1] - mu) / sd > th_lax) <= 210 + _, th_strict, _ = null_threshold(fields[0], 0.1) + assert th_strict > th_lax + with pytest.raises(ValueError): + null_threshold(fields[0], 0.0) + with pytest.raises(ValueError): + null_threshold(np.zeros((20, 20)), 1.0) + + +def test_background_override() -> None: + """The image's own median and robust SD as the background reproduce MATLAB's threshold. + + A doubled scale with half the threshold does too. + """ + rng = np.random.default_rng(2) + im = _noise_field(rng, (60, 60)) * 0.2 + for r, c in ((15, 15), (30, 44), (45, 20)): + im[r - 2 : r + 3, c - 2 : c + 3] += 3 * np.exp( + -np.add.outer(np.arange(-2, 3) ** 2, np.arange(-2, 3) ** 2) / 2 + ) + v = im[np.isfinite(im)] + mu = np.median(v) + sd = np.median(np.abs(v - mu)) / 0.6741891400433162 + ref = get_act_im_peaks(im, 5.0, fit="local") + same = get_act_im_peaks(im, 5.0, fit="local", background=(mu, sd)) + half = get_act_im_peaks(im, 2.5, fit="local", background=(mu, 2 * sd)) + np.testing.assert_allclose(same, ref) + np.testing.assert_allclose(half, ref) + assert ref.shape[0] == 3 + with pytest.raises(ValueError): + get_act_im_peaks(im, 5.0, background=(0.0, 0.0)) + + +def test_seed_sources_with_the_null() -> None: + """acceptance='null' seeds at the null's threshold and reports it. + + It needs the null image. + """ + rng = np.random.default_rng(3) + im = _noise_field(rng, (80, 80)) + g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) + im[37:44, 37:44] += 3.0 * g # a source well above the noise (SD ~0.2) + null = np.stack([_noise_field(rng, (80, 80)) for _ in range(2)]) + info = {} + seeds = seed_sources( + im, + 99.0, + fit="local", + acceptance="null", + null_im=null, + false_per_field=1.0, + info=info, + ) + bg, th, _ = null_threshold(null, 1.0) + np.testing.assert_allclose(seeds, get_act_im_peaks(im, th, fit="local", background=bg)) + assert info["peak_th"] == pytest.approx(th) and info["draws"] == 2 + assert np.hypot(*(seeds[:, 1:3] - 40).T).min() < 1.0 + with pytest.raises(ValueError): + seed_sources(im, 3.0, acceptance="null") + with pytest.raises(ValueError): + seed_sources(im, 3.0, acceptance="robust") + info = {} + seed_sources(im, 3.0, fit="local", info=info) + assert info == {"peak_th": 3.0, "background": None} + + +def test_combined_null_is_combined_like_the_image() -> None: + """Null images equal to the activity images combine to the combined activity image. + + Same scale, mask and median subtraction. + """ + rng = np.random.default_rng(4) + act = np.stack([np.abs(_noise_field(rng, (30, 40))) * 50 for _ in range(4)]) + act[1, :2] = np.nan + im, _, _ = combined_activity_image(act, 0.33) + null = combined_null_image(act[:, None], act, 0.33) + assert null.shape == (1, 30, 40) + np.testing.assert_allclose(null[0], im, equal_nan=True) + + +def _trials( + rng: np.random.Generator, + n: int = 3, + shape: tuple[int, int] = (48, 52), + null: bool = True, +) -> list[TrialImages]: + """Trials of one structured mean image with noise activity images. + + Returns + ------- + list of TrialImages + n trials sharing a mean image, each with a noise activity image + and, when null is true, a noise null image. + """ + base = ndimage.gaussian_filter(rng.random(shape), 2) * 100 + 10 + out = [] + for _ in range(n): + act = np.abs(_noise_field(rng, shape)) + act[20, 20] += 5 + nul = np.abs(_noise_field(rng, shape))[None] if null else None + out.append(TrialImages(base[..., None] + rng.random(shape + (1,)), act, null_im=nul)) + return out + + +def test_plan_with_null_acceptance() -> None: + """The plan seeds with the trials' null images and reports the threshold. + + Without null images it refuses. + """ + rng = np.random.default_rng(5) + trials = _trials(rng) + det = {} + p = PlanParams( + seed_acceptance="null", + seed_false_per_field=2.0, + inter_trial_alignment="rigid", + ) + plan = plan_path(trials, params=p, details=det) + assert det["null_im"].shape == (1,) + plan.shape + assert det["seed_info"]["draws"] == 1 and det["seed_info"]["background"] + det0 = {} + plan_path(trials, params=PlanParams(inter_trial_alignment="rigid"), details=det0) + assert det0["seed_info"]["background"] is None and "null_im" not in det0 + with pytest.raises(ValueError, match="null images"): + plan_path(_trials(rng, null=False), params=p) + with pytest.raises(ValueError): + PlanParams(seed_acceptance="robust") + with pytest.raises(ValueError): + PlanParams(seed_false_per_field=0) + + +def test_null_images_round_trip(tmp_path: Path) -> None: + """Localization files keep the null images when given.""" + rng = np.random.default_rng(6) + act = rng.random((6, 7)) + null = rng.random((2, 6, 7)).astype(np.float32) + path = tmp_path / "loc.h5" + write_localization( + path, + rng.random((6, 7, 1)), + act, + act, + np.zeros(5, bool), + None, + {}, + None, + null, + ) + rec = read_localization(path) + np.testing.assert_array_equal(rec.null_im, null) + assert rec.attrs["null_im"] == 1 + np.testing.assert_array_equal(rec.trial_images().null_im, null) + write_localization(path, rng.random((6, 7, 1)), act, act, np.zeros(5, bool), None, {}) + assert read_localization(path).null_im is None + + +def test_silo_params_null_acceptance() -> None: + """The localization keeps null images exactly when the seeding needs them (unless set). + + Both need the bootstrap null; defaults leave the stage hashes and MATLAB's + fields alone. + """ + default = SiloParams() + assert default.seed_acceptance == "image" + assert default.localization_keep_null is False + net = SiloParams(baseline_source="network", seed_acceptance="null") + assert net.localization_keep_null is True + assert net.plan_params().seed_acceptance == "null" + assert "localization_keep_null" in net.stage_settings("localize") + assert "seed_acceptance" in net.stage_settings("plan") + assert "localization_keep_null" not in SiloParams(baseline_source="network").stage_settings( + "localize" + ) + m = net.to_matlab(2, 80.0) + assert m["seedAcceptance"] == "null" and m["localizationKeepNull"] + assert "seedAcceptance" not in default.to_matlab(2, 80.0) + keep = SiloParams(baseline_source="network", localization_keep_null=True) + assert keep.seed_acceptance == "image" and keep.localization_keep_null + for bad in ( + dict(seed_acceptance="null"), # no bootstrap null + dict( + baseline_source="network", + seed_acceptance="null", + localization_keep_null=False, + ), + dict(baseline_source="network", seed_false_per_field=-1.0), + dict(baseline_source="network", seed_acceptance="robust"), + ): + with pytest.raises(ValueError): + SiloParams(**bad) + + +def test_silo_params_evidence_test() -> None: + """The evidence test is off by default with MATLAB's baseline. + + It is on with the network's (min_source_event_rate 2 per minute) and + reaches only the collect stage's settings when on. + """ + default = SiloParams() + assert default.min_source_snr == 0 and default.min_source_event_rate == 0 + assert "min_source_snr" not in default.stage_settings("collect") + assert "min_source_event_rate" not in default.stage_settings("collect") + net = SiloParams(baseline_source="network") + assert net.min_source_snr == 0 and net.min_source_event_rate == 2.0 + assert net.stage_settings("collect")["min_source_event_rate"] == 2.0 + assert "min_source_event_rate" not in net.stage_settings("plan") + on = SiloParams(min_source_snr=2.0, min_source_event_rate=1.5) + assert on.stage_settings("collect")["min_source_snr"] == 2.0 + assert on.to_matlab(2, 80.0)["minSourceSNR"] == 2.0 + assert on.to_matlab(2, 80.0)["minSourceEventRate"] == 1.5 + for bad in (dict(min_source_snr=-1.0), dict(min_source_event_rate=-1)): + with pytest.raises(ValueError): + SiloParams(**bad) + + +def test_seed_heights() -> None: + """A source's seed height: the second-largest 3 x 3 value around its pixel. + + In robust SDs above the image's median (NaN left out). + """ + from giant_python.extraction.raster.peaks import _MAD_SCALE + from giant_python.extraction.raster.seeding import seed_heights + + rng = np.random.default_rng(3) + im = rng.standard_normal((40, 50)) + mu = np.median(im) + sigma = np.median(np.abs(im - mu)) / _MAD_SCALE + im[10, 10], im[10, 11] = 50.0, 9.0 * sigma + mu # second largest: 9 SDs + im[0, 0], im[0, 1], im[1, 0], im[1, 1] = 40.0, 30.0, np.nan, np.nan + h = seed_heights(im, np.array([10, 0, 25]), np.array([10, 0, 30])) + # the planted values barely move the image's median and MAD + vals = im[np.isfinite(im)] + mu = np.median(vals) + sigma = np.median(np.abs(vals - mu)) / _MAD_SCALE + win = np.sort(im[24:27, 29:32].ravel()) + np.testing.assert_allclose( + h, [(im[10, 11] - mu) / sigma, (30.0 - mu) / sigma, (win[-2] - mu) / sigma] + ) + assert np.isnan(seed_heights(np.full((5, 5), np.nan), [2], [2])).all() + assert np.isnan(seed_heights(np.ones((5, 5)), [2], [2])).all() + + +def test_silo_params_evidence_margin() -> None: + """The evidence test judges sources seeded below peak_th + 2 by default. + + The margin enters the collect hash and the params struct only when the + test is on, so MATLAB's settings keep both. + """ + m = SiloParams() + assert m.evidence_margin == 2.0 and not m.evidence_test + assert "evidence_margin" not in m.stage_settings("collect") + assert "evidenceMargin" not in m.to_matlab(2, 80.0) + net = SiloParams(baseline_source="network") + assert net.evidence_test and net.evidence_judge_below == 5.0 + assert net.stage_settings("collect")["evidence_margin"] == 2.0 + assert net.to_matlab(2, 80.0)["evidenceMargin"] == 2.0 + every = SiloParams(baseline_source="network", evidence_margin=None) + assert every.evidence_judge_below is None + assert every.to_matlab(2, 80.0)["evidenceMargin"] == np.inf + assert every.stage_settings("collect") != net.stage_settings("collect") + with pytest.raises(ValueError): + SiloParams(evidence_margin=-1.0) + # the null seed thresholds do not count in the image's robust SDs + # above peak_th: the evidence test then judges every source + for mode in ("null", "null_sd"): + p = SiloParams(baseline_source="network", seed_acceptance=mode) + assert p.evidence_test and p.evidence_judge_below is None + + +def test_null_sd_acceptance() -> None: + """acceptance='null_sd' counts peak_th in robust SDs of the null. + + The plan and SiloParams accept it with the null images. + """ + rng = np.random.default_rng(7) + im = _noise_field(rng, (80, 80)) + g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) + im[37:44, 37:44] += 3.0 * g + null = 2.0 * _noise_field(rng, (80, 80))[None] + info = {} + seeds = seed_sources(im, 4.0, fit="local", acceptance="null_sd", null_im=null, info=info) + bg = null_background(null) + np.testing.assert_allclose(seeds, get_act_im_peaks(im, 4.0, fit="local", background=bg)) + assert info["background"] == pytest.approx(bg) + with pytest.raises(ValueError): + seed_sources(im, 4.0, acceptance="null_sd") + det = {} + plan_path( + _trials(np.random.default_rng(8)), + params=PlanParams(seed_acceptance="null_sd", inter_trial_alignment="rigid"), + details=det, + ) + assert det["null_im"].shape[0] == 1 and det["seed_info"]["background"] + p = SiloParams(baseline_source="network", seed_acceptance="null_sd") + assert p.localization_keep_null and p.plan_params().seed_acceptance == ("null_sd") + + +def test_amplitude_rule_pixel_keeps_sharp_peaks() -> None: + """The 'pixel' amplitude rule keeps sharp peaks that MATLAB's test drops. + + MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a sharp + peak whose own pixel is well above the threshold; 'pixel' keeps it, and + drops a peak whose own pixel is below. + """ + from giant_python.extraction.raster.peaks import _finish + + theta = np.array([[0.9, 10.0, 10.0, 0.3], [0.1, 20.0, 20.0, 0.3]]) + excl = np.zeros((30, 30), bool) + assert _finish(theta, 0.22, excl, False).shape[0] == 0 + kept = _finish(theta, 0.22, excl, False, "pixel") + np.testing.assert_allclose(kept[:, 1:3], [[9.0, 9.0]]) + with pytest.raises(ValueError): + get_act_im_peaks(np.zeros((10, 10)), 3.0, amplitude_rule="area") + with pytest.raises(ValueError): + PlanParams(seed_amplitude_rule="area") + p = SiloParams(seed_amplitude_rule="pixel") + assert p.plan_params().seed_amplitude_rule == "pixel" + assert "seed_amplitude_rule" in p.stage_settings("plan") + assert "seed_amplitude_rule" not in SiloParams().stage_settings("plan") + + +def test_null_images_from_localization_and_empty_plans() -> None: + """The in-memory adapter carries the localization's null images. + + A plan without valid trials has no seeds in the null modes too. + """ + from types import SimpleNamespace + + rng = np.random.default_rng(9) + null = rng.random((1, 6, 7)) + loc = SimpleNamespace(act_im=rng.random((6, 7)), peaks=None, info={"null": {"null_im": null}}) + trial = SimpleNamespace(mean_im=rng.random((6, 7, 1)), discard=np.zeros(4, bool), half_ims=None) + np.testing.assert_array_equal(TrialImages.from_localization(loc, trial).null_im, null) + loc.info = {} + assert TrialImages.from_localization(loc, trial).null_im is None + blank = [ + TrialImages(t.mean_im, np.full(t.act_im.shape, np.nan), null_im=t.null_im) + for t in _trials(np.random.default_rng(10)) + ] + plan = plan_path( + blank, + params=PlanParams(seed_acceptance="null", inter_trial_alignment="rigid"), + ) + assert plan.valid_trials.size == 0 and plan.seeds.shape == (0, 4) + + +def test_trial_null_seeds_are_independent() -> None: + """With kept null images every trial-path draws its own null movies. + + Distinct seeds, apart by more than a trial's draws; the default + calibration's seed is not used for them. + """ + from giant_python.pipeline.silo import trial_null_seed + + seeds = {trial_null_seed(0, d, t) for d in range(3) for t in range(200)} + assert len(seeds) == 600 + s = sorted(seeds) + assert min(np.diff(s)) >= 1000 and min(s) > 0 + assert trial_null_seed(7, 0, 0) == trial_null_seed(0, 0, 0) + 7 + + +def test_pixel_rule_uses_the_fits_pixel_edges() -> None: + """Beside a gap in the imaged columns the fits' pixel is wider. + + The 'pixel' rule integrates the same wider pixel. + """ + from giant_python.extraction.raster.peaks import _finish, _pixel_bounds + + finite = np.ones((20, 20), bool) + finite[:, 11:14] = False # a gap of 3 columns right of column 10 + (ylo, yhi), (xlo, xhi) = _pixel_bounds(finite) + np.testing.assert_allclose([ylo[5], yhi[5]], [5.5, 6.5]) + assert xhi[10] - xlo[10] == pytest.approx(2.5) # midpoint to column 15 + theta = np.array([[0.3, 10.0, 11.4, 0.6]]) # 1-based centre in col 11 + excl = np.zeros((20, 20), bool) + unit = _finish(theta, 0.22, excl, False, "pixel") + wide = _finish(theta, 0.22, excl, False, "pixel", 0.0, ((ylo, yhi), (xlo, xhi))) + assert unit.shape[0] == 0 and wide.shape[0] == 1 + + +def test_trial_null_seeds_leave_room_for_many_draws() -> None: + """With more draws than the default block, blocks widen. + + So no two trial-paths share a seed. + """ + from giant_python.pipeline.silo import trial_null_seed + + draws = 2500 + used = set() + for d in range(2): + for t in range(4): + s0 = trial_null_seed(0, d, t, draws) + block = set(range(s0, s0 + draws)) + assert not block & used + used |= block diff --git a/tests/raster/test_raster_seeding.py b/tests/raster/test_raster_seeding.py index 8f5b920e..d3c4b853 100644 --- a/tests/raster/test_raster_seeding.py +++ b/tests/raster/test_raster_seeding.py @@ -1,135 +1,135 @@ -"""Tests of source seeding and pixel selection of SiLo's plan stage.""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.seeding import ( - disk_strel, - seed_sources, - select_source_pixels, - sources_from_seeds, -) - -FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" - - -def test_disk_strel_matches_matlab() -> None: - """strel('disk', r).Neighborhood of MATLAB R2024b for r = 0 .. 39.""" - with h5py.File(FIXTURE, "r") as f: - g = f["strel_disk"] - for r in range(40): - np.testing.assert_array_equal( - disk_strel(r), g[str(r)][()].astype(bool), err_msg=f"r={r}" - ) - - -def test_disk_strel_shapes() -> None: - """MATLAB's disk is smaller than its radius says. - - Radius 3 is a full 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's - selRadius). - """ - assert disk_strel(0).shape == (1, 1) - np.testing.assert_array_equal(disk_strel(1), [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) - np.testing.assert_array_equal(disk_strel(3), np.ones((5, 5), bool)) - d6 = disk_strel(6) - assert d6.shape == (11, 11) and d6.sum() == 109 - np.testing.assert_array_equal(d6[0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) - np.testing.assert_array_equal(d6[1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]) - assert d6[2:9].all() - np.testing.assert_array_equal(d6, d6.T) - np.testing.assert_array_equal(d6, d6[::-1, ::-1]) - # n = 0 is the Euclidean disk - assert disk_strel(6, 0).shape == (13, 13) - with pytest.raises(ValueError): - disk_strel(-1) - with pytest.raises(ValueError): - disk_strel(5, 5) - - -def test_sources_from_seeds_rounds_and_prunes() -> None: - """Positions round as MATLAB's (halves up in its one-based coordinates). - - The first seed of a pixel wins, order is kept, and positions are clamped - to the image. - """ - seeds = np.array([ - [5.0, 3.5, 7.49, 0.4], # MATLAB 4.5, 8.49 -> pixel (5, 8) - [2.0, 9.2, 1.0, 0.4], - [9.0, 3.6, 7.2, 0.4], # same pixel as the first: dropped - [1.0, -0.5, 19.5, 0.4], # MATLAB 0.5, 20.5 -> (1, 21): clamped - [4.0, 2.5 - 1e-12, 0.0, 0.4], - ]) - rows, cols, values = sources_from_seeds(seeds, (12, 20)) - np.testing.assert_array_equal(rows, [4, 9, 0, 2]) - np.testing.assert_array_equal(cols, [7, 1, 19, 0]) - np.testing.assert_array_equal(values, [5.0, 2.0, 1.0, 4.0]) - empty = sources_from_seeds(np.zeros((0, 4)), (12, 20)) - assert all(x.size == 0 for x in empty) - - -def test_select_source_pixels() -> None: - """A source's pixels are MATLAB's disk within the image and the valid pixels. - - They are in column-major order; sources that lose their own pixel or - nearly all pixels are pruned. - """ - valid = np.ones((30, 40), bool) - valid[:, 25:] = False - valid[12, 10] = False - rows = np.array([12, 2, 12, 12, 20]) - cols = np.array([8, 3, 29, 10, 30]) - sel = select_source_pixels(rows, cols, valid, sel_radius=6) - np.testing.assert_array_equal(sel.keep, [True, True, False, False, False]) - # an interior source has the whole disk but the invalid pixel - disk = np.zeros((30, 40), bool) - disk[7:18, 3:14] = disk_strel(6) - disk[12, 10] = False - cc, rr = np.nonzero(disk.T) - np.testing.assert_array_equal(sel.pixels[0], rr + cc * 30) - assert (np.diff(sel.pixels[0]) > 0).all() - # near the corner the disk is clipped by the image - assert sel.pixels[1].size < 109 and sel.pixels[1].min() == 0 - # a source on an invalid pixel is pruned although pixels remain: the - # third keeps the disk's first column (7 pixels), the fourth nearly all - assert sel.pixels[2].size == 7 and sel.pixels[3].size == 108 - assert sel.pixels[4].size == 0 - # a source needs more than 5 pixels - island = np.zeros((20, 20), bool) - island[5:7, 5:7] = True # 4 pixels - few = select_source_pixels(np.array([5]), np.array([5]), island, 6) - assert few.pixels[0].size == 4 and not few.keep[0] - island[5:7, 7] = True # 6 pixels - more = select_source_pixels(np.array([5]), np.array([5]), island, 6) - assert more.pixels[0].size == 6 and more.keep[0] - - -def test_seed_sources() -> None: - """The default method seeds blobs; the soma mask excludes them. - - Unknown and unported methods are refused; an image without usable pixels - gives no seeds. - """ - rng = np.random.default_rng(0) - im = rng.normal(0, 0.3, (40, 50)) - rr, cc = np.mgrid[:40, :50] - for r0, c0 in [(10, 12), (28, 35)]: - im += 20 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) - seeds = seed_sources(im, 8.0) - assert seeds.shape == (2, 4) - np.testing.assert_allclose(seeds[np.argsort(seeds[:, 1]), 1:3], [(10, 12), (28, 35)], atol=0.3) - soma = np.zeros(im.shape, bool) - soma[20:, 25:] = True - masked = seed_sources(im, 8.0, soma) - assert masked.shape == (1, 4) and abs(masked[0, 1] - 10) < 0.3 - # an all-false mask is no mask - np.testing.assert_array_equal(seed_sources(im, 8.0, np.zeros(im.shape, bool)), seeds) - assert seed_sources(np.full((5, 5), np.nan), 3.0).shape == (0, 4) - assert seed_sources(im, 8.0, np.ones(im.shape, bool)).shape == (0, 4) - with pytest.raises(NotImplementedError, match="WMF"): - seed_sources(im, 8.0, method="wmf") - with pytest.raises(ValueError, match="method"): - seed_sources(im, 8.0, method="other") +"""Tests of source seeding and pixel selection of SiLo's plan stage.""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.seeding import ( + disk_strel, + seed_sources, + select_source_pixels, + sources_from_seeds, +) + +FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" + + +def test_disk_strel_matches_matlab() -> None: + """strel('disk', r).Neighborhood of MATLAB R2024b for r = 0 .. 39.""" + with h5py.File(FIXTURE, "r") as f: + g = f["strel_disk"] + for r in range(40): + np.testing.assert_array_equal( + disk_strel(r), g[str(r)][()].astype(bool), err_msg=f"r={r}" + ) + + +def test_disk_strel_shapes() -> None: + """MATLAB's disk is smaller than its radius says. + + Radius 3 is a full 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's + selRadius). + """ + assert disk_strel(0).shape == (1, 1) + np.testing.assert_array_equal(disk_strel(1), [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) + np.testing.assert_array_equal(disk_strel(3), np.ones((5, 5), bool)) + d6 = disk_strel(6) + assert d6.shape == (11, 11) and d6.sum() == 109 + np.testing.assert_array_equal(d6[0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) + np.testing.assert_array_equal(d6[1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]) + assert d6[2:9].all() + np.testing.assert_array_equal(d6, d6.T) + np.testing.assert_array_equal(d6, d6[::-1, ::-1]) + # n = 0 is the Euclidean disk + assert disk_strel(6, 0).shape == (13, 13) + with pytest.raises(ValueError): + disk_strel(-1) + with pytest.raises(ValueError): + disk_strel(5, 5) + + +def test_sources_from_seeds_rounds_and_prunes() -> None: + """Positions round as MATLAB's (halves up in its one-based coordinates). + + The first seed of a pixel wins, order is kept, and positions are clamped + to the image. + """ + seeds = np.array([ + [5.0, 3.5, 7.49, 0.4], # MATLAB 4.5, 8.49 -> pixel (5, 8) + [2.0, 9.2, 1.0, 0.4], + [9.0, 3.6, 7.2, 0.4], # same pixel as the first: dropped + [1.0, -0.5, 19.5, 0.4], # MATLAB 0.5, 20.5 -> (1, 21): clamped + [4.0, 2.5 - 1e-12, 0.0, 0.4], + ]) + rows, cols, values = sources_from_seeds(seeds, (12, 20)) + np.testing.assert_array_equal(rows, [4, 9, 0, 2]) + np.testing.assert_array_equal(cols, [7, 1, 19, 0]) + np.testing.assert_array_equal(values, [5.0, 2.0, 1.0, 4.0]) + empty = sources_from_seeds(np.zeros((0, 4)), (12, 20)) + assert all(x.size == 0 for x in empty) + + +def test_select_source_pixels() -> None: + """A source's pixels are MATLAB's disk within the image and the valid pixels. + + They are in column-major order; sources that lose their own pixel or + nearly all pixels are pruned. + """ + valid = np.ones((30, 40), bool) + valid[:, 25:] = False + valid[12, 10] = False + rows = np.array([12, 2, 12, 12, 20]) + cols = np.array([8, 3, 29, 10, 30]) + sel = select_source_pixels(rows, cols, valid, sel_radius=6) + np.testing.assert_array_equal(sel.keep, [True, True, False, False, False]) + # an interior source has the whole disk but the invalid pixel + disk = np.zeros((30, 40), bool) + disk[7:18, 3:14] = disk_strel(6) + disk[12, 10] = False + cc, rr = np.nonzero(disk.T) + np.testing.assert_array_equal(sel.pixels[0], rr + cc * 30) + assert (np.diff(sel.pixels[0]) > 0).all() + # near the corner the disk is clipped by the image + assert sel.pixels[1].size < 109 and sel.pixels[1].min() == 0 + # a source on an invalid pixel is pruned although pixels remain: the + # third keeps the disk's first column (7 pixels), the fourth nearly all + assert sel.pixels[2].size == 7 and sel.pixels[3].size == 108 + assert sel.pixels[4].size == 0 + # a source needs more than 5 pixels + island = np.zeros((20, 20), bool) + island[5:7, 5:7] = True # 4 pixels + few = select_source_pixels(np.array([5]), np.array([5]), island, 6) + assert few.pixels[0].size == 4 and not few.keep[0] + island[5:7, 7] = True # 6 pixels + more = select_source_pixels(np.array([5]), np.array([5]), island, 6) + assert more.pixels[0].size == 6 and more.keep[0] + + +def test_seed_sources() -> None: + """The default method seeds blobs; the soma mask excludes them. + + Unknown and unported methods are refused; an image without usable pixels + gives no seeds. + """ + rng = np.random.default_rng(0) + im = rng.normal(0, 0.3, (40, 50)) + rr, cc = np.mgrid[:40, :50] + for r0, c0 in [(10, 12), (28, 35)]: + im += 20 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) + seeds = seed_sources(im, 8.0) + assert seeds.shape == (2, 4) + np.testing.assert_allclose(seeds[np.argsort(seeds[:, 1]), 1:3], [(10, 12), (28, 35)], atol=0.3) + soma = np.zeros(im.shape, bool) + soma[20:, 25:] = True + masked = seed_sources(im, 8.0, soma) + assert masked.shape == (1, 4) and abs(masked[0, 1] - 10) < 0.3 + # an all-false mask is no mask + np.testing.assert_array_equal(seed_sources(im, 8.0, np.zeros(im.shape, bool)), seeds) + assert seed_sources(np.full((5, 5), np.nan), 3.0).shape == (0, 4) + assert seed_sources(im, 8.0, np.ones(im.shape, bool)).shape == (0, 4) + with pytest.raises(NotImplementedError, match="WMF"): + seed_sources(im, 8.0, method="wmf") + with pytest.raises(ValueError, match="method"): + seed_sources(im, 8.0, method="other") diff --git a/tests/raster/test_raster_silo_alignment.py b/tests/raster/test_raster_silo_alignment.py index c5ee3b8a..477e7cbe 100644 --- a/tests/raster/test_raster_silo_alignment.py +++ b/tests/raster/test_raster_silo_alignment.py @@ -1,270 +1,276 @@ -"""The affine and patchwise across-trial alignments in giant silo's stages. - -Half images in the localization files, staged and streamed runs, the plan's -maps in the summaries, ROIs and per-trial peaks. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import ( - TrialWarp, - mask_to_consensus, - warp_trial_image, -) -from giant_python.extraction.raster.annotations import ( - PathAnnotations, - UserRoi, - rois_to_consensus, -) -from giant_python.extraction.raster.plan import ( - PlanParams, - plan_path, - read_plan, - write_plan, -) -from giant_python.extraction.raster.stage_files import ( - read_localization, - write_localization, -) -from giant_python.extraction.raster.summary import _peaks_to_consensus -from giant_python.pipeline import silo, silo_collect, silo_solve -from giant_python.pipeline.silo_session import SiloSession - -from .test_raster_plan import _synthetic_trials -from .test_raster_silo_stages import ( # noqa: F401 - EX, - N_PATHS, - N_TRIALS, - PARAMS, - _all_results, - _equal, - _summary, - fake, - make_session, -) - -PATCHWISE = replace(PARAMS, inter_trial_alignment="patchwise", align_patch_px=200) - - -@pytest.fixture -def halves(fake: None) -> None: # noqa: F811 - """Provide the fake session's localization (half images when asked).""" - - -def test_patchwise_streamed_and_staged_runs_agree(tmp_path: Path, halves: None) -> None: - """Patchwise alignment: the streaming driver and the stages agree. - - Under patchwise alignment the streaming driver and the stages give the - same results and summaries; the localization files hold the half images, - the plans a patchwise field, the summary its displacements. - """ - table = make_session(tmp_path / "streamed") - silo.run_silo(table, PATCHWISE, EX) - s1 = SiloSession.open(table) - rec = read_localization(s1.localize_file(0, 0)) - assert rec.half_ims is not None and rec.attrs["half_ims"] == 1 - plan = read_plan(s1.plan_file(0)) - assert plan.warp.is_patchwise and plan.warp.patch is not None - with h5py.File(s1.out_dir / "experiment_summary.h5", "r") as f: - disp = f["Path1/frame_info/trial_alignment_displacement"][()] - assert np.isfinite(disp).any() - streamed = _all_results(s1) - s2 = SiloSession.open(make_session(tmp_path / "staged")) - silo.localize(s2, PATCHWISE, EX) - silo.plan(s2, PATCHWISE, EX) - silo.prepare(s2, PATCHWISE, EX) - for job in silo_solve.dispatch(s2, PATCHWISE, 2, EX): - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(s2, PATCHWISE, EX) - staged = _all_results(s2) - assert staged.keys() == streamed.keys() - for key in staged: - for name, value in staged[key].items(): - np.testing.assert_array_equal(value, streamed[key][name]) - _equal( - _summary(s2.out_dir / "experiment_summary.h5"), - _summary(s1.out_dir / "experiment_summary.h5"), - ) - - -def test_localize_redoes_files_without_halves(tmp_path: Path, halves: None) -> None: - """Files localized for a rigid plan lack the half images. - - A patchwise plan refuses them and the patchwise localize stage redoes - them. Rigid and affine runs accept files with and without half images and - redo neither, so existing localizations stay usable. - """ - s = SiloSession.open(make_session(tmp_path)) - rigid = replace(PATCHWISE, inter_trial_alignment="rigid") - affine = replace(PATCHWISE, inter_trial_alignment="affine") - assert len(silo.localize(s, rigid, EX)) == N_PATHS * N_TRIALS - assert read_localization(s.localize_file(0, 0)).half_ims is None - for p in (rigid, affine): - assert silo.localize_jobs(s, p) == [] - assert silo.plan_one(s, p, 0, overwrite=True).exists() - with pytest.raises(ValueError, match="half images"): - silo.plan_one(s, PATCHWISE, 0) - jobs = silo.localize_jobs(s, PATCHWISE) - assert len(jobs) == N_PATHS * N_TRIALS - silo.localize(s, PATCHWISE, EX) - assert silo.localize_jobs(s, PATCHWISE) == [] - for p in (rigid, affine): - assert silo.localize_jobs(s, p) == [] - assert silo.plan_one(s, p, 0, overwrite=True).exists() - assert silo.plan_one(s, PATCHWISE, 0).exists() - # only a patchwise plan reads the half images - assert all(r.half_ims is None for r in silo._plan_inputs(s, 0)) - assert all(r.half_ims is not None for r in silo._plan_inputs(s, 0, True)) - - -def test_later_stages_refuse_another_alignment(tmp_path: Path, halves: None) -> None: - """Prepare and collect use the plan's maps and record the settings. - - Another alignment, or another patch size for patchwise, is refused. - """ - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PATCHWISE, EX) - silo.plan(s, PATCHWISE, EX) - rigid = replace(PATCHWISE, inter_trial_alignment="rigid") - other = replace(PATCHWISE, align_patch_px=300) - # a fractional plan setting is not equal to its integer part - pf = s.plan_file(0) - plan = read_plan(pf) - plan.params = replace(plan.params, align_patch_px=200.5) - with pytest.raises(ValueError, match="align_patch_px"): - silo.check_plan_alignment("plan", plan, PATCHWISE) - silo.check_plan_alignment("plan", read_plan(pf), PATCHWISE) - for p in (rigid, other): - with pytest.raises(ValueError, match="align"): - silo.prepare(s, p, EX) - with pytest.raises(ValueError, match="align"): - silo_collect.collect(s, p, EX) - - -@pytest.mark.parametrize("mode", ["affine", "patchwise"]) -def test_plan_with_a_refined_alignment(tmp_path: Path, mode: str) -> None: - """The valid trials get the refined maps (the same valid trials as rigid). - - The aligned images are warped through them; the shifts are the - displacements at the canvas centre; the plan file keeps the maps. - """ - trials = _synthetic_trials() - for t in trials: - t.half_ims = np.stack([t.mean_im, t.mean_im * 1.01]) - rigid = plan_path(trials, params=PlanParams(peak_th=12.0, inter_trial_alignment="rigid")) - details = {} - plan = plan_path( - trials, - params=PlanParams(peak_th=12.0, inter_trial_alignment=mode, align_patch_px=600), - details=details, - ) - np.testing.assert_array_equal(plan.valid_trials, rigid.valid_trials) - assert np.isfinite(details["alignment_info"].corr[plan.valid_trials]).all() - assert plan.warp.is_patchwise == (mode == "patchwise") - h, w = plan.shape - x0 = np.array([(h - 1) / 2, (w - 1) / 2]) - for t in plan.aligned_trials: - r, c = plan.warp.coords(t, x0[:1], x0[1:]) - np.testing.assert_allclose(plan.shifts[t], [r[0] - x0[0], c[0] - x0[1]], atol=1e-12) - np.testing.assert_array_equal( - plan.mean_aligned[t], - warp_trial_image(plan.mean_ims[t], plan.warp, t), - ) - # the refinement moves the maps by well under a pixel here (pure - # shifts), and the sources stay where they were - assert np.abs(plan.shifts - rigid.shifts).max() < 0.2 - np.testing.assert_array_equal(plan.source_rows, rigid.source_rows) - write_plan(tmp_path / "plan.h5", plan) - back = read_plan(tmp_path / "plan.h5") - np.testing.assert_array_equal(back.warp.affine, plan.warp.affine) - np.testing.assert_array_equal(back.warp.disp, plan.warp.disp) - assert back.warp.sigma == plan.warp.sigma or mode == "affine" - if mode == "patchwise": - np.testing.assert_array_equal(back.warp.patch, plan.warp.patch) - assert back.params.align_patch_px == 600 - - -def test_localization_file_keeps_half_images(tmp_path: Path) -> None: - """The half images round-trip as float32; files without them read as None.""" - rng = np.random.default_rng(0) - mean = rng.random((5, 6, 2)) - halves = rng.random((2, 5, 6, 2)) - f = write_localization( - tmp_path / "a.h5", - mean, - mean[..., 0], - mean[..., 0], - [0, 1], - None, - {"settings_hash": "x"}, - halves, - ) - rec = read_localization(f) - np.testing.assert_array_equal(rec.half_ims, halves.astype(np.float32)) - assert rec.trial_images().half_ims is rec.half_ims - assert read_localization(f, half_ims=False).half_ims is None - g = write_localization(tmp_path / "b.h5", mean, mean[..., 0], mean[..., 0], [0, 1], None, {}) - assert read_localization(g).half_ims is None - assert read_localization(g).attrs["half_ims"] == 0 - - -def _bent_warp(n_trials: int = 2, shape: tuple[int, int] = (40, 50)) -> TrialWarp: - """Build an affine map with a bent field on top, per trial.""" - rng = np.random.default_rng(1) - nodes = rng.uniform([5, 5], [shape[0] - 5, shape[1] - 5], (6, 2)) - affine = np.zeros((n_trials, 2, 3)) - disp = np.zeros((n_trials, 6, 2)) - for t in range(n_trials): - a = np.array([[1.003, 0.002, 0.6 + t], [-0.002, 0.998, -1.1]]) - affine[t] = a - disp[t] = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T - disp[t] += 0.3 * rng.standard_normal((6, 2)) - return TrialWarp(affine, nodes, 8.0, disp) - - -def test_rois_through_a_full_map() -> None: - """ROIs go through a full map. - - Masks take the trial mask's value at each consensus pixel's mapped - position; geometry goes through the inverse map (one-based [x, y]). - """ - warp = _bent_warp() - mask = np.zeros((40, 50), bool) - mask[18:23, 20:26] = True - center = np.array([23.0, 21.0]) # x (col), y (row), one-based - ann = PathAnnotations( - path=1, - dr="", - fn="E1T2DMD1", - rois=[UserRoi("SOMA a", "circle", mask, center=center)], - ) - rois = rois_to_consensus(ann, ["E1T1DMD1.tif", "E1T2DMD1.tif"], warp, (40, 50)) - np.testing.assert_array_equal(rois[0].mask, mask_to_consensus(mask, warp, 1, (40, 50))) - r, c = warp.coords(1, rois[0].center[1:] - 1, rois[0].center[:1] - 1) - np.testing.assert_allclose([c[0] + 1, r[0] + 1], center, atol=1e-6) - - -def test_per_trial_peaks_into_the_consensus_frame() -> None: - """Through the inverse of a non-shift map, minus the shift of a rigid one.""" - - class Plan: - """What _peaks_to_consensus reads of a plan.""" - - def __init__(self, warp: TrialWarp, shifts: np.ndarray) -> None: - """Store a warp and its shifts.""" - self.warp, self.shifts = warp, shifts - - peaks = np.array([[1.0, 10.0, 12.0, 0.5], [2.0, 30.5, 40.25, 0.5]]) - warp = _bent_warp() - out = _peaks_to_consensus(Plan(warp, np.zeros((2, 2))), 1, peaks) - r, c = warp.coords(1, out[:, 0], out[:, 1]) - np.testing.assert_allclose(np.column_stack([r, c]), peaks[:, 1:3], atol=1e-6) - rigid = TrialWarp.from_shifts([[0.5, -1.0], [1.0, 2.0]]) - shifts = np.array([[0.5, -1], [1, 2]]) - out = _peaks_to_consensus(Plan(rigid, shifts), 1, peaks) - np.testing.assert_array_equal(out, peaks[:, 1:3] - [1.0, 2.0]) +"""The affine and patchwise across-trial alignments in giant silo's stages. + +Half images in the localization files, staged and streamed runs, the plan's +maps in the summaries, ROIs and per-trial peaks. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import ( + TrialWarp, + mask_to_consensus, + warp_trial_image, +) +from giant_python.extraction.raster.annotations import ( + PathAnnotations, + UserRoi, + rois_to_consensus, +) +from giant_python.extraction.raster.plan import ( + PlanParams, + plan_path, + read_plan, + write_plan, +) +from giant_python.extraction.raster.stage_files import ( + read_localization, + write_localization, +) +from giant_python.extraction.raster.summary import _peaks_to_consensus +from giant_python.pipeline import silo, silo_collect, silo_solve +from giant_python.pipeline.silo_session import SiloSession + +from .test_raster_plan import _synthetic_trials +from .test_raster_silo_stages import ( # noqa: F401 + EX, + N_PATHS, + N_TRIALS, + PARAMS, + _all_results, + _equal, + _summary, + fake, + make_session, +) + +PATCHWISE = replace(PARAMS, inter_trial_alignment="patchwise", align_patch_px=200) + + +@pytest.fixture +def halves(fake: None) -> None: # noqa: F811 + """Provide the fake session's localization (half images when asked).""" + + +def test_patchwise_streamed_and_staged_runs_agree(tmp_path: Path, halves: None) -> None: + """Patchwise alignment: the streaming driver and the stages agree. + + Under patchwise alignment the streaming driver and the stages give the + same results and summaries; the localization files hold the half images, + the plans a patchwise field, the summary its displacements. + """ + table = make_session(tmp_path / "streamed") + silo.run_silo(table, PATCHWISE, EX) + s1 = SiloSession.open(table) + rec = read_localization(s1.localize_file(0, 0)) + assert rec.half_ims is not None and rec.attrs["half_ims"] == 1 + plan = read_plan(s1.plan_file(0)) + assert plan.warp.is_patchwise and plan.warp.patch is not None + with h5py.File(s1.out_dir / "experiment_summary.h5", "r") as f: + disp = f["Path1/frame_info/trial_alignment_displacement"][()] + assert np.isfinite(disp).any() + streamed = _all_results(s1) + s2 = SiloSession.open(make_session(tmp_path / "staged")) + silo.localize(s2, PATCHWISE, EX) + silo.plan(s2, PATCHWISE, EX) + silo.prepare(s2, PATCHWISE, EX) + for job in silo_solve.dispatch(s2, PATCHWISE, 2, EX): + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(s2, PATCHWISE, EX) + staged = _all_results(s2) + assert staged.keys() == streamed.keys() + for key in staged: + for name, value in staged[key].items(): + np.testing.assert_array_equal(value, streamed[key][name]) + _equal( + _summary(s2.out_dir / "experiment_summary.h5"), + _summary(s1.out_dir / "experiment_summary.h5"), + ) + + +def test_localize_redoes_files_without_halves(tmp_path: Path, halves: None) -> None: + """Files localized for a rigid plan lack the half images. + + A patchwise plan refuses them and the patchwise localize stage redoes + them. Rigid and affine runs accept files with and without half images and + redo neither, so existing localizations stay usable. + """ + s = SiloSession.open(make_session(tmp_path)) + rigid = replace(PATCHWISE, inter_trial_alignment="rigid") + affine = replace(PATCHWISE, inter_trial_alignment="affine") + assert len(silo.localize(s, rigid, EX)) == N_PATHS * N_TRIALS + assert read_localization(s.localize_file(0, 0)).half_ims is None + for p in (rigid, affine): + assert silo.localize_jobs(s, p) == [] + assert silo.plan_one(s, p, 0, overwrite=True).exists() + with pytest.raises(ValueError, match="half images"): + silo.plan_one(s, PATCHWISE, 0) + jobs = silo.localize_jobs(s, PATCHWISE) + assert len(jobs) == N_PATHS * N_TRIALS + silo.localize(s, PATCHWISE, EX) + assert silo.localize_jobs(s, PATCHWISE) == [] + for p in (rigid, affine): + assert silo.localize_jobs(s, p) == [] + assert silo.plan_one(s, p, 0, overwrite=True).exists() + assert silo.plan_one(s, PATCHWISE, 0).exists() + # only a patchwise plan reads the half images + assert all(r.half_ims is None for r in silo._plan_inputs(s, 0)) + assert all(r.half_ims is not None for r in silo._plan_inputs(s, 0, True)) + + +def test_later_stages_refuse_another_alignment(tmp_path: Path, halves: None) -> None: + """Prepare and collect use the plan's maps and record the settings. + + Another alignment, or another patch size for patchwise, is refused. + """ + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PATCHWISE, EX) + silo.plan(s, PATCHWISE, EX) + rigid = replace(PATCHWISE, inter_trial_alignment="rigid") + other = replace(PATCHWISE, align_patch_px=300) + # a fractional plan setting is not equal to its integer part + pf = s.plan_file(0) + plan = read_plan(pf) + plan.params = replace(plan.params, align_patch_px=200.5) + with pytest.raises(ValueError, match="align_patch_px"): + silo.check_plan_alignment("plan", plan, PATCHWISE) + silo.check_plan_alignment("plan", read_plan(pf), PATCHWISE) + for p in (rigid, other): + with pytest.raises(ValueError, match="align"): + silo.prepare(s, p, EX) + with pytest.raises(ValueError, match="align"): + silo_collect.collect(s, p, EX) + + +@pytest.mark.parametrize("mode", ["affine", "patchwise"]) +def test_plan_with_a_refined_alignment(tmp_path: Path, mode: str) -> None: + """The valid trials get the refined maps (the same valid trials as rigid). + + The aligned images are warped through them; the shifts are the + displacements at the canvas centre; the plan file keeps the maps. + """ + trials = _synthetic_trials() + for t in trials: + t.half_ims = np.stack([t.mean_im, t.mean_im * 1.01]) + rigid = plan_path(trials, params=PlanParams(peak_th=12.0, inter_trial_alignment="rigid")) + details = {} + plan = plan_path( + trials, + params=PlanParams(peak_th=12.0, inter_trial_alignment=mode, align_patch_px=600), + details=details, + ) + np.testing.assert_array_equal(plan.valid_trials, rigid.valid_trials) + assert np.isfinite(details["alignment_info"].corr[plan.valid_trials]).all() + assert plan.warp.is_patchwise == (mode == "patchwise") + h, w = plan.shape + x0 = np.array([(h - 1) / 2, (w - 1) / 2]) + for t in plan.aligned_trials: + r, c = plan.warp.coords(t, x0[:1], x0[1:]) + np.testing.assert_allclose(plan.shifts[t], [r[0] - x0[0], c[0] - x0[1]], atol=1e-12) + np.testing.assert_array_equal( + plan.mean_aligned[t], + warp_trial_image(plan.mean_ims[t], plan.warp, t), + ) + # the refinement moves the maps by well under a pixel here (pure + # shifts), and the sources stay where they were + assert np.abs(plan.shifts - rigid.shifts).max() < 0.2 + np.testing.assert_array_equal(plan.source_rows, rigid.source_rows) + write_plan(tmp_path / "plan.h5", plan) + back = read_plan(tmp_path / "plan.h5") + np.testing.assert_array_equal(back.warp.affine, plan.warp.affine) + np.testing.assert_array_equal(back.warp.disp, plan.warp.disp) + assert back.warp.sigma == plan.warp.sigma or mode == "affine" + if mode == "patchwise": + np.testing.assert_array_equal(back.warp.patch, plan.warp.patch) + assert back.params.align_patch_px == 600 + + +def test_localization_file_keeps_half_images(tmp_path: Path) -> None: + """The half images round-trip as float32; files without them read as None.""" + rng = np.random.default_rng(0) + mean = rng.random((5, 6, 2)) + halves = rng.random((2, 5, 6, 2)) + f = write_localization( + tmp_path / "a.h5", + mean, + mean[..., 0], + mean[..., 0], + [0, 1], + None, + {"settings_hash": "x"}, + halves, + ) + rec = read_localization(f) + np.testing.assert_array_equal(rec.half_ims, halves.astype(np.float32)) + assert rec.trial_images().half_ims is rec.half_ims + assert read_localization(f, half_ims=False).half_ims is None + g = write_localization(tmp_path / "b.h5", mean, mean[..., 0], mean[..., 0], [0, 1], None, {}) + assert read_localization(g).half_ims is None + assert read_localization(g).attrs["half_ims"] == 0 + + +def _bent_warp(n_trials: int = 2, shape: tuple[int, int] = (40, 50)) -> TrialWarp: + """Build an affine map with a bent field on top, per trial. + + Returns + ------- + TrialWarp + The per-trial affine maps, with the displacements of six random nodes. + """ + rng = np.random.default_rng(1) + nodes = rng.uniform([5, 5], [shape[0] - 5, shape[1] - 5], (6, 2)) + affine = np.zeros((n_trials, 2, 3)) + disp = np.zeros((n_trials, 6, 2)) + for t in range(n_trials): + a = np.array([[1.003, 0.002, 0.6 + t], [-0.002, 0.998, -1.1]]) + affine[t] = a + disp[t] = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T + disp[t] += 0.3 * rng.standard_normal((6, 2)) + return TrialWarp(affine, nodes, 8.0, disp) + + +def test_rois_through_a_full_map() -> None: + """ROIs go through a full map. + + Masks take the trial mask's value at each consensus pixel's mapped + position; geometry goes through the inverse map (one-based [x, y]). + """ + warp = _bent_warp() + mask = np.zeros((40, 50), bool) + mask[18:23, 20:26] = True + center = np.array([23.0, 21.0]) # x (col), y (row), one-based + ann = PathAnnotations( + path=1, + dr="", + fn="E1T2DMD1", + rois=[UserRoi("SOMA a", "circle", mask, center=center)], + ) + rois = rois_to_consensus(ann, ["E1T1DMD1.tif", "E1T2DMD1.tif"], warp, (40, 50)) + np.testing.assert_array_equal(rois[0].mask, mask_to_consensus(mask, warp, 1, (40, 50))) + r, c = warp.coords(1, rois[0].center[1:] - 1, rois[0].center[:1] - 1) + np.testing.assert_allclose([c[0] + 1, r[0] + 1], center, atol=1e-6) + + +def test_per_trial_peaks_into_the_consensus_frame() -> None: + """Through the inverse of a non-shift map, minus the shift of a rigid one.""" + + class Plan: + """What _peaks_to_consensus reads of a plan.""" + + def __init__(self, warp: TrialWarp, shifts: np.ndarray) -> None: + """Store a warp and its shifts.""" + self.warp, self.shifts = warp, shifts + + peaks = np.array([[1.0, 10.0, 12.0, 0.5], [2.0, 30.5, 40.25, 0.5]]) + warp = _bent_warp() + out = _peaks_to_consensus(Plan(warp, np.zeros((2, 2))), 1, peaks) + r, c = warp.coords(1, out[:, 0], out[:, 1]) + np.testing.assert_allclose(np.column_stack([r, c]), peaks[:, 1:3], atol=1e-6) + rigid = TrialWarp.from_shifts([[0.5, -1.0], [1.0, 2.0]]) + shifts = np.array([[0.5, -1], [1, 2]]) + out = _peaks_to_consensus(Plan(rigid, shifts), 1, peaks) + np.testing.assert_array_equal(out, peaks[:, 1:3] - [1.0, 2.0]) diff --git a/tests/raster/test_raster_silo_load_ahead.py b/tests/raster/test_raster_silo_load_ahead.py index c708ff77..5203f0e9 100644 --- a/tests/raster/test_raster_silo_load_ahead.py +++ b/tests/raster/test_raster_silo_load_ahead.py @@ -1,257 +1,320 @@ -"""Loading trials ahead of the solver in the streamed run. - -Options ``SiloExecution.load_workers`` and ``load_memory_gb``. -""" - -import threading -import time -from collections.abc import Iterable, Iterator -from dataclasses import replace -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.models.params import SiloExecution, SiloParams -from giant_python.pipeline import silo -from giant_python.pipeline.silo_session import SiloSession - -from .test_raster_silo_stages import ( # noqa: F401 - EX, - PARAMS, - _all_results, - _equal, - _summary, - fake, - make_session, -) - - -def _units(n: int, lines: float = 100.0) -> list[silo._Unit]: - """``n`` units of a path, each of ``lines`` lines.""" - return [silo._Unit(0, t, None, "", "", Path(f"r{t}.h5"), Path(""), lines) for t in range(n)] - - -def test_loaded_keeps_order_and_limits(monkeypatch: pytest.MonkeyPatch) -> None: - """Units come back in order whatever finishes first. - - At most ``load_workers`` load at once; with a memory limit only one loads - until a load has measured the bytes per line, then as many as fit. - """ - active, most, started = [0], [0], [] - lock = threading.Lock() - - def load(u: silo._Unit) -> dict: - """Simulate a load that takes longer for earlier units.""" - with lock: - active[0] += 1 - most[0] = max(most[0], active[0]) - started.append(u.t) - time.sleep(0.3 + 0.05 * (5 - u.t)) # earlier units finish last - with lock: - active[0] -= 1 - return {"t": u.t, "nbytes": 1000} - - units = _units(6) - ex = SiloExecution(load_workers=3) - got = [(u.t, item["t"]) for u, item in silo._loaded(units, load, ex)] - assert got == [(t, t) for t in range(6)] - assert most[0] == 3 - # 10 bytes per line: 1000 bytes per unit; a 2500-byte limit holds two - active[0], most[0] = 0, 0 - ex = SiloExecution(load_workers=4, load_memory_gb=2.5e-6) - got = [u.t for u, _ in silo._loaded(units, load, ex)] - assert got == list(range(6)) and most[0] == 2 - # one worker: each unit is loaded when it is asked for - started.clear() - gen = silo._loaded(units, load, SiloExecution(load_workers=1)) - next(gen) - assert started == [0] - - -def test_loaded_waits_for_a_measured_load_and_takes_units_lazily() -> None: - """A load without ``nbytes`` (a trial too short to extract) gives no estimate. - - With a memory limit the loads stay one at a time until a load reports - its bytes. Units are taken from the iterable only when they are about to - be loaded. - """ - active, most, taken = [0], [0], [] - lock = threading.Lock() - - def load(u: silo._Unit) -> dict: - """Load a unit; the first unit is short (no subproblems, no bytes).""" - with lock: - active[0] += 1 - most[0] = max(most[0], active[0]) - time.sleep(0.2) - with lock: - active[0] -= 1 - if u.t == 0: - return {} - return {"nbytes": 1000} - - def lazy(units: Iterable[silo._Unit]) -> Iterator[silo._Unit]: - """Yield the units, noting when each is taken.""" - for u in units: - taken.append(u.t) - yield u - - # 10 bytes per line from the second load on; the limit holds two - ex = SiloExecution(load_workers=4, load_memory_gb=2.5e-6) - gen = silo._loaded(lazy(_units(6)), load, ex) - first = next(gen) - assert first[0].t == 0 and most[0] == 1 - assert taken == [0, 1] # the second is taken, waiting for an estimate - rest = [u.t for u, _ in gen] - assert rest == [1, 2, 3, 4, 5] and most[0] == 2 - # one worker: a unit is taken when it is asked for - taken.clear() - gen = silo._loaded(lazy(_units(3)), load, SiloExecution(load_workers=1)) - next(gen) - assert taken == [0] - - -def test_loaded_hands_on_earlier_units_before_a_failed_check() -> None: - """With several loaders, an error raised while taking a unit (its check) is deferred. - - It reaches the caller after the units taken before it. - """ - - def units() -> Iterator[silo._Unit]: - """Two units, then a failing check.""" - yield from _units(2) - raise FileNotFoundError("no baseline") - - gen = silo._loaded(units(), lambda u: {"t": u.t}, SiloExecution(load_workers=3)) - got = [] - with pytest.raises(FileNotFoundError, match="no baseline"): - for u, item in gen: - got.append(item["t"]) - assert got == [0, 1] - - -@pytest.mark.parametrize("load_workers", [1, 3]) -def test_streamed_run_checks_later_trials_when_it_reaches_them( - tmp_path: Path, - fake: None, # noqa: F811 - monkeypatch: pytest.MonkeyPatch, - load_workers: int, -) -> None: - """A later trial whose check fails (here its baseline) does not stop the earlier trials. - - The earlier trials are extracted and written, with one loader or several - (the trial waiting for its results is written before the error is - raised). - """ - s = make_session(tmp_path / "s") - real = silo._extraction_baseline - calls = [] - - def failing( - session: SiloSession, - params: SiloParams, - d: int, - t: int, - baseline_dir: str | Path | None, - ) -> Path | None: - """Fails for the last trial of the first path.""" - calls.append((d, t)) - if (d, t) == (0, session.n_trials - 1): - raise FileNotFoundError("no baseline for this trial") - return real(session, params, d, t, baseline_dir) - - monkeypatch.setattr(silo, "_extraction_baseline", failing) - with pytest.raises(FileNotFoundError, match="no baseline"): - silo.run_silo(s, PARAMS, replace(EX, load_workers=load_workers)) - session = SiloSession.open(s) - written = [t for t in range(session.n_trials) if session.results_file(0, t).exists()] - assert written == list(range(session.n_trials - 1)) - - -def test_loaded_passes_on_errors() -> None: - """A load's error reaches the caller at its unit. - - Later loads are not waited for beyond the running ones. - """ - - def load(u: silo._Unit) -> dict: - """Fails on the second unit.""" - if u.t == 1: - raise RuntimeError("bad trial") - return {"nbytes": 10} - - gen = silo._loaded(_units(5), load, SiloExecution(load_workers=2)) - assert next(gen)[0].t == 0 - with pytest.raises(RuntimeError, match="bad trial"): - next(gen) - - -def test_options_are_checked() -> None: - """Worker counts are positive integers, the limit positive. - - The loader options come after the earlier fields, which keep their - positions. - """ - with pytest.raises(ValueError): - SiloExecution(load_workers=0) - with pytest.raises(ValueError): - SiloExecution(load_memory_gb=0.0) - names = list(SiloExecution.__dataclass_fields__) - assert names[-2:] == ["load_workers", "load_memory_gb"] - assert names[-4:-2] == ["overwrite", "verbose"] - ex = SiloExecution(6, 3, 4, "cpu", "float64", None, "cpu", True, True) - assert ex.overwrite and ex.verbose and ex.load_workers == 4 - - -@pytest.mark.parametrize("memory", [None, 1e-9]) -def test_streamed_run_loading_ahead_is_the_same( - tmp_path: Path, - fake: None, # noqa: F811 - memory: float | None, -) -> None: - """Loading three trials ahead gives the results files and summaries of loading one at a time.""" - one = make_session(tmp_path / "one") - r1 = silo.run_silo(one, PARAMS, replace(EX, load_workers=1)) - ahead = make_session(tmp_path / "ahead") - ex = replace(EX, load_workers=3, load_memory_gb=memory) - r2 = silo.run_silo(ahead, PARAMS, ex) - - def loaded(report: dict) -> list[tuple]: - """Return the units the run loaded.""" - return [tuple(e["unit"]) for e in report["trials"] if "load" in e] - - assert loaded(r1) == loaded(r2) and loaded(r1) - # each loaded trial reports the loader's phases (none for the fake one) - assert all(e["load_phases"] == {} for e in r2["trials"] if "load" in e) - a, b = SiloSession.open(one), SiloSession.open(ahead) - ra, rb = _all_results(a), _all_results(b) - assert ra.keys() == rb.keys() and ra - for key in ra: - for name, value in ra[key].items(): - np.testing.assert_array_equal(value, rb[key][name]) - _equal( - _summary(a.out_dir / "experiment_summary.h5"), - _summary(b.out_dir / "experiment_summary.h5"), - ) - - -def test_held_bytes_count_what_a_loaded_trial_keeps() -> None: - """The memory of a loaded trial waiting for the solver. - - That is its subproblems' data, variance multipliers and baselines, and - its traces. - """ - from types import SimpleNamespace - - y = np.zeros((2, 10, 50), np.float32) - sub = SimpleNamespace(y=y, finv=np.zeros((10, 50), np.float32), baseline=None) - with_base = SimpleNamespace(y=y, finv=sub.finv, baseline=np.zeros((10, 50), np.float32)) - rec = SimpleNamespace( - global_f=np.zeros((2, 50)), - roi_f=np.zeros((1, 2, 50)), - roi_fsvd=np.zeros((1, 2, 50)), - ) - traces = 3 * 100 * 8 - assert silo._held_bytes([sub], rec) == 4000 + 2000 + traces - assert silo._held_bytes([sub, with_base], rec) == 2 * 6000 + 2000 + traces +"""Loading trials ahead of the solver in the streamed run. + +Options SiloExecution.load_workers and load_memory_gb. +""" + +import threading +import time +from collections.abc import Iterable, Iterator +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.models.params import SiloExecution, SiloParams +from giant_python.pipeline import silo +from giant_python.pipeline.silo_session import SiloSession + +from .test_raster_silo_stages import ( # noqa: F401 + EX, + PARAMS, + _all_results, + _equal, + _summary, + fake, + make_session, +) + + +def _units(n: int, lines: float = 100.0) -> list[silo._Unit]: + """``n`` units of a path, each of lines lines. + + Returns + ------- + list[silo._Unit] + The n units, for trials 0 to n - 1 of the first path. + """ + return [silo._Unit(0, t, None, "", "", Path(f"r{t}.h5"), Path(""), lines) for t in range(n)] + + +def test_loaded_keeps_order_and_limits(monkeypatch: pytest.MonkeyPatch) -> None: + """Units come back in order whatever finishes first. + + At most load_workers load at once; with a memory limit only one loads + until a load has measured the bytes per line, then as many as fit. + """ + active, most, started = [0], [0], [] + lock = threading.Lock() + + def load(u: silo._Unit) -> dict: + """Simulate a load that takes longer for earlier units. + + Returns + ------- + dict + The unit's trial t and nbytes (1000). + """ + with lock: + active[0] += 1 + most[0] = max(most[0], active[0]) + started.append(u.t) + time.sleep(0.3 + 0.05 * (5 - u.t)) # earlier units finish last + with lock: + active[0] -= 1 + return {"t": u.t, "nbytes": 1000} + + units = _units(6) + ex = SiloExecution(load_workers=3) + got = [(u.t, item["t"]) for u, item in silo._loaded(units, load, ex)] + assert got == [(t, t) for t in range(6)] + assert most[0] == 3 + # 10 bytes per line: 1000 bytes per unit; a 2500-byte limit holds two + active[0], most[0] = 0, 0 + ex = SiloExecution(load_workers=4, load_memory_gb=2.5e-6) + got = [u.t for u, _ in silo._loaded(units, load, ex)] + assert got == list(range(6)) and most[0] == 2 + # one worker: each unit is loaded when it is asked for + started.clear() + gen = silo._loaded(units, load, SiloExecution(load_workers=1)) + next(gen) + assert started == [0] + + +def test_loaded_waits_for_a_measured_load_and_takes_units_lazily() -> None: + """A load without nbytes (a trial too short to extract) gives no estimate. + + With a memory limit the loads stay one at a time until a load reports + its bytes. Units are taken from the iterable only when they are about to + be loaded. + """ + active, most, taken = [0], [0], [] + lock = threading.Lock() + + def load(u: silo._Unit) -> dict: + """Load a unit; the first unit is short (no subproblems, no bytes). + + Returns + ------- + dict + Empty for the first unit, else nbytes (1000). + """ + with lock: + active[0] += 1 + most[0] = max(most[0], active[0]) + time.sleep(0.2) + with lock: + active[0] -= 1 + if u.t == 0: + return {} + return {"nbytes": 1000} + + def lazy(units: Iterable[silo._Unit]) -> Iterator[silo._Unit]: + """Yield the units, noting when each is taken. + + Yields + ------ + silo._Unit + Each of units, in order. + """ + for u in units: + taken.append(u.t) + yield u + + # 10 bytes per line from the second load on; the limit holds two + ex = SiloExecution(load_workers=4, load_memory_gb=2.5e-6) + gen = silo._loaded(lazy(_units(6)), load, ex) + first = next(gen) + assert first[0].t == 0 and most[0] == 1 + assert taken == [0, 1] # the second is taken, waiting for an estimate + rest = [u.t for u, _ in gen] + assert rest == [1, 2, 3, 4, 5] and most[0] == 2 + # one worker: a unit is taken when it is asked for + taken.clear() + gen = silo._loaded(lazy(_units(3)), load, SiloExecution(load_workers=1)) + next(gen) + assert taken == [0] + + +def test_loaded_hands_on_earlier_units_before_a_failed_check() -> None: + """With several loaders, an error raised while taking a unit (its check) is deferred. + + It reaches the caller after the units taken before it. + """ + + def units() -> Iterator[silo._Unit]: + """Two units, then a failing check. + + Yields + ------ + silo._Unit + Each of the two units; the failing check is raised after them. + + Raises + ------ + FileNotFoundError + After the two units, as the failing check. + """ + yield from _units(2) + raise FileNotFoundError("no baseline") + + gen = silo._loaded(units(), lambda u: {"t": u.t}, SiloExecution(load_workers=3)) + got = [] + with pytest.raises(FileNotFoundError, match="no baseline"): + for u, item in gen: + got.append(item["t"]) + assert got == [0, 1] + + +@pytest.mark.parametrize("load_workers", [1, 3]) +def test_streamed_run_checks_later_trials_when_it_reaches_them( + tmp_path: Path, + fake: None, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, + load_workers: int, +) -> None: + """A later trial whose check fails (here its baseline) does not stop the earlier trials. + + The earlier trials are extracted and written, with one loader or several + (the trial waiting for its results is written before the error is + raised). + """ + s = make_session(tmp_path / "s") + real = silo._extraction_baseline + calls = [] + + def failing( + session: SiloSession, + params: SiloParams, + d: int, + t: int, + baseline_dir: str | Path | None, + ) -> Path | None: + """Fails for the last trial of the first path. + + Returns + ------- + Path or None + What _extraction_baseline returns for the trial, for every other trial. + + Raises + ------ + FileNotFoundError + For the last trial of the first path. + """ + calls.append((d, t)) + if (d, t) == (0, session.n_trials - 1): + raise FileNotFoundError("no baseline for this trial") + return real(session, params, d, t, baseline_dir) + + monkeypatch.setattr(silo, "_extraction_baseline", failing) + with pytest.raises(FileNotFoundError, match="no baseline"): + silo.run_silo(s, PARAMS, replace(EX, load_workers=load_workers)) + session = SiloSession.open(s) + written = [t for t in range(session.n_trials) if session.results_file(0, t).exists()] + assert written == list(range(session.n_trials - 1)) + + +def test_loaded_passes_on_errors() -> None: + """A load's error reaches the caller at its unit. + + Later loads are not waited for beyond the running ones. + """ + + def load(u: silo._Unit) -> dict: + """Fails on the second unit. + + Returns + ------- + dict + nbytes (10), for every other unit. + + Raises + ------ + RuntimeError + On the second unit. + """ + if u.t == 1: + raise RuntimeError("bad trial") + return {"nbytes": 10} + + gen = silo._loaded(_units(5), load, SiloExecution(load_workers=2)) + assert next(gen)[0].t == 0 + with pytest.raises(RuntimeError, match="bad trial"): + next(gen) + + +def test_options_are_checked() -> None: + """Worker counts are positive integers, the limit positive. + + The loader options come after the earlier fields, which keep their + positions. + """ + with pytest.raises(ValueError): + SiloExecution(load_workers=0) + with pytest.raises(ValueError): + SiloExecution(load_memory_gb=0.0) + names = list(SiloExecution.__dataclass_fields__) + assert names[-2:] == ["load_workers", "load_memory_gb"] + assert names[-4:-2] == ["overwrite", "verbose"] + ex = SiloExecution(6, 3, 4, "cpu", "float64", None, "cpu", True, True) + assert ex.overwrite and ex.verbose and ex.load_workers == 4 + + +@pytest.mark.parametrize("memory", [None, 1e-9]) +def test_streamed_run_loading_ahead_is_the_same( + tmp_path: Path, + fake: None, # noqa: F811 + memory: float | None, +) -> None: + """Loading three trials ahead gives the results files and summaries of loading one at a time.""" + one = make_session(tmp_path / "one") + r1 = silo.run_silo(one, PARAMS, replace(EX, load_workers=1)) + ahead = make_session(tmp_path / "ahead") + ex = replace(EX, load_workers=3, load_memory_gb=memory) + r2 = silo.run_silo(ahead, PARAMS, ex) + + def loaded(report: dict) -> list[tuple]: + """Return the units the run loaded. + + Returns + ------- + list[tuple] + The unit of each trial entry of the report that has a load. + """ + return [tuple(e["unit"]) for e in report["trials"] if "load" in e] + + assert loaded(r1) == loaded(r2) and loaded(r1) + # each loaded trial reports the loader's phases (none for the fake one) + assert all(e["load_phases"] == {} for e in r2["trials"] if "load" in e) + a, b = SiloSession.open(one), SiloSession.open(ahead) + ra, rb = _all_results(a), _all_results(b) + assert ra.keys() == rb.keys() and ra + for key in ra: + for name, value in ra[key].items(): + np.testing.assert_array_equal(value, rb[key][name]) + _equal( + _summary(a.out_dir / "experiment_summary.h5"), + _summary(b.out_dir / "experiment_summary.h5"), + ) + + +def test_held_bytes_count_what_a_loaded_trial_keeps() -> None: + """The memory of a loaded trial waiting for the solver. + + That is its subproblems' data, variance multipliers and baselines, and + its traces. + """ + from types import SimpleNamespace + + y = np.zeros((2, 10, 50), np.float32) + sub = SimpleNamespace(y=y, finv=np.zeros((10, 50), np.float32), baseline=None) + with_base = SimpleNamespace(y=y, finv=sub.finv, baseline=np.zeros((10, 50), np.float32)) + rec = SimpleNamespace( + global_f=np.zeros((2, 50)), + roi_f=np.zeros((1, 2, 50)), + roi_fsvd=np.zeros((1, 2, 50)), + ) + traces = 3 * 100 * 8 + assert silo._held_bytes([sub], rec) == 4000 + 2000 + traces + assert silo._held_bytes([sub, with_base], rec) == 2 * 6000 + 2000 + traces diff --git a/tests/raster/test_raster_silo_network.py b/tests/raster/test_raster_silo_network.py index 7b2161e6..9673cbd1 100644 --- a/tests/raster/test_raster_silo_network.py +++ b/tests/raster/test_raster_silo_network.py @@ -1,1105 +1,1162 @@ -"""SILo with the F0 network's baseline (``baseline_source='network'``). - -The synthetic session of :mod:`test_raster_silo_stages`, with baseline -files as ``slap2-f0 predict-registered`` writes them: the network's -baseline is mapped into the containers and the streamed run's subproblems -alike, so that streamed, staged and sharded runs agree; each stage refuses -files made with another baseline; the prediction step calls slap2-f0 for -the missing files only. -""" - -import argparse -import json -import os -import subprocess -from dataclasses import asdict, replace -from pathlib import Path -from typing import NoReturn - -import h5py -import numpy as np -import pytest - -from giant_python.cli import build_parser, main -from giant_python.cli_silo import params_from_args -from giant_python.extraction.raster import trial as trial_mod -from giant_python.extraction.raster import trial_data as trial_data_mod -from giant_python.extraction.raster.baseline_map import ( - map_baseline, - read_network_baseline, - read_trial_baseline, - subproblem_baseline, -) -from giant_python.extraction.raster.container import ( - read_container, - read_subproblem, - write_container, -) -from giant_python.extraction.raster.solver_setup import SolverParams -from giant_python.models.params import SiloExecution, SiloParams -from giant_python.pipeline import silo, silo_baseline, silo_collect, silo_solve -from giant_python.pipeline.silo_session import ( - SiloSession, - file_id, - recording_ids, - stage_hash, -) - -from . import test_raster_silo_stages as stages -from .test_raster_silo_stages import ( - FRAMES, - N_PATHS, - N_TRIALS, - H, - W, - _all_results, - _equal, - _seeds, - _summary, - fake_load, - make_session, - seeds_file, -) - - -@pytest.fixture -def fake(monkeypatch: pytest.MonkeyPatch) -> None: - """Synthetic localization and loading (as in the stages' tests).""" - monkeypatch.setattr(trial_mod, "localize_trial", stages.fake_localize) - monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) - - -EX = SiloExecution(workers=1, solver_workers=1, solver_threads=1) -NET = SiloParams(baseline_source="network", min_kinetic_score=0.0) -MEDIAN = SiloParams(min_kinetic_score=0.0) - - -def _baseline_stack(d: int, t: int, n_frames: int, level: float = 50.0) -> np.ndarray: - """Build a smooth baseline in movie counts, (frames, rows, cols). - - It has a corner without values (NaN, as outside the valid pixels). - """ - r, c = np.mgrid[:H, :W] - img = level * (1 + 0.2 * np.sin(r / 5.0 + d) * np.cos(c / 7.0 + t)) - ramp = 1 + 0.05 * np.linspace(-1, 1, n_frames) - stack = img[None] * ramp[:, None, None] - stack[:, :3, :3] = np.nan - return stack.astype(np.float32) - - -def write_baselines(root: Path, folder: Path, level: float = 50.0) -> Path: - """Write baseline files of every trial-path, laid out as slap2-f0 writes them. - - ``/baseline`` (frame, col, row) float16, with its attributes. - """ - folder.mkdir(parents=True, exist_ok=True) - moco = root / "motion_correction" - for d in range(N_PATHS): - for t in range(N_TRIALS): - stem = f"E1T{t + 1}DMD{d + 1}" - with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "r") as f: - n = np.asarray(f["DSframes"]).size - stack = _baseline_stack(d, t, n, level) - with h5py.File(folder / f"{stem}_BASELINE-80Hz.h5", "w") as f: - f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) - f.attrs["checkpoint"] = "ckpt/s6_test.pt" - f.attrs["step"] = 1700 - f.attrs["gain"] = 130.0 - f.attrs["n_frames"] = n - f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" - return folder - - -def test_params_baseline_source() -> None: - """'network' sets the localization settings and N1; each can still be set. - - MATLAB's algorithm keeps its settings, hashes and params struct. - """ - m = SiloParams() - assert (m.peak_th, m.localization_baseline, m.baseline_mode) == ( - 3.0, - "median", - "fit", - ) - assert m.localization_surround and m.localization_null == "none" - assert m.min_source_event_rate == 0 - assert not m.needs_network_baseline - n = SiloParams(baseline_source="network") - assert n.peak_th == 3.0 and n.localization_baseline == "network" - assert n.min_source_event_rate == 2.0 and n.min_source_snr == 0 - assert not n.localization_surround and n.localization_null == "bootstrap" - assert n.localization_variance_floor - assert n.baseline_mode == "gain" == n.solver_params().baseline_mode - assert n.needs_network_baseline - o = SiloParams(baseline_source="network", peak_th=8, baseline_mode="fixed") - assert o.peak_th == 8 and o.baseline_mode == "fixed" - # the network's defaults before 2026-11-28 (GIAnT-Python#51) - old = SiloParams(baseline_source="network", peak_th=8, min_source_event_rate=0) - assert old.min_source_event_rate == 0 - assert "min_source_event_rate" not in old.stage_settings("collect") - assert n.stage_settings("collect")["min_source_event_rate"] == 2.0 - assert n.stage_settings("plan")["peak_th"] == 3.0 - assert SiloParams(**asdict(n)) == n - assert SiloParams(**json.loads(json.dumps(asdict(n)))) == n - # MATLAB's algorithm: no new fields in the hashes or the params struct - assert "baseline_mode" not in m.stage_settings("solve") - assert "min_source_event_rate" not in m.stage_settings("collect") - assert n.stage_settings("solve")["baseline_mode"] == "gain" - pm = m.to_matlab(2, 80.0) - assert "baselineSource" not in pm and "baselineMode" not in pm - assert pm["peakth"] == 3.0 and "minSourceEventRate" not in pm - pn = n.to_matlab(2, 80.0) - assert pn["baselineSource"] == "network" and pn["baselineMode"] == "gain" - assert pn["peakth"] == 3.0 and pn["localizationNull"] == "bootstrap" - assert pn["minSourceEventRate"] == 2.0 - with pytest.raises(ValueError, match="baseline_source"): - SiloParams(baseline_source="spline") - with pytest.raises(ValueError, match="baseline_mode"): - SiloParams(baseline_mode="guess") - - -def test_trial_baseline_is_map_baseline(tmp_path: Path) -> None: - """The pipeline's two steps give map_baseline's values. - - The two steps: space and units at the registration's frames, then time - and the fallback. - """ - rng = np.random.default_rng(3) - n_t, n_r, n_c = 9, 20, 16 - stack = (40 + 10 * rng.random((n_t, n_r, n_c))).astype(np.float32) - stack[:, :4, :] = np.nan # rows without values - stack[3, 10, 10] = np.nan # one missing sample - path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" - with h5py.File(path, "w") as f: - f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) - f.attrs["checkpoint"] = "x.pt" - full, _ = read_network_baseline(path) - rc = np.column_stack([rng.uniform(-0.8, n_r - 0.2, 60), rng.uniform(2, 9, 60)]) - rc[:5, 0] = rng.uniform(0, 2, 5) # no network value: fallback - ds_lines = np.linspace(1, 400, n_t) - frame_lines = np.arange(1, 401, 3) - data = 1.5 + rng.random((rc.shape[0], frame_lines.size)) - ref = map_baseline(full, rc, ds_lines, frame_lines, 25.0, fallback_data=data) - tb = read_trial_baseline(path, rc, ds_lines, 25.0) - assert tb.values.dtype == np.float32 - assert tb.identity["missing_pixels"] == int(ref.missing.sum()) > 0 - assert tb.identity["network"]["checkpoint"] == "x.pt" - got = subproblem_baseline(tb.values, tb.lines, frame_lines, data) - np.testing.assert_allclose(got, ref.values, rtol=2e-6) - np.testing.assert_array_equal(tb.weight, ref.weight) - # any subset of pixels: the same rows (the fallback is per pixel) - rows = np.array([1, 4, 7, 30, 59]) - np.testing.assert_array_equal( - subproblem_baseline(tb.values[rows], tb.lines, frame_lines, data[rows]), - got[rows], - ) - - -def test_container_holds_the_baseline(tmp_path: Path) -> None: - """A container stores the baseline at the registration's frames. - - Its subproblems get it for a mode that uses it, from memory or the file. - """ - trial = fake_load( - "x_DMD1-TRIAL000001.dat", - 1, - 2000, - None, - np.ones((H, W), bool), - None, - None, - None, - ) - n_px = trial.y.shape[1] - path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" - stack = _baseline_stack(0, 0, 6) - with h5py.File(path, "w") as f: - f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) - ds_lines = np.linspace(1, FRAMES[0] * 8, 6) - tb = read_trial_baseline(path, trial.trial_rc, ds_lines, 25.0) - groups = [np.arange(0, 50), np.arange(40, n_px)] - out = write_container( - tmp_path / "c.h5", - trial, - np.array([[5, 1], [10, 10]]), - groups, - [[0], [1]], - (H, W), - baseline=tb, - ) - sp = SolverParams(baseline_mode="gain") - c = read_container(out) - assert c.baseline_filled and c.baseline_values.dtype == np.float32 - np.testing.assert_array_equal(c.baseline_values, tb.values) - for k, pix in enumerate(groups): - expect = subproblem_baseline( - tb.values[pix], tb.lines, trial.frame_lines, trial.y[0, pix], sp - ) - a = c.subproblem(k, sp) - b = read_subproblem(out, k, sp) - np.testing.assert_array_equal(a.baseline, expect) - np.testing.assert_array_equal(b.baseline, expect) - assert np.isfinite(expect).all() # NaN corner: the fallback - # MATLAB's mode, or no solver parameters: no baseline is attached - assert c.subproblem(k).baseline is None - assert read_subproblem(out, k, SolverParams()).baseline is None - # a container without the baseline cannot feed a mode that needs it - bare = write_container( - tmp_path / "bare.h5", - trial, - np.array([[5, 1]]), - [groups[0]], - [[0]], - (H, W), - ) - assert not read_container(bare).baseline_filled - with pytest.raises(ValueError, match="no network baseline"): - read_subproblem(bare, 0, sp) - with pytest.raises(ValueError, match="no network baseline"): - read_container(bare).subproblem(0, sp) - - -def test_network_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: - """With the network's baseline (N1), streamed and staged runs agree. - - The streamed run, one job and three jobs give the same results and - summaries; the summaries record the baseline; the baseline changes the - results. - """ - root = tmp_path / "streamed" - table = make_session(root) - bdir = write_baselines(root, tmp_path / "baselines") - seeds = seeds_file(tmp_path) - silo.run_silo(table, NET, EX, seeds_file=seeds, baseline_dir=bdir) - s1 = SiloSession.open(table) - exp = s1.out_dir / "experiment_summary.h5" - streamed = _all_results(s1) - with h5py.File(exp, "r") as f: - assert f.attrs["baseline_source"] == "network" - assert f.attrs["baseline_mode"] == "gain" - used = json.loads(f.attrs["network_baseline"]) - assert len(used) == N_PATHS * N_TRIALS - first = used["path1_trial0001"] - assert first["file"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" - assert first["network"]["checkpoint"] == "ckpt/s6_test.pt" - assert first["network"]["step"] == 1700 - with h5py.File(s1.localize_file(0, 0), "r") as f: - assert f.attrs["localization_baseline"] == "network" - with h5py.File(s1.plan_file(0), "r") as f: - assert f.attrs["baseline_source"] == "network" - - for machines in (1, 3): - r2 = tmp_path / f"staged{machines}" - s2 = SiloSession.open(make_session(r2)) - silo.localize(s2, NET, EX, baseline_dir=bdir) - silo.plan(s2, NET, EX, seeds=_seeds(s2, tmp_path)) - silo.prepare(s2, NET, EX, baseline_dir=bdir) - c = read_container(s2.container_file(0, 0), data=False) - assert c.baseline_filled and c.params["baseline_source"] == "network" - for job in silo_solve.dispatch(s2, NET, machines, EX): - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(s2, NET, EX, baseline_dir=bdir) - staged = _all_results(s2) - assert staged.keys() == streamed.keys() - for key in staged: - for name, value in staged[key].items(): - np.testing.assert_array_equal(value, streamed[key][name]) - _equal(_summary(s2.out_dir / "experiment_summary.h5"), _summary(exp)) - - # the same run with MATLAB's baseline fit gives other results - r3 = tmp_path / "median" - silo.run_silo(make_session(r3), MEDIAN, EX, seeds_file=seeds) - s3 = SiloSession.open(r3 / "trial_table.h5") - median = _all_results(s3) - assert median.keys() == streamed.keys() - key = next(iter(median)) - assert not np.array_equal(median[key]["f0"], streamed[key]["f0"]) - with h5py.File(s3.out_dir / "experiment_summary.h5", "r") as f: - assert "baseline_source" not in f.attrs # as MATLAB writes it - - -def test_baseline_file_change_redoes_its_containers(tmp_path: Path, fake: None) -> None: - """The settings hash of a container covers its baseline file. - - MATLAB's algorithm keeps the hash it had before the network was wired in. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, root / "source_extraction" / "silo" / "baselines") - # localized with the moving median, extracted with the network: a new - # baseline file redoes its container only (with network localization it - # redoes the localization, hence the plan, first) - ext = replace( - NET, - localization_baseline="median", - localization_surround=True, - localization_null="none", - ) - silo.localize(s, ext, EX) - silo.plan(s, ext, EX, seeds=_seeds(s, tmp_path)) - assert len(silo.prepare(s, ext, EX)) == N_PATHS * N_TRIALS - assert silo.prepare(s, ext, EX) == [] # the default baselines folder - f = bdir / "E1T2DMD1_BASELINE-80Hz.h5" - with h5py.File(f, "a") as h: - h["baseline"][0, 0, 0] = 1.0 - redone = silo.prepare(s, ext, EX) - assert [r["unit"] for r in redone] == [(0, 1)] - # MATLAB's algorithm: the hash of the stage files before this change - ph = "abc" - old = stage_hash({ - "stage": "prepare", - "settings": MEDIAN.stage_settings("prepare"), - "plan": ph, - "unit": [0, 0], - "raw": recording_ids(s.raw(0, 0)), - "lines": [ - float(s.first_line[0, 0]), - float(s.last_line[0, 0]), - ], - "alignment": file_id(s.alignment(0, 0)), - }) - assert silo._prepare_hash(s, MEDIAN, ph, 0, 0) == old - assert silo._prepare_hash(s, NET, ph, 0, 0, f) != old - - -def test_stages_refuse_another_baseline(tmp_path: Path, fake: None) -> None: - """Each stage checks that the stage before it used the same baseline.""" - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - silo.localize(s, NET, EX, baseline_dir=bdir) - with pytest.raises(ValueError, match="localization_baseline='network'"): - silo.plan(s, MEDIAN, EX, seeds=_seeds(s, tmp_path)) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - with pytest.raises(ValueError, match="baseline_source='network'"): - silo.prepare(s, MEDIAN, EX) - # network localization and plan, MATLAB's baseline fit: no baseline - fit = replace(NET, baseline_mode="fit") - silo.prepare(s, fit, EX, baseline_dir=bdir) - assert not read_container(s.container_file(0, 0), data=False).baseline_filled - with pytest.raises(ValueError, match="has no network baseline"): - silo_solve.dispatch(s, NET, 2, EX) - with pytest.raises(ValueError, match="baseline_source='network'"): - silo_solve.dispatch(s, MEDIAN, 2, EX) - with pytest.raises(ValueError, match="baseline_source='network'"): - silo_collect.collect(s, MEDIAN, EX) - # a missing baseline file names itself and the ways to get it - (bdir / "E1T1DMD2_BASELINE-80Hz.h5").unlink() - with pytest.raises(FileNotFoundError, match="--f0-ckpt"): - silo.prepare(s, NET, EX, baseline_dir=bdir) - - -def _args(*argv: str) -> argparse.Namespace: - """Parse the arguments of a ``giant`` command line.""" - return build_parser().parse_args(list(argv)) - - -def test_cli_baseline_default() -> None: - """--baseline-dir or --f0-ckpt make the network the default. - - --baseline chooses; otherwise MATLAB's moving median. - """ - p = params_from_args(_args("silo", "t.h5")) - assert p.baseline_source == "median" and p.peak_th == 3.0 - p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b")) - assert p.baseline_source == "network" and p.peak_th == 3.0 - assert p.min_source_event_rate == 2.0 - p = params_from_args( - _args( - "silo", - "t.h5", - "--baseline-dir", - "b", - "--peak-th", - "8", - "--min-source-event-rate", - "0", - ) - ) - assert (p.peak_th, p.min_source_event_rate) == (8.0, 0.0) - p = params_from_args(_args("silo", "t.h5", "--f0-ckpt", "x.pt")) - assert p.baseline_source == "network" - p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b", "--baseline", "median")) - assert p.baseline_source == "median" - p = params_from_args(_args("silo-plan", "t.h5", "--baseline", "network")) - assert p.baseline_source == "network" and p.baseline_mode == "gain" - p = params_from_args(_args("silo-prepare", "t.h5", "--baseline-dir", "b", "--peak-th", "6")) - assert p.baseline_source == "network" and p.peak_th == 6.0 - p = params_from_args( - _args( - "silo-collect", - "t.h5", - "--set", - "baseline_source=median", - "--baseline-dir", - "b", - ) - ) - assert p.baseline_source == "median" - a = _args("silo", "t.h5", "--f0-ckpt", "x.pt", "--f0-device", "cpu") - assert a.f0_device == "cpu" and a.f0_command is None - - -def test_run_silo_default_source( - tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """run_silo: a dict or no params take the network with its baselines. - - A SiloParams is used as it is (with a warning that they are unused). - """ - root = tmp_path / "s" - table = make_session(root) - bdir = write_baselines(root, tmp_path / "b") - seen = [] - - def stop(session: SiloSession, params: SiloParams, *args: object, **kw: object) -> NoReturn: - """Record the params and stop the run.""" - seen.append(params) - raise RuntimeError("stop") - - monkeypatch.setattr(silo, "_ready_paths", stop) - for params in (None, {"min_kinetic_score": 0.0}): - with pytest.raises(RuntimeError, match="stop"): - silo.run_silo(table, params, EX, baseline_dir=bdir) - assert seen[-1].baseline_source == "network" - with pytest.warns(UserWarning, match="not used"): - with pytest.raises(RuntimeError, match="stop"): - silo.run_silo(table, MEDIAN, EX, baseline_dir=bdir) - assert seen[-1].baseline_source == "median" - assert silo.default_baseline_source(None, False) is None - - -def test_predict_baselines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """--f0-ckpt runs slap2-f0 predict-registered once. - - It runs for the trial-paths without a baseline file, with the run's trial - preparation settings. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = tmp_path / "b" - write_baselines(root, bdir) - for t in (1, 2): - (bdir / f"E1T{t + 1}DMD2_BASELINE-80Hz.h5").unlink() - ckpt = tmp_path / "s6_test.pt" - ckpt.write_bytes(b"weights") - calls = [] - monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") - - def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: - """slap2-f0 stood in for: write the files asked for.""" - calls.append(args) - keys = args[args.index("--files") + 1].split(",") - for k in keys: - stem = k[: -len("_REGISTERED")] - src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" - (bdir / f"{stem}_BASELINE-80Hz.h5").write_bytes(src.read_bytes()) - with h5py.File(bdir / f"{stem}_BASELINE-80Hz.h5", "a") as f: - f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" - return subprocess.CompletedProcess(args, 0) - - monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) - params = SiloParams(baseline_source="network", motion_thresh=1.5) - rec = silo_baseline.predict_baselines(s, params, bdir, ckpt, device="cpu") - assert rec["predicted"] == [[2, 2], [2, 3]] - assert rec["checkpoint"]["name"] == "s6_test.pt" - rec_ckpt = rec["checkpoint"] - assert len(rec["checkpoint"]["sha256"]) == 64 - (args,) = calls - assert args[:2] == ["/bin/slap2-f0", "predict-registered"] - assert args[args.index("--ckpt") + 1] == str(ckpt) - assert args[args.index("--out") + 1] == str(bdir) - assert args[args.index("--files") + 1] == ("E1T2DMD2_REGISTERED,E1T3DMD2_REGISTERED") - assert args[args.index("--motion_thresh") + 1] == "1.5" - assert args[args.index("--channel") + 1] == "1" - assert args[args.index("--device") + 1] == "cpu" - # nothing missing: nothing run - calls.clear() - assert silo_baseline.predict_baselines(s, params, bdir, ckpt)["predicted"] == [] - assert not calls - - # the predicted files have records: the prediction's settings, the - # inputs and the checkpoint as it was then - base = bdir / "E1T2DMD2_BASELINE-80Hz.h5" - rec = json.loads(silo_baseline.record_path(base).read_text()) - assert rec["settings"]["motion_thresh"] == 1.5 - assert rec["checkpoint"] == rec_ckpt - assert rec["movie"]["name"].startswith("E1T2DMD2_REGISTERED") - imported = bdir / "E1T1DMD1_BASELINE-80Hz.h5" - assert not silo_baseline.record_path(imported).exists() - ckpt.write_bytes(b"other weights") # overwritten after the prediction - trial = fake_load( - "x_DMD2-TRIAL000002.dat", - 1, - 2000, - None, - np.ones((H, W), bool), - None, - None, - None, - ) - tb = silo.load_trial_baseline(s, params, trial, base, 1, 1) - assert tb.identity["checkpoint"] == rec_ckpt - assert tb.identity["prediction"]["activity_channel"] == 1 - tb = silo.load_trial_baseline(s, params, trial, imported, 0, 0) - assert "checkpoint" not in tb.identity # not verified: path and step only - assert tb.identity["network"]["step"] == 1700 - # a baseline predicted with other settings is refused, not reused - other = replace(params, activity_channel=2) - with pytest.raises(ValueError, match="was predicted with"): - silo_baseline.predict_baselines(s, other, bdir, ckpt) - with pytest.raises(ValueError, match="was predicted with"): - silo.localize(s, other, EX, baseline_dir=bdir) - # a record of a file that was replaced since - with h5py.File(base, "a") as f: - f.attrs["step"] = 1800 - with pytest.raises(ValueError, match="does not describe"): - silo.localize(s, params, EX, baseline_dir=bdir) - silo_baseline.record_path(base).unlink() - ckpt.write_bytes(b"weights") - - # a failed or incomplete prediction is an error - (bdir / "E1T3DMD1_BASELINE-80Hz.h5").unlink() - # a trial with both movies, the newer not SILo's: refused before the GPU - moco = root / "motion_correction" - tif = moco / "E1T3DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" - h5 = tif.with_suffix(".h5") - h5.write_bytes(b"") - os.utime(h5, (tif.stat().st_mtime + 10, tif.stat().st_mtime + 10)) - with pytest.raises(ValueError, match="remove one of them"): - silo_baseline.predict_baselines(s, params, bdir, ckpt) - assert silo_baseline.f0_movie(moco, "E1T3DMD1") == h5 - h5.unlink() - monkeypatch.setattr( - silo_baseline.subprocess, - "run", - lambda args, **kw: subprocess.CompletedProcess(args, 3), - ) - with pytest.raises(RuntimeError, match="exited with 3"): - silo_baseline.predict_baselines(s, params, bdir, ckpt) - - # a run that writes a file and then fails: the file has its record, so - # a retry with other settings does not reuse it unchecked - def fail_after_one(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: - """Write the files, then fail.""" - fake_run(args, **kw) - return subprocess.CompletedProcess(args, 1) - - monkeypatch.setattr(silo_baseline.subprocess, "run", fail_after_one) - with pytest.raises(RuntimeError, match="exited with 1"): - silo_baseline.predict_baselines(s, params, bdir, ckpt) - written = bdir / "E1T3DMD1_BASELINE-80Hz.h5" - rec = json.loads(silo_baseline.record_path(written).read_text()) - assert rec["baseline"]["name"] == written.name - with pytest.raises(ValueError, match="was predicted with"): - silo_baseline.predict_baselines(s, other, bdir, ckpt) - # stopped before the record got the file's identity: its settings hold - rec["baseline"] = None - silo_baseline.record_path(written).write_text(json.dumps(rec)) - args = (written, s.movie(0, 2), s.alignment(0, 2)) - assert silo_baseline.check_baseline_record(*args, params) is not None - with pytest.raises(ValueError, match="was predicted with"): - silo_baseline.check_baseline_record(*args, other) - written.unlink() - monkeypatch.setattr( - silo_baseline.subprocess, - "run", - lambda args, **kw: subprocess.CompletedProcess(args, 0), - ) - with pytest.raises(RuntimeError, match="E1T3DMD1"): - silo_baseline.predict_baselines(s, params, bdir, ckpt) - monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: None) - with pytest.raises(FileNotFoundError, match="--f0-command"): - silo_baseline.predict_baselines(s, params, bdir, ckpt) - with pytest.raises(FileNotFoundError, match="no checkpoint"): - silo_baseline.predict_baselines(s, params, bdir, tmp_path / "x.pt") - - -def test_source_alone_redoes_plan_and_containers(tmp_path: Path, fake: None) -> None: - """baseline_source enters the plan and prepare hashes (when it is not MATLAB's). - - Changing it alone redoes those stages rather than reusing files that the - next stage would refuse. - """ - alt = SiloParams( - baseline_source="median", - localization_baseline="network", - localization_surround=False, - localization_null="bootstrap", - peak_th=3.0, - baseline_mode="gain", - min_kinetic_score=0.0, - min_source_event_rate=2.0, - ) - for stage in ("localize", "solve", "collect"): - assert alt.stage_settings(stage) == NET.stage_settings(stage) - for stage in ("plan", "prepare"): - assert alt.stage_settings(stage) != NET.stage_settings(stage) - assert "baseline_source" not in MEDIAN.stage_settings(stage) - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - silo.localize(s, NET, EX, baseline_dir=bdir) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, NET, EX, baseline_dir=bdir) - silo.plan(s, alt, EX, seeds=_seeds(s, tmp_path)) # redone, not reused - with h5py.File(s.plan_file(0), "r") as f: - assert f.attrs["baseline_source"] == "median" - assert len(silo.prepare(s, alt, EX, baseline_dir=bdir)) == 6 - with pytest.raises(ValueError, match="baseline_source='median'"): - silo.prepare(s, NET, EX, baseline_dir=bdir) - - -def test_earlier_network_defaults_are_localized_again(tmp_path: Path, fake: None) -> None: - """Files made with the network's defaults before 2026-11-28 are localized again. - - Files made with those defaults (peak_th 8, no evidence test) are - localized again with the current ones (peak_th is also the per-trial - peaks' threshold, and every later stage checks the hash of the one - before), so a run never mixes the two; the earlier defaults given as - options keep the files. - """ - old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) - s = SiloSession.open(make_session(tmp_path / "s")) - bdir = write_baselines(tmp_path / "s", tmp_path / "b") - silo.localize(s, old, EX, baseline_dir=bdir) - assert silo.localize_jobs(s, old, baseline_dir=bdir) == [] - every = silo.localize_jobs(s, NET, baseline_dir=bdir, overwrite=True) - assert len(silo.localize_jobs(s, NET, baseline_dir=bdir)) == len(every) - assert old.stage_settings("collect") != NET.stage_settings("collect") - assert old.stage_settings("solve") == NET.stage_settings("solve") - - -def test_collect_refuses_another_seed_threshold(tmp_path: Path, fake: None) -> None: - """Refuse a collect of a folder seeded with another peak_th. - - A standalone collect of a folder seeded with the network's earlier - default (peak_th 8) is refused under today's (3), which would record - peakth 3 and judge the sources' evidence against it; the earlier - settings collect it. - """ - old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) - s = SiloSession.open(make_session(tmp_path / "s")) - bdir = write_baselines(tmp_path / "s", tmp_path / "b") - silo.localize(s, old, EX, baseline_dir=bdir) - silo.plan(s, old, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, old, EX, baseline_dir=bdir) - for job in silo_solve.dispatch(s, old, 3, EX): - silo_solve.solve_job(job, execution=EX) - with pytest.raises(ValueError, match="seeded with peak_th=8.*--peak-th 8"): - silo_collect.collect(s, NET, EX, baseline_dir=bdir) - record = silo_collect.collect(s, old, EX, baseline_dir=bdir) - assert record is not None - with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: - assert float(np.ravel(f["params/peakth"][()])[0]) == 8.0 - - -def test_collect_refuses_another_seed_acceptance(tmp_path: Path, fake: None) -> None: - """A standalone collect of a plan seeded with the null threshold is refused. - - It is refused under the image threshold (whose evidence test would exempt - strong seeds that the null mode judges); its own settings collect it. - """ - null = replace(NET, seed_acceptance="null_sd", localization_keep_null=True) - assert null.evidence_judge_below is None - s = SiloSession.open(make_session(tmp_path / "s")) - bdir = write_baselines(tmp_path / "s", tmp_path / "b") - silo.localize(s, null, EX, baseline_dir=bdir) - silo.plan(s, null, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, null, EX, baseline_dir=bdir) - for job in silo_solve.dispatch(s, null, 3, EX): - silo_solve.solve_job(job, execution=EX) - with pytest.raises(ValueError, match="seed_acceptance='null_sd'"): - silo_collect.collect(s, NET, EX, baseline_dir=bdir) - assert silo_collect.collect(s, null, EX, baseline_dir=bdir) is not None - - -def test_unrecorded_network_localization_is_redone(tmp_path: Path, fake: None) -> None: - """A localization file without the record of its baseline counts as the median's. - - Such a file (made before the baseline was recorded) counts as the moving - median's: with the network's settings it is localized again, with MATLAB's - it is kept. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - silo.localize(s, NET, EX, baseline_dir=bdir) - assert silo.localize_jobs(s, NET, baseline_dir=bdir) == [] - with h5py.File(s.localize_file(1, 2), "a") as f: - del f.attrs["localization_baseline"] - jobs = silo.localize_jobs(s, NET, baseline_dir=bdir) - assert [j["unit"] for j in jobs] == [(1, 2)] - m = SiloSession.open(make_session(tmp_path / "m")) - silo.localize(m, MEDIAN, EX) - with h5py.File(m.localize_file(0, 1), "a") as f: - del f.attrs["localization_baseline"] - assert silo.localize_jobs(m, MEDIAN) == [] - - -def test_summary_records_the_baseline_of_the_results_used(tmp_path: Path, fake: None) -> None: - """The summary's network_baseline comes from the results files that are assembled. - - It does not come from earlier runs' files left in the folder. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - silo.localize(s, NET, EX, baseline_dir=bdir) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, NET, EX, baseline_dir=bdir) - for job in silo_solve.dispatch(s, NET, 3, EX): - silo_solve.solve_job(job, execution=EX) - shard = sorted(s.results_dir.glob("*_s*.h5"))[0] - stem = shard.name.split("_s")[0] - stale = s.results_dir / f"{stem}.h5" # sorts before the shards - assert not stale.exists() - stale.write_bytes(shard.read_bytes()) - with h5py.File(stale, "a") as f: - f.attrs["plan_hash"] = "an earlier plan" - f.attrs["network_baseline"] = json.dumps({"file": {"name": "old"}}) - with pytest.warns(UserWarning, match="left out"): - record = silo_collect.collect(s, NET, EX, baseline_dir=bdir) - used = record["network_baseline"][stem] - assert used["file"]["name"].endswith("_BASELINE-80Hz.h5") - with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: - assert json.loads(f.attrs["network_baseline"])[stem] == used - - -def test_baseline_from_another_movie_is_refused(tmp_path: Path, fake: None) -> None: - """A baseline file predicted from another movie than SILo reads is refused. - - The movie it was predicted from is its 'source'. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - with h5py.File(bdir / "E1T2DMD1_BASELINE-80Hz.h5", "a") as f: - f.attrs["source"] = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - with pytest.raises(ValueError, match="was predicted from"): - silo.localize(s, NET, EX, baseline_dir=bdir) - - -def test_collect_checks_baselines_without_movies(tmp_path: Path, fake: None) -> None: - """A collect machine without the registered movies still checks the baselines. - - It checks the results against the baseline files (named after the trial - table's movies): a replaced baseline leaves the results stale. - """ - root = tmp_path / "s" - table = make_session(root) - bdir = write_baselines(root, tmp_path / "b") - silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) - for movie in (root / "motion_correction").glob("*_REGISTERED_*"): - movie.unlink() - s = SiloSession.open(table, inputs="collect") - assert s.movie(0, 0) is None - silo_collect.collect(s, NET, EX, baseline_dir=bdir) - with h5py.File(bdir / "E1T1DMD2_BASELINE-80Hz.h5", "a") as f: - f["baseline"][0, 5, 5] = 1.0 - with pytest.warns(UserWarning, match="left out"): - with pytest.raises(FileNotFoundError, match="path 2, trial 1"): - silo_collect.collect(s, NET, EX, baseline_dir=bdir) - - -def test_localize_predicts_for_extraction_too( - tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """silo-localize --f0-ckpt predicts whenever a stage uses the network's baselines. - - It also predicts when localization alone uses the moving median. - """ - table = make_session(tmp_path / "s") - calls = [] - monkeypatch.setattr( - silo_baseline, - "predict_baselines", - lambda *a, **k: calls.append(a[1]) or {"predicted": []}, - ) - monkeypatch.setattr(silo, "localize", lambda *a, **k: []) - argv = ["silo-localize", str(table), "--f0-ckpt", "x.pt"] - assert main(argv + ["--localization-baseline", "median"]) == 0 - assert len(calls) == 1 and calls[0].baseline_mode == "gain" - assert main(argv + ["--baseline", "median"]) == 0 - assert len(calls) == 1 - - -def test_extraction_uses_the_localization_baseline(tmp_path: Path, fake: None) -> None: - """Extraction refuses another baseline file than the trial was localized with. - - Here the stages are given different folders. - """ - import shutil - - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - a = write_baselines(root, tmp_path / "a") - b = tmp_path / "b" - # the same baselines, other files (new modification times) - shutil.copytree(a, b, copy_function=shutil.copy) - silo.localize(s, NET, EX, baseline_dir=a) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - with pytest.raises(ValueError, match="localized with another baseline"): - silo.prepare(s, NET, EX, baseline_dir=b) - assert len(silo.prepare(s, NET, EX, baseline_dir=a)) == 6 - - -def test_predict_units_may_be_a_generator(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The trial-paths to predict may be given as a generator.""" - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() - ckpt = tmp_path / "s6_test.pt" - ckpt.write_bytes(b"weights") - monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") - - rec_args = [] - - def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: - """Write the one file asked for.""" - rec_args.append(args) - src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" - dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" - dest.write_bytes(src.read_bytes()) - with h5py.File(dest, "a") as f: - f.attrs["source"] = "E1T2DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif" - return subprocess.CompletedProcess(args, 0) - - monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) - units = (u for u in [(0, 0), (1, 1)]) - rec = silo_baseline.predict_baselines(s, NET, bdir, ckpt, units, out_frames=512) - assert rec["predicted"] == [[2, 2]] - args = rec_args[-1] - assert args[args.index("--out_frames") + 1] == "512" - assert _args("silo", "t.h5", "--f0-out-frames", "256").f0_out_frames == 256 - - -def test_summary_records_the_localization_baseline(tmp_path: Path, fake: None) -> None: - """The summary records the baseline that decided the seeds. - - Here the trials are localized with the network's baseline and extracted - with MATLAB's fit. - """ - root = tmp_path / "s" - table = make_session(root) - bdir = write_baselines(root, tmp_path / "b") - loc_only = replace(NET, baseline_mode="fit") - silo.run_silo(table, loc_only, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) - s = SiloSession.open(table) - with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: - assert f.attrs["baseline_mode"] == "fit" - assert "network_baseline" not in f.attrs # not extracted with it - loc = json.loads(f.attrs["localization_network_baseline"]) - assert len(loc) == N_PATHS * N_TRIALS - first = loc["path1_trial0001"] - assert first["file"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" - assert first["network"] == {"checkpoint": "ckpt/s6_test.pt", "step": 1700} - - -def test_localized_again_after_the_plan(tmp_path: Path, fake: None) -> None: - """Prepare and collect refuse a plan made before the trials were localized again. - - Trials localized again (here with other baseline files) after their plan - was made: prepare and collect refuse the stale plan and results instead - of reading the new localization's peaks and baselines. - """ - import shutil - - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - a = write_baselines(root, tmp_path / "a") - b = tmp_path / "b" - shutil.copytree(a, b, copy_function=shutil.copy) - silo.localize(s, NET, EX, baseline_dir=a) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, NET, EX, baseline_dir=a) - for job in silo_solve.dispatch(s, NET, 1, EX): - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(s, NET, EX, baseline_dir=a) - silo.localize(s, NET, EX, baseline_dir=b) # every trial again - with pytest.raises(ValueError, match="localized again since its plan"): - silo_collect.collect(s, NET, EX, baseline_dir=a) - with pytest.raises(ValueError, match="localized again since its plan"): - silo.prepare(s, NET, EX, baseline_dir=b) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) # made again: fine - assert len(silo.prepare(s, NET, EX, baseline_dir=b)) == 6 - - -def test_one_baseline_mode_per_run(tmp_path: Path, fake: None) -> None: - """Containers prepared with the network's baseline are not solved with MATLAB's fit. - - Their hash covers a baseline the fit does not use, so collect would take - the results for stale; results name the baseline only when the solver - used it. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - silo.localize(s, NET, EX, baseline_dir=bdir) - silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, NET, EX, baseline_dir=bdir) - fit = replace(NET, baseline_mode="fit") - with pytest.raises(ValueError, match="baseline_mode 'fit'"): - silo_solve.dispatch(s, fit, 1, EX) - job = silo_solve.dispatch(s, NET, 1, EX)[0] - with pytest.raises(ValueError, match="baseline_mode 'fit'"): - silo_solve.solve_container( - s.container_file(0, 0), - s.results_file(0, 0), - fit, - EX.solver_options(), - ) - silo_solve.solve_job(job, execution=EX) - with h5py.File(s.results_file(0, 0), "r") as h: - assert "network_baseline" in h.attrs - c = read_container(s.container_file(0, 0), data=False) - attrs = silo_solve.results_attrs(c, "c.h5", "h", (0, 1), 1, True, "r", fit, EX.solver_options()) - assert "network_baseline" not in attrs - - -def test_collect_checks_the_localization_baseline(tmp_path: Path, fake: None) -> None: - """Collect refuses settings with another localization baseline than the trials'. - - It refuses settings whose localization baseline is not the one the trials - were localized with (the summary would mislabel them). - """ - root = tmp_path / "s" - table = make_session(root) - bdir = write_baselines(root, tmp_path / "b") - silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) - s = SiloSession.open(table) - median_loc = replace( - NET, - localization_baseline="median", - localization_surround=True, - localization_null="none", - ) - assert median_loc.stage_settings("solve") == NET.stage_settings("solve") - with pytest.raises(ValueError, match="localization_baseline='network'"): - silo_collect.collect(s, median_loc, EX, baseline_dir=bdir) - - -def test_one_checkpoint_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Baselines kept from an earlier prediction must match the given checkpoint. - - They must have been made with the given checkpoint (its SHA-256, not only - its name). - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - bdir = write_baselines(root, tmp_path / "b") - (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() - ckpt = tmp_path / "s6_test.pt" - ckpt.write_bytes(b"weights") - monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") - - def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: - """Write the one file asked for.""" - src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" - dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" - dest.write_bytes(src.read_bytes()) - with h5py.File(dest, "a") as f: - f.attrs["source"] = "E1T2DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif" - return subprocess.CompletedProcess(args, 0) - - monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) - silo_baseline.predict_baselines(s, NET, bdir, ckpt) - assert silo_baseline.predict_baselines(s, NET, bdir, ckpt)["predicted"] == [] - ckpt.write_bytes(b"retrained weights") # same name, other model - with pytest.raises(ValueError, match="another checkpoint"): - silo_baseline.predict_baselines(s, NET, bdir, ckpt) - - -def _copy_tree(src: Path, dest: Path) -> Path: - """Copy a tree, giving its files new modification times. - - The copies have new modification times as a data asset's files carry - their upload times. - """ - import shutil - - shutil.copytree(src, dest, copy_function=shutil.copyfile) - for f in dest.rglob("*"): - if f.is_file(): - st = f.stat() - os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns + 7_000_000_000)) - return dest - - -def test_records_with_digests_identify_copied_files( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Records written with digests=True still identify copied files. - - They identify the baseline, movie and alignment files after they are - copied elsewhere (another modification time), and refuse a copy whose - content changed; records without digests refuse any copy, as before. - """ - root = tmp_path / "s" - s = SiloSession.open(make_session(root)) - for d in range(N_PATHS): # movies with content, so that digests differ - for t in range(N_TRIALS): - s.movie(d, t).write_bytes(bytes([d, t]) * 64) - bdir = tmp_path / "b" - write_baselines(root, bdir) - stem = "E1T2DMD2" - (bdir / f"{stem}_BASELINE-80Hz.h5").unlink() - ckpt = tmp_path / "s6_test.pt" - ckpt.write_bytes(b"weights") - monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") - - def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: - """Write the file asked for.""" - dest = bdir / f"{stem}_BASELINE-80Hz.h5" - dest.write_bytes((bdir / "E1T1DMD1_BASELINE-80Hz.h5").read_bytes()) - with h5py.File(dest, "a") as f: - f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" - return subprocess.CompletedProcess(args, 0) - - monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) - rec = silo_baseline.predict_baselines(s, NET, bdir, ckpt, digests=True) - assert rec["predicted"] == [[2, 2]] - base = bdir / f"{stem}_BASELINE-80Hz.h5" - record = json.loads(silo_baseline.record_path(base).read_text()) - for name, f in ( - ("baseline", base), - ("movie", s.movie(1, 1)), - ("alignment", s.alignment(1, 1)), - ): - assert record[name]["sha256"] == silo_baseline.file_sha256(f) - assert record[name]["mtime_ns"] == file_id(f)["mtime_ns"] - - # the registration and the baselines copied, as two data assets - root2 = _copy_tree(root, tmp_path / "asset_reg") - bdir2 = _copy_tree(bdir, tmp_path / "asset_base") - s2 = SiloSession.open(root2, moco_dir=root2 / "motion_correction") - base2 = bdir2 / base.name - assert file_id(base2)["mtime_ns"] != record["baseline"]["mtime_ns"] - args = (base2, s2.movie(1, 1), s2.alignment(1, 1)) - assert silo_baseline.check_baseline_record(*args, NET) == record - assert silo_baseline.same_file(record["movie"], s2.movie(1, 1)) - # the stages take the copies (the localization checks the record) - assert silo._network_baseline(s2, NET, 1, 1, bdir2) == base2 - # another movie than the one predicted from (same name and size) - other_movie = s2.movie(1, 1) - other_movie.write_bytes(bytes([9, 9]) * 64) - with pytest.raises(ValueError, match="from another movie"): - silo_baseline.check_baseline_record(*args, NET) - # a changed copy of the baseline (same name and size) - data = bytearray(base2.read_bytes()) - data[-1] ^= 0xFF - base2.write_bytes(bytes(data)) - with pytest.raises(ValueError, match="does not describe"): - silo_baseline.check_baseline_record(base2, None, args[2], NET) - - # without digests (the default) a copy is not identified - bdir3 = _copy_tree(bdir, tmp_path / "copy_plain") - rec3 = silo_baseline.record_path(bdir3 / base.name) - old = json.loads(rec3.read_text()) - for k in ("baseline", "movie", "alignment"): - old[k].pop("sha256") - rec3.write_text(json.dumps(old)) - with pytest.raises(ValueError, match="does not describe"): - silo_baseline.check_baseline_record(bdir3 / base.name, None, s.alignment(1, 1), NET) - assert not silo_baseline.same_file(None, base) +"""SILo with the F0 network's baseline (baseline_source='network'). + +The synthetic session of :mod:`test_raster_silo_stages`, with baseline +files as slap2-f0 predict-registered writes them: the network's +baseline is mapped into the containers and the streamed run's subproblems +alike, so that streamed, staged and sharded runs agree; each stage refuses +files made with another baseline; the prediction step calls slap2-f0 for +the missing files only. +""" + +import argparse +import json +import os +import subprocess +from dataclasses import asdict, replace +from pathlib import Path +from typing import NoReturn + +import h5py +import numpy as np +import pytest + +from giant_python.cli import build_parser, main +from giant_python.cli_silo import params_from_args +from giant_python.extraction.raster import trial as trial_mod +from giant_python.extraction.raster import trial_data as trial_data_mod +from giant_python.extraction.raster.baseline_map import ( + map_baseline, + read_network_baseline, + read_trial_baseline, + subproblem_baseline, +) +from giant_python.extraction.raster.container import ( + read_container, + read_subproblem, + write_container, +) +from giant_python.extraction.raster.solver_setup import SolverParams +from giant_python.models.params import SiloExecution, SiloParams +from giant_python.pipeline import silo, silo_baseline, silo_collect, silo_solve +from giant_python.pipeline.silo_session import ( + SiloSession, + file_id, + recording_ids, + stage_hash, +) + +from . import test_raster_silo_stages as stages +from .test_raster_silo_stages import ( + FRAMES, + N_PATHS, + N_TRIALS, + H, + W, + _all_results, + _equal, + _seeds, + _summary, + fake_load, + make_session, + seeds_file, +) + + +@pytest.fixture +def fake(monkeypatch: pytest.MonkeyPatch) -> None: + """Synthetic localization and loading (as in the stages' tests).""" + monkeypatch.setattr(trial_mod, "localize_trial", stages.fake_localize) + monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) + + +EX = SiloExecution(workers=1, solver_workers=1, solver_threads=1) +NET = SiloParams(baseline_source="network", min_kinetic_score=0.0) +MEDIAN = SiloParams(min_kinetic_score=0.0) + + +def _baseline_stack(d: int, t: int, n_frames: int, level: float = 50.0) -> np.ndarray: + """Build a smooth baseline in movie counts, (frames, rows, cols). + + It has a corner without values (NaN, as outside the valid pixels). + + Returns + ------- + np.ndarray + The float32 baseline, (frames, rows, cols), in movie counts. + """ + r, c = np.mgrid[:H, :W] + img = level * (1 + 0.2 * np.sin(r / 5.0 + d) * np.cos(c / 7.0 + t)) + ramp = 1 + 0.05 * np.linspace(-1, 1, n_frames) + stack = img[None] * ramp[:, None, None] + stack[:, :3, :3] = np.nan + return stack.astype(np.float32) + + +def write_baselines(root: Path, folder: Path, level: float = 50.0) -> Path: + """Write baseline files of every trial-path, laid out as slap2-f0 writes them. + + /baseline (frame, col, row) float16, with its attributes. + + Returns + ------- + Path + The folder the baseline files were written to. + """ + folder.mkdir(parents=True, exist_ok=True) + moco = root / "motion_correction" + for d in range(N_PATHS): + for t in range(N_TRIALS): + stem = f"E1T{t + 1}DMD{d + 1}" + with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "r") as f: + n = np.asarray(f["DSframes"]).size + stack = _baseline_stack(d, t, n, level) + with h5py.File(folder / f"{stem}_BASELINE-80Hz.h5", "w") as f: + f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) + f.attrs["checkpoint"] = "ckpt/s6_test.pt" + f.attrs["step"] = 1700 + f.attrs["gain"] = 130.0 + f.attrs["n_frames"] = n + f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" + return folder + + +def test_params_baseline_source() -> None: + """'network' sets the localization settings and N1; each can still be set. + + MATLAB's algorithm keeps its settings, hashes and params struct. + """ + m = SiloParams() + assert (m.peak_th, m.localization_baseline, m.baseline_mode) == ( + 3.0, + "median", + "fit", + ) + assert m.localization_surround and m.localization_null == "none" + assert m.min_source_event_rate == 0 + assert not m.needs_network_baseline + n = SiloParams(baseline_source="network") + assert n.peak_th == 3.0 and n.localization_baseline == "network" + assert n.min_source_event_rate == 2.0 and n.min_source_snr == 0 + assert not n.localization_surround and n.localization_null == "bootstrap" + assert n.localization_variance_floor + assert n.baseline_mode == "gain" == n.solver_params().baseline_mode + assert n.needs_network_baseline + o = SiloParams(baseline_source="network", peak_th=8, baseline_mode="fixed") + assert o.peak_th == 8 and o.baseline_mode == "fixed" + # the network's defaults before 2026-11-28 (GIAnT-Python#51) + old = SiloParams(baseline_source="network", peak_th=8, min_source_event_rate=0) + assert old.min_source_event_rate == 0 + assert "min_source_event_rate" not in old.stage_settings("collect") + assert n.stage_settings("collect")["min_source_event_rate"] == 2.0 + assert n.stage_settings("plan")["peak_th"] == 3.0 + assert SiloParams(**asdict(n)) == n + assert SiloParams(**json.loads(json.dumps(asdict(n)))) == n + # MATLAB's algorithm: no new fields in the hashes or the params struct + assert "baseline_mode" not in m.stage_settings("solve") + assert "min_source_event_rate" not in m.stage_settings("collect") + assert n.stage_settings("solve")["baseline_mode"] == "gain" + pm = m.to_matlab(2, 80.0) + assert "baselineSource" not in pm and "baselineMode" not in pm + assert pm["peakth"] == 3.0 and "minSourceEventRate" not in pm + pn = n.to_matlab(2, 80.0) + assert pn["baselineSource"] == "network" and pn["baselineMode"] == "gain" + assert pn["peakth"] == 3.0 and pn["localizationNull"] == "bootstrap" + assert pn["minSourceEventRate"] == 2.0 + with pytest.raises(ValueError, match="baseline_source"): + SiloParams(baseline_source="spline") + with pytest.raises(ValueError, match="baseline_mode"): + SiloParams(baseline_mode="guess") + + +def test_trial_baseline_is_map_baseline(tmp_path: Path) -> None: + """The pipeline's two steps give map_baseline's values. + + The two steps: space and units at the registration's frames, then time + and the fallback. + """ + rng = np.random.default_rng(3) + n_t, n_r, n_c = 9, 20, 16 + stack = (40 + 10 * rng.random((n_t, n_r, n_c))).astype(np.float32) + stack[:, :4, :] = np.nan # rows without values + stack[3, 10, 10] = np.nan # one missing sample + path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" + with h5py.File(path, "w") as f: + f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) + f.attrs["checkpoint"] = "x.pt" + full, _ = read_network_baseline(path) + rc = np.column_stack([rng.uniform(-0.8, n_r - 0.2, 60), rng.uniform(2, 9, 60)]) + rc[:5, 0] = rng.uniform(0, 2, 5) # no network value: fallback + ds_lines = np.linspace(1, 400, n_t) + frame_lines = np.arange(1, 401, 3) + data = 1.5 + rng.random((rc.shape[0], frame_lines.size)) + ref = map_baseline(full, rc, ds_lines, frame_lines, 25.0, fallback_data=data) + tb = read_trial_baseline(path, rc, ds_lines, 25.0) + assert tb.values.dtype == np.float32 + assert tb.identity["missing_pixels"] == int(ref.missing.sum()) > 0 + assert tb.identity["network"]["checkpoint"] == "x.pt" + got = subproblem_baseline(tb.values, tb.lines, frame_lines, data) + np.testing.assert_allclose(got, ref.values, rtol=2e-6) + np.testing.assert_array_equal(tb.weight, ref.weight) + # any subset of pixels: the same rows (the fallback is per pixel) + rows = np.array([1, 4, 7, 30, 59]) + np.testing.assert_array_equal( + subproblem_baseline(tb.values[rows], tb.lines, frame_lines, data[rows]), + got[rows], + ) + + +def test_container_holds_the_baseline(tmp_path: Path) -> None: + """A container stores the baseline at the registration's frames. + + Its subproblems get it for a mode that uses it, from memory or the file. + """ + trial = fake_load( + "x_DMD1-TRIAL000001.dat", + 1, + 2000, + None, + np.ones((H, W), bool), + None, + None, + None, + ) + n_px = trial.y.shape[1] + path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" + stack = _baseline_stack(0, 0, 6) + with h5py.File(path, "w") as f: + f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) + ds_lines = np.linspace(1, FRAMES[0] * 8, 6) + tb = read_trial_baseline(path, trial.trial_rc, ds_lines, 25.0) + groups = [np.arange(0, 50), np.arange(40, n_px)] + out = write_container( + tmp_path / "c.h5", + trial, + np.array([[5, 1], [10, 10]]), + groups, + [[0], [1]], + (H, W), + baseline=tb, + ) + sp = SolverParams(baseline_mode="gain") + c = read_container(out) + assert c.baseline_filled and c.baseline_values.dtype == np.float32 + np.testing.assert_array_equal(c.baseline_values, tb.values) + for k, pix in enumerate(groups): + expect = subproblem_baseline( + tb.values[pix], tb.lines, trial.frame_lines, trial.y[0, pix], sp + ) + a = c.subproblem(k, sp) + b = read_subproblem(out, k, sp) + np.testing.assert_array_equal(a.baseline, expect) + np.testing.assert_array_equal(b.baseline, expect) + assert np.isfinite(expect).all() # NaN corner: the fallback + # MATLAB's mode, or no solver parameters: no baseline is attached + assert c.subproblem(k).baseline is None + assert read_subproblem(out, k, SolverParams()).baseline is None + # a container without the baseline cannot feed a mode that needs it + bare = write_container( + tmp_path / "bare.h5", + trial, + np.array([[5, 1]]), + [groups[0]], + [[0]], + (H, W), + ) + assert not read_container(bare).baseline_filled + with pytest.raises(ValueError, match="no network baseline"): + read_subproblem(bare, 0, sp) + with pytest.raises(ValueError, match="no network baseline"): + read_container(bare).subproblem(0, sp) + + +def test_network_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: + """With the network's baseline (N1), streamed and staged runs agree. + + The streamed run, one job and three jobs give the same results and + summaries; the summaries record the baseline; the baseline changes the + results. + """ + root = tmp_path / "streamed" + table = make_session(root) + bdir = write_baselines(root, tmp_path / "baselines") + seeds = seeds_file(tmp_path) + silo.run_silo(table, NET, EX, seeds_file=seeds, baseline_dir=bdir) + s1 = SiloSession.open(table) + exp = s1.out_dir / "experiment_summary.h5" + streamed = _all_results(s1) + with h5py.File(exp, "r") as f: + assert f.attrs["baseline_source"] == "network" + assert f.attrs["baseline_mode"] == "gain" + used = json.loads(f.attrs["network_baseline"]) + assert len(used) == N_PATHS * N_TRIALS + first = used["path1_trial0001"] + assert first["file"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" + assert first["network"]["checkpoint"] == "ckpt/s6_test.pt" + assert first["network"]["step"] == 1700 + with h5py.File(s1.localize_file(0, 0), "r") as f: + assert f.attrs["localization_baseline"] == "network" + with h5py.File(s1.plan_file(0), "r") as f: + assert f.attrs["baseline_source"] == "network" + + for machines in (1, 3): + r2 = tmp_path / f"staged{machines}" + s2 = SiloSession.open(make_session(r2)) + silo.localize(s2, NET, EX, baseline_dir=bdir) + silo.plan(s2, NET, EX, seeds=_seeds(s2, tmp_path)) + silo.prepare(s2, NET, EX, baseline_dir=bdir) + c = read_container(s2.container_file(0, 0), data=False) + assert c.baseline_filled and c.params["baseline_source"] == "network" + for job in silo_solve.dispatch(s2, NET, machines, EX): + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(s2, NET, EX, baseline_dir=bdir) + staged = _all_results(s2) + assert staged.keys() == streamed.keys() + for key in staged: + for name, value in staged[key].items(): + np.testing.assert_array_equal(value, streamed[key][name]) + _equal(_summary(s2.out_dir / "experiment_summary.h5"), _summary(exp)) + + # the same run with MATLAB's baseline fit gives other results + r3 = tmp_path / "median" + silo.run_silo(make_session(r3), MEDIAN, EX, seeds_file=seeds) + s3 = SiloSession.open(r3 / "trial_table.h5") + median = _all_results(s3) + assert median.keys() == streamed.keys() + key = next(iter(median)) + assert not np.array_equal(median[key]["f0"], streamed[key]["f0"]) + with h5py.File(s3.out_dir / "experiment_summary.h5", "r") as f: + assert "baseline_source" not in f.attrs # as MATLAB writes it + + +def test_baseline_file_change_redoes_its_containers(tmp_path: Path, fake: None) -> None: + """The settings hash of a container covers its baseline file. + + MATLAB's algorithm keeps the hash it had before the network was wired in. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, root / "source_extraction" / "silo" / "baselines") + # localized with the moving median, extracted with the network: a new + # baseline file redoes its container only (with network localization it + # redoes the localization, hence the plan, first) + ext = replace( + NET, + localization_baseline="median", + localization_surround=True, + localization_null="none", + ) + silo.localize(s, ext, EX) + silo.plan(s, ext, EX, seeds=_seeds(s, tmp_path)) + assert len(silo.prepare(s, ext, EX)) == N_PATHS * N_TRIALS + assert silo.prepare(s, ext, EX) == [] # the default baselines folder + f = bdir / "E1T2DMD1_BASELINE-80Hz.h5" + with h5py.File(f, "a") as h: + h["baseline"][0, 0, 0] = 1.0 + redone = silo.prepare(s, ext, EX) + assert [r["unit"] for r in redone] == [(0, 1)] + # MATLAB's algorithm: the hash of the stage files before this change + ph = "abc" + old = stage_hash({ + "stage": "prepare", + "settings": MEDIAN.stage_settings("prepare"), + "plan": ph, + "unit": [0, 0], + "raw": recording_ids(s.raw(0, 0)), + "lines": [ + float(s.first_line[0, 0]), + float(s.last_line[0, 0]), + ], + "alignment": file_id(s.alignment(0, 0)), + }) + assert silo._prepare_hash(s, MEDIAN, ph, 0, 0) == old + assert silo._prepare_hash(s, NET, ph, 0, 0, f) != old + + +def test_stages_refuse_another_baseline(tmp_path: Path, fake: None) -> None: + """Each stage checks that the stage before it used the same baseline.""" + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + silo.localize(s, NET, EX, baseline_dir=bdir) + with pytest.raises(ValueError, match="localization_baseline='network'"): + silo.plan(s, MEDIAN, EX, seeds=_seeds(s, tmp_path)) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + with pytest.raises(ValueError, match="baseline_source='network'"): + silo.prepare(s, MEDIAN, EX) + # network localization and plan, MATLAB's baseline fit: no baseline + fit = replace(NET, baseline_mode="fit") + silo.prepare(s, fit, EX, baseline_dir=bdir) + assert not read_container(s.container_file(0, 0), data=False).baseline_filled + with pytest.raises(ValueError, match="has no network baseline"): + silo_solve.dispatch(s, NET, 2, EX) + with pytest.raises(ValueError, match="baseline_source='network'"): + silo_solve.dispatch(s, MEDIAN, 2, EX) + with pytest.raises(ValueError, match="baseline_source='network'"): + silo_collect.collect(s, MEDIAN, EX) + # a missing baseline file names itself and the ways to get it + (bdir / "E1T1DMD2_BASELINE-80Hz.h5").unlink() + with pytest.raises(FileNotFoundError, match="--f0-ckpt"): + silo.prepare(s, NET, EX, baseline_dir=bdir) + + +def _args(*argv: str) -> argparse.Namespace: + """Parse the arguments of a giant command line. + + Returns + ------- + argparse.Namespace + The parsed arguments. + """ + return build_parser().parse_args(list(argv)) + + +def test_cli_baseline_default() -> None: + """--baseline-dir or --f0-ckpt make the network the default. + + --baseline chooses; otherwise MATLAB's moving median. + """ + p = params_from_args(_args("silo", "t.h5")) + assert p.baseline_source == "median" and p.peak_th == 3.0 + p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b")) + assert p.baseline_source == "network" and p.peak_th == 3.0 + assert p.min_source_event_rate == 2.0 + p = params_from_args( + _args( + "silo", + "t.h5", + "--baseline-dir", + "b", + "--peak-th", + "8", + "--min-source-event-rate", + "0", + ) + ) + assert (p.peak_th, p.min_source_event_rate) == (8.0, 0.0) + p = params_from_args(_args("silo", "t.h5", "--f0-ckpt", "x.pt")) + assert p.baseline_source == "network" + p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b", "--baseline", "median")) + assert p.baseline_source == "median" + p = params_from_args(_args("silo-plan", "t.h5", "--baseline", "network")) + assert p.baseline_source == "network" and p.baseline_mode == "gain" + p = params_from_args(_args("silo-prepare", "t.h5", "--baseline-dir", "b", "--peak-th", "6")) + assert p.baseline_source == "network" and p.peak_th == 6.0 + p = params_from_args( + _args( + "silo-collect", + "t.h5", + "--set", + "baseline_source=median", + "--baseline-dir", + "b", + ) + ) + assert p.baseline_source == "median" + a = _args("silo", "t.h5", "--f0-ckpt", "x.pt", "--f0-device", "cpu") + assert a.f0_device == "cpu" and a.f0_command is None + + +def test_run_silo_default_source( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """run_silo: a dict or no params take the network with its baselines. + + A SiloParams is used as it is (with a warning that they are unused). + """ + root = tmp_path / "s" + table = make_session(root) + bdir = write_baselines(root, tmp_path / "b") + seen = [] + + def stop(session: SiloSession, params: SiloParams, *args: object, **kw: object) -> NoReturn: + """Record the params and stop the run. + + Raises + ------ + RuntimeError + Always, to stop the run. + """ + seen.append(params) + raise RuntimeError("stop") + + monkeypatch.setattr(silo, "_ready_paths", stop) + for params in (None, {"min_kinetic_score": 0.0}): + with pytest.raises(RuntimeError, match="stop"): + silo.run_silo(table, params, EX, baseline_dir=bdir) + assert seen[-1].baseline_source == "network" + with pytest.warns(UserWarning, match="not used"): + with pytest.raises(RuntimeError, match="stop"): + silo.run_silo(table, MEDIAN, EX, baseline_dir=bdir) + assert seen[-1].baseline_source == "median" + assert silo.default_baseline_source(None, False) is None + + +def test_predict_baselines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """--f0-ckpt runs slap2-f0 predict-registered once. + + It runs for the trial-paths without a baseline file, with the run's trial + preparation settings. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = tmp_path / "b" + write_baselines(root, bdir) + for t in (1, 2): + (bdir / f"E1T{t + 1}DMD2_BASELINE-80Hz.h5").unlink() + ckpt = tmp_path / "s6_test.pt" + ckpt.write_bytes(b"weights") + calls = [] + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: + """slap2-f0 stood in for: write the files asked for. + + Returns + ------- + subprocess.CompletedProcess[bytes] + A finished process for args with return code 0. + """ + calls.append(args) + keys = args[args.index("--files") + 1].split(",") + for k in keys: + stem = k[: -len("_REGISTERED")] + src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" + (bdir / f"{stem}_BASELINE-80Hz.h5").write_bytes(src.read_bytes()) + with h5py.File(bdir / f"{stem}_BASELINE-80Hz.h5", "a") as f: + f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" + return subprocess.CompletedProcess(args, 0) + + monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) + params = SiloParams(baseline_source="network", motion_thresh=1.5) + rec = silo_baseline.predict_baselines(s, params, bdir, ckpt, device="cpu") + assert rec["predicted"] == [[2, 2], [2, 3]] + assert rec["checkpoint"]["name"] == "s6_test.pt" + rec_ckpt = rec["checkpoint"] + assert len(rec["checkpoint"]["sha256"]) == 64 + (args,) = calls + assert args[:2] == ["/bin/slap2-f0", "predict-registered"] + assert args[args.index("--ckpt") + 1] == str(ckpt) + assert args[args.index("--out") + 1] == str(bdir) + assert args[args.index("--files") + 1] == ("E1T2DMD2_REGISTERED,E1T3DMD2_REGISTERED") + assert args[args.index("--motion_thresh") + 1] == "1.5" + assert args[args.index("--channel") + 1] == "1" + assert args[args.index("--device") + 1] == "cpu" + # nothing missing: nothing run + calls.clear() + assert silo_baseline.predict_baselines(s, params, bdir, ckpt)["predicted"] == [] + assert not calls + + # the predicted files have records: the prediction's settings, the + # inputs and the checkpoint as it was then + base = bdir / "E1T2DMD2_BASELINE-80Hz.h5" + rec = json.loads(silo_baseline.record_path(base).read_text()) + assert rec["settings"]["motion_thresh"] == 1.5 + assert rec["checkpoint"] == rec_ckpt + assert rec["movie"]["name"].startswith("E1T2DMD2_REGISTERED") + imported = bdir / "E1T1DMD1_BASELINE-80Hz.h5" + assert not silo_baseline.record_path(imported).exists() + ckpt.write_bytes(b"other weights") # overwritten after the prediction + trial = fake_load( + "x_DMD2-TRIAL000002.dat", + 1, + 2000, + None, + np.ones((H, W), bool), + None, + None, + None, + ) + tb = silo.load_trial_baseline(s, params, trial, base, 1, 1) + assert tb.identity["checkpoint"] == rec_ckpt + assert tb.identity["prediction"]["activity_channel"] == 1 + tb = silo.load_trial_baseline(s, params, trial, imported, 0, 0) + assert "checkpoint" not in tb.identity # not verified: path and step only + assert tb.identity["network"]["step"] == 1700 + # a baseline predicted with other settings is refused, not reused + other = replace(params, activity_channel=2) + with pytest.raises(ValueError, match="was predicted with"): + silo_baseline.predict_baselines(s, other, bdir, ckpt) + with pytest.raises(ValueError, match="was predicted with"): + silo.localize(s, other, EX, baseline_dir=bdir) + # a record of a file that was replaced since + with h5py.File(base, "a") as f: + f.attrs["step"] = 1800 + with pytest.raises(ValueError, match="does not describe"): + silo.localize(s, params, EX, baseline_dir=bdir) + silo_baseline.record_path(base).unlink() + ckpt.write_bytes(b"weights") + + # a failed or incomplete prediction is an error + (bdir / "E1T3DMD1_BASELINE-80Hz.h5").unlink() + # a trial with both movies, the newer not SILo's: refused before the GPU + moco = root / "motion_correction" + tif = moco / "E1T3DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" + h5 = tif.with_suffix(".h5") + h5.write_bytes(b"") + os.utime(h5, (tif.stat().st_mtime + 10, tif.stat().st_mtime + 10)) + with pytest.raises(ValueError, match="remove one of them"): + silo_baseline.predict_baselines(s, params, bdir, ckpt) + assert silo_baseline.f0_movie(moco, "E1T3DMD1") == h5 + h5.unlink() + monkeypatch.setattr( + silo_baseline.subprocess, + "run", + lambda args, **kw: subprocess.CompletedProcess(args, 3), + ) + with pytest.raises(RuntimeError, match="exited with 3"): + silo_baseline.predict_baselines(s, params, bdir, ckpt) + + # a run that writes a file and then fails: the file has its record, so + # a retry with other settings does not reuse it unchecked + def fail_after_one(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: + """Write the files, then fail. + + Returns + ------- + subprocess.CompletedProcess[bytes] + A finished process for args with return code 1. + """ + fake_run(args, **kw) + return subprocess.CompletedProcess(args, 1) + + monkeypatch.setattr(silo_baseline.subprocess, "run", fail_after_one) + with pytest.raises(RuntimeError, match="exited with 1"): + silo_baseline.predict_baselines(s, params, bdir, ckpt) + written = bdir / "E1T3DMD1_BASELINE-80Hz.h5" + rec = json.loads(silo_baseline.record_path(written).read_text()) + assert rec["baseline"]["name"] == written.name + with pytest.raises(ValueError, match="was predicted with"): + silo_baseline.predict_baselines(s, other, bdir, ckpt) + # stopped before the record got the file's identity: its settings hold + rec["baseline"] = None + silo_baseline.record_path(written).write_text(json.dumps(rec)) + args = (written, s.movie(0, 2), s.alignment(0, 2)) + assert silo_baseline.check_baseline_record(*args, params) is not None + with pytest.raises(ValueError, match="was predicted with"): + silo_baseline.check_baseline_record(*args, other) + written.unlink() + monkeypatch.setattr( + silo_baseline.subprocess, + "run", + lambda args, **kw: subprocess.CompletedProcess(args, 0), + ) + with pytest.raises(RuntimeError, match="E1T3DMD1"): + silo_baseline.predict_baselines(s, params, bdir, ckpt) + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: None) + with pytest.raises(FileNotFoundError, match="--f0-command"): + silo_baseline.predict_baselines(s, params, bdir, ckpt) + with pytest.raises(FileNotFoundError, match="no checkpoint"): + silo_baseline.predict_baselines(s, params, bdir, tmp_path / "x.pt") + + +def test_source_alone_redoes_plan_and_containers(tmp_path: Path, fake: None) -> None: + """baseline_source enters the plan and prepare hashes (when it is not MATLAB's). + + Changing it alone redoes those stages rather than reusing files that the + next stage would refuse. + """ + alt = SiloParams( + baseline_source="median", + localization_baseline="network", + localization_surround=False, + localization_null="bootstrap", + peak_th=3.0, + baseline_mode="gain", + min_kinetic_score=0.0, + min_source_event_rate=2.0, + ) + for stage in ("localize", "solve", "collect"): + assert alt.stage_settings(stage) == NET.stage_settings(stage) + for stage in ("plan", "prepare"): + assert alt.stage_settings(stage) != NET.stage_settings(stage) + assert "baseline_source" not in MEDIAN.stage_settings(stage) + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + silo.localize(s, NET, EX, baseline_dir=bdir) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, NET, EX, baseline_dir=bdir) + silo.plan(s, alt, EX, seeds=_seeds(s, tmp_path)) # redone, not reused + with h5py.File(s.plan_file(0), "r") as f: + assert f.attrs["baseline_source"] == "median" + assert len(silo.prepare(s, alt, EX, baseline_dir=bdir)) == 6 + with pytest.raises(ValueError, match="baseline_source='median'"): + silo.prepare(s, NET, EX, baseline_dir=bdir) + + +def test_earlier_network_defaults_are_localized_again(tmp_path: Path, fake: None) -> None: + """Files made with the network's defaults before 2026-11-28 are localized again. + + Files made with those defaults (peak_th 8, no evidence test) are + localized again with the current ones (peak_th is also the per-trial + peaks' threshold, and every later stage checks the hash of the one + before), so a run never mixes the two; the earlier defaults given as + options keep the files. + """ + old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) + s = SiloSession.open(make_session(tmp_path / "s")) + bdir = write_baselines(tmp_path / "s", tmp_path / "b") + silo.localize(s, old, EX, baseline_dir=bdir) + assert silo.localize_jobs(s, old, baseline_dir=bdir) == [] + every = silo.localize_jobs(s, NET, baseline_dir=bdir, overwrite=True) + assert len(silo.localize_jobs(s, NET, baseline_dir=bdir)) == len(every) + assert old.stage_settings("collect") != NET.stage_settings("collect") + assert old.stage_settings("solve") == NET.stage_settings("solve") + + +def test_collect_refuses_another_seed_threshold(tmp_path: Path, fake: None) -> None: + """Refuse a collect of a folder seeded with another peak_th. + + A standalone collect of a folder seeded with the network's earlier + default (peak_th 8) is refused under today's (3), which would record + peakth 3 and judge the sources' evidence against it; the earlier + settings collect it. + """ + old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) + s = SiloSession.open(make_session(tmp_path / "s")) + bdir = write_baselines(tmp_path / "s", tmp_path / "b") + silo.localize(s, old, EX, baseline_dir=bdir) + silo.plan(s, old, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, old, EX, baseline_dir=bdir) + for job in silo_solve.dispatch(s, old, 3, EX): + silo_solve.solve_job(job, execution=EX) + with pytest.raises(ValueError, match="seeded with peak_th=8.*--peak-th 8"): + silo_collect.collect(s, NET, EX, baseline_dir=bdir) + record = silo_collect.collect(s, old, EX, baseline_dir=bdir) + assert record is not None + with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: + assert float(np.ravel(f["params/peakth"][()])[0]) == 8.0 + + +def test_collect_refuses_another_seed_acceptance(tmp_path: Path, fake: None) -> None: + """A standalone collect of a plan seeded with the null threshold is refused. + + It is refused under the image threshold (whose evidence test would exempt + strong seeds that the null mode judges); its own settings collect it. + """ + null = replace(NET, seed_acceptance="null_sd", localization_keep_null=True) + assert null.evidence_judge_below is None + s = SiloSession.open(make_session(tmp_path / "s")) + bdir = write_baselines(tmp_path / "s", tmp_path / "b") + silo.localize(s, null, EX, baseline_dir=bdir) + silo.plan(s, null, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, null, EX, baseline_dir=bdir) + for job in silo_solve.dispatch(s, null, 3, EX): + silo_solve.solve_job(job, execution=EX) + with pytest.raises(ValueError, match="seed_acceptance='null_sd'"): + silo_collect.collect(s, NET, EX, baseline_dir=bdir) + assert silo_collect.collect(s, null, EX, baseline_dir=bdir) is not None + + +def test_unrecorded_network_localization_is_redone(tmp_path: Path, fake: None) -> None: + """A localization file without the record of its baseline counts as the median's. + + Such a file (made before the baseline was recorded) counts as the moving + median's: with the network's settings it is localized again, with MATLAB's + it is kept. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + silo.localize(s, NET, EX, baseline_dir=bdir) + assert silo.localize_jobs(s, NET, baseline_dir=bdir) == [] + with h5py.File(s.localize_file(1, 2), "a") as f: + del f.attrs["localization_baseline"] + jobs = silo.localize_jobs(s, NET, baseline_dir=bdir) + assert [j["unit"] for j in jobs] == [(1, 2)] + m = SiloSession.open(make_session(tmp_path / "m")) + silo.localize(m, MEDIAN, EX) + with h5py.File(m.localize_file(0, 1), "a") as f: + del f.attrs["localization_baseline"] + assert silo.localize_jobs(m, MEDIAN) == [] + + +def test_summary_records_the_baseline_of_the_results_used(tmp_path: Path, fake: None) -> None: + """The summary's network_baseline comes from the results files that are assembled. + + It does not come from earlier runs' files left in the folder. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + silo.localize(s, NET, EX, baseline_dir=bdir) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, NET, EX, baseline_dir=bdir) + for job in silo_solve.dispatch(s, NET, 3, EX): + silo_solve.solve_job(job, execution=EX) + shard = sorted(s.results_dir.glob("*_s*.h5"))[0] + stem = shard.name.split("_s")[0] + stale = s.results_dir / f"{stem}.h5" # sorts before the shards + assert not stale.exists() + stale.write_bytes(shard.read_bytes()) + with h5py.File(stale, "a") as f: + f.attrs["plan_hash"] = "an earlier plan" + f.attrs["network_baseline"] = json.dumps({"file": {"name": "old"}}) + with pytest.warns(UserWarning, match="left out"): + record = silo_collect.collect(s, NET, EX, baseline_dir=bdir) + used = record["network_baseline"][stem] + assert used["file"]["name"].endswith("_BASELINE-80Hz.h5") + with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: + assert json.loads(f.attrs["network_baseline"])[stem] == used + + +def test_baseline_from_another_movie_is_refused(tmp_path: Path, fake: None) -> None: + """A baseline file predicted from another movie than SILo reads is refused. + + The movie it was predicted from is its 'source'. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + with h5py.File(bdir / "E1T2DMD1_BASELINE-80Hz.h5", "a") as f: + f.attrs["source"] = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + with pytest.raises(ValueError, match="was predicted from"): + silo.localize(s, NET, EX, baseline_dir=bdir) + + +def test_collect_checks_baselines_without_movies(tmp_path: Path, fake: None) -> None: + """A collect machine without the registered movies still checks the baselines. + + It checks the results against the baseline files (named after the trial + table's movies): a replaced baseline leaves the results stale. + """ + root = tmp_path / "s" + table = make_session(root) + bdir = write_baselines(root, tmp_path / "b") + silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) + for movie in (root / "motion_correction").glob("*_REGISTERED_*"): + movie.unlink() + s = SiloSession.open(table, inputs="collect") + assert s.movie(0, 0) is None + silo_collect.collect(s, NET, EX, baseline_dir=bdir) + with h5py.File(bdir / "E1T1DMD2_BASELINE-80Hz.h5", "a") as f: + f["baseline"][0, 5, 5] = 1.0 + with pytest.warns(UserWarning, match="left out"): + with pytest.raises(FileNotFoundError, match="path 2, trial 1"): + silo_collect.collect(s, NET, EX, baseline_dir=bdir) + + +def test_localize_predicts_for_extraction_too( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """silo-localize --f0-ckpt predicts whenever a stage uses the network's baselines. + + It also predicts when localization alone uses the moving median. + """ + table = make_session(tmp_path / "s") + calls = [] + monkeypatch.setattr( + silo_baseline, + "predict_baselines", + lambda *a, **k: calls.append(a[1]) or {"predicted": []}, + ) + monkeypatch.setattr(silo, "localize", lambda *a, **k: []) + argv = ["silo-localize", str(table), "--f0-ckpt", "x.pt"] + assert main(argv + ["--localization-baseline", "median"]) == 0 + assert len(calls) == 1 and calls[0].baseline_mode == "gain" + assert main(argv + ["--baseline", "median"]) == 0 + assert len(calls) == 1 + + +def test_extraction_uses_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """Extraction refuses another baseline file than the trial was localized with. + + Here the stages are given different folders. + """ + import shutil + + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + a = write_baselines(root, tmp_path / "a") + b = tmp_path / "b" + # the same baselines, other files (new modification times) + shutil.copytree(a, b, copy_function=shutil.copy) + silo.localize(s, NET, EX, baseline_dir=a) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + with pytest.raises(ValueError, match="localized with another baseline"): + silo.prepare(s, NET, EX, baseline_dir=b) + assert len(silo.prepare(s, NET, EX, baseline_dir=a)) == 6 + + +def test_predict_units_may_be_a_generator(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The trial-paths to predict may be given as a generator.""" + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() + ckpt = tmp_path / "s6_test.pt" + ckpt.write_bytes(b"weights") + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + rec_args = [] + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: + """Write the one file asked for. + + Returns + ------- + subprocess.CompletedProcess[bytes] + A finished process for args with return code 0. + """ + rec_args.append(args) + src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" + dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" + dest.write_bytes(src.read_bytes()) + with h5py.File(dest, "a") as f: + f.attrs["source"] = "E1T2DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif" + return subprocess.CompletedProcess(args, 0) + + monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) + units = (u for u in [(0, 0), (1, 1)]) + rec = silo_baseline.predict_baselines(s, NET, bdir, ckpt, units, out_frames=512) + assert rec["predicted"] == [[2, 2]] + args = rec_args[-1] + assert args[args.index("--out_frames") + 1] == "512" + assert _args("silo", "t.h5", "--f0-out-frames", "256").f0_out_frames == 256 + + +def test_summary_records_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """The summary records the baseline that decided the seeds. + + Here the trials are localized with the network's baseline and extracted + with MATLAB's fit. + """ + root = tmp_path / "s" + table = make_session(root) + bdir = write_baselines(root, tmp_path / "b") + loc_only = replace(NET, baseline_mode="fit") + silo.run_silo(table, loc_only, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) + s = SiloSession.open(table) + with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: + assert f.attrs["baseline_mode"] == "fit" + assert "network_baseline" not in f.attrs # not extracted with it + loc = json.loads(f.attrs["localization_network_baseline"]) + assert len(loc) == N_PATHS * N_TRIALS + first = loc["path1_trial0001"] + assert first["file"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" + assert first["network"] == {"checkpoint": "ckpt/s6_test.pt", "step": 1700} + + +def test_localized_again_after_the_plan(tmp_path: Path, fake: None) -> None: + """Prepare and collect refuse a plan made before the trials were localized again. + + Trials localized again (here with other baseline files) after their plan + was made: prepare and collect refuse the stale plan and results instead + of reading the new localization's peaks and baselines. + """ + import shutil + + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + a = write_baselines(root, tmp_path / "a") + b = tmp_path / "b" + shutil.copytree(a, b, copy_function=shutil.copy) + silo.localize(s, NET, EX, baseline_dir=a) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, NET, EX, baseline_dir=a) + for job in silo_solve.dispatch(s, NET, 1, EX): + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(s, NET, EX, baseline_dir=a) + silo.localize(s, NET, EX, baseline_dir=b) # every trial again + with pytest.raises(ValueError, match="localized again since its plan"): + silo_collect.collect(s, NET, EX, baseline_dir=a) + with pytest.raises(ValueError, match="localized again since its plan"): + silo.prepare(s, NET, EX, baseline_dir=b) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) # made again: fine + assert len(silo.prepare(s, NET, EX, baseline_dir=b)) == 6 + + +def test_one_baseline_mode_per_run(tmp_path: Path, fake: None) -> None: + """Containers prepared with the network's baseline are not solved with MATLAB's fit. + + Their hash covers a baseline the fit does not use, so collect would take + the results for stale; results name the baseline only when the solver + used it. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + silo.localize(s, NET, EX, baseline_dir=bdir) + silo.plan(s, NET, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, NET, EX, baseline_dir=bdir) + fit = replace(NET, baseline_mode="fit") + with pytest.raises(ValueError, match="baseline_mode 'fit'"): + silo_solve.dispatch(s, fit, 1, EX) + job = silo_solve.dispatch(s, NET, 1, EX)[0] + with pytest.raises(ValueError, match="baseline_mode 'fit'"): + silo_solve.solve_container( + s.container_file(0, 0), + s.results_file(0, 0), + fit, + EX.solver_options(), + ) + silo_solve.solve_job(job, execution=EX) + with h5py.File(s.results_file(0, 0), "r") as h: + assert "network_baseline" in h.attrs + c = read_container(s.container_file(0, 0), data=False) + attrs = silo_solve.results_attrs(c, "c.h5", "h", (0, 1), 1, True, "r", fit, EX.solver_options()) + assert "network_baseline" not in attrs + + +def test_collect_checks_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """Collect refuses settings with another localization baseline than the trials'. + + It refuses settings whose localization baseline is not the one the trials + were localized with (the summary would mislabel them). + """ + root = tmp_path / "s" + table = make_session(root) + bdir = write_baselines(root, tmp_path / "b") + silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) + s = SiloSession.open(table) + median_loc = replace( + NET, + localization_baseline="median", + localization_surround=True, + localization_null="none", + ) + assert median_loc.stage_settings("solve") == NET.stage_settings("solve") + with pytest.raises(ValueError, match="localization_baseline='network'"): + silo_collect.collect(s, median_loc, EX, baseline_dir=bdir) + + +def test_one_checkpoint_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Baselines kept from an earlier prediction must match the given checkpoint. + + They must have been made with the given checkpoint (its SHA-256, not only + its name). + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + bdir = write_baselines(root, tmp_path / "b") + (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() + ckpt = tmp_path / "s6_test.pt" + ckpt.write_bytes(b"weights") + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: + """Write the one file asked for. + + Returns + ------- + subprocess.CompletedProcess[bytes] + A finished process for args with return code 0. + """ + src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" + dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" + dest.write_bytes(src.read_bytes()) + with h5py.File(dest, "a") as f: + f.attrs["source"] = "E1T2DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif" + return subprocess.CompletedProcess(args, 0) + + monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) + silo_baseline.predict_baselines(s, NET, bdir, ckpt) + assert silo_baseline.predict_baselines(s, NET, bdir, ckpt)["predicted"] == [] + ckpt.write_bytes(b"retrained weights") # same name, other model + with pytest.raises(ValueError, match="another checkpoint"): + silo_baseline.predict_baselines(s, NET, bdir, ckpt) + + +def _copy_tree(src: Path, dest: Path) -> Path: + """Copy a tree, giving its files new modification times. + + The copies have new modification times as a data asset's files carry + their upload times. + + Returns + ------- + Path + The destination folder, dest. + """ + import shutil + + shutil.copytree(src, dest, copy_function=shutil.copyfile) + for f in dest.rglob("*"): + if f.is_file(): + st = f.stat() + os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns + 7_000_000_000)) + return dest + + +def test_records_with_digests_identify_copied_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Records written with digests=True still identify copied files. + + They identify the baseline, movie and alignment files after they are + copied elsewhere (another modification time), and refuse a copy whose + content changed; records without digests refuse any copy, as before. + """ + root = tmp_path / "s" + s = SiloSession.open(make_session(root)) + for d in range(N_PATHS): # movies with content, so that digests differ + for t in range(N_TRIALS): + s.movie(d, t).write_bytes(bytes([d, t]) * 64) + bdir = tmp_path / "b" + write_baselines(root, bdir) + stem = "E1T2DMD2" + (bdir / f"{stem}_BASELINE-80Hz.h5").unlink() + ckpt = tmp_path / "s6_test.pt" + ckpt.write_bytes(b"weights") + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[bytes]: + """Write the file asked for. + + Returns + ------- + subprocess.CompletedProcess[bytes] + A finished process for args with return code 0. + """ + dest = bdir / f"{stem}_BASELINE-80Hz.h5" + dest.write_bytes((bdir / "E1T1DMD1_BASELINE-80Hz.h5").read_bytes()) + with h5py.File(dest, "a") as f: + f.attrs["source"] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" + return subprocess.CompletedProcess(args, 0) + + monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) + rec = silo_baseline.predict_baselines(s, NET, bdir, ckpt, digests=True) + assert rec["predicted"] == [[2, 2]] + base = bdir / f"{stem}_BASELINE-80Hz.h5" + record = json.loads(silo_baseline.record_path(base).read_text()) + for name, f in ( + ("baseline", base), + ("movie", s.movie(1, 1)), + ("alignment", s.alignment(1, 1)), + ): + assert record[name]["sha256"] == silo_baseline.file_sha256(f) + assert record[name]["mtime_ns"] == file_id(f)["mtime_ns"] + + # the registration and the baselines copied, as two data assets + root2 = _copy_tree(root, tmp_path / "asset_reg") + bdir2 = _copy_tree(bdir, tmp_path / "asset_base") + s2 = SiloSession.open(root2, moco_dir=root2 / "motion_correction") + base2 = bdir2 / base.name + assert file_id(base2)["mtime_ns"] != record["baseline"]["mtime_ns"] + args = (base2, s2.movie(1, 1), s2.alignment(1, 1)) + assert silo_baseline.check_baseline_record(*args, NET) == record + assert silo_baseline.same_file(record["movie"], s2.movie(1, 1)) + # the stages take the copies (the localization checks the record) + assert silo._network_baseline(s2, NET, 1, 1, bdir2) == base2 + # another movie than the one predicted from (same name and size) + other_movie = s2.movie(1, 1) + other_movie.write_bytes(bytes([9, 9]) * 64) + with pytest.raises(ValueError, match="from another movie"): + silo_baseline.check_baseline_record(*args, NET) + # a changed copy of the baseline (same name and size) + data = bytearray(base2.read_bytes()) + data[-1] ^= 0xFF + base2.write_bytes(bytes(data)) + with pytest.raises(ValueError, match="does not describe"): + silo_baseline.check_baseline_record(base2, None, args[2], NET) + + # without digests (the default) a copy is not identified + bdir3 = _copy_tree(bdir, tmp_path / "copy_plain") + rec3 = silo_baseline.record_path(bdir3 / base.name) + old = json.loads(rec3.read_text()) + for k in ("baseline", "movie", "alignment"): + old[k].pop("sha256") + rec3.write_text(json.dumps(old)) + with pytest.raises(ValueError, match="does not describe"): + silo_baseline.check_baseline_record(bdir3 / base.name, None, s.alignment(1, 1), NET) + assert not silo_baseline.same_file(None, base) diff --git a/tests/raster/test_raster_silo_noise_seeds.py b/tests/raster/test_raster_silo_noise_seeds.py index 14b787a0..1ffb2b43 100644 --- a/tests/raster/test_raster_silo_noise_seeds.py +++ b/tests/raster/test_raster_silo_noise_seeds.py @@ -1,36 +1,36 @@ -"""giant silo on the synthetic session with its own seeding (seeds in noise). - -Seeds placed in noise can end with an all-zero footprint, which made the -activity noise's normal matrix singular (numpy's inv raised where MATLAB's -warns); the run must complete. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.pipeline import silo -from giant_python.pipeline.silo_session import SiloSession - -# the fixture is used by name -from .test_raster_silo_stages import ( - EX, - PARAMS, - fake, # noqa: F401 - make_session, -) - - -@pytest.mark.filterwarnings("ignore::RuntimeWarning") -def test_own_seeding_in_noise_completes(tmp_path: Path, fake: None) -> None: # noqa: F811 - """Without a seeds file the session seeds itself. - - The run finishes and writes its summaries. - """ - table = make_session(tmp_path / "own") - report = silo.run_silo(table, PARAMS, EX) - s = SiloSession.open(table) - assert (s.out_dir / "experiment_summary.h5").exists() - assert report["total"] > 0 - assert np.isfinite(report["total"]) +"""giant silo on the synthetic session with its own seeding (seeds in noise). + +Seeds placed in noise can end with an all-zero footprint, which made the +activity noise's normal matrix singular (numpy's inv raised where MATLAB's +warns); the run must complete. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.pipeline import silo +from giant_python.pipeline.silo_session import SiloSession + +# the fixture is used by name +from .test_raster_silo_stages import ( + EX, + PARAMS, + fake, # noqa: F401 + make_session, +) + + +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_own_seeding_in_noise_completes(tmp_path: Path, fake: None) -> None: # noqa: F811 + """Without a seeds file the session seeds itself. + + The run finishes and writes its summaries. + """ + table = make_session(tmp_path / "own") + report = silo.run_silo(table, PARAMS, EX) + s = SiloSession.open(table) + assert (s.out_dir / "experiment_summary.h5").exists() + assert report["total"] > 0 + assert np.isfinite(report["total"]) diff --git a/tests/raster/test_raster_silo_params.py b/tests/raster/test_raster_silo_params.py index d3c8833f..dacdb186 100644 --- a/tests/raster/test_raster_silo_params.py +++ b/tests/raster/test_raster_silo_params.py @@ -1,468 +1,474 @@ -"""Tests of SILo's one parameter set and the types shared by its stages.""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import TrialWarp -from giant_python.extraction.raster.container import ( - read_container, - read_subproblem, - write_container, -) -from giant_python.extraction.raster.localization import ( - RasterLocalizationParams, -) -from giant_python.extraction.raster.plan import ( - PlanParams, - group_sources, - loader_warp, -) -from giant_python.extraction.raster.solver import SolverOptions -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, -) -from giant_python.extraction.raster.trial_data import ( - RigidShift, - TrialData, - TrialLoadParams, -) -from giant_python.io.hdf5 import write_matlab_value -from giant_python.models.params import ( - SiloExecution, - SiloParams, - resolve_silo_options, -) - -# GIAnT-MATLAB's /params of a SLAP2 SILo run (main 5a0673b): name, MATLAB -# size and class. Values of the scalars are checked below. -# the settings that make SiloParams MATLAB's algorithm (the defaults differ -# from it in the footprint fit and the seed fit) -MATLAB_ALGORITHM = dict( - footprint_variance="model", - seed_fit="matlab", - seed_merge_px=0.0, - valid_kernel=3, - f0_im_trim_s=None, -) - -MATLAB_FIELDS = { - "Bfilter": ((25, 25, 3), np.float64), - "Hfilter": ((9, 9), np.float64), - "VIF": ((1, 1), np.float64), - "activityChannel": ((1, 1), np.float64), - "alignHz": ((1, 1), np.float64), - "alignPatchPx": ((1, 1), np.float64), - "allowAnnotationGUI": ((1, 1), np.int8), - "analyzeHz": ((1, 1), np.float64), - "baselineWindow_Ca_s": ((1, 1), np.float64), - "baselineWindow_Glu_s": ((1, 1), np.float64), - "baselineWindow_samps": ((1, 1), np.float64), - "dXY": ((1, 1), np.float64), - "debiasVariance": ((1, 1), object), - "denoiseWindow_s": ((1, 1), np.float64), - "denoiseWindow_samps": ((1, 1), np.float64), - "discardInitial_s": ((1, 1), np.float64), - "drawUserRois": ((1, 1), np.int8), - "endTime": ((1, 1), object), - "includeIntegrationROIs": ((1, 1), np.int8), - "interTrialAlignment": ((1, 1), object), - "isSLAP2": ((1, 1), np.int8), - "k": ((1, 59), np.float64), - "k2": ((1, 361), np.float64), - "lambda": ((1, 1), np.float64), - "minBaseline": ((1, 1), np.float64), - "minKineticScore": ((1, 1), np.float64), - "minPeakDistance": ((1, 1), np.float64), - "motionThresh": ((1, 1), np.float64), - "nWorkers": ((1, 1), np.float64), - "nanThresh": ((1, 1), np.float64), - "nmfIter": ((1, 1), np.float64), - "numChannels": ((1, 1), np.float64), - "peakMethod": ((1, 1), object), - "peakth": ((1, 1), np.float64), - "phi": ((1, 1), np.float64), - "photonScale": ((1, 1), np.float64), - "saveSubproblemsDir": ((1, 1), object), - "selRadius": ((1, 1), np.float64), - "sigma_px": ((1, 1), np.float64), - "startTime": ((1, 1), object), - "tau2_s": ((1, 1), np.float64), - "tau2_samps": ((1, 1), np.float64), - "tau_full": ((1, 1), np.float64), - "tau_s": ((1, 1), np.float64), - "validKernel": ((3, 3), np.int8), - "wmfDeblendth": ((1, 1), np.float64), - "wmfDip": ((1, 1), np.float64), - "wmfPeakth": ((1, 1), np.float64), -} - -MATLAB_VALUES = { - "VIF": 1.67, - "activityChannel": 1, - "alignHz": 80, - "alignPatchPx": 1500, - "analyzeHz": 200, - "baselineWindow_Glu_s": 4, - "baselineWindow_samps": 800, - "dXY": 3, - "denoiseWindow_samps": 40, - "lambda": 0.9, - "minBaseline": 0.01, - "minKineticScore": 0.2, - "nanThresh": 0.33, - "nmfIter": 2, - "numChannels": 2, - "peakth": 3, - "photonScale": 25, - "selRadius": 6, - "tau2_samps": 30, - "tau_full": 4.8, - "wmfDeblendth": 8, -} - - -def test_defaults_are_matlabs_slap2_silo() -> None: - """The derived stage parameters keep each stage's MATLAB defaults.""" - p = SiloParams() - assert p.plan_params() == PlanParams() - assert p.load_params() == TrialLoadParams() - assert p.solver_params() == SolverParams() - loc = p.localization_params(80.0) - # peakth is 3 for SLAP2 in every stage (RasterLocalizationParams' own - # default, 8, is MATLAB's for other recordings) - assert loc.peak_th == 3.0 - from dataclasses import replace - - assert replace(loc, peak_th=8.0) == RasterLocalizationParams() - assert p.sel_radius == 6 - - -def test_footprint_default_is_the_solvers(monkeypatch: pytest.MonkeyPatch) -> None: - """The footprint fit's default comes from the solver, not from here.""" - from dataclasses import fields - - from giant_python.extraction.raster import solver_setup - - assert SiloParams().footprint_variance == SolverParams.footprint_variance - default = next( - f.default for f in fields(solver_setup.SolverParams) if f.name == "footprint_variance" - ) - assert SiloParams().solver_params().footprint_variance == default - monkeypatch.setattr(solver_setup.SolverParams, "footprint_variance", "model") - assert SiloParams().footprint_variance == "model" - assert SiloParams(footprint_variance="fixed").footprint_variance == ("fixed") - - -def test_one_setting_reaches_every_stage() -> None: - """A shared setting is passed to each stage that uses it.""" - p = SiloParams(sigma_px=1.5, nan_thresh=0.2, peak_th=4.0) - assert p.plan_params().sigma_px == 1.5 - assert p.solver_params().sigma_px == 1.5 - assert p.localization_params(80).sigma_px == 1.5 - assert p.plan_params().nan_thresh == 0.2 - assert p.load_params().nan_thresh == 0.2 - assert p.localization_params(80).nan_thresh == 0.2 - assert p.localization_params(80).peak_th == 4.0 - assert SiloParams(localization_peak_th=8.0).localization_params(80).peak_th == 8.0 - assert p.localization_params(123.0).align_hz == 123.0 - net = SiloParams(localization_baseline="network", localization_variance_floor=False) - assert net.localization_params(80).variance_floor is False - - -def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path: Path) -> None: - """Written as saveStructToH5 would, the struct of MATLAB's algorithm has MATLAB's schema.""" - m = SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0, 12, "a", "b") - assert set(m) == set(MATLAB_FIELDS) - path = tmp_path / "p.h5" - with h5py.File(path, "w") as f: - write_matlab_value(f, "params", m) - with h5py.File(path) as f: - g = f["params"] - for name, (size, cls) in MATLAB_FIELDS.items(): - # h5py shows MATLAB's dimensions reversed - assert g[name].shape == size[::-1], name - if cls is object: - assert g[name].dtype.kind == "O", name - else: - assert g[name].dtype == cls, name - for name, value in MATLAB_VALUES.items(): - assert g[name][()].item() == pytest.approx(value), name - assert g["debiasVariance"][()].item() == b"fixed" - assert g["peakMethod"][()].item() == b"getactimpeaks" - assert g["saveSubproblemsDir"][()].item() == b"" - assert g["isSLAP2"][()].item() == 1 - assert g["allowAnnotationGUI"][()].item() == 0 - sp = SolverParams() - np.testing.assert_array_equal(m["k"], sp.k) - np.testing.assert_array_equal(m["Bfilter"][:, :, 2], sp.bfilter[2]) - - -def test_python_only_settings_are_recorded_when_not_matlabs() -> None: - """MATLAB's algorithm has MATLAB's fields only. - - Other settings add one each, the defaults (fixed-variance footprint fit, - local seed fit with merging, F0 images) too. - """ - assert set(SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0)) == set(MATLAB_FIELDS) - assert set(SiloParams().to_matlab(2, 80.0)) - set(MATLAB_FIELDS) == { - "footprintVariance", - "seedFit", - "seedMergePx", - "F0imTrim_s", - } - m = SiloParams( - localization_baseline="network", - trial_peaks=False, - localization_peak_th=8.0, - seed_fit="matlab", - seed_merge_px=0.0, - f0_im_trim_s=None, - ).to_matlab(2, 80.0) - assert m["footprintVariance"] == "fixed" - assert m["localizationBaseline"] == "network" - assert m["trialPeaks"] == np.bool_(False) - assert m["localizationPeakth"] == 8.0 - assert set(m) - set(MATLAB_FIELDS) == { - "footprintVariance", - "localizationBaseline", - "trialPeaks", - "localizationPeakth", - } - - -@pytest.mark.parametrize( - "kwargs", - [ - {"sigma_px": 0}, - {"activity_channel": 0}, - {"activity_channel": 1.5}, - {"lam": -1}, - {"debias_variance": "other"}, - {"footprint_variance": "other"}, - {"localization_baseline": "other"}, - {"localization_null": "other"}, - {"trial_peaks": 1}, - {"min_frames": 0}, - {"nan_thresh": 1.1}, - {"localization_null_seed": -1}, - {"localization_null_seed": 1.5}, - {"localization_null_seed": True}, - # without the variance floor localization needs the network baseline - {"localization_variance_floor": False}, - {"min_kinetic_score": float("nan")}, - # the solver needs a baseline window longer than the denoise window - {"baseline_window_s": 0.1}, - {"seed_fit": "other"}, - {"seed_merge_px": -1.0}, - {"valid_kernel": 4}, - {"valid_kernel": 0}, - {"valid_kernel": -3}, - {"valid_kernel": 5.0}, - {"valid_kernel": True}, - ], -) -def test_invalid_values_are_rejected(kwargs: dict[str, object]) -> None: - """Values no stage can run with raise ValueError.""" - with pytest.raises(ValueError): - SiloParams(**kwargs) - - -def test_modes_not_ported_raise() -> None: - """WMF seeding is not ported yet.""" - with pytest.raises(NotImplementedError): - SiloParams(peak_method="wmf") - - -def test_alignment_modes() -> None: - """The three across-trial alignments are accepted and reach the plan stage. - - Others are rejected. The patch size counts in the plan's settings only - when it is not the default (plans made before it was a field stay - current). - """ - for mode in ("rigid", "affine", "patchwise"): - p = SiloParams(inter_trial_alignment=mode, align_patch_px=1200) - assert p.plan_params().inter_trial_alignment == mode - assert p.plan_params().align_patch_px == 1200 - with pytest.raises(ValueError, match="inter_trial_alignment"): - SiloParams(inter_trial_alignment="elastic") - assert "align_patch_px" not in SiloParams().stage_settings("plan") - assert SiloParams(align_patch_px=1000).stage_settings("plan")["align_patch_px"] == 1000 - assert SiloParams().stage_settings("localize") == SiloParams( - inter_trial_alignment="patchwise" - ).stage_settings("localize") - - -def test_stage_settings_change_only_with_their_fields() -> None: - """A solver setting changes the solve stage's settings only.""" - a, b = SiloParams(), SiloParams(lam=0.5) - for stage in ("localize", "plan", "prepare", "collect"): - assert a.stage_settings(stage) == b.stage_settings(stage) - assert a.stage_settings("solve") != b.stage_settings("solve") - assert a.stage_settings("plan") != SiloParams(peak_th=4.0).stage_settings("plan") - with pytest.raises(ValueError): - a.stage_settings("other") - - -def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes() -> None: - """The seed fit's defaults (local fits, merging within 1.5 px) are the plan stage's. - - They reach the plan and the per-trial peaks' stage and are in those - stages' settings, so outputs made with MATLAB's fit (the behaviour before - the options existed) are not current. Asking for MATLAB's fit leaves those - stages' settings as they were then. - """ - a = SiloParams() - assert ( - (a.seed_fit, a.seed_merge_px) - == ( - PlanParams.seed_fit, - PlanParams.seed_merge_px, - ) - == ("local", 1.5) - ) - assert (a.plan_params().seed_fit, a.plan_params().seed_merge_px) == ( - "local", - 1.5, - ) - matlab = SiloParams(seed_fit="matlab", seed_merge_px=0.0) - for stage in ("localize", "plan"): - assert a.stage_settings(stage)["seed_fit"] == "local" - assert a.stage_settings(stage)["seed_merge_px"] == 1.5 - assert "seed_fit" not in matlab.stage_settings(stage) - assert "seed_merge_px" not in matlab.stage_settings(stage) - for stage in ("prepare", "solve", "collect"): - assert a.stage_settings(stage) == matlab.stage_settings(stage) - m = a.to_matlab(2, 80.0) - assert (m["seedFit"], m["seedMergePx"]) == ("local", 1.5) - assert "seedFit" not in matlab.to_matlab(2, 80.0) - - -def test_valid_kernel_is_one_setting_for_plan_and_solver() -> None: - """The footprint support reaches the plan's zones and the solver together. - - The default is 5 x 5, one default for the three types; 3 (MATLAB's) - leaves every stage's settings as before the setting existed, so outputs - made then stay current with it; another value changes the plan's and - the solve's only; the saved params struct records validKernel at its - size. - """ - a, b = SiloParams(valid_kernel=3), SiloParams() - assert b.valid_kernel == PlanParams.valid_kernel == 5 - assert b.valid_kernel == SolverParams.valid_kernel - assert a.plan_params().valid_kernel == a.solver_params().valid_kernel == 3 - assert b.plan_params().valid_kernel == b.solver_params().valid_kernel == 5 - assert a.plan_params().zone_radius == 3 - assert b.plan_params().zone_radius == 4 - for stage in ("localize", "plan", "prepare", "solve", "collect"): - assert "valid_kernel" not in a.stage_settings(stage) - for stage in ("localize", "prepare", "collect"): - assert a.stage_settings(stage) == b.stage_settings(stage) - for stage in ("plan", "solve"): - assert b.stage_settings(stage) == { - **a.stage_settings(stage), - "valid_kernel": 5, - } - ma, mb = a.to_matlab(2, 80.0), b.to_matlab(2, 80.0) - assert set(ma) == set(mb) # validKernel is MATLAB's own field - np.testing.assert_array_equal(ma["validKernel"], np.ones((3, 3), bool)) - np.testing.assert_array_equal(mb["validKernel"], np.ones((5, 5), bool)) - - -def test_execution_options() -> None: - """Execution options validate and give the solver's options.""" - e = SiloExecution(device="cuda", dtype="float32", batch_bytes=1e8) - assert e.solver_options() == SolverOptions(device="cuda", dtype="float32", batch_bytes=1e8) - for bad in ( - {"solver_threads": 0}, - {"device": "gpu"}, - {"device": "cudax"}, - {"device": "cuda:"}, - {"device": "cuda:-1"}, - {"loader_device": "cpu:0"}, - {"dtype": "float16"}, - {"batch_bytes": -1.0}, - {"overwrite": 1}, - ): - with pytest.raises(ValueError): - SiloExecution(**bad) - assert SiloExecution(device="cuda:1").device == "cuda:1" - p, e = resolve_silo_options({"lam": 0.5}, {"workers": 2}) - assert p.lam == 0.5 and e.workers == 2 - with pytest.raises(TypeError): - resolve_silo_options({"nWorkers": 2}) - - -def _trial(sel: np.ndarray, n_frames: int = 30, seed: int = 0) -> TrialData: - """Build a trial with random data at the selected pixels of ``sel``.""" - rng = np.random.default_rng(seed) - cols, rows = np.nonzero(sel.T) - rc = np.stack([rows, cols], 1) - return TrialData( - y=rng.random((2, rows.size, n_frames)).astype(np.float32), - finv=(1 + rng.random((rows.size, n_frames))).astype(np.float32), - frame_lines=np.arange(1, n_frames + 1), - motion_r=np.zeros(n_frames), - motion_c=np.zeros(n_frames), - discard=np.zeros(n_frames, bool), - global_f=rng.random((2, n_frames)), - roi_f=np.zeros((0, 2, n_frames)), - roi_fsvd=np.zeros((0, 2, n_frames)), - pixel_rc=rc, - trial_rc=rc.astype(float), - photon_scale=25.0, - ) - - -def test_plan_groups_container_and_solver_share_one_type(tmp_path: Path) -> None: - """A plan group's subproblem equals the container's: the solver's type.""" - shape = (20, 24) - rows, cols = np.array([5, 6, 14]), np.array([5, 8, 17]) - sel = np.zeros(shape, bool) - for r, c in zip(rows, cols): - sel[max(r - 4, 0) : r + 5, max(c - 4, 0) : c + 5] = True - groups = group_sources(rows, cols, sel, zone_radius=3, sel_radius=6) - assert len(groups) == 2 - trial = _trial(sel) - direct = [g.subproblem(trial.y, trial.finv) for g in groups] - assert all(isinstance(s, Subproblem) for s in direct) - path = tmp_path / "c.h5" - write_container( - path, - trial, - np.stack([rows, cols], 1), - [g.pixels for g in groups], - [g.sources for g in groups], - shape, - ) - container = read_container(path) - for k, sub in enumerate(direct): - for got in (container.subproblem(k), read_subproblem(path, k)): - assert isinstance(got, Subproblem) - for name in ("y", "finv", "sel", "sources_rc", "pixels"): - np.testing.assert_array_equal(getattr(got, name), getattr(sub, name)) - np.testing.assert_array_equal(got.sources, sub.sources) - assert (got.row0, got.col0) == (sub.row0, sub.col0) - - -def test_loader_warp() -> None: - """A shift reaches the loader as a RigidShift. - - An affine map reaches it as a function of zero-based coordinates; an - unaligned trial raises. - """ - warp = TrialWarp.from_shifts(np.array([[1.5, -2.0], [np.nan, np.nan]])) - w = loader_warp(warp, 0) - assert w == RigidShift(1.5, -2.0) - with pytest.raises(ValueError): - loader_warp(warp, 1) - affine = np.array([[[1.0, 0.1, 0.5], [0.0, 1.0, -1.0]]]) - warp = TrialWarp(affine) - f = loader_warp(warp, 0) - r, c = f(np.array([2.0]), np.array([3.0])) - np.testing.assert_allclose(r, [2 + 0.3 + 0.5]) - np.testing.assert_allclose(c, [3 - 1.0]) +"""Tests of SILo's one parameter set and the types shared by its stages.""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import TrialWarp +from giant_python.extraction.raster.container import ( + read_container, + read_subproblem, + write_container, +) +from giant_python.extraction.raster.localization import ( + RasterLocalizationParams, +) +from giant_python.extraction.raster.plan import ( + PlanParams, + group_sources, + loader_warp, +) +from giant_python.extraction.raster.solver import SolverOptions +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, +) +from giant_python.extraction.raster.trial_data import ( + RigidShift, + TrialData, + TrialLoadParams, +) +from giant_python.io.hdf5 import write_matlab_value +from giant_python.models.params import ( + SiloExecution, + SiloParams, + resolve_silo_options, +) + +# GIAnT-MATLAB's /params of a SLAP2 SILo run (main 5a0673b): name, MATLAB +# size and class. Values of the scalars are checked below. +# the settings that make SiloParams MATLAB's algorithm (the defaults differ +# from it in the footprint fit and the seed fit) +MATLAB_ALGORITHM = dict( + footprint_variance="model", + seed_fit="matlab", + seed_merge_px=0.0, + valid_kernel=3, + f0_im_trim_s=None, +) + +MATLAB_FIELDS = { + "Bfilter": ((25, 25, 3), np.float64), + "Hfilter": ((9, 9), np.float64), + "VIF": ((1, 1), np.float64), + "activityChannel": ((1, 1), np.float64), + "alignHz": ((1, 1), np.float64), + "alignPatchPx": ((1, 1), np.float64), + "allowAnnotationGUI": ((1, 1), np.int8), + "analyzeHz": ((1, 1), np.float64), + "baselineWindow_Ca_s": ((1, 1), np.float64), + "baselineWindow_Glu_s": ((1, 1), np.float64), + "baselineWindow_samps": ((1, 1), np.float64), + "dXY": ((1, 1), np.float64), + "debiasVariance": ((1, 1), object), + "denoiseWindow_s": ((1, 1), np.float64), + "denoiseWindow_samps": ((1, 1), np.float64), + "discardInitial_s": ((1, 1), np.float64), + "drawUserRois": ((1, 1), np.int8), + "endTime": ((1, 1), object), + "includeIntegrationROIs": ((1, 1), np.int8), + "interTrialAlignment": ((1, 1), object), + "isSLAP2": ((1, 1), np.int8), + "k": ((1, 59), np.float64), + "k2": ((1, 361), np.float64), + "lambda": ((1, 1), np.float64), + "minBaseline": ((1, 1), np.float64), + "minKineticScore": ((1, 1), np.float64), + "minPeakDistance": ((1, 1), np.float64), + "motionThresh": ((1, 1), np.float64), + "nWorkers": ((1, 1), np.float64), + "nanThresh": ((1, 1), np.float64), + "nmfIter": ((1, 1), np.float64), + "numChannels": ((1, 1), np.float64), + "peakMethod": ((1, 1), object), + "peakth": ((1, 1), np.float64), + "phi": ((1, 1), np.float64), + "photonScale": ((1, 1), np.float64), + "saveSubproblemsDir": ((1, 1), object), + "selRadius": ((1, 1), np.float64), + "sigma_px": ((1, 1), np.float64), + "startTime": ((1, 1), object), + "tau2_s": ((1, 1), np.float64), + "tau2_samps": ((1, 1), np.float64), + "tau_full": ((1, 1), np.float64), + "tau_s": ((1, 1), np.float64), + "validKernel": ((3, 3), np.int8), + "wmfDeblendth": ((1, 1), np.float64), + "wmfDip": ((1, 1), np.float64), + "wmfPeakth": ((1, 1), np.float64), +} + +MATLAB_VALUES = { + "VIF": 1.67, + "activityChannel": 1, + "alignHz": 80, + "alignPatchPx": 1500, + "analyzeHz": 200, + "baselineWindow_Glu_s": 4, + "baselineWindow_samps": 800, + "dXY": 3, + "denoiseWindow_samps": 40, + "lambda": 0.9, + "minBaseline": 0.01, + "minKineticScore": 0.2, + "nanThresh": 0.33, + "nmfIter": 2, + "numChannels": 2, + "peakth": 3, + "photonScale": 25, + "selRadius": 6, + "tau2_samps": 30, + "tau_full": 4.8, + "wmfDeblendth": 8, +} + + +def test_defaults_are_matlabs_slap2_silo() -> None: + """The derived stage parameters keep each stage's MATLAB defaults.""" + p = SiloParams() + assert p.plan_params() == PlanParams() + assert p.load_params() == TrialLoadParams() + assert p.solver_params() == SolverParams() + loc = p.localization_params(80.0) + # peakth is 3 for SLAP2 in every stage (RasterLocalizationParams' own + # default, 8, is MATLAB's for other recordings) + assert loc.peak_th == 3.0 + from dataclasses import replace + + assert replace(loc, peak_th=8.0) == RasterLocalizationParams() + assert p.sel_radius == 6 + + +def test_footprint_default_is_the_solvers(monkeypatch: pytest.MonkeyPatch) -> None: + """The footprint fit's default comes from the solver, not from here.""" + from dataclasses import fields + + from giant_python.extraction.raster import solver_setup + + assert SiloParams().footprint_variance == SolverParams.footprint_variance + default = next( + f.default for f in fields(solver_setup.SolverParams) if f.name == "footprint_variance" + ) + assert SiloParams().solver_params().footprint_variance == default + monkeypatch.setattr(solver_setup.SolverParams, "footprint_variance", "model") + assert SiloParams().footprint_variance == "model" + assert SiloParams(footprint_variance="fixed").footprint_variance == ("fixed") + + +def test_one_setting_reaches_every_stage() -> None: + """A shared setting is passed to each stage that uses it.""" + p = SiloParams(sigma_px=1.5, nan_thresh=0.2, peak_th=4.0) + assert p.plan_params().sigma_px == 1.5 + assert p.solver_params().sigma_px == 1.5 + assert p.localization_params(80).sigma_px == 1.5 + assert p.plan_params().nan_thresh == 0.2 + assert p.load_params().nan_thresh == 0.2 + assert p.localization_params(80).nan_thresh == 0.2 + assert p.localization_params(80).peak_th == 4.0 + assert SiloParams(localization_peak_th=8.0).localization_params(80).peak_th == 8.0 + assert p.localization_params(123.0).align_hz == 123.0 + net = SiloParams(localization_baseline="network", localization_variance_floor=False) + assert net.localization_params(80).variance_floor is False + + +def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path: Path) -> None: + """Written as saveStructToH5 would, the struct of MATLAB's algorithm has MATLAB's schema.""" + m = SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0, 12, "a", "b") + assert set(m) == set(MATLAB_FIELDS) + path = tmp_path / "p.h5" + with h5py.File(path, "w") as f: + write_matlab_value(f, "params", m) + with h5py.File(path) as f: + g = f["params"] + for name, (size, cls) in MATLAB_FIELDS.items(): + # h5py shows MATLAB's dimensions reversed + assert g[name].shape == size[::-1], name + if cls is object: + assert g[name].dtype.kind == "O", name + else: + assert g[name].dtype == cls, name + for name, value in MATLAB_VALUES.items(): + assert g[name][()].item() == pytest.approx(value), name + assert g["debiasVariance"][()].item() == b"fixed" + assert g["peakMethod"][()].item() == b"getactimpeaks" + assert g["saveSubproblemsDir"][()].item() == b"" + assert g["isSLAP2"][()].item() == 1 + assert g["allowAnnotationGUI"][()].item() == 0 + sp = SolverParams() + np.testing.assert_array_equal(m["k"], sp.k) + np.testing.assert_array_equal(m["Bfilter"][:, :, 2], sp.bfilter[2]) + + +def test_python_only_settings_are_recorded_when_not_matlabs() -> None: + """MATLAB's algorithm has MATLAB's fields only. + + Other settings add one each, the defaults (fixed-variance footprint fit, + local seed fit with merging, F0 images) too. + """ + assert set(SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0)) == set(MATLAB_FIELDS) + assert set(SiloParams().to_matlab(2, 80.0)) - set(MATLAB_FIELDS) == { + "footprintVariance", + "seedFit", + "seedMergePx", + "F0imTrim_s", + } + m = SiloParams( + localization_baseline="network", + trial_peaks=False, + localization_peak_th=8.0, + seed_fit="matlab", + seed_merge_px=0.0, + f0_im_trim_s=None, + ).to_matlab(2, 80.0) + assert m["footprintVariance"] == "fixed" + assert m["localizationBaseline"] == "network" + assert m["trialPeaks"] == np.bool_(False) + assert m["localizationPeakth"] == 8.0 + assert set(m) - set(MATLAB_FIELDS) == { + "footprintVariance", + "localizationBaseline", + "trialPeaks", + "localizationPeakth", + } + + +@pytest.mark.parametrize( + "kwargs", + [ + {"sigma_px": 0}, + {"activity_channel": 0}, + {"activity_channel": 1.5}, + {"lam": -1}, + {"debias_variance": "other"}, + {"footprint_variance": "other"}, + {"localization_baseline": "other"}, + {"localization_null": "other"}, + {"trial_peaks": 1}, + {"min_frames": 0}, + {"nan_thresh": 1.1}, + {"localization_null_seed": -1}, + {"localization_null_seed": 1.5}, + {"localization_null_seed": True}, + # without the variance floor localization needs the network baseline + {"localization_variance_floor": False}, + {"min_kinetic_score": float("nan")}, + # the solver needs a baseline window longer than the denoise window + {"baseline_window_s": 0.1}, + {"seed_fit": "other"}, + {"seed_merge_px": -1.0}, + {"valid_kernel": 4}, + {"valid_kernel": 0}, + {"valid_kernel": -3}, + {"valid_kernel": 5.0}, + {"valid_kernel": True}, + ], +) +def test_invalid_values_are_rejected(kwargs: dict[str, object]) -> None: + """Values no stage can run with raise ValueError.""" + with pytest.raises(ValueError): + SiloParams(**kwargs) + + +def test_modes_not_ported_raise() -> None: + """WMF seeding is not ported yet.""" + with pytest.raises(NotImplementedError): + SiloParams(peak_method="wmf") + + +def test_alignment_modes() -> None: + """The three across-trial alignments are accepted and reach the plan stage. + + Others are rejected. The patch size counts in the plan's settings only + when it is not the default (plans made before it was a field stay + current). + """ + for mode in ("rigid", "affine", "patchwise"): + p = SiloParams(inter_trial_alignment=mode, align_patch_px=1200) + assert p.plan_params().inter_trial_alignment == mode + assert p.plan_params().align_patch_px == 1200 + with pytest.raises(ValueError, match="inter_trial_alignment"): + SiloParams(inter_trial_alignment="elastic") + assert "align_patch_px" not in SiloParams().stage_settings("plan") + assert SiloParams(align_patch_px=1000).stage_settings("plan")["align_patch_px"] == 1000 + assert SiloParams().stage_settings("localize") == SiloParams( + inter_trial_alignment="patchwise" + ).stage_settings("localize") + + +def test_stage_settings_change_only_with_their_fields() -> None: + """A solver setting changes the solve stage's settings only.""" + a, b = SiloParams(), SiloParams(lam=0.5) + for stage in ("localize", "plan", "prepare", "collect"): + assert a.stage_settings(stage) == b.stage_settings(stage) + assert a.stage_settings("solve") != b.stage_settings("solve") + assert a.stage_settings("plan") != SiloParams(peak_th=4.0).stage_settings("plan") + with pytest.raises(ValueError): + a.stage_settings("other") + + +def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes() -> None: + """The seed fit's defaults (local fits, merging within 1.5 px) are the plan stage's. + + They reach the plan and the per-trial peaks' stage and are in those + stages' settings, so outputs made with MATLAB's fit (the behaviour before + the options existed) are not current. Asking for MATLAB's fit leaves those + stages' settings as they were then. + """ + a = SiloParams() + assert ( + (a.seed_fit, a.seed_merge_px) + == ( + PlanParams.seed_fit, + PlanParams.seed_merge_px, + ) + == ("local", 1.5) + ) + assert (a.plan_params().seed_fit, a.plan_params().seed_merge_px) == ( + "local", + 1.5, + ) + matlab = SiloParams(seed_fit="matlab", seed_merge_px=0.0) + for stage in ("localize", "plan"): + assert a.stage_settings(stage)["seed_fit"] == "local" + assert a.stage_settings(stage)["seed_merge_px"] == 1.5 + assert "seed_fit" not in matlab.stage_settings(stage) + assert "seed_merge_px" not in matlab.stage_settings(stage) + for stage in ("prepare", "solve", "collect"): + assert a.stage_settings(stage) == matlab.stage_settings(stage) + m = a.to_matlab(2, 80.0) + assert (m["seedFit"], m["seedMergePx"]) == ("local", 1.5) + assert "seedFit" not in matlab.to_matlab(2, 80.0) + + +def test_valid_kernel_is_one_setting_for_plan_and_solver() -> None: + """The footprint support reaches the plan's zones and the solver together. + + The default is 5 x 5, one default for the three types; 3 (MATLAB's) + leaves every stage's settings as before the setting existed, so outputs + made then stay current with it; another value changes the plan's and + the solve's only; the saved params struct records validKernel at its + size. + """ + a, b = SiloParams(valid_kernel=3), SiloParams() + assert b.valid_kernel == PlanParams.valid_kernel == 5 + assert b.valid_kernel == SolverParams.valid_kernel + assert a.plan_params().valid_kernel == a.solver_params().valid_kernel == 3 + assert b.plan_params().valid_kernel == b.solver_params().valid_kernel == 5 + assert a.plan_params().zone_radius == 3 + assert b.plan_params().zone_radius == 4 + for stage in ("localize", "plan", "prepare", "solve", "collect"): + assert "valid_kernel" not in a.stage_settings(stage) + for stage in ("localize", "prepare", "collect"): + assert a.stage_settings(stage) == b.stage_settings(stage) + for stage in ("plan", "solve"): + assert b.stage_settings(stage) == { + **a.stage_settings(stage), + "valid_kernel": 5, + } + ma, mb = a.to_matlab(2, 80.0), b.to_matlab(2, 80.0) + assert set(ma) == set(mb) # validKernel is MATLAB's own field + np.testing.assert_array_equal(ma["validKernel"], np.ones((3, 3), bool)) + np.testing.assert_array_equal(mb["validKernel"], np.ones((5, 5), bool)) + + +def test_execution_options() -> None: + """Execution options validate and give the solver's options.""" + e = SiloExecution(device="cuda", dtype="float32", batch_bytes=1e8) + assert e.solver_options() == SolverOptions(device="cuda", dtype="float32", batch_bytes=1e8) + for bad in ( + {"solver_threads": 0}, + {"device": "gpu"}, + {"device": "cudax"}, + {"device": "cuda:"}, + {"device": "cuda:-1"}, + {"loader_device": "cpu:0"}, + {"dtype": "float16"}, + {"batch_bytes": -1.0}, + {"overwrite": 1}, + ): + with pytest.raises(ValueError): + SiloExecution(**bad) + assert SiloExecution(device="cuda:1").device == "cuda:1" + p, e = resolve_silo_options({"lam": 0.5}, {"workers": 2}) + assert p.lam == 0.5 and e.workers == 2 + with pytest.raises(TypeError): + resolve_silo_options({"nWorkers": 2}) + + +def _trial(sel: np.ndarray, n_frames: int = 30, seed: int = 0) -> TrialData: + """Build a trial with random data at the selected pixels of sel. + + Returns + ------- + TrialData + The trial, with random data at the pixels of sel and no discarded frames. + """ + rng = np.random.default_rng(seed) + cols, rows = np.nonzero(sel.T) + rc = np.stack([rows, cols], 1) + return TrialData( + y=rng.random((2, rows.size, n_frames)).astype(np.float32), + finv=(1 + rng.random((rows.size, n_frames))).astype(np.float32), + frame_lines=np.arange(1, n_frames + 1), + motion_r=np.zeros(n_frames), + motion_c=np.zeros(n_frames), + discard=np.zeros(n_frames, bool), + global_f=rng.random((2, n_frames)), + roi_f=np.zeros((0, 2, n_frames)), + roi_fsvd=np.zeros((0, 2, n_frames)), + pixel_rc=rc, + trial_rc=rc.astype(float), + photon_scale=25.0, + ) + + +def test_plan_groups_container_and_solver_share_one_type(tmp_path: Path) -> None: + """A plan group's subproblem equals the container's: the solver's type.""" + shape = (20, 24) + rows, cols = np.array([5, 6, 14]), np.array([5, 8, 17]) + sel = np.zeros(shape, bool) + for r, c in zip(rows, cols): + sel[max(r - 4, 0) : r + 5, max(c - 4, 0) : c + 5] = True + groups = group_sources(rows, cols, sel, zone_radius=3, sel_radius=6) + assert len(groups) == 2 + trial = _trial(sel) + direct = [g.subproblem(trial.y, trial.finv) for g in groups] + assert all(isinstance(s, Subproblem) for s in direct) + path = tmp_path / "c.h5" + write_container( + path, + trial, + np.stack([rows, cols], 1), + [g.pixels for g in groups], + [g.sources for g in groups], + shape, + ) + container = read_container(path) + for k, sub in enumerate(direct): + for got in (container.subproblem(k), read_subproblem(path, k)): + assert isinstance(got, Subproblem) + for name in ("y", "finv", "sel", "sources_rc", "pixels"): + np.testing.assert_array_equal(getattr(got, name), getattr(sub, name)) + np.testing.assert_array_equal(got.sources, sub.sources) + assert (got.row0, got.col0) == (sub.row0, sub.col0) + + +def test_loader_warp() -> None: + """A shift reaches the loader as a RigidShift. + + An affine map reaches it as a function of zero-based coordinates; an + unaligned trial raises. + """ + warp = TrialWarp.from_shifts(np.array([[1.5, -2.0], [np.nan, np.nan]])) + w = loader_warp(warp, 0) + assert w == RigidShift(1.5, -2.0) + with pytest.raises(ValueError): + loader_warp(warp, 1) + affine = np.array([[[1.0, 0.1, 0.5], [0.0, 1.0, -1.0]]]) + warp = TrialWarp(affine) + f = loader_warp(warp, 0) + r, c = f(np.array([2.0]), np.array([3.0])) + np.testing.assert_allclose(r, [2 + 0.3 + 0.5]) + np.testing.assert_allclose(c, [3 - 1.0]) diff --git a/tests/raster/test_raster_silo_stages.py b/tests/raster/test_raster_silo_stages.py index 9977d15c..3318b357 100644 --- a/tests/raster/test_raster_silo_stages.py +++ b/tests/raster/test_raster_silo_stages.py @@ -1,759 +1,842 @@ -"""SILo's stages and driver on a small synthetic session. - -The registered movies and the raw data are stood in for: localization and -trial loading are replaced by functions that return synthetic images and -200 Hz data (with known sources), so that the stages' plumbing (files, -settings hashes, skipping, shards, assembly, summaries) is tested with the -real plan stage, solver, kinetics test and writers. -""" - -from collections.abc import Callable, Sequence -from concurrent.futures import Future -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -import torch -from numpy.typing import ArrayLike, DTypeLike - -from giant_python.cli import build_parser, main -from giant_python.cli_silo import params_from_args, parse_numbers -from giant_python.extraction.raster import trial as trial_mod -from giant_python.extraction.raster import trial_data as trial_data_mod -from giant_python.extraction.raster.localization import ( - RasterLocalization, - RasterLocalizationParams, -) -from giant_python.extraction.raster.plan import read_plan -from giant_python.extraction.raster.results import read_results -from giant_python.extraction.raster.trial import RegisteredTrial -from giant_python.extraction.raster.trial_data import TrialAlignment, TrialData, TrialLoadParams -from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 -from giant_python.models.params import SiloExecution, SiloParams -from giant_python.pipeline import silo, silo_collect, silo_solve -from giant_python.pipeline.silo_session import SiloSession - -H, W = 24, 30 -N_PATHS, N_TRIALS = 2, 3 -SOURCES = np.array([[6, 7], [8, 9], [15, 20], [18, 8]]) -FRAMES = {0: 260, 1: 240, 2: 60} # trial 3 is too short to extract -SHIFTS = {0: (0, 0), 1: (1, -1), 2: (0, 1)} - - -def _blobs( - amplitude: Sequence[float], sigma: float = 1.3, shift: tuple[int, int] = (0, 0) -) -> np.ndarray: - """Gaussian blobs at the sources (moved into a trial's frame).""" - r, c = np.mgrid[:H, :W] - img = np.zeros((H, W)) - for (sr, sc), a in zip(SOURCES, amplitude): - img += a * np.exp(-((r - sr - shift[0]) ** 2 + (c - sc - shift[1]) ** 2) / (2 * sigma**2)) - return img - - -def fake_localize( - moco_dir: str | Path, - fn: str, - num_channels: int, - params: RasterLocalizationParams | None = None, - **kw: object, -) -> tuple[RasterLocalization, RegisteredTrial]: - """Images of a localized trial (instead of reading its movie).""" - t = int(fn.split("T")[1][0]) - 1 - rng = np.random.default_rng(t) - shift = SHIFTS[t] - act = _blobs([30, 25, 40, 20], shift=shift) + rng.random((H, W)) - mean = np.stack([_blobs([5, 5, 5, 5], 3, shift) + 10, np.full((H, W), 4.0)], 2) - loc = RasterLocalization( - act_im=act, - summary=act, - peaks=None, - valid=np.ones((H, W), bool), - ) - half_ims = None - if kw.get("half_ims"): # two noisy halves, as the patchwise plan needs - noise = 0.05 * rng.standard_normal((2,) + mean.shape) - half_ims = (mean[None] + noise).astype(np.float32) - reg = RegisteredTrial( - movie=np.zeros((1, H, W), np.float32), - var_factor=None, - mean_im=mean.astype(np.float32), - discard=np.zeros(50, bool), - align_hz=80.0, - half_ims=half_ims, - ) - return loc, reg - - -def fake_load( - dat_path: str | Path, - first_line: float, - last_line: float, - alignment: TrialAlignment | str | Path, - sel_pix: np.ndarray, - warp: Callable, - discard_frames: ArrayLike, - mean_image: np.ndarray, - roi_masks: Sequence[np.ndarray] = (), - params: TrialLoadParams | None = None, - device: str | torch.device = "cpu", - dtype: DTypeLike = np.float32, -) -> TrialData: - """Make a trial at the selected pixels: baseline plus sources with events.""" - name = Path(dat_path).name - t = int(name.split("TRIAL")[1][:6]) - 1 - d = int(name.split("DMD")[1][0]) - 1 - n = FRAMES[t] - rng = np.random.default_rng(100 * d + t) - cols, rows = np.nonzero(np.asarray(sel_pix).T) - y = np.full((2, rows.size, n), 2.0) - k = np.exp(-np.arange(30) / 4.8) - for sr, sc in SOURCES: - fp = np.exp(-((rows - sr) ** 2 + (cols - sc) ** 2) / (2 * 1.3**2)) - ev = (rng.random(n) < 0.03) * rng.uniform(2, 6, n) - trace = np.convolve(ev, k)[:n] - y[0] += fp[:, None] * trace[None] - y = rng.poisson(y * 25) / 25.0 - return TrialData( - y=y.astype(dtype), - finv=np.ones((rows.size, n), dtype), - frame_lines=np.arange(n) * 8 + 1 + 1000 * t, - motion_r=np.zeros(n), - motion_c=np.zeros(n), - discard=np.arange(n) % 50 == 0, - global_f=rng.random((2, n)), - roi_f=rng.random((len(roi_masks), 2, n)), - roi_fsvd=rng.random((len(roi_masks), 2, n)), - pixel_rc=np.stack([rows, cols], 1), - trial_rc=np.stack([rows, cols], 1).astype(float), - photon_scale=25.0, - ) - - -def make_session(root: Path) -> Path: - """Trial table, alignment files and empty movies and raw files.""" - moco, raw = root / "motion_correction", root / "raw" - moco.mkdir(parents=True) - raw.mkdir() - fn = np.empty((N_PATHS, N_TRIALS), object) - reg = np.empty_like(fn) - adata = np.empty_like(fn) - for d in range(N_PATHS): - for t in range(N_TRIALS): - fn[d, t] = f"x_DMD{d + 1}-TRIAL{t + 1:06d}.dat" - stem = f"E1T{t + 1}DMD{d + 1}" - reg[d, t] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" - adata[d, t] = f"{stem}_ALIGNMENTDATA.h5" - (raw / fn[d, t]).write_bytes(b"") - (moco / reg[d, t]).write_bytes(b"") - n_ds = 6 - save_struct_h5( - moco / adata[d, t], - { - "numChannels": 2.0, - "alignHz": 80.0, - "DSframes": np.linspace(1, FRAMES[t] * 8, n_ds) + 1000 * t, - "motionDSr": np.linspace(0, 0.5, n_ds), - "motionDSc": np.linspace(0.2, 0, n_ds), - "slap2": { - "Z_depths": np.float32(-20.0), - "onlineMotionXshift": np.arange(n_ds, dtype=float), - "onlineMotionYshift": np.zeros(n_ds), - "onlineMotionZshift": np.zeros(n_ds), - }, - }, - ) - save_struct_h5( - root / "trial_table.h5", - { - "datadr": str(raw), - "savedr": str(root), - "filename": fn, - "slap2_info": { - "first_line": np.ones((N_PATHS, N_TRIALS)), - "last_line": np.full((N_PATHS, N_TRIALS), 2000.0), - }, - "motion_correction": { - "fn_reg_ds": reg, - "fn_adata": adata, - "registration_failed": np.zeros((N_PATHS, N_TRIALS), bool), - }, - }, - ) - return root / "trial_table.h5" - - -@pytest.fixture -def fake(monkeypatch: pytest.MonkeyPatch) -> None: - """Synthetic localization and loading, in this process.""" - monkeypatch.setattr(trial_mod, "localize_trial", fake_localize) - monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) - - -EX = SiloExecution(workers=1, solver_workers=1, solver_threads=1) -PARAMS = SiloParams(min_kinetic_score=0.0) - - -def seeds_file(root: Path) -> Path: - """Write the sources as seeds of both paths (zero-based). - - The plan's own seeding is tested with the plan stage. - """ - from giant_python.extraction.raster.stage_files import write_seeds - - seeds = np.column_stack([ - np.full(len(SOURCES), 10.0), - SOURCES, - np.full(len(SOURCES), 1.3), - ]).astype(float) - path = root / "seeds.h5" - write_seeds(path, {1: seeds, 2: seeds}, index_base=0) - return path - - -def _seeds(session: SiloSession, root: Path) -> list: - """Read the seeds of :func:`seeds_file` per path.""" - from giant_python.extraction.raster.stage_files import read_seeds - - return read_seeds(seeds_file(root), session.n_paths) - - -def _data(path: Path) -> dict: - """Read the solved arrays of a results file, by subproblem.""" - r = read_results(path) - return { - k: {n: getattr(v[2], n) for n in ("footprints", "events", "ls", "f0", "snr", "f0_image")} - for k, v in r.results.items() - } - - -def _all_results(session: SiloSession) -> dict: - """Every subproblem's arrays, keyed by (path, trial, subproblem).""" - out = {} - for f in sorted(session.results_dir.glob("*.h5")): - r = read_results(f) - for k, v in _data(f).items(): - out[(r.attrs["path"], r.attrs["trial"], k)] = v - return out - - -def _summary(path: Path) -> dict: - """Read a summary file's datasets (params' times left out).""" - s = load_struct_h5(path) - s.pop("params", None) - return s - - -def _equal(a: dict, b: dict) -> None: - """Nested dicts of arrays are equal (NaN equal).""" - assert a.keys() == b.keys() - for k in a: - if isinstance(a[k], dict): - _equal(a[k], b[k]) - else: - np.testing.assert_array_equal(a[k], b[k]) - - -def test_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: - """The streaming driver, one job and three jobs give the same results and summaries. - - Reruns keep finished units. - """ - table = make_session(tmp_path / "streamed") - seeds = seeds_file(tmp_path) - report = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) - s1 = SiloSession.open(table) - assert s1.keep.all() and s1.num_channels == 2 and s1.align_hz == 80.0 - exp = s1.out_dir / "experiment_summary.h5" - assert exp.exists() and (s1.out_dir / "per_trial_summary.h5").exists() - assert report["total"] > 0 - # timings per trial-path: localization, and each trial's solve span - assert len(report["localize_trials"]) == N_PATHS * N_TRIALS - assert all(r["seconds"] > 0 for r in report["localize_trials"]) - loaded = [r for r in report["trials"] if "load" in r] - assert loaded and all(0 <= r["submitted"] <= r["solved"] <= report["total"] for r in loaded) - streamed = _all_results(s1) - # every subproblem has its F0 image, and the summaries the trials' F0 - # images on the selected pixels of the extracted trials (not trial 3) - assert all(v["f0_image"] is not None for v in streamed.values()) - per = load_struct_h5(s1.out_dir / "per_trial_summary.h5") - plan = read_plan(s1.plan_file(0)) - f0 = np.asarray(per["Path1"]["visualizations"]["per_trial_F0_im"]) - assert f0.shape == np.shape(per["Path1"]["visualizations"]["per_trial_mean_im"]) - act = f0[:, 0, 0] # trials, rows, cols (activity channel 1) - for t in range(N_TRIALS): - if t == 2: - assert np.isnan(act[t]).all() - else: - np.testing.assert_array_equal(np.isfinite(act[t]), plan.sel) - assert (act[t][plan.sel] > 0).all() - exp_s = load_struct_h5(exp) - assert "F0_im" in exp_s["Path1"]["visualizations"] - # trial 3 is short: its results file has its record and no subproblems - short = read_results(s1.results_file(0, 2)) - assert short.attrs["extracted"] == 0 and not short.results - table_after = load_struct_h5(table) - assert table_after["source_extraction"]["fn_raw"][0, 0].endswith(".dat") - assert table_after["source_extraction"]["analysis_params"]["peakth"] == 3 - - # rerun: everything is up to date - mtime = s1.results_file(0, 0).stat().st_mtime_ns - again = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) - assert again["localize_units"] == 0 - assert all("skipped" in t for t in again["trials"]) - assert s1.results_file(0, 0).stat().st_mtime_ns == mtime - - for machines in (1, 3): - root = tmp_path / f"staged{machines}" - s2 = SiloSession.open(make_session(root)) - silo.localize(s2, PARAMS, EX) - silo.plan(s2, PARAMS, EX, seeds=_seeds(s2, tmp_path)) - prepared = silo.prepare(s2, PARAMS, EX) - assert len(prepared) == N_PATHS * N_TRIALS - jobs = silo_solve.dispatch(s2, PARAMS, machines, EX) - assert len(jobs) == machines - for job in jobs: - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(s2, PARAMS, EX) - staged = _all_results(s2) - assert staged.keys() == streamed.keys() - for key in staged: - for name, value in staged[key].items(): - np.testing.assert_array_equal(value, streamed[key][name]) - _equal(_summary(s2.out_dir / "experiment_summary.h5"), _summary(exp)) - _equal( - _summary(s2.out_dir / "per_trial_summary.h5"), - _summary(s1.out_dir / "per_trial_summary.h5"), - ) - many = list((tmp_path / "staged3" / "source_extraction" / "silo" / "results").glob("*_s*.h5")) - assert many, "three jobs split a container into ranges" - - -def test_valid_kernel_through_the_run(tmp_path: Path, fake: None) -> None: - """One footprint support for the whole run. - - Streamed and staged runs at 5 agree, differ from 3, and record it; a - changed support redoes the plan; the stages after the plan refuse files - made with another one. - """ - import json - from dataclasses import replace - - from giant_python.extraction.raster.container import read_container - from giant_python.extraction.raster.plan import read_plan - - p5 = replace(PARAMS, valid_kernel=5) - p3 = replace(PARAMS, valid_kernel=3) # MATLAB's - seeds = seeds_file(tmp_path) - table = make_session(tmp_path / "streamed") - silo.run_silo(table, p5, EX, seeds_file=seeds) - s1 = SiloSession.open(table) - streamed = _all_results(s1) - assert read_plan(s1.plan_file(0)).params.valid_kernel == 5 - s = SiloSession.open(make_session(tmp_path / "staged")) - silo.localize(s, p5, EX) - silo.plan(s, p5, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, p5, EX) - c = read_container(s.container_file(0, 0), data=False) - assert c.params["valid_kernel"] == 5 - # the solve and collect stages refuse another support - with pytest.raises(ValueError, match="valid_kernel=5"): - silo_solve.dispatch(s, p3, 1, EX) - for job in silo_solve.dispatch(s, p5, 1, EX): - silo_solve.solve_job(job, execution=EX) - with pytest.raises(ValueError, match="valid_kernel=5"): - silo_collect.collect(s, p3, EX) - silo_collect.collect(s, p5, EX) - staged = _all_results(s) - assert staged.keys() == streamed.keys() - for key in staged: - for name, value in staged[key].items(): - np.testing.assert_array_equal(value, streamed[key][name]) - with h5py.File(s.out_dir / "experiment_summary.h5") as f: - assert f["params"]["validKernel"].shape == (5, 5) - record = json.loads((s.work_dir / "collect.json").read_text()) - assert record["valid_kernel"] == 5 - # a solver at 3 on these containers is refused before anything runs - with pytest.raises(ValueError, match="--valid-kernel 5"): - silo_solve.solve_containers(s, p3, EX) - # a plan at 5 is refused by a prepare at 3; planning at 3 redoes it - with pytest.raises(ValueError, match="valid_kernel=5"): - silo.prepare(s, p3, EX) - assert silo.plan(s, p3, EX, seeds=_seeds(s, tmp_path))[0]["file"] - assert read_plan(s.plan_file(0)).params.valid_kernel == 3 - silo.prepare(s, p3, EX) - silo_solve.solve_containers(s, p3, EX) - three = _all_results(s) - assert three.keys() == staged.keys() - assert any(not np.array_equal(three[k]["footprints"], staged[k]["footprints"]) for k in staged) - - -def test_settings_change_redoes_units(tmp_path: Path, fake: None) -> None: - """A changed solver setting redoes the solve stage only.""" - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PARAMS, EX) - silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, PARAMS, EX) - silo_solve.solve_containers(s, PARAMS, EX) - assert silo.localize(s, PARAMS, EX) == [] - assert silo.prepare(s, PARAMS, EX) == [] - done = silo_solve.solve_containers(s, PARAMS, EX) - assert all(v is None for v in done.values()) - other = SiloParams(min_kinetic_score=0.0, lam=0.5) - assert silo.prepare(s, other, EX) == [] - done = silo_solve.solve_containers(s, other, EX) - assert all(v is not None for v in done.values()) - - -def test_inputs_and_stale_results( - tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """A changed raw file redoes prepare. - - Collect uses only results of the current plan and solve settings; a trial - found without data loses its earlier container and results. - """ - import os - - from giant_python.pipeline.silo_session import NO_DATA - - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PARAMS, EX) - silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, PARAMS, EX) - assert silo.prepare(s, PARAMS, EX) == [] - raw = s.raw(0, 0) - os.utime(raw, ns=(raw.stat().st_atime_ns, raw.stat().st_mtime_ns + 10**9)) - assert [u["unit"] for u in silo.prepare(s, PARAMS, EX)] == [(0, 0)] - - # results of three jobs with lam 0.9, then whole files with lam 0.5 - for job in silo_solve.dispatch(s, PARAMS, 3, EX): - silo_solve.solve_job(job, execution=EX) - split = list(s.results_dir.glob("*_s*.h5")) - assert split - other = SiloParams(min_kinetic_score=0.0, lam=0.5) - silo_solve.solve_containers(s, other, EX) - # the three jobs' range files are from other settings: left out - with pytest.warns(UserWarning, match="left out"): - silo_collect.collect(s, other, EX) - third = SiloParams(min_kinetic_score=0.0, lam=0.3) - with pytest.raises(FileNotFoundError, match="current"): - with pytest.warns(UserWarning): - silo_collect.collect(s, third, EX) - - # the trial has no data any more: its container and results go - def no_data(dat_path: str | Path, *args: Any, **kw: Any) -> TrialData: # noqa: ANN401 - """Path 1, trial 1 has no data now.""" - if "DMD1-TRIAL000001" in str(dat_path): - raise ValueError(NO_DATA) - return fake_load(dat_path, *args, **kw) - - monkeypatch.setattr(trial_data_mod, "load_trial", no_data) - ex = SiloExecution(workers=1, solver_workers=1, solver_threads=1, overwrite=True) - silo.prepare(s, other, ex, units=[(0, 0)]) - assert s.skip_file(0, 0).exists() - assert not s.container_file(0, 0).exists() - assert not list(s.results_dir.glob("path1_trial0001*.h5")) - assert all(u != (0, 0) for u, _ in silo_solve._containers(s)) - silo_collect.collect(s, other, EX) - e = load_struct_h5(s.out_dir / "experiment_summary.h5") - frames = e["Path1"]["frame_info"]["trial_num_frames"].ravel() - assert frames.tolist() == [0, FRAMES[1], FRAMES[2]] - - # a raw file changed after solving: its results are stale - raw = s.raw(1, 1) - os.utime(raw, ns=(raw.stat().st_atime_ns, raw.stat().st_mtime_ns + 10**9)) - with pytest.raises(FileNotFoundError, match="current"): - with pytest.warns(UserWarning, match="left out"): - silo_collect.collect(s, other, EX) - - -def test_collect_and_dispatch_without_raw_data(tmp_path: Path, fake: None) -> None: - """Dispatch and collect need neither the raw data nor the movies. - - A short trial is one item of no work. - """ - import json - import shutil - - table = make_session(tmp_path) - s = SiloSession.open(table) - silo.localize(s, PARAMS, EX) - silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, PARAMS, EX) - shutil.rmtree(tmp_path / "raw") - for movie in (tmp_path / "motion_correction").glob("*.tif"): - movie.unlink() - with pytest.raises(ValueError): - SiloSession.open(table) - c = SiloSession.open(table, inputs="collect") - jobs = silo_solve.dispatch(c, PARAMS, 3, EX) - items = [it for j in jobs for it in json.loads(j.read_text(encoding="utf-8"))["items"]] - short = [it for it in items if it["container"] == "path1_trial0003.h5"] - assert len(short) == 1 and short[0]["work"] == 0 - for job in jobs: - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(c, PARAMS, EX) - e = load_struct_h5(c.out_dir / "experiment_summary.h5") - frames = e["Path1"]["frame_info"]["trial_num_frames"].ravel() - assert frames.tolist() == [FRAMES[0], FRAMES[1], FRAMES[2]] - - -def test_localize_fits_missing_peaks(tmp_path: Path, fake: None) -> None: - """Localization files without their peaks get them from silo-localize. - - Such files come from a streaming run stopped before its background fits. - """ - from giant_python.extraction.raster.stage_files import localization_attrs - - s = SiloSession.open(make_session(tmp_path)) - jobs = silo.localize_jobs(s, PARAMS, fit_peaks=False) - for job in jobs: - silo._localize_job(job) - f = s.localize_file(0, 0) - assert localization_attrs(f)["peaks_fitted"] == 0 - done = silo.localize(s, PARAMS, EX) - assert len(done) == N_PATHS * N_TRIALS # peak fits only - assert localization_attrs(f)["peaks_fitted"] == 1 - assert silo.localize(s, PARAMS, EX) == [] - - -def test_job_needs_its_container(tmp_path: Path, fake: None) -> None: - """A job refuses a container other than the one it was made for.""" - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PARAMS, EX) - silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, PARAMS, EX) - job = silo_solve.dispatch(s, PARAMS, 1, EX)[0] - with h5py.File(s.container_file(0, 0), "a") as f: - f.attrs["settings_hash"] = "other" - with pytest.raises(ValueError, match="not the container"): - silo_solve.solve_job(job, execution=EX) - - -def test_job_without_valid_kernel_is_matlabs(tmp_path: Path, fake: None) -> None: - """A job file written before valid_kernel existed solves at MATLAB's 3 x 3. - - Its params lack the field; its containers are solved at MATLAB's 3 x 3, - which they were prepared for, not at today's default. - """ - import json - from dataclasses import replace - - p3 = replace(PARAMS, valid_kernel=3) - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, p3, EX) - silo.plan(s, p3, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, p3, EX) - job = silo_solve.dispatch(s, p3, 1, EX)[0] - record = json.loads(job.read_text(encoding="utf-8")) - del record["params"]["valid_kernel"] - job.write_text(json.dumps(record), encoding="utf-8") - done = silo_solve.solve_job(job, execution=EX) - assert done["items"] - results = read_results(s.results_file(0, 0)) - assert results.results - - -def test_trial_without_data_is_skipped( - tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """A trial whose selected pixels have no sample is marked and left out of the summaries. - - Streamed and staged alike. - """ - from giant_python.pipeline.silo_session import NO_DATA - - def no_data(dat_path: str | Path, *args: Any, **kw: Any) -> TrialData: # noqa: ANN401 - """Path 2, trial 2 has no data.""" - if "DMD2-TRIAL000002" in str(dat_path): - raise ValueError(NO_DATA) - return fake_load(dat_path, *args, **kw) - - monkeypatch.setattr(trial_data_mod, "load_trial", no_data) - for staged in (False, True): - root = tmp_path / str(staged) - table = make_session(root) - s = SiloSession.open(table) - if staged: - silo.localize(s, PARAMS, EX) - silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) - silo.prepare(s, PARAMS, EX) - assert not s.container_file(1, 1).exists() - silo_solve.solve_containers(s, PARAMS, EX) - silo_collect.collect(s, PARAMS, EX) - else: - silo.run_silo(table, PARAMS, EX, seeds_file=seeds_file(tmp_path)) - assert s.skip_file(1, 1).exists() - e = load_struct_h5(s.out_dir / "experiment_summary.h5") - frames = e["Path2"]["frame_info"]["trial_num_frames"].ravel() - assert frames.tolist() == [FRAMES[0], 0, FRAMES[2]] - # a rerun does not try the trial again - assert silo.prepare(s, PARAMS, EX, units=[(1, 1)]) == [] - - -def test_seeds_file_replaces_seeding(tmp_path: Path, fake: None) -> None: - """Seeds from a file (one-based, MATLAB's thetaf) give the plan's sources.""" - from giant_python.extraction.raster.plan import read_plan - from giant_python.extraction.raster.stage_files import ( - read_seeds, - write_seeds, - ) - - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PARAMS, EX) - seeds = np.array([[5.0, 7.0, 8.0, 1.0], [4.0, 16.0, 21.0, 1.0]]) - write_seeds(tmp_path / "seeds.h5", {1: seeds}, index_base=1) - got = read_seeds(tmp_path / "seeds.h5", 2) - assert got[1] is None - np.testing.assert_array_equal(got[0][:, 1:3], seeds[:, 1:3] - 1) - silo.plan(s, PARAMS, EX, paths=[0], seeds=got) - p = read_plan(s.plan_file(0)) - np.testing.assert_array_equal(p.source_rows, [6, 15]) - np.testing.assert_array_equal(p.source_cols, [7, 20]) - - -def test_cli(tmp_path: Path, fake: None, capsys: pytest.CaptureFixture[str]) -> None: - """The commands parse their options and run the stages.""" - assert parse_numbers("1,3-4") == [1, 3, 4] - assert parse_numbers(None) is None - with pytest.raises(ValueError): - parse_numbers("0") - (tmp_path / "p.json").write_text('{"lam": 0.5}') - args = build_parser().parse_args([ - "silo", - "t.h5", - "--params", - str(tmp_path / "p.json"), - "--set", - "nmf_iter=3", - "--set", - "footprint_variance=fixed", - "--peak-th", - "4", - "--no-trial-peaks", - ]) - p = params_from_args(args) - assert p.valid_kernel == 5 # the default - for cmd in ("silo", "silo-plan", "silo-prepare", "silo-collect"): - assert ( - params_from_args( - build_parser().parse_args([cmd, "t.h5", "--valid-kernel", "5"]) - ).valid_kernel - == 5 - ) - assert (p.lam, p.nmf_iter, p.footprint_variance, p.peak_th) == ( - 0.5, - 3, - "fixed", - 4.0, - ) - assert p.trial_peaks is False - with pytest.raises(ValueError): - params_from_args(build_parser().parse_args(["silo", "t", "--set", "x=1"])) - table = make_session(tmp_path / "s") - opts = ["--workers", "1", "--set", "min_kinetic_score=0"] - assert main(["silo-localize", str(table), "--paths", "1", *opts]) == 0 - assert main(["silo-localize", str(table), *opts]) == 0 - seeds = str(seeds_file(tmp_path)) - assert main(["silo-plan", str(table), "--seeds", seeds, *opts]) == 0 - assert main(["silo-prepare", str(table), "--trials", "1-3", *opts]) == 0 - assert ( - main([ - "silo-dispatch", - str(table), - "--machines", - "2", - "--solver-workers", - "1", - *opts, - ]) - == 0 - ) - jobs = sorted((tmp_path / "s" / "source_extraction" / "silo" / "jobs").glob("*.json")) - for job in jobs: - assert main(["silo-solve", str(job), "--solver-workers", "1"]) == 0 - assert main(["silo-collect", str(table), *opts]) == 0 - assert (tmp_path / "s" / "source_extraction" / "experiment_summary.h5").exists() - capsys.readouterr() - - -class _FakePool: - """A pool whose tasks finish at a set time on a controlled clock.""" - - def __init__(self, now: list[float], finish_at: list[float | None]) -> None: - """Take the clock and each task's finish time.""" - self.now, self.finish_at, self.futures = now, list(finish_at), [] - - def submit(self, *args: object, **kwargs: object) -> Future[None]: - """Return a future. - - It is finished at once (before the next submit) when its time is None. - """ - import concurrent.futures as cf - - f = cf.Future() - self.now[0] += 0.01 # submitting takes time - if self.finish_at[len(self.futures)] is None: - f.set_result(None) - self.futures.append(f) - return f - - -def test_solve_span_is_the_last_subproblem_solved(monkeypatch: pytest.MonkeyPatch) -> None: - """A trial's solve span ends when its last subproblem is done. - - A subproblem solved while the rest are still submitted keeps its own - time, a trial collected later still ends then, and a trial solved here - ends when that solve returns. Controlled clock, set completion order. - """ - import types - - from giant_python.extraction.raster import solver as solver_mod - - now = [0.0] - monkeypatch.setattr(silo, "time", types.SimpleNamespace(perf_counter=lambda: now[0])) - sub = types.SimpleNamespace(n_pixels=1, n_frames=1, n_sources=1) - # the first task is done before the second is submitted - pool = _FakePool(now, [None, 0.2]) - done = silo._Done() - futures, _ = silo._submit([sub, sub], None, EX.solver_options(), pool, done) - assert done.times == [0.01] - now[0] = 0.2 - pool.futures[1].set_result(None) # the last subproblem - now[0] = 0.6 # collected later - p = silo._Pending(0, 0, None, [], futures, [], {}, Path("x"), 0.0, done) - assert silo._solve_span(p, 0.0) == (0.0, 0.2) - # solved here: done when the solve returned - monkeypatch.setattr( - solver_mod, - "solve_subproblems", - lambda subs, sp, options: now.__setitem__(0, 0.9) or [1], - ) - now[0] = 0.7 - done = silo._Done() - _, results = silo._submit([sub], None, EX.solver_options(), None, done) - now[0] = 1.5 - q = silo._Pending(0, 1, None, [], [], results, {}, Path("y"), 0.7, done) - assert silo._solve_span(q, 0.0) == (0.7, 0.9) - - -def test_pool_workers_are_spawned_with_their_thread_counts() -> None: - """Pool workers start a fresh interpreter (not a fork of this one). - - So the thread variables are set before numpy loads its BLAS. - """ - import os - - from giant_python.pipeline.silo_session import make_pool - - with make_pool(1, 2) as pool: - assert pool._mp_context.get_start_method() == "spawn" - for name in ( - "OMP_NUM_THREADS", - "MKL_NUM_THREADS", - "OPENBLAS_NUM_THREADS", - ): - assert pool.submit(os.getenv, name).result() == "2" +"""SILo's stages and driver on a small synthetic session. + +The registered movies and the raw data are stood in for: localization and +trial loading are replaced by functions that return synthetic images and +200 Hz data (with known sources), so that the stages' plumbing (files, +settings hashes, skipping, shards, assembly, summaries) is tested with the +real plan stage, solver, kinetics test and writers. +""" + +from collections.abc import Callable, Sequence +from concurrent.futures import Future +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +import torch +from numpy.typing import ArrayLike, DTypeLike + +from giant_python.cli import build_parser, main +from giant_python.cli_silo import params_from_args, parse_numbers +from giant_python.extraction.raster import trial as trial_mod +from giant_python.extraction.raster import trial_data as trial_data_mod +from giant_python.extraction.raster.localization import ( + RasterLocalization, + RasterLocalizationParams, +) +from giant_python.extraction.raster.plan import read_plan +from giant_python.extraction.raster.results import read_results +from giant_python.extraction.raster.trial import RegisteredTrial +from giant_python.extraction.raster.trial_data import TrialAlignment, TrialData, TrialLoadParams +from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 +from giant_python.models.params import SiloExecution, SiloParams +from giant_python.pipeline import silo, silo_collect, silo_solve +from giant_python.pipeline.silo_session import SiloSession + +H, W = 24, 30 +N_PATHS, N_TRIALS = 2, 3 +SOURCES = np.array([[6, 7], [8, 9], [15, 20], [18, 8]]) +FRAMES = {0: 260, 1: 240, 2: 60} # trial 3 is too short to extract +SHIFTS = {0: (0, 0), 1: (1, -1), 2: (0, 1)} + + +def _blobs( + amplitude: Sequence[float], sigma: float = 1.3, shift: tuple[int, int] = (0, 0) +) -> np.ndarray: + """Gaussian blobs at the sources (moved into a trial's frame). + + Returns + ------- + np.ndarray + The (H, W) image of the blobs, with the given amplitude at each source. + """ + r, c = np.mgrid[:H, :W] + img = np.zeros((H, W)) + for (sr, sc), a in zip(SOURCES, amplitude): + img += a * np.exp(-((r - sr - shift[0]) ** 2 + (c - sc - shift[1]) ** 2) / (2 * sigma**2)) + return img + + +def fake_localize( + moco_dir: str | Path, + fn: str, + num_channels: int, + params: RasterLocalizationParams | None = None, + **kw: object, +) -> tuple[RasterLocalization, RegisteredTrial]: + """Images of a localized trial (instead of reading its movie). + + Returns + ------- + loc : RasterLocalization + The trial's localization, with its activity image. + reg : RegisteredTrial + The trial's registered mean image (and half images when half_ims is passed). + """ + t = int(fn.split("T")[1][0]) - 1 + rng = np.random.default_rng(t) + shift = SHIFTS[t] + act = _blobs([30, 25, 40, 20], shift=shift) + rng.random((H, W)) + mean = np.stack([_blobs([5, 5, 5, 5], 3, shift) + 10, np.full((H, W), 4.0)], 2) + loc = RasterLocalization( + act_im=act, + summary=act, + peaks=None, + valid=np.ones((H, W), bool), + ) + half_ims = None + if kw.get("half_ims"): # two noisy halves, as the patchwise plan needs + noise = 0.05 * rng.standard_normal((2,) + mean.shape) + half_ims = (mean[None] + noise).astype(np.float32) + reg = RegisteredTrial( + movie=np.zeros((1, H, W), np.float32), + var_factor=None, + mean_im=mean.astype(np.float32), + discard=np.zeros(50, bool), + align_hz=80.0, + half_ims=half_ims, + ) + return loc, reg + + +def fake_load( + dat_path: str | Path, + first_line: float, + last_line: float, + alignment: TrialAlignment | str | Path, + sel_pix: np.ndarray, + warp: Callable, + discard_frames: ArrayLike, + mean_image: np.ndarray, + roi_masks: Sequence[np.ndarray] = (), + params: TrialLoadParams | None = None, + device: str | torch.device = "cpu", + dtype: DTypeLike = np.float32, +) -> TrialData: + """Make a trial at the selected pixels: baseline plus sources with events. + + Returns + ------- + TrialData + The trial's data at the selected pixels. + """ + name = Path(dat_path).name + t = int(name.split("TRIAL")[1][:6]) - 1 + d = int(name.split("DMD")[1][0]) - 1 + n = FRAMES[t] + rng = np.random.default_rng(100 * d + t) + cols, rows = np.nonzero(np.asarray(sel_pix).T) + y = np.full((2, rows.size, n), 2.0) + k = np.exp(-np.arange(30) / 4.8) + for sr, sc in SOURCES: + fp = np.exp(-((rows - sr) ** 2 + (cols - sc) ** 2) / (2 * 1.3**2)) + ev = (rng.random(n) < 0.03) * rng.uniform(2, 6, n) + trace = np.convolve(ev, k)[:n] + y[0] += fp[:, None] * trace[None] + y = rng.poisson(y * 25) / 25.0 + return TrialData( + y=y.astype(dtype), + finv=np.ones((rows.size, n), dtype), + frame_lines=np.arange(n) * 8 + 1 + 1000 * t, + motion_r=np.zeros(n), + motion_c=np.zeros(n), + discard=np.arange(n) % 50 == 0, + global_f=rng.random((2, n)), + roi_f=rng.random((len(roi_masks), 2, n)), + roi_fsvd=rng.random((len(roi_masks), 2, n)), + pixel_rc=np.stack([rows, cols], 1), + trial_rc=np.stack([rows, cols], 1).astype(float), + photon_scale=25.0, + ) + + +def make_session(root: Path) -> Path: + """Trial table, alignment files and empty movies and raw files. + + Returns + ------- + Path + The trial table file of the session. + """ + moco, raw = root / "motion_correction", root / "raw" + moco.mkdir(parents=True) + raw.mkdir() + fn = np.empty((N_PATHS, N_TRIALS), object) + reg = np.empty_like(fn) + adata = np.empty_like(fn) + for d in range(N_PATHS): + for t in range(N_TRIALS): + fn[d, t] = f"x_DMD{d + 1}-TRIAL{t + 1:06d}.dat" + stem = f"E1T{t + 1}DMD{d + 1}" + reg[d, t] = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" + adata[d, t] = f"{stem}_ALIGNMENTDATA.h5" + (raw / fn[d, t]).write_bytes(b"") + (moco / reg[d, t]).write_bytes(b"") + n_ds = 6 + save_struct_h5( + moco / adata[d, t], + { + "numChannels": 2.0, + "alignHz": 80.0, + "DSframes": np.linspace(1, FRAMES[t] * 8, n_ds) + 1000 * t, + "motionDSr": np.linspace(0, 0.5, n_ds), + "motionDSc": np.linspace(0.2, 0, n_ds), + "slap2": { + "Z_depths": np.float32(-20.0), + "onlineMotionXshift": np.arange(n_ds, dtype=float), + "onlineMotionYshift": np.zeros(n_ds), + "onlineMotionZshift": np.zeros(n_ds), + }, + }, + ) + save_struct_h5( + root / "trial_table.h5", + { + "datadr": str(raw), + "savedr": str(root), + "filename": fn, + "slap2_info": { + "first_line": np.ones((N_PATHS, N_TRIALS)), + "last_line": np.full((N_PATHS, N_TRIALS), 2000.0), + }, + "motion_correction": { + "fn_reg_ds": reg, + "fn_adata": adata, + "registration_failed": np.zeros((N_PATHS, N_TRIALS), bool), + }, + }, + ) + return root / "trial_table.h5" + + +@pytest.fixture +def fake(monkeypatch: pytest.MonkeyPatch) -> None: + """Synthetic localization and loading, in this process.""" + monkeypatch.setattr(trial_mod, "localize_trial", fake_localize) + monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) + + +EX = SiloExecution(workers=1, solver_workers=1, solver_threads=1) +PARAMS = SiloParams(min_kinetic_score=0.0) + + +def seeds_file(root: Path) -> Path: + """Write the sources as seeds of both paths (zero-based). + + The plan's own seeding is tested with the plan stage. + + Returns + ------- + Path + The seeds file. + """ + from giant_python.extraction.raster.stage_files import write_seeds + + seeds = np.column_stack([ + np.full(len(SOURCES), 10.0), + SOURCES, + np.full(len(SOURCES), 1.3), + ]).astype(float) + path = root / "seeds.h5" + write_seeds(path, {1: seeds, 2: seeds}, index_base=0) + return path + + +def _seeds(session: SiloSession, root: Path) -> list: + """Read the seeds of :func:`seeds_file` per path. + + Returns + ------- + list + The seeds of each path. + """ + from giant_python.extraction.raster.stage_files import read_seeds + + return read_seeds(seeds_file(root), session.n_paths) + + +def _data(path: Path) -> dict: + """Read the solved arrays of a results file, by subproblem. + + Returns + ------- + dict + For each subproblem index, its footprints, events, ls, f0, snr + and f0_image arrays. + """ + r = read_results(path) + return { + k: {n: getattr(v[2], n) for n in ("footprints", "events", "ls", "f0", "snr", "f0_image")} + for k, v in r.results.items() + } + + +def _all_results(session: SiloSession) -> dict: + """Every subproblem's arrays, keyed by (path, trial, subproblem). + + Returns + ------- + dict + The arrays of each subproblem, as from :func:`_data`. + """ + out = {} + for f in sorted(session.results_dir.glob("*.h5")): + r = read_results(f) + for k, v in _data(f).items(): + out[(r.attrs["path"], r.attrs["trial"], k)] = v + return out + + +def _summary(path: Path) -> dict: + """Read a summary file's datasets (params' times left out). + + Returns + ------- + dict + The file's contents without its params entry. + """ + s = load_struct_h5(path) + s.pop("params", None) + return s + + +def _equal(a: dict, b: dict) -> None: + """Nested dicts of arrays are equal (NaN equal).""" + assert a.keys() == b.keys() + for k in a: + if isinstance(a[k], dict): + _equal(a[k], b[k]) + else: + np.testing.assert_array_equal(a[k], b[k]) + + +def test_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: + """The streaming driver, one job and three jobs give the same results and summaries. + + Reruns keep finished units. + """ + table = make_session(tmp_path / "streamed") + seeds = seeds_file(tmp_path) + report = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) + s1 = SiloSession.open(table) + assert s1.keep.all() and s1.num_channels == 2 and s1.align_hz == 80.0 + exp = s1.out_dir / "experiment_summary.h5" + assert exp.exists() and (s1.out_dir / "per_trial_summary.h5").exists() + assert report["total"] > 0 + # timings per trial-path: localization, and each trial's solve span + assert len(report["localize_trials"]) == N_PATHS * N_TRIALS + assert all(r["seconds"] > 0 for r in report["localize_trials"]) + loaded = [r for r in report["trials"] if "load" in r] + assert loaded and all(0 <= r["submitted"] <= r["solved"] <= report["total"] for r in loaded) + streamed = _all_results(s1) + # every subproblem has its F0 image, and the summaries the trials' F0 + # images on the selected pixels of the extracted trials (not trial 3) + assert all(v["f0_image"] is not None for v in streamed.values()) + per = load_struct_h5(s1.out_dir / "per_trial_summary.h5") + plan = read_plan(s1.plan_file(0)) + f0 = np.asarray(per["Path1"]["visualizations"]["per_trial_F0_im"]) + assert f0.shape == np.shape(per["Path1"]["visualizations"]["per_trial_mean_im"]) + act = f0[:, 0, 0] # trials, rows, cols (activity channel 1) + for t in range(N_TRIALS): + if t == 2: + assert np.isnan(act[t]).all() + else: + np.testing.assert_array_equal(np.isfinite(act[t]), plan.sel) + assert (act[t][plan.sel] > 0).all() + exp_s = load_struct_h5(exp) + assert "F0_im" in exp_s["Path1"]["visualizations"] + # trial 3 is short: its results file has its record and no subproblems + short = read_results(s1.results_file(0, 2)) + assert short.attrs["extracted"] == 0 and not short.results + table_after = load_struct_h5(table) + assert table_after["source_extraction"]["fn_raw"][0, 0].endswith(".dat") + assert table_after["source_extraction"]["analysis_params"]["peakth"] == 3 + + # rerun: everything is up to date + mtime = s1.results_file(0, 0).stat().st_mtime_ns + again = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) + assert again["localize_units"] == 0 + assert all("skipped" in t for t in again["trials"]) + assert s1.results_file(0, 0).stat().st_mtime_ns == mtime + + for machines in (1, 3): + root = tmp_path / f"staged{machines}" + s2 = SiloSession.open(make_session(root)) + silo.localize(s2, PARAMS, EX) + silo.plan(s2, PARAMS, EX, seeds=_seeds(s2, tmp_path)) + prepared = silo.prepare(s2, PARAMS, EX) + assert len(prepared) == N_PATHS * N_TRIALS + jobs = silo_solve.dispatch(s2, PARAMS, machines, EX) + assert len(jobs) == machines + for job in jobs: + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(s2, PARAMS, EX) + staged = _all_results(s2) + assert staged.keys() == streamed.keys() + for key in staged: + for name, value in staged[key].items(): + np.testing.assert_array_equal(value, streamed[key][name]) + _equal(_summary(s2.out_dir / "experiment_summary.h5"), _summary(exp)) + _equal( + _summary(s2.out_dir / "per_trial_summary.h5"), + _summary(s1.out_dir / "per_trial_summary.h5"), + ) + many = list((tmp_path / "staged3" / "source_extraction" / "silo" / "results").glob("*_s*.h5")) + assert many, "three jobs split a container into ranges" + + +def test_valid_kernel_through_the_run(tmp_path: Path, fake: None) -> None: + """One footprint support for the whole run. + + Streamed and staged runs at 5 agree, differ from 3, and record it; a + changed support redoes the plan; the stages after the plan refuse files + made with another one. + """ + import json + from dataclasses import replace + + from giant_python.extraction.raster.container import read_container + from giant_python.extraction.raster.plan import read_plan + + p5 = replace(PARAMS, valid_kernel=5) + p3 = replace(PARAMS, valid_kernel=3) # MATLAB's + seeds = seeds_file(tmp_path) + table = make_session(tmp_path / "streamed") + silo.run_silo(table, p5, EX, seeds_file=seeds) + s1 = SiloSession.open(table) + streamed = _all_results(s1) + assert read_plan(s1.plan_file(0)).params.valid_kernel == 5 + s = SiloSession.open(make_session(tmp_path / "staged")) + silo.localize(s, p5, EX) + silo.plan(s, p5, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, p5, EX) + c = read_container(s.container_file(0, 0), data=False) + assert c.params["valid_kernel"] == 5 + # the solve and collect stages refuse another support + with pytest.raises(ValueError, match="valid_kernel=5"): + silo_solve.dispatch(s, p3, 1, EX) + for job in silo_solve.dispatch(s, p5, 1, EX): + silo_solve.solve_job(job, execution=EX) + with pytest.raises(ValueError, match="valid_kernel=5"): + silo_collect.collect(s, p3, EX) + silo_collect.collect(s, p5, EX) + staged = _all_results(s) + assert staged.keys() == streamed.keys() + for key in staged: + for name, value in staged[key].items(): + np.testing.assert_array_equal(value, streamed[key][name]) + with h5py.File(s.out_dir / "experiment_summary.h5") as f: + assert f["params"]["validKernel"].shape == (5, 5) + record = json.loads((s.work_dir / "collect.json").read_text()) + assert record["valid_kernel"] == 5 + # a solver at 3 on these containers is refused before anything runs + with pytest.raises(ValueError, match="--valid-kernel 5"): + silo_solve.solve_containers(s, p3, EX) + # a plan at 5 is refused by a prepare at 3; planning at 3 redoes it + with pytest.raises(ValueError, match="valid_kernel=5"): + silo.prepare(s, p3, EX) + assert silo.plan(s, p3, EX, seeds=_seeds(s, tmp_path))[0]["file"] + assert read_plan(s.plan_file(0)).params.valid_kernel == 3 + silo.prepare(s, p3, EX) + silo_solve.solve_containers(s, p3, EX) + three = _all_results(s) + assert three.keys() == staged.keys() + assert any(not np.array_equal(three[k]["footprints"], staged[k]["footprints"]) for k in staged) + + +def test_settings_change_redoes_units(tmp_path: Path, fake: None) -> None: + """A changed solver setting redoes the solve stage only.""" + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PARAMS, EX) + silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, PARAMS, EX) + silo_solve.solve_containers(s, PARAMS, EX) + assert silo.localize(s, PARAMS, EX) == [] + assert silo.prepare(s, PARAMS, EX) == [] + done = silo_solve.solve_containers(s, PARAMS, EX) + assert all(v is None for v in done.values()) + other = SiloParams(min_kinetic_score=0.0, lam=0.5) + assert silo.prepare(s, other, EX) == [] + done = silo_solve.solve_containers(s, other, EX) + assert all(v is not None for v in done.values()) + + +def test_inputs_and_stale_results( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """A changed raw file redoes prepare. + + Collect uses only results of the current plan and solve settings; a trial + found without data loses its earlier container and results. + """ + import os + + from giant_python.pipeline.silo_session import NO_DATA + + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PARAMS, EX) + silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, PARAMS, EX) + assert silo.prepare(s, PARAMS, EX) == [] + raw = s.raw(0, 0) + os.utime(raw, ns=(raw.stat().st_atime_ns, raw.stat().st_mtime_ns + 10**9)) + assert [u["unit"] for u in silo.prepare(s, PARAMS, EX)] == [(0, 0)] + + # results of three jobs with lam 0.9, then whole files with lam 0.5 + for job in silo_solve.dispatch(s, PARAMS, 3, EX): + silo_solve.solve_job(job, execution=EX) + split = list(s.results_dir.glob("*_s*.h5")) + assert split + other = SiloParams(min_kinetic_score=0.0, lam=0.5) + silo_solve.solve_containers(s, other, EX) + # the three jobs' range files are from other settings: left out + with pytest.warns(UserWarning, match="left out"): + silo_collect.collect(s, other, EX) + third = SiloParams(min_kinetic_score=0.0, lam=0.3) + with pytest.raises(FileNotFoundError, match="current"): + with pytest.warns(UserWarning): + silo_collect.collect(s, third, EX) + + # the trial has no data any more: its container and results go + def no_data(dat_path: str | Path, *args: Any, **kw: Any) -> TrialData: # noqa: ANN401 + """Path 1, trial 1 has no data now. + + Returns + ------- + TrialData + The trial from :func:`fake_load` for every other trial. + + Raises + ------ + ValueError + If `dat_path` is path 1, trial 1's raw file. + """ + if "DMD1-TRIAL000001" in str(dat_path): + raise ValueError(NO_DATA) + return fake_load(dat_path, *args, **kw) + + monkeypatch.setattr(trial_data_mod, "load_trial", no_data) + ex = SiloExecution(workers=1, solver_workers=1, solver_threads=1, overwrite=True) + silo.prepare(s, other, ex, units=[(0, 0)]) + assert s.skip_file(0, 0).exists() + assert not s.container_file(0, 0).exists() + assert not list(s.results_dir.glob("path1_trial0001*.h5")) + assert all(u != (0, 0) for u, _ in silo_solve._containers(s)) + silo_collect.collect(s, other, EX) + e = load_struct_h5(s.out_dir / "experiment_summary.h5") + frames = e["Path1"]["frame_info"]["trial_num_frames"].ravel() + assert frames.tolist() == [0, FRAMES[1], FRAMES[2]] + + # a raw file changed after solving: its results are stale + raw = s.raw(1, 1) + os.utime(raw, ns=(raw.stat().st_atime_ns, raw.stat().st_mtime_ns + 10**9)) + with pytest.raises(FileNotFoundError, match="current"): + with pytest.warns(UserWarning, match="left out"): + silo_collect.collect(s, other, EX) + + +def test_collect_and_dispatch_without_raw_data(tmp_path: Path, fake: None) -> None: + """Dispatch and collect need neither the raw data nor the movies. + + A short trial is one item of no work. + """ + import json + import shutil + + table = make_session(tmp_path) + s = SiloSession.open(table) + silo.localize(s, PARAMS, EX) + silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, PARAMS, EX) + shutil.rmtree(tmp_path / "raw") + for movie in (tmp_path / "motion_correction").glob("*.tif"): + movie.unlink() + with pytest.raises(ValueError): + SiloSession.open(table) + c = SiloSession.open(table, inputs="collect") + jobs = silo_solve.dispatch(c, PARAMS, 3, EX) + items = [it for j in jobs for it in json.loads(j.read_text(encoding="utf-8"))["items"]] + short = [it for it in items if it["container"] == "path1_trial0003.h5"] + assert len(short) == 1 and short[0]["work"] == 0 + for job in jobs: + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(c, PARAMS, EX) + e = load_struct_h5(c.out_dir / "experiment_summary.h5") + frames = e["Path1"]["frame_info"]["trial_num_frames"].ravel() + assert frames.tolist() == [FRAMES[0], FRAMES[1], FRAMES[2]] + + +def test_localize_fits_missing_peaks(tmp_path: Path, fake: None) -> None: + """Localization files without their peaks get them from silo-localize. + + Such files come from a streaming run stopped before its background fits. + """ + from giant_python.extraction.raster.stage_files import localization_attrs + + s = SiloSession.open(make_session(tmp_path)) + jobs = silo.localize_jobs(s, PARAMS, fit_peaks=False) + for job in jobs: + silo._localize_job(job) + f = s.localize_file(0, 0) + assert localization_attrs(f)["peaks_fitted"] == 0 + done = silo.localize(s, PARAMS, EX) + assert len(done) == N_PATHS * N_TRIALS # peak fits only + assert localization_attrs(f)["peaks_fitted"] == 1 + assert silo.localize(s, PARAMS, EX) == [] + + +def test_job_needs_its_container(tmp_path: Path, fake: None) -> None: + """A job refuses a container other than the one it was made for.""" + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PARAMS, EX) + silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, PARAMS, EX) + job = silo_solve.dispatch(s, PARAMS, 1, EX)[0] + with h5py.File(s.container_file(0, 0), "a") as f: + f.attrs["settings_hash"] = "other" + with pytest.raises(ValueError, match="not the container"): + silo_solve.solve_job(job, execution=EX) + + +def test_job_without_valid_kernel_is_matlabs(tmp_path: Path, fake: None) -> None: + """A job file written before valid_kernel existed solves at MATLAB's 3 x 3. + + Its params lack the field; its containers are solved at MATLAB's 3 x 3, + which they were prepared for, not at today's default. + """ + import json + from dataclasses import replace + + p3 = replace(PARAMS, valid_kernel=3) + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, p3, EX) + silo.plan(s, p3, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, p3, EX) + job = silo_solve.dispatch(s, p3, 1, EX)[0] + record = json.loads(job.read_text(encoding="utf-8")) + del record["params"]["valid_kernel"] + job.write_text(json.dumps(record), encoding="utf-8") + done = silo_solve.solve_job(job, execution=EX) + assert done["items"] + results = read_results(s.results_file(0, 0)) + assert results.results + + +def test_trial_without_data_is_skipped( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """A trial whose selected pixels have no sample is marked and left out of the summaries. + + Streamed and staged alike. + """ + from giant_python.pipeline.silo_session import NO_DATA + + def no_data(dat_path: str | Path, *args: Any, **kw: Any) -> TrialData: # noqa: ANN401 + """Path 2, trial 2 has no data. + + Returns + ------- + TrialData + The trial from :func:`fake_load` for every other trial. + + Raises + ------ + ValueError + If `dat_path` is path 2, trial 2's raw file. + """ + if "DMD2-TRIAL000002" in str(dat_path): + raise ValueError(NO_DATA) + return fake_load(dat_path, *args, **kw) + + monkeypatch.setattr(trial_data_mod, "load_trial", no_data) + for staged in (False, True): + root = tmp_path / str(staged) + table = make_session(root) + s = SiloSession.open(table) + if staged: + silo.localize(s, PARAMS, EX) + silo.plan(s, PARAMS, EX, seeds=_seeds(s, tmp_path)) + silo.prepare(s, PARAMS, EX) + assert not s.container_file(1, 1).exists() + silo_solve.solve_containers(s, PARAMS, EX) + silo_collect.collect(s, PARAMS, EX) + else: + silo.run_silo(table, PARAMS, EX, seeds_file=seeds_file(tmp_path)) + assert s.skip_file(1, 1).exists() + e = load_struct_h5(s.out_dir / "experiment_summary.h5") + frames = e["Path2"]["frame_info"]["trial_num_frames"].ravel() + assert frames.tolist() == [FRAMES[0], 0, FRAMES[2]] + # a rerun does not try the trial again + assert silo.prepare(s, PARAMS, EX, units=[(1, 1)]) == [] + + +def test_seeds_file_replaces_seeding(tmp_path: Path, fake: None) -> None: + """Seeds from a file (one-based, MATLAB's thetaf) give the plan's sources.""" + from giant_python.extraction.raster.plan import read_plan + from giant_python.extraction.raster.stage_files import ( + read_seeds, + write_seeds, + ) + + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PARAMS, EX) + seeds = np.array([[5.0, 7.0, 8.0, 1.0], [4.0, 16.0, 21.0, 1.0]]) + write_seeds(tmp_path / "seeds.h5", {1: seeds}, index_base=1) + got = read_seeds(tmp_path / "seeds.h5", 2) + assert got[1] is None + np.testing.assert_array_equal(got[0][:, 1:3], seeds[:, 1:3] - 1) + silo.plan(s, PARAMS, EX, paths=[0], seeds=got) + p = read_plan(s.plan_file(0)) + np.testing.assert_array_equal(p.source_rows, [6, 15]) + np.testing.assert_array_equal(p.source_cols, [7, 20]) + + +def test_cli(tmp_path: Path, fake: None, capsys: pytest.CaptureFixture[str]) -> None: + """The commands parse their options and run the stages.""" + assert parse_numbers("1,3-4") == [1, 3, 4] + assert parse_numbers(None) is None + with pytest.raises(ValueError): + parse_numbers("0") + (tmp_path / "p.json").write_text('{"lam": 0.5}') + args = build_parser().parse_args([ + "silo", + "t.h5", + "--params", + str(tmp_path / "p.json"), + "--set", + "nmf_iter=3", + "--set", + "footprint_variance=fixed", + "--peak-th", + "4", + "--no-trial-peaks", + ]) + p = params_from_args(args) + assert p.valid_kernel == 5 # the default + for cmd in ("silo", "silo-plan", "silo-prepare", "silo-collect"): + assert ( + params_from_args( + build_parser().parse_args([cmd, "t.h5", "--valid-kernel", "5"]) + ).valid_kernel + == 5 + ) + assert (p.lam, p.nmf_iter, p.footprint_variance, p.peak_th) == ( + 0.5, + 3, + "fixed", + 4.0, + ) + assert p.trial_peaks is False + with pytest.raises(ValueError): + params_from_args(build_parser().parse_args(["silo", "t", "--set", "x=1"])) + table = make_session(tmp_path / "s") + opts = ["--workers", "1", "--set", "min_kinetic_score=0"] + assert main(["silo-localize", str(table), "--paths", "1", *opts]) == 0 + assert main(["silo-localize", str(table), *opts]) == 0 + seeds = str(seeds_file(tmp_path)) + assert main(["silo-plan", str(table), "--seeds", seeds, *opts]) == 0 + assert main(["silo-prepare", str(table), "--trials", "1-3", *opts]) == 0 + assert ( + main([ + "silo-dispatch", + str(table), + "--machines", + "2", + "--solver-workers", + "1", + *opts, + ]) + == 0 + ) + jobs = sorted((tmp_path / "s" / "source_extraction" / "silo" / "jobs").glob("*.json")) + for job in jobs: + assert main(["silo-solve", str(job), "--solver-workers", "1"]) == 0 + assert main(["silo-collect", str(table), *opts]) == 0 + assert (tmp_path / "s" / "source_extraction" / "experiment_summary.h5").exists() + capsys.readouterr() + + +class _FakePool: + """A pool whose tasks finish at a set time on a controlled clock.""" + + def __init__(self, now: list[float], finish_at: list[float | None]) -> None: + """Take the clock and each task's finish time.""" + self.now, self.finish_at, self.futures = now, list(finish_at), [] + + def submit(self, *args: object, **kwargs: object) -> Future[None]: + """Return a future. + + It is finished at once (before the next submit) when its time is None. + + Returns + ------- + Future[None] + The future of the submitted task. + """ + import concurrent.futures as cf + + f = cf.Future() + self.now[0] += 0.01 # submitting takes time + if self.finish_at[len(self.futures)] is None: + f.set_result(None) + self.futures.append(f) + return f + + +def test_solve_span_is_the_last_subproblem_solved(monkeypatch: pytest.MonkeyPatch) -> None: + """A trial's solve span ends when its last subproblem is done. + + A subproblem solved while the rest are still submitted keeps its own + time, a trial collected later still ends then, and a trial solved here + ends when that solve returns. Controlled clock, set completion order. + """ + import types + + from giant_python.extraction.raster import solver as solver_mod + + now = [0.0] + monkeypatch.setattr(silo, "time", types.SimpleNamespace(perf_counter=lambda: now[0])) + sub = types.SimpleNamespace(n_pixels=1, n_frames=1, n_sources=1) + # the first task is done before the second is submitted + pool = _FakePool(now, [None, 0.2]) + done = silo._Done() + futures, _ = silo._submit([sub, sub], None, EX.solver_options(), pool, done) + assert done.times == [0.01] + now[0] = 0.2 + pool.futures[1].set_result(None) # the last subproblem + now[0] = 0.6 # collected later + p = silo._Pending(0, 0, None, [], futures, [], {}, Path("x"), 0.0, done) + assert silo._solve_span(p, 0.0) == (0.0, 0.2) + # solved here: done when the solve returned + monkeypatch.setattr( + solver_mod, + "solve_subproblems", + lambda subs, sp, options: now.__setitem__(0, 0.9) or [1], + ) + now[0] = 0.7 + done = silo._Done() + _, results = silo._submit([sub], None, EX.solver_options(), None, done) + now[0] = 1.5 + q = silo._Pending(0, 1, None, [], [], results, {}, Path("y"), 0.7, done) + assert silo._solve_span(q, 0.0) == (0.7, 0.9) + + +def test_pool_workers_are_spawned_with_their_thread_counts() -> None: + """Pool workers start a fresh interpreter (not a fork of this one). + + So the thread variables are set before numpy loads its BLAS. + """ + import os + + from giant_python.pipeline.silo_session import make_pool + + with make_pool(1, 2) as pool: + assert pool._mp_context.get_start_method() == "spawn" + for name in ( + "OMP_NUM_THREADS", + "MKL_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + ): + assert pool.submit(os.getenv, name).result() == "2" diff --git a/tests/raster/test_raster_solver.py b/tests/raster/test_raster_solver.py index baf73769..0039c573 100644 --- a/tests/raster/test_raster_solver.py +++ b/tests/raster/test_raster_solver.py @@ -1,527 +1,572 @@ -"""Tests of the subproblem solver end to end. - -Also tests the assembly of a trial's results and the trial's activity traces. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - assemble_results, - conv_same, - estimate_photon_scale, - process_result, - solve_subproblem, - solve_subproblems, -) -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, - conv_operator, - initial_footprints, - sel_coords, -) - -DATA = Path(__file__).parent / "data" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" -HELPERS = DATA / "matlab_solver_helpers.h5" -# MATLAB's 3 x 3 support: the outputs are compared with MATLAB's (the -# default is 5 x 5; test_valid_kernel_lets_a_wide_footprint_be_fit sets it) -PARAMS = SolverParams(valid_kernel=3) -# MATLAB's loss for the footprint fit (the default holds its variance) -MATLAB_LOSS = replace(PARAMS, footprint_variance="model") - -# the real subproblem and MATLAB's outputs for it -SubproblemFixture = tuple[Subproblem, dict[str, np.ndarray]] - - -def _corr(a: np.ndarray, b: np.ndarray) -> float: - """Pearson correlation of two traces.""" - return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) - - -@pytest.fixture(scope="module") -def fixture() -> SubproblemFixture: - """Load a real two-source subproblem and MATLAB's outputs for it.""" - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - out = {k: v[()] for k, v in f["out"].items()} - return sub, out - - -@pytest.fixture(scope="module") -def solved(fixture: SubproblemFixture) -> SubproblemResult: - """Return the solver's result on the fixture, with its baseline.""" - sub, _ = fixture - return solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) - - -@pytest.fixture(scope="module") -def solved_matlab_loss(fixture: SubproblemFixture) -> SubproblemResult: - """Return the result with MATLAB's loss for the footprint fit.""" - sub, _ = fixture - opt = SolverOptions(keep_baseline=True) - return solve_subproblem(sub, MATLAB_LOSS, opt) - - -def test_agrees_with_matlab( - fixture: SubproblemFixture, solved_matlab_loss: SubproblemResult -) -> None: - """With MATLAB's loss, the converged solver's outputs are close to MATLAB's. - - MATLAB's fits stop early: same footprints and least squares, similar - activity. - """ - sub, out = fixture - r = solved_matlab_loss - assert r.footprints.shape == (sub.n_pixels, 2) - assert r.events.shape == r.ls.shape == r.f0.shape == (2, 2, 1000) - assert r.baseline.shape == (2, sub.n_pixels, 1000) - np.testing.assert_allclose(r.footprints.sum(0), 1.0, atol=1e-12) - assert r.events.min() >= 0 - for j in range(2): - hp, hm = r.footprints[:, j], out["H"][:, j] - cos = hp @ hm / np.sqrt((hp @ hp) * (hm @ hm)) - assert cos > 0.97 - assert _corr(r.ls[0, j], out["LS"][0, j]) > 0.97 - x = conv_same(r.events[0, j], PARAMS.k) - xm = conv_same(out["S"][0, j], PARAMS.k) - assert _corr(x, xm) > 0.9 - assert 0.8 < x.sum() / xm.sum() < 1.25 - ratio = r.f0[:, j].mean(1) / out["F0"][:, j].mean(1) - assert np.all(np.abs(ratio - 1) < 0.1) - assert np.all(np.isfinite(r.snr)) and np.all(r.snr > 0) - assert np.all(np.abs(r.snr / out["SNR"] - 1) < 0.3) - # channel 2's least squares do not depend on the activity fits - for j in range(2): - assert _corr(r.ls[1, j], out["LS"][1, j]) > 0.97 - - -def test_fits_converge_and_are_recorded(solved: SubproblemResult) -> None: - """Every fit ends on its tolerance, and its record is kept.""" - fits = {k: v for k, v in solved.info.items() if isinstance(v, dict)} - assert set(fits) == { - "activity1", - "footprints1", - "activity2", - "debias", - "activity_ch2", - "debias_ch2", - } - for name, fit in fits.items(): - assert fit["converged"], name - assert fit["iterations"] <= 20 and np.isfinite(fit["loss"]) - assert solved.info["baseline1_seconds"] > 0 - - -def test_events_below_the_floor_are_dropped(solved: SubproblemResult) -> None: - """The debias refit keeps the events of 0.1 or more only. - - It does not move the others' places. - """ - ev = solved.events - assert not np.any((ev > 0) & (ev < 1e-3)) - assert 0.01 < (ev[0] > 0).mean() < 0.5 - - -def test_batch_matches_single_solves(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """Subproblems of different sizes solved together get the results they get alone. - - They agree to the fits' tolerance. - """ - sub, _ = fixture - # a smaller subproblem: the first source and the pixels near it - rows, cols = sel_coords(sub.sel) - r0, c0 = sub.sources_rc[0] - keep = np.hypot(rows - r0, cols - c0) <= 4.2 - sel = np.zeros_like(sub.sel) - sel[rows[keep], cols[keep]] = True - small = Subproblem(y=sub.y[:, keep], finv=sub.finv[keep], sel=sel, sources_rc=[[r0, c0]]) - alone = solve_subproblem(small, PARAMS) - both = solve_subproblems([small, sub], PARAMS, SolverOptions(batch_bytes=1e9)) - assert both[0].footprints.shape == (int(keep.sum()), 1) - for got, ref in ((both[0], alone), (both[1], solved)): - np.testing.assert_allclose(got.footprints, ref.footprints, atol=1e-6) - np.testing.assert_allclose(got.snr, ref.snr, rtol=1e-4) - np.testing.assert_allclose(got.f0, ref.f0, rtol=1e-5) - scale = ref.events.max() - np.testing.assert_allclose(got.events, ref.events, atol=1e-3 * scale) - assert got.baseline is None - - -def test_batches_count_the_footprint_filter( - fixture: SubproblemFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """The size of a batch counts each member's data and its filter arrays. - - The filter arrays are dense, pixels x pixels. - """ - import giant_python.extraction.raster.solver as solver - - sub, _ = fixture - sizes = [] - monkeypatch.setattr( - solver, - "_solve_batch", - lambda subs, p, o: sizes.append(len(subs)) or subs, - ) - n_px, n_t = sub.n_pixels, sub.n_frames - member = (n_px * n_t + 4 * n_px**2) * 8 - solve_subproblems([sub] * 5, PARAMS, SolverOptions(batch_bytes=2 * member)) - assert sizes == [2, 2, 1] - sizes.clear() - # the data alone would let three through - solve_subproblems([sub] * 3, PARAMS, SolverOptions(batch_bytes=3 * n_px * n_t * 8)) - assert sizes == [2, 1] - sizes.clear() - solve_subproblems([sub] * 3, PARAMS) # the CPU's default: one at a time - assert sizes == [1, 1, 1] - - -def test_trials_of_different_length_are_grouped( - fixture: SubproblemFixture, solved: SubproblemResult -) -> None: - """Subproblems with other numbers of frames or channels are solved in their own batches. - - They are returned in the order given. - """ - sub, _ = fixture - short = replace(sub, y=sub.y[:1, :, :600].copy(), finv=sub.finv[:, :600].copy()) - out = solve_subproblems([short, sub], PARAMS, SolverOptions(batch_bytes=1)) - assert out[0].events.shape == (1, 2, 600) - assert out[1].events.shape == (2, 2, 1000) - np.testing.assert_allclose(out[1].footprints, solved.footprints, atol=1e-6) - - -def test_more_than_two_channels_are_refused(fixture: SubproblemFixture) -> None: - """The solver fits the activity channel and one more, as MATLAB's. - - A third channel is refused, not dropped. - """ - sub, _ = fixture - three = replace(sub, y=np.concatenate([sub.y, sub.y[:1]])) - with pytest.raises(ValueError, match="3 channels"): - solve_subproblem(three, PARAMS) - - -def test_data_the_fits_cannot_weigh_are_refused(fixture: SubproblemFixture) -> None: - """Samples and variance multipliers the fits cannot weigh are input errors, not NaN results. - - That is, NaN samples and variance multipliers that are not positive and - finite. - """ - sub, _ = fixture - y = sub.y[:1].copy() - y[0, 3, 7] = np.nan - with pytest.raises(ValueError, match="NaN or infinite"): - solve_subproblem(replace(sub, y=y), PARAMS) - for bad in (0.0, -1.0, np.nan, np.inf): - finv = sub.finv.copy() - finv[5, 9] = bad - with pytest.raises(ValueError, match="variance multiplier"): - solve_subproblem(replace(sub, y=sub.y[:1], finv=finv), PARAMS) - empty = replace(sub, y=sub.y[:1], sources_rc=np.zeros((0, 2), int)) - with pytest.raises(ValueError, match="no source"): - solve_subproblem(empty, PARAMS) - assert solve_subproblems([], PARAMS) == [] - - -def test_options_are_checked() -> None: - """Options the fits cannot run with are refused when they are made.""" - with pytest.raises(ValueError, match="dtype"): - SolverOptions(dtype="float16") - with pytest.raises(ValueError, match="max_iter"): - SolverOptions(max_iter=-1) - with pytest.raises(ValueError, match="names no fit"): - SolverOptions(fit_max_iter={"footprint1": 0}) - with pytest.raises(ValueError, match="whole number"): - SolverOptions(fit_max_iter={"footprints1": -1}) - with pytest.raises(ValueError, match="batch_bytes"): - SolverOptions(batch_bytes=-1.0) - caps = {"activity2": 3, "debias": 0, "activity_ch2": 1, "debias_ch2": 2} - opt = SolverOptions(fit_max_iter=caps, max_iter=7) - assert opt.fit_options("activity2")["max_iter"] == 3 - assert opt.fit_options("activity1")["max_iter"] == 7 - - -def test_float32_fits_are_close(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """Fits in float32 give nearly the float64 result.""" - sub, _ = fixture - r = solve_subproblem(sub, PARAMS, SolverOptions(dtype="float32")) - for j in range(2): - assert _corr(r.footprints[:, j], solved.footprints[:, j]) > 0.999 - x = conv_same(r.events[0, j], PARAMS.k) - ref = conv_same(solved.events[0, j], PARAMS.k) - assert _corr(x, ref) > 0.995 - np.testing.assert_allclose(r.f0, solved.f0, rtol=1e-2) - - -def test_iteration_cap_is_reported(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """With one Newton iteration per fit, the fits are marked as not converged. - - They also reach higher losses. - """ - sub, _ = fixture - r = solve_subproblem(sub, PARAMS, SolverOptions(max_iter=1)) - assert not r.info["activity1"]["converged"] - assert r.info["activity1"]["iterations"] == 1 - assert r.info["activity1"]["loss"] > solved.info["activity1"]["loss"] - - -def test_single_fits_can_be_capped(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """A cap on one fit leaves the others to converge. - - A cap of 0 on the footprint fit keeps the starting footprints' shape. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - opt = SolverOptions(fit_max_iter={"footprints1": 0}) - r = solve_subproblem(one, PARAMS, opt) - assert r.info["footprints1"]["iterations"] == 0 - assert not r.info["footprints1"]["converged"] - assert r.info["activity1"]["converged"] and r.info["activity2"]["converged"] - assert r.info["activity1"]["loss"] == pytest.approx(solved.info["activity1"]["loss"], rel=1e-9) - # the starting Hs through the footprint filter, normalized - start = initial_footprints(sub.sel, sub.sources_rc, PARAMS.sigma_px)[0] - h = conv_operator(sub.sel, PARAMS.hfilter) @ start - np.testing.assert_allclose(r.footprints, h / h.sum(0), atol=1e-12) - assert np.abs(r.footprints - solved.footprints).max() > 1e-3 - - -def test_default_footprint_fit_holds_its_variance( - solved: SubproblemResult, solved_matlab_loss: SubproblemResult -) -> None: - """By default the variance of the footprint fit is held at its value at the fit's start. - - So the fit does not gain from raising the model: the footprints come out - more compact than with MATLAB's loss, and F0, which scales with their - spread, lower. Both fits converge. - """ - assert PARAMS.footprint_variance == "fixed" - fixed, model = solved, solved_matlab_loss - assert fixed.info["footprints1"]["converged"] - assert model.info["footprints1"]["converged"] - np.testing.assert_allclose(fixed.footprints.sum(0), 1.0, atol=1e-12) - compact = (fixed.footprints**2).sum(0) - assert np.all(compact > 1.02 * (model.footprints**2).sum(0)) - assert np.all(fixed.f0[0].mean(1) < model.f0[0].mean(1)) - for j in range(2): - assert _corr(fixed.footprints[:, j], model.footprints[:, j]) > 0.98 - # what precedes the footprint fit does not depend on the choice - assert fixed.info["activity1"]["loss"] == pytest.approx( - model.info["activity1"]["loss"], rel=1e-12 - ) - with pytest.raises(ValueError, match="footprint_variance"): - replace(PARAMS, footprint_variance="other") - - -def test_debias_variance_model_gives_larger_events( - fixture: SubproblemFixture, solved: SubproblemResult -) -> None: - """The model-variance debias refit rewards larger activity. - - This is MATLAB's behaviour before the fixed variance; the rest is unchanged. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - r = solve_subproblem(one, replace(PARAMS, debias_variance="model")) - assert r.events.shape == (1, 2, 1000) - np.testing.assert_allclose(r.footprints, solved.footprints, atol=1e-6) - np.testing.assert_allclose(r.ls[0], solved.ls[0], atol=1e-6) - assert r.events.sum() > 1.1 * solved.events[0].sum() - # both refit the events that the L1 fits found - same = (r.events[0] > 0) == (solved.events[0] > 0) - assert same.mean() > 0.99 - - -def test_one_outer_iteration(fixture: SubproblemFixture) -> None: - """With nmf_iter 1 the footprints stay at their start. - - No baseline or footprint fit runs. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - r = solve_subproblem(one, replace(PARAMS, nmf_iter=1)) - assert "footprints1" not in r.info and "activity1" in r.info - assert r.events.shape == (1, 2, 1000) - - -def test_photon_scale_matches_matlab() -> None: - """ExtractTrial's photon scale estimate.""" - with h5py.File(HELPERS, "r") as f: - finv = f["photon/Finv"][()] - y = 3 * f["photon/counts"][()] * np.sqrt(finv) - ref = float(f["photon/scale"][()]) - assert estimate_photon_scale(y, finv) == pytest.approx(ref, rel=1e-12) - - -def _result(n_px: int, n_src: int, n_t: int, value: float, n_ch: int = 2) -> SubproblemResult: - """Build a subproblem result filled with a constant.""" - return SubproblemResult( - footprints=np.full((n_px, n_src), value), - events=np.full((n_ch, n_src, n_t), value), - ls=np.full((n_ch, n_src, n_t), 2 * value), - f0=np.full((n_ch, n_src, n_t), 3 * value), - snr=np.full(n_src, 10 * value), - ) - - -def _placed(pixels: list[int], sources: list[int], n_t: int) -> Subproblem: - """Build a subproblem that only says where its results go.""" - n_px = len(pixels) - return Subproblem( - y=np.zeros((2, n_px, n_t), np.float32), - finv=np.ones((n_px, n_t), np.float32), - sel=np.ones((1, n_px), dtype=bool), - sources_rc=[[0, j] for j in range(len(sources))], - pixels=np.array(pixels), - sources=np.array(sources), - ) - - -def test_assemble_results() -> None: - """Results go to their pixels and sources. - - Events, least squares and F0 return to movie units; what no subproblem - covers is NaN. - """ - subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] - results = [_result(3, 1, 6, 1.0), _result(2, 2, 6, 2.0)] - t = assemble_results(subs, results, 6, 5, photon_scale=25.0) - assert t.footprints.dtype == np.float32 - assert t.footprints.shape == (6, 5) - assert np.all(t.footprints[[0, 1, 4], 2] == 1.0) - assert np.all(t.footprints[[2, 4]][:, [0, 3]] == 2.0) - assert np.isnan(t.footprints[0, 0]) and np.isnan(t.footprints[5]).all() - assert t.events.shape == t.ls.shape == t.f0.shape == (2, 5, 6) - assert np.all(t.events[:, 2] == 25.0) and np.all(t.events[:, 3] == 50.0) - assert np.all(t.ls[:, 0] == 100.0) and np.all(t.f0[:, 2] == 75.0) - assert np.isnan(t.events[:, [1, 4]]).all() - assert np.array_equal(t.snr[[0, 2, 3]], [20.0, 10.0, 20.0]) - assert np.isnan(t.snr[[1, 4]]).all() - with pytest.raises(ValueError, match="pixels and sources"): - assemble_results([replace(subs[0], pixels=None)], results[:1], 6, 5, 25.0) - # indices that would put results in the wrong place are refused - for bad, message in ( - (dict(pixels=np.array([0, 1, 6])), "pixels indices must lie"), - (dict(sources=np.array([5])), "sources indices must lie"), - (dict(pixels=np.array([0, 1])), "3 pixels and 2 indices for"), - (dict(pixels=np.array([0, 1, 1])), "pixels indices repeat"), - ): - with pytest.raises(ValueError, match=message): - assemble_results([replace(subs[0], **bad)], results[:1], 6, 5, 25.0) - with pytest.raises(ValueError, match="negative index"): - replace(subs[0], pixels=np.array([0, -1, 4])) - # one result per subproblem, each of the trial's channels and frames - with pytest.raises(ValueError, match="2 subproblems and 1 results"): - assemble_results(subs, results[:1], 6, 5, 25.0) - with pytest.raises(ValueError, match="at least one"): - assemble_results([], [], 6, 5, 25.0) - one_channel = _result(2, 2, 6, 2.0, n_ch=1) - with pytest.raises(ValueError, match="events are"): - assemble_results(subs, [results[0], one_channel], 6, 5, 25.0) - short = _result(2, 2, 5, 2.0) - with pytest.raises(ValueError, match="events are"): - assemble_results(subs, [results[0], short], 6, 5, 25.0) - wrong_snr = _result(2, 2, 6, 2.0) - wrong_snr.snr = np.ones(3) - with pytest.raises(ValueError, match="one SNR per source"): - assemble_results(subs, [results[0], wrong_snr], 6, 5, 25.0) - - -def test_process_result() -> None: - """The denoised activity is the events convolved with each channel's kernel. - - Discarded frames are NaN in the traces, as MATLAB leaves them (channel 2's - events keep their values). - """ - n_t = 40 - rng = np.random.default_rng(0) - subs = [_placed([0, 1], [0, 1], n_t)] - res = _result(2, 2, n_t, 1.0) - res.events = (rng.random((2, 2, n_t)) < 0.2) * rng.random((2, 2, n_t)) - trial = assemble_results(subs, [res], 2, 2, photon_scale=2.0) - discard = np.zeros(n_t, dtype=bool) - discard[[3, 4, 30]] = True - params = SolverParams(tau_s=0.01, tau2_s=0.02) - act = process_result(trial, params, discard) - keep = ~discard - np.testing.assert_allclose( - act.denoised[0][:, keep], - conv_same(trial.events[0], params.k)[:, keep], - ) - np.testing.assert_allclose( - act.denoised[1][:, keep], - conv_same(trial.events[1], params.k2)[:, keep], - ) - assert np.isnan(act.denoised[:, :, discard]).all() - assert np.isnan(act.ls[:, :, discard]).all() - assert np.isnan(act.events[0][:, discard]).all() - assert np.array_equal(act.events[1], trial.events[1]) - assert np.array_equal(act.events[0][:, keep], trial.events[0][:, keep]) - assert act.f0 is trial.f0 and act.snr is trial.snr - with pytest.raises(ValueError, match="discard has 39 frames"): - process_result(trial, params, discard[:-1]) - # the trial's own arrays are left as they were - assert not np.isnan(trial.events).any() - - -def test_conv_same_is_matlabs() -> None: - """'same' keeps the first argument's length, also below the kernel's.""" - k = np.array([0.0, 0.0, 1.0, 0.5, 0.25]) - x = np.array([[1.0, 0.0, 0.0, 2.0]]) - assert np.array_equal(conv_same(x, k), [[1.0, 0.5, 0.25, 2.0]]) - assert np.array_equal(conv_same(x[:, :2], k), [[1.0, 0.5]]) - - -def _rms_width(h: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> float: - """RMS width per axis of a footprint about its centroid.""" - h = np.clip(h, 0, None) / np.clip(h, 0, None).sum() - m = np.array([h @ rows, h @ cols]) - return float(np.sqrt((h @ ((rows - m[0]) ** 2 + (cols - m[1]) ** 2)) / 2)) - - -def test_valid_kernel_lets_a_wide_footprint_be_fit() -> None: - """A sigma-1.8 source on its true baseline, fit with the 3 x 3 and 5 x 5 supports. - - With the 3 x 3 support the fitted footprint stops near its ceiling (1.56 px), - with 5 x 5 it gets close to the truth (1.8 px). - """ - rng = np.random.default_rng(3) - sel = np.ones((13, 13), dtype=bool) - rows, cols = sel_coords(sel) - rows, cols = rows.astype(float), cols.astype(float) - h = np.exp(-((rows - 6) ** 2 + (cols - 6) ** 2) / (2 * 1.8**2)) - h /= h.sum() - n = 8000 - ev = np.where(rng.random(n) < 0.01, rng.exponential(150.0, n), 0.0) - x = np.convolve(ev, PARAMS.k, mode="same") - b = np.full((h.size, n), 2.0) - y = rng.poisson(b + h[:, None] * x[None]).astype(np.float64)[None] - sub = Subproblem( - y=y, - finv=np.ones(y.shape[1:]), - sel=sel, - sources_rc=np.array([[6, 6]]), - baseline=b, - ) - true_w = _rms_width(h, rows, cols) - widths = {} - for vk in (3, 5): - p = replace(PARAMS, baseline_mode="fixed", valid_kernel=vk) - res = solve_subproblem(sub, p) - widths[vk] = _rms_width(res.footprints[:, 0], rows, cols) - assert widths[3] < 1.57 - assert abs(widths[5] - true_w) < 0.1 - assert abs(widths[5] - true_w) < abs(widths[3] - true_w) / 2 +"""Tests of the subproblem solver end to end. + +Also tests the assembly of a trial's results and the trial's activity traces. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + assemble_results, + conv_same, + estimate_photon_scale, + process_result, + solve_subproblem, + solve_subproblems, +) +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, + conv_operator, + initial_footprints, + sel_coords, +) + +DATA = Path(__file__).parent / "data" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" +HELPERS = DATA / "matlab_solver_helpers.h5" +# MATLAB's 3 x 3 support: the outputs are compared with MATLAB's (the +# default is 5 x 5; test_valid_kernel_lets_a_wide_footprint_be_fit sets it) +PARAMS = SolverParams(valid_kernel=3) +# MATLAB's loss for the footprint fit (the default holds its variance) +MATLAB_LOSS = replace(PARAMS, footprint_variance="model") + +# the real subproblem and MATLAB's outputs for it +SubproblemFixture = tuple[Subproblem, dict[str, np.ndarray]] + + +def _corr(a: np.ndarray, b: np.ndarray) -> float: + """Pearson correlation of two traces. + + Returns + ------- + float + The correlation coefficient of the flattened traces. + """ + return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) + + +@pytest.fixture(scope="module") +def fixture() -> SubproblemFixture: + """Load a real two-source subproblem and MATLAB's outputs for it. + + Returns + ------- + sub : Subproblem + The subproblem. + out : dict[str, np.ndarray] + MATLAB's outputs for it, by name. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + out = {k: v[()] for k, v in f["out"].items()} + return sub, out + + +@pytest.fixture(scope="module") +def solved(fixture: SubproblemFixture) -> SubproblemResult: + """Return the solver's result on the fixture, with its baseline. + + Returns + ------- + SubproblemResult + The result of solve_subproblem with the default test parameters. + """ + sub, _ = fixture + return solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) + + +@pytest.fixture(scope="module") +def solved_matlab_loss(fixture: SubproblemFixture) -> SubproblemResult: + """Return the result with MATLAB's loss for the footprint fit. + + Returns + ------- + SubproblemResult + The result of solve_subproblem with MATLAB_LOSS, with its baseline. + """ + sub, _ = fixture + opt = SolverOptions(keep_baseline=True) + return solve_subproblem(sub, MATLAB_LOSS, opt) + + +def test_agrees_with_matlab( + fixture: SubproblemFixture, solved_matlab_loss: SubproblemResult +) -> None: + """With MATLAB's loss, the converged solver's outputs are close to MATLAB's. + + MATLAB's fits stop early: same footprints and least squares, similar + activity. + """ + sub, out = fixture + r = solved_matlab_loss + assert r.footprints.shape == (sub.n_pixels, 2) + assert r.events.shape == r.ls.shape == r.f0.shape == (2, 2, 1000) + assert r.baseline.shape == (2, sub.n_pixels, 1000) + np.testing.assert_allclose(r.footprints.sum(0), 1.0, atol=1e-12) + assert r.events.min() >= 0 + for j in range(2): + hp, hm = r.footprints[:, j], out["H"][:, j] + cos = hp @ hm / np.sqrt((hp @ hp) * (hm @ hm)) + assert cos > 0.97 + assert _corr(r.ls[0, j], out["LS"][0, j]) > 0.97 + x = conv_same(r.events[0, j], PARAMS.k) + xm = conv_same(out["S"][0, j], PARAMS.k) + assert _corr(x, xm) > 0.9 + assert 0.8 < x.sum() / xm.sum() < 1.25 + ratio = r.f0[:, j].mean(1) / out["F0"][:, j].mean(1) + assert np.all(np.abs(ratio - 1) < 0.1) + assert np.all(np.isfinite(r.snr)) and np.all(r.snr > 0) + assert np.all(np.abs(r.snr / out["SNR"] - 1) < 0.3) + # channel 2's least squares do not depend on the activity fits + for j in range(2): + assert _corr(r.ls[1, j], out["LS"][1, j]) > 0.97 + + +def test_fits_converge_and_are_recorded(solved: SubproblemResult) -> None: + """Every fit ends on its tolerance, and its record is kept.""" + fits = {k: v for k, v in solved.info.items() if isinstance(v, dict)} + assert set(fits) == { + "activity1", + "footprints1", + "activity2", + "debias", + "activity_ch2", + "debias_ch2", + } + for name, fit in fits.items(): + assert fit["converged"], name + assert fit["iterations"] <= 20 and np.isfinite(fit["loss"]) + assert solved.info["baseline1_seconds"] > 0 + + +def test_events_below_the_floor_are_dropped(solved: SubproblemResult) -> None: + """The debias refit keeps the events of 0.1 or more only. + + It does not move the others' places. + """ + ev = solved.events + assert not np.any((ev > 0) & (ev < 1e-3)) + assert 0.01 < (ev[0] > 0).mean() < 0.5 + + +def test_batch_matches_single_solves(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """Subproblems of different sizes solved together get the results they get alone. + + They agree to the fits' tolerance. + """ + sub, _ = fixture + # a smaller subproblem: the first source and the pixels near it + rows, cols = sel_coords(sub.sel) + r0, c0 = sub.sources_rc[0] + keep = np.hypot(rows - r0, cols - c0) <= 4.2 + sel = np.zeros_like(sub.sel) + sel[rows[keep], cols[keep]] = True + small = Subproblem(y=sub.y[:, keep], finv=sub.finv[keep], sel=sel, sources_rc=[[r0, c0]]) + alone = solve_subproblem(small, PARAMS) + both = solve_subproblems([small, sub], PARAMS, SolverOptions(batch_bytes=1e9)) + assert both[0].footprints.shape == (int(keep.sum()), 1) + for got, ref in ((both[0], alone), (both[1], solved)): + np.testing.assert_allclose(got.footprints, ref.footprints, atol=1e-6) + np.testing.assert_allclose(got.snr, ref.snr, rtol=1e-4) + np.testing.assert_allclose(got.f0, ref.f0, rtol=1e-5) + scale = ref.events.max() + np.testing.assert_allclose(got.events, ref.events, atol=1e-3 * scale) + assert got.baseline is None + + +def test_batches_count_the_footprint_filter( + fixture: SubproblemFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """The size of a batch counts each member's data and its filter arrays. + + The filter arrays are dense, pixels x pixels. + """ + import giant_python.extraction.raster.solver as solver + + sub, _ = fixture + sizes = [] + monkeypatch.setattr( + solver, + "_solve_batch", + lambda subs, p, o: sizes.append(len(subs)) or subs, + ) + n_px, n_t = sub.n_pixels, sub.n_frames + member = (n_px * n_t + 4 * n_px**2) * 8 + solve_subproblems([sub] * 5, PARAMS, SolverOptions(batch_bytes=2 * member)) + assert sizes == [2, 2, 1] + sizes.clear() + # the data alone would let three through + solve_subproblems([sub] * 3, PARAMS, SolverOptions(batch_bytes=3 * n_px * n_t * 8)) + assert sizes == [2, 1] + sizes.clear() + solve_subproblems([sub] * 3, PARAMS) # the CPU's default: one at a time + assert sizes == [1, 1, 1] + + +def test_trials_of_different_length_are_grouped( + fixture: SubproblemFixture, solved: SubproblemResult +) -> None: + """Subproblems with other numbers of frames or channels are solved in their own batches. + + They are returned in the order given. + """ + sub, _ = fixture + short = replace(sub, y=sub.y[:1, :, :600].copy(), finv=sub.finv[:, :600].copy()) + out = solve_subproblems([short, sub], PARAMS, SolverOptions(batch_bytes=1)) + assert out[0].events.shape == (1, 2, 600) + assert out[1].events.shape == (2, 2, 1000) + np.testing.assert_allclose(out[1].footprints, solved.footprints, atol=1e-6) + + +def test_more_than_two_channels_are_refused(fixture: SubproblemFixture) -> None: + """The solver fits the activity channel and one more, as MATLAB's. + + A third channel is refused, not dropped. + """ + sub, _ = fixture + three = replace(sub, y=np.concatenate([sub.y, sub.y[:1]])) + with pytest.raises(ValueError, match="3 channels"): + solve_subproblem(three, PARAMS) + + +def test_data_the_fits_cannot_weigh_are_refused(fixture: SubproblemFixture) -> None: + """Samples and variance multipliers the fits cannot weigh are input errors, not NaN results. + + That is, NaN samples and variance multipliers that are not positive and + finite. + """ + sub, _ = fixture + y = sub.y[:1].copy() + y[0, 3, 7] = np.nan + with pytest.raises(ValueError, match="NaN or infinite"): + solve_subproblem(replace(sub, y=y), PARAMS) + for bad in (0.0, -1.0, np.nan, np.inf): + finv = sub.finv.copy() + finv[5, 9] = bad + with pytest.raises(ValueError, match="variance multiplier"): + solve_subproblem(replace(sub, y=sub.y[:1], finv=finv), PARAMS) + empty = replace(sub, y=sub.y[:1], sources_rc=np.zeros((0, 2), int)) + with pytest.raises(ValueError, match="no source"): + solve_subproblem(empty, PARAMS) + assert solve_subproblems([], PARAMS) == [] + + +def test_options_are_checked() -> None: + """Options the fits cannot run with are refused when they are made.""" + with pytest.raises(ValueError, match="dtype"): + SolverOptions(dtype="float16") + with pytest.raises(ValueError, match="max_iter"): + SolverOptions(max_iter=-1) + with pytest.raises(ValueError, match="names no fit"): + SolverOptions(fit_max_iter={"footprint1": 0}) + with pytest.raises(ValueError, match="whole number"): + SolverOptions(fit_max_iter={"footprints1": -1}) + with pytest.raises(ValueError, match="batch_bytes"): + SolverOptions(batch_bytes=-1.0) + caps = {"activity2": 3, "debias": 0, "activity_ch2": 1, "debias_ch2": 2} + opt = SolverOptions(fit_max_iter=caps, max_iter=7) + assert opt.fit_options("activity2")["max_iter"] == 3 + assert opt.fit_options("activity1")["max_iter"] == 7 + + +def test_float32_fits_are_close(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """Fits in float32 give nearly the float64 result.""" + sub, _ = fixture + r = solve_subproblem(sub, PARAMS, SolverOptions(dtype="float32")) + for j in range(2): + assert _corr(r.footprints[:, j], solved.footprints[:, j]) > 0.999 + x = conv_same(r.events[0, j], PARAMS.k) + ref = conv_same(solved.events[0, j], PARAMS.k) + assert _corr(x, ref) > 0.995 + np.testing.assert_allclose(r.f0, solved.f0, rtol=1e-2) + + +def test_iteration_cap_is_reported(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """With one Newton iteration per fit, the fits are marked as not converged. + + They also reach higher losses. + """ + sub, _ = fixture + r = solve_subproblem(sub, PARAMS, SolverOptions(max_iter=1)) + assert not r.info["activity1"]["converged"] + assert r.info["activity1"]["iterations"] == 1 + assert r.info["activity1"]["loss"] > solved.info["activity1"]["loss"] + + +def test_single_fits_can_be_capped(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """A cap on one fit leaves the others to converge. + + A cap of 0 on the footprint fit keeps the starting footprints' shape. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + opt = SolverOptions(fit_max_iter={"footprints1": 0}) + r = solve_subproblem(one, PARAMS, opt) + assert r.info["footprints1"]["iterations"] == 0 + assert not r.info["footprints1"]["converged"] + assert r.info["activity1"]["converged"] and r.info["activity2"]["converged"] + assert r.info["activity1"]["loss"] == pytest.approx(solved.info["activity1"]["loss"], rel=1e-9) + # the starting Hs through the footprint filter, normalized + start = initial_footprints(sub.sel, sub.sources_rc, PARAMS.sigma_px)[0] + h = conv_operator(sub.sel, PARAMS.hfilter) @ start + np.testing.assert_allclose(r.footprints, h / h.sum(0), atol=1e-12) + assert np.abs(r.footprints - solved.footprints).max() > 1e-3 + + +def test_default_footprint_fit_holds_its_variance( + solved: SubproblemResult, solved_matlab_loss: SubproblemResult +) -> None: + """By default the variance of the footprint fit is held at its value at the fit's start. + + So the fit does not gain from raising the model: the footprints come out + more compact than with MATLAB's loss, and F0, which scales with their + spread, lower. Both fits converge. + """ + assert PARAMS.footprint_variance == "fixed" + fixed, model = solved, solved_matlab_loss + assert fixed.info["footprints1"]["converged"] + assert model.info["footprints1"]["converged"] + np.testing.assert_allclose(fixed.footprints.sum(0), 1.0, atol=1e-12) + compact = (fixed.footprints**2).sum(0) + assert np.all(compact > 1.02 * (model.footprints**2).sum(0)) + assert np.all(fixed.f0[0].mean(1) < model.f0[0].mean(1)) + for j in range(2): + assert _corr(fixed.footprints[:, j], model.footprints[:, j]) > 0.98 + # what precedes the footprint fit does not depend on the choice + assert fixed.info["activity1"]["loss"] == pytest.approx( + model.info["activity1"]["loss"], rel=1e-12 + ) + with pytest.raises(ValueError, match="footprint_variance"): + replace(PARAMS, footprint_variance="other") + + +def test_debias_variance_model_gives_larger_events( + fixture: SubproblemFixture, solved: SubproblemResult +) -> None: + """The model-variance debias refit rewards larger activity. + + This is MATLAB's behaviour before the fixed variance; the rest is unchanged. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + r = solve_subproblem(one, replace(PARAMS, debias_variance="model")) + assert r.events.shape == (1, 2, 1000) + np.testing.assert_allclose(r.footprints, solved.footprints, atol=1e-6) + np.testing.assert_allclose(r.ls[0], solved.ls[0], atol=1e-6) + assert r.events.sum() > 1.1 * solved.events[0].sum() + # both refit the events that the L1 fits found + same = (r.events[0] > 0) == (solved.events[0] > 0) + assert same.mean() > 0.99 + + +def test_one_outer_iteration(fixture: SubproblemFixture) -> None: + """With nmf_iter 1 the footprints stay at their start. + + No baseline or footprint fit runs. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + r = solve_subproblem(one, replace(PARAMS, nmf_iter=1)) + assert "footprints1" not in r.info and "activity1" in r.info + assert r.events.shape == (1, 2, 1000) + + +def test_photon_scale_matches_matlab() -> None: + """ExtractTrial's photon scale estimate.""" + with h5py.File(HELPERS, "r") as f: + finv = f["photon/Finv"][()] + y = 3 * f["photon/counts"][()] * np.sqrt(finv) + ref = float(f["photon/scale"][()]) + assert estimate_photon_scale(y, finv) == pytest.approx(ref, rel=1e-12) + + +def _result(n_px: int, n_src: int, n_t: int, value: float, n_ch: int = 2) -> SubproblemResult: + """Build a subproblem result filled with a constant. + + Returns + ------- + SubproblemResult + Footprints equal to value, events value, least squares 2 * value, + F0 3 * value and SNR 10 * value. + """ + return SubproblemResult( + footprints=np.full((n_px, n_src), value), + events=np.full((n_ch, n_src, n_t), value), + ls=np.full((n_ch, n_src, n_t), 2 * value), + f0=np.full((n_ch, n_src, n_t), 3 * value), + snr=np.full(n_src, 10 * value), + ) + + +def _placed(pixels: list[int], sources: list[int], n_t: int) -> Subproblem: + """Build a subproblem that only says where its results go. + + Returns + ------- + Subproblem + A subproblem with zero data whose pixels and sources are those given. + """ + n_px = len(pixels) + return Subproblem( + y=np.zeros((2, n_px, n_t), np.float32), + finv=np.ones((n_px, n_t), np.float32), + sel=np.ones((1, n_px), dtype=bool), + sources_rc=[[0, j] for j in range(len(sources))], + pixels=np.array(pixels), + sources=np.array(sources), + ) + + +def test_assemble_results() -> None: + """Results go to their pixels and sources. + + Events, least squares and F0 return to movie units; what no subproblem + covers is NaN. + """ + subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] + results = [_result(3, 1, 6, 1.0), _result(2, 2, 6, 2.0)] + t = assemble_results(subs, results, 6, 5, photon_scale=25.0) + assert t.footprints.dtype == np.float32 + assert t.footprints.shape == (6, 5) + assert np.all(t.footprints[[0, 1, 4], 2] == 1.0) + assert np.all(t.footprints[[2, 4]][:, [0, 3]] == 2.0) + assert np.isnan(t.footprints[0, 0]) and np.isnan(t.footprints[5]).all() + assert t.events.shape == t.ls.shape == t.f0.shape == (2, 5, 6) + assert np.all(t.events[:, 2] == 25.0) and np.all(t.events[:, 3] == 50.0) + assert np.all(t.ls[:, 0] == 100.0) and np.all(t.f0[:, 2] == 75.0) + assert np.isnan(t.events[:, [1, 4]]).all() + assert np.array_equal(t.snr[[0, 2, 3]], [20.0, 10.0, 20.0]) + assert np.isnan(t.snr[[1, 4]]).all() + with pytest.raises(ValueError, match="pixels and sources"): + assemble_results([replace(subs[0], pixels=None)], results[:1], 6, 5, 25.0) + # indices that would put results in the wrong place are refused + for bad, message in ( + (dict(pixels=np.array([0, 1, 6])), "pixels indices must lie"), + (dict(sources=np.array([5])), "sources indices must lie"), + (dict(pixels=np.array([0, 1])), "3 pixels and 2 indices for"), + (dict(pixels=np.array([0, 1, 1])), "pixels indices repeat"), + ): + with pytest.raises(ValueError, match=message): + assemble_results([replace(subs[0], **bad)], results[:1], 6, 5, 25.0) + with pytest.raises(ValueError, match="negative index"): + replace(subs[0], pixels=np.array([0, -1, 4])) + # one result per subproblem, each of the trial's channels and frames + with pytest.raises(ValueError, match="2 subproblems and 1 results"): + assemble_results(subs, results[:1], 6, 5, 25.0) + with pytest.raises(ValueError, match="at least one"): + assemble_results([], [], 6, 5, 25.0) + one_channel = _result(2, 2, 6, 2.0, n_ch=1) + with pytest.raises(ValueError, match="events are"): + assemble_results(subs, [results[0], one_channel], 6, 5, 25.0) + short = _result(2, 2, 5, 2.0) + with pytest.raises(ValueError, match="events are"): + assemble_results(subs, [results[0], short], 6, 5, 25.0) + wrong_snr = _result(2, 2, 6, 2.0) + wrong_snr.snr = np.ones(3) + with pytest.raises(ValueError, match="one SNR per source"): + assemble_results(subs, [results[0], wrong_snr], 6, 5, 25.0) + + +def test_process_result() -> None: + """The denoised activity is the events convolved with each channel's kernel. + + Discarded frames are NaN in the traces, as MATLAB leaves them (channel 2's + events keep their values). + """ + n_t = 40 + rng = np.random.default_rng(0) + subs = [_placed([0, 1], [0, 1], n_t)] + res = _result(2, 2, n_t, 1.0) + res.events = (rng.random((2, 2, n_t)) < 0.2) * rng.random((2, 2, n_t)) + trial = assemble_results(subs, [res], 2, 2, photon_scale=2.0) + discard = np.zeros(n_t, dtype=bool) + discard[[3, 4, 30]] = True + params = SolverParams(tau_s=0.01, tau2_s=0.02) + act = process_result(trial, params, discard) + keep = ~discard + np.testing.assert_allclose( + act.denoised[0][:, keep], + conv_same(trial.events[0], params.k)[:, keep], + ) + np.testing.assert_allclose( + act.denoised[1][:, keep], + conv_same(trial.events[1], params.k2)[:, keep], + ) + assert np.isnan(act.denoised[:, :, discard]).all() + assert np.isnan(act.ls[:, :, discard]).all() + assert np.isnan(act.events[0][:, discard]).all() + assert np.array_equal(act.events[1], trial.events[1]) + assert np.array_equal(act.events[0][:, keep], trial.events[0][:, keep]) + assert act.f0 is trial.f0 and act.snr is trial.snr + with pytest.raises(ValueError, match="discard has 39 frames"): + process_result(trial, params, discard[:-1]) + # the trial's own arrays are left as they were + assert not np.isnan(trial.events).any() + + +def test_conv_same_is_matlabs() -> None: + """'same' keeps the first argument's length, also below the kernel's.""" + k = np.array([0.0, 0.0, 1.0, 0.5, 0.25]) + x = np.array([[1.0, 0.0, 0.0, 2.0]]) + assert np.array_equal(conv_same(x, k), [[1.0, 0.5, 0.25, 2.0]]) + assert np.array_equal(conv_same(x[:, :2], k), [[1.0, 0.5]]) + + +def _rms_width(h: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> float: + """RMS width per axis of a footprint about its centroid. + + Returns + ------- + float + The root mean square width per axis of the clipped, normalised footprint. + """ + h = np.clip(h, 0, None) / np.clip(h, 0, None).sum() + m = np.array([h @ rows, h @ cols]) + return float(np.sqrt((h @ ((rows - m[0]) ** 2 + (cols - m[1]) ** 2)) / 2)) + + +def test_valid_kernel_lets_a_wide_footprint_be_fit() -> None: + """A sigma-1.8 source on its true baseline, fit with the 3 x 3 and 5 x 5 supports. + + With the 3 x 3 support the fitted footprint stops near its ceiling (1.56 px), + with 5 x 5 it gets close to the truth (1.8 px). + """ + rng = np.random.default_rng(3) + sel = np.ones((13, 13), dtype=bool) + rows, cols = sel_coords(sel) + rows, cols = rows.astype(float), cols.astype(float) + h = np.exp(-((rows - 6) ** 2 + (cols - 6) ** 2) / (2 * 1.8**2)) + h /= h.sum() + n = 8000 + ev = np.where(rng.random(n) < 0.01, rng.exponential(150.0, n), 0.0) + x = np.convolve(ev, PARAMS.k, mode="same") + b = np.full((h.size, n), 2.0) + y = rng.poisson(b + h[:, None] * x[None]).astype(np.float64)[None] + sub = Subproblem( + y=y, + finv=np.ones(y.shape[1:]), + sel=sel, + sources_rc=np.array([[6, 6]]), + baseline=b, + ) + true_w = _rms_width(h, rows, cols) + widths = {} + for vk in (3, 5): + p = replace(PARAMS, baseline_mode="fixed", valid_kernel=vk) + res = solve_subproblem(sub, p) + widths[vk] = _rms_width(res.footprints[:, 0], rows, cols) + assert widths[3] < 1.57 + assert abs(widths[5] - true_w) < 0.1 + assert abs(widths[5] - true_w) < abs(widths[3] - true_w) / 2 diff --git a/tests/raster/test_raster_solver_baseline.py b/tests/raster/test_raster_solver_baseline.py index d9df5ae6..c95c7a7b 100644 --- a/tests/raster/test_raster_solver_baseline.py +++ b/tests/raster/test_raster_solver_baseline.py @@ -1,459 +1,496 @@ -"""Tests of the deterministic parts of the subproblem solver. - -The baseline (splitFreq, fitB and its helpers), the floor and the noise -estimate, against GIAnT-MATLAB's values. -""" - -import warnings -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -from numpy.typing import ArrayLike -from scipy import optimize - -from giant_python.extraction.raster import solver_baseline as sb -from giant_python.extraction.raster.localization import movmean_nan -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - conv_operator, - sel_coords, -) - -DATA = Path(__file__).parent / "data" -HELPERS = DATA / "matlab_solver_helpers.h5" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() # SILo's defaults for SLAP2, as the subproblem's -# parameters of the small fitB and getSurround references -SMALL = SolverParams( - sigma_px=1.33, - sel_radius=2, - tau_full=3, - tau2_s=0.05, - analyze_hz=100, - baseline_window_s=0.6, - denoise_window_s=0.1, -) - - -def _close(a: ArrayLike, b: ArrayLike, tol: float = 1e-12) -> None: - """Equal NaN patterns, and differences below tol of the largest value.""" - a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) - assert a.shape == b.shape - assert np.array_equal(np.isnan(a), np.isnan(b)) - assert np.nanmax(np.abs(a - b)) <= tol * np.nanmax(np.abs(b)) - - -def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: - """MATLAB convn(x, k, 'same') along the rows.""" - c = len(k) // 2 - return np.stack([np.convolve(r, k)[c : c + x.shape[1]] for r in x]) - - -def _read_tree(g: h5py.Group) -> dict[str, Any]: - """Read an HDF5 group as nested dicts of arrays.""" - return {k: _read_tree(v) if isinstance(v, h5py.Group) else v[()] for k, v in g.items()} - - -@pytest.fixture(scope="module") -def helpers() -> dict[str, Any]: - """MATLAB's values for the helper functions.""" - with h5py.File(HELPERS, "r") as f: - return _read_tree(f) - - -@pytest.fixture(scope="module") -def sub() -> dict[str, Any]: - """Load the subproblem fixture: inputs as float64, MATLAB's intermediates.""" - with h5py.File(SUBPROBLEM, "r") as f: - d = _read_tree(f) - d["every"] = int(f.attrs["baseline_every"]) - d["y"] = d["in"]["y"].astype(np.float64) - d["finv"] = d["in"]["finv"].astype(np.float64) - d["sel"] = d["in"]["sel"].astype(bool) - return d - - -@pytest.mark.parametrize("window", [4, 7, 20, 50]) -def test_lowess_and_movmean_match_matlab(helpers: dict[str, Any], window: int) -> None: - """Smoothdata's lowess and movmean, for even, odd and too long windows.""" - s = helpers["smooth"] - _close(sb.smooth_lowess(s["A"], window), s[f"lowess_{window}"]) - _close(movmean_nan(s["A"].T, window).T, s[f"movmean_{window}"]) - - -@pytest.mark.parametrize("window", [7, 20]) -def test_lowess_omits_nan_as_matlab(helpers: dict[str, Any], window: int) -> None: - """NaN samples are left out of the local fits.""" - s = helpers["smooth"] - assert np.isnan(s["An"]).sum() == 10 - _close(sb.smooth_lowess(s["An"], window), s[f"lowess_nan_{window}"]) - - -def test_lowess_degenerate_windows() -> None: - """A window of one sample returns the data. - - A window whose only weighted sample is the centre returns it; all-NaN - windows give NaN. - """ - a = np.array([[1.0, 4.0, 2.0, np.nan, np.nan, np.nan, 7.0]]) - assert np.array_equal(sb.smooth_lowess(a[:, :3], 1), a[:, :3]) - out = sb.smooth_lowess(a, 3) - assert np.array_equal(out[0, :3], a[0, :3]) - assert np.isnan(out[0, 4]) - # the NaN next to a value takes it (zero weight, so the window's mean) - assert out[0, 3] == 2.0 and out[0, 5] == 7.0 - - -@pytest.mark.parametrize( - "name, order, n, pad", - [ - ("zeros_3_20", 3, 20, "zeros"), - ("zeros_2_5", 2, 5, "zeros"), - ("zeros_1_4", 1, 4, "zeros"), - ("sym_5_46", 5, 46, "symmetric"), - ("sym_3_7", 3, 7, "symmetric"), - ("sym_2_6", 2, 6, "symmetric"), - ("med_9", 5, 9, "symmetric"), - ], -) -def test_order_filters_match_matlab( - helpers: dict[str, Any], name: str, order: int, n: int, pad: str -) -> None: - """ordfilt2 and medfilt2 along rows, with both paddings. - - The window of 46 is longer than the 41 samples. - """ - o = helpers["ord"] - assert np.array_equal(sb.ordfilt_rows(o["a"], order, n, pad), o[name]) - - -def test_split_freq_matches_matlab(helpers: dict[str, Any]) -> None: - """splitFreq, also for a trial too short to interpolate.""" - s = helpers["split"] - lp, hp = sb.split_freq(s["A"], 10, 6) - _close(lp, s["LP"]) - assert np.array_equal(hp, s["A"] - lp) - short, _ = sb.split_freq(s["A"][:, :15], 10, 6) - _close(short, s["LP_short"]) - _close(sb.split_freq(s["D"], 10, 6)[0], s["LP_nan"]) - - -def test_initial_baseline_takes_min_where_nan(monkeypatch: pytest.MonkeyPatch) -> None: - """Where splitFreq's low-pass is NaN the baseline is min_baseline. - - As MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below. - """ - lp = np.array([[np.nan, 0.5, -1.0], [2.0, np.nan, 0.001]]) - monkeypatch.setattr(sb, "split_freq", lambda *a: (lp, None)) - b = sb.initial_baseline(np.zeros((2, 3)), PARAMS) - assert np.array_equal(b, [[0.01, 0.5, 0.01], [2.0, 0.01, 0.01]]) - - -def test_compute_floor_matches_matlab(helpers: dict[str, Any]) -> None: - """computeFloor, for integer and fractional windows.""" - f = helpers["floor"] - _close(sb.compute_floor(f["X"], 7, 45.5), f["out"]) - _close(sb.compute_floor(f["X"], 6, 40), f["out_int"]) - - -def test_bspline_basis_matches_matlab(helpers: dict[str, Any]) -> None: - """bsplineBasis: whole knot intervals tile the trial. - - One interval when the spacing exceeds it. The products are those of the - basis. - """ - s = helpers["spline"] - b = sb.bspline_basis(101, 17.3) - _close(b.toarray(), s["B"], 1e-14) - _close(sb.bspline_basis(40, 100).toarray(), s["B1"], 1e-14) - assert b.shape == (101, 9) and s["B1"].shape == (40, 4) - np.testing.assert_allclose(b.sum(1), 1.0, atol=1e-14) - dense = b.toarray() - prod = sb._bspline_products(101, 17.3).toarray().reshape(101, 9, 9) - np.testing.assert_allclose(prod, dense[:, :, None] * dense[:, None, :], atol=1e-15) - - -def test_curvature_penalty() -> None: - """Squared second differences per knot interval: constants and lines cost nothing.""" - pc = sb.curvature_penalty(7) - c = np.arange(7.0) - assert np.allclose(pc @ np.ones(7), 0) and np.allclose(pc @ c, 0) - quad = c**2 - assert quad @ pc @ quad == pytest.approx(5 * 2.0**2 / 4) - - -def test_surround_matches_matlab(helpers: dict[str, Any]) -> None: - """GetSurround on a map with a hole, dense and sparse operators.""" - sel = helpers["foot"]["selPix"].astype(bool) - s = helpers["surround"] - _close(SMALL.bfilter, s["Bfilter"].transpose(2, 0, 1)) - ops = sb.surround_operators(sel, SMALL) - assert all(isinstance(op, np.ndarray) for op in ops) # small: dense - ref = s["out"].transpose(2, 0, 1) - _close(sb.get_surround(s["HP"], ops), ref) - sparse_ops = [conv_operator(sel, f) for f in SMALL.bfilter] - _close(sb.get_surround(s["HP"], sparse_ops), ref) - - -def test_fit_baseline_matches_matlab(helpers: dict[str, Any]) -> None: - """FitB on a small synthetic problem. - - MATLAB's quadprog stops at its tolerance, so the baselines agree to about - 1e-8; Python's programs are solved to machine precision. - """ - sel = helpers["foot"]["selPix"].astype(bool) - f = helpers["fitB"] - y = f["Finv"] * f["counts"] - b0 = np.full(y.shape, 1.4) - b, info = sb.fit_baseline(b0, y, f["X"], f["H"], f["Finv"], sel, SMALL, return_info=True) - _close(b, f["B"], 1e-7) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - assert info["coef"].shape == (y.shape[0], 2 + 3 + 13) - # the sources' coefficients are not negative - assert info["coef"][:, :2].min() >= 0 - - -def _random_qp( - rng: np.random.Generator, m: int, n: int, rank: int | None = None -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Build a stack of random bounded quadratic programs.""" - a = rng.standard_normal((m, rank or n + 3, n)) - g = np.einsum("mki,mkj->mij", a, a) - c = rng.standard_normal((m, n)) * 3 - lb = -rng.random((m, n)) - ub = rng.random((m, n)) - return g, c, lb, ub - - -def test_box_qp_matches_scipy() -> None: - """The batched solver finds the minimum that a bounded least-squares solver finds. - - With many bounds active. - """ - rng = np.random.default_rng(3) - g, c, lb, ub = _random_qp(rng, 40, 6) - x, info = sb.solve_box_qp(g, c, lb, ub) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - assert (x >= lb).all() and (x <= ub).all() - assert ((x == lb) | (x == ub)).mean() > 0.2 - for i in range(40): - # min x'Gx/2 - c'x == min |R x - R^-T c|^2 with G = R'R - r = np.linalg.cholesky(g[i]).T - rhs = np.linalg.solve(r.T, c[i]) - ref = optimize.lsq_linear(r, rhs, bounds=(lb[i], ub[i]), method="bvls", tol=1e-13).x - np.testing.assert_allclose(x[i], ref, atol=1e-8) - - -def test_box_qp_zero_curvature_follows_the_linear_term() -> None: - """A variable without curvature goes to the bound that its linear term favours.""" - g = np.zeros((3, 1, 1)) - c = np.array([[1.0], [-1.0], [0.0]]) - lb, ub = np.full((3, 1), -3.0), np.full((3, 1), 2.0) - x, info = sb.solve_box_qp(g, c, lb, ub) - assert x.ravel().tolist() == [2.0, -3.0, 0.0] - assert info["converged"].all() - # beside variables with curvature, which do not depend on it - g = np.array([[[2.0, 0.0], [0.0, 0.0]]]) - x, _ = sb.solve_box_qp(g, np.array([[1.0, 5.0]]), np.full((1, 2), -4.0), np.full((1, 2), 3.0)) - assert x.ravel().tolist() == [0.5, 3.0] - - -def test_box_qp_fixed_variables() -> None: - """Bounds that coincide fix a variable, in the Newton iterations and in the fallback. - - The others are solved around it. - """ - one = np.ones((1, 1)) - for max_iter in (100, 0): - x, _ = sb.solve_box_qp(one[None], 0 * one, one, one, max_iter=max_iter) - assert x.tolist() == [[1.0]] - rng = np.random.default_rng(9) - g, c, lb, ub = _random_qp(rng, 8, 5) - lb[:, 1] = ub[:, 1] = 0.3 - lb[:, 4] = ub[:, 4] = -0.2 - x, info = sb.solve_box_qp(g, c, lb, ub) - assert info["converged"].all() - assert np.all(x[:, 1] == 0.3) and np.all(x[:, 4] == -0.2) - fallback, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert not info["converged"].any() - np.testing.assert_allclose(fallback, x, atol=1e-7) - # the free variables solve the program with the fixed ones moved into - # its linear term - keep = [0, 2, 3] - shift = g[:, keep][:, :, [1, 4]] @ np.array([0.3, -0.2]) - ref, _ = sb.solve_box_qp(g[:, keep][:, :, keep], c[:, keep] - shift, lb[:, keep], ub[:, keep]) - np.testing.assert_allclose(x[:, keep], ref, atol=1e-9) - - -def test_box_qp_fallback_keeps_the_objective() -> None: - """The fallback solves the program as given. - - A singular G whose linear term acts along the null direction ends on the - bounds, without a warning, as the Newton iterations do. - """ - g = np.array([[[1.0, 1.0], [1.0, 1.0]]]) - lb, ub = np.full((1, 2), -2.0), np.full((1, 2), 2.0) - for c in ([[1e-16, -1e-16]], [[0.5, -0.5]]): - c = np.array(c) - for max_iter in (100, 0): - with warnings.catch_warnings(): - warnings.simplefilter("error") - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=max_iter) - assert x.tolist() == [[2.0, -2.0]], (c, max_iter) - assert info["kkt"].max() < 1e-9 - # no linear term at all: the quadratic alone, pushed to the bounds - ones = np.ones((1, 4, 4)) - zero = np.zeros((1, 4)) - x, info = sb.solve_box_qp(ones, zero, np.full((1, 4), 1.0), np.full((1, 4), 2.0), max_iter=0) - assert x.tolist() == [[1.0] * 4] and np.isfinite(info["kkt"]).all() - # a positive semidefinite program with its minimum inside the bounds - c = np.array([[1.0, 1.0]]) - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert x.sum() == pytest.approx(1.0, abs=1e-9) and info["kkt"].max() < 1e-9 - - -def test_box_qp_zero_rows_and_fallback() -> None: - """A variable with a zero row is left at its bound nearest zero. - - A problem the Newton iterations do not finish goes to the fallback. - """ - rng = np.random.default_rng(4) - g, c, lb, ub = _random_qp(rng, 5, 4) - g[:, 2, :] = g[:, :, 2] = 0 - c[:, 2] = 0 - lb[:, 2], ub[:, 2] = 0.25, 3.0 - x, info = sb.solve_box_qp(g, c, lb, ub) - assert np.all(x[:, 2] == 0.25) and info["converged"].all() - ref, _ = sb.solve_box_qp( - np.delete(np.delete(g, 2, 1), 2, 2), - np.delete(c, 2, 1), - np.delete(lb, 2, 1), - np.delete(ub, 2, 1), - ) - np.testing.assert_allclose(np.delete(x, 2, 1), ref, atol=1e-10) - # no iterations: every problem is solved by the fallback - g, c, lb, ub = _random_qp(rng, 6, 5) - good, _ = sb.solve_box_qp(g, c, lb, ub) - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert not info["converged"].any() - np.testing.assert_allclose(x, good, atol=1e-7) - - -def test_subproblem_start_matches_matlab(sub: dict[str, Any]) -> None: - """Starting baseline, least squares and events of a real subproblem.""" - y, every = sub["y"][0], sub["every"] - b = sb.initial_baseline(y, PARAMS) - _close(b[:, ::every], sub["init"]["B"]) - ls = np.linalg.lstsq(sub["init"]["H"], y - b, rcond=None)[0] - _close(ls, sub["init"]["dFls"]) - prev = np.concatenate([np.zeros((2, 1)), ls[:, :-1]], axis=1) - k_peak = PARAMS.k[PARAMS.k.size // 2] - _close(np.fmax(0, ls - prev) / k_peak, sub["init"]["S"]) - b2 = sb.initial_baseline(sub["y"][1], PARAMS) - _close(b2[:, ::every], sub["ch2"]["B"]) - - -def test_subproblem_noise_and_floor_match_matlab(sub: dict[str, Any]) -> None: - """Noise, SNR and floor from MATLAB's first activity fit.""" - y, it1 = sub["y"][0], sub["it1"] - b = sb.initial_baseline(y, PARAMS) - x = _conv_same(it1["S_out"], PARAMS.k) - var, noise, snr = sb.activity_noise(y, sub["finv"], b, sub["init"]["H"], x, PARAMS.tau_frames) - _close(var, it1["residVar"]) - _close(noise, it1["Xnoise"]) - _close(snr, it1["Xsnr"]) - floor = sb.compute_floor(x, PARAMS.denoise_window, PARAMS.baseline_window) - _close(floor, it1["Xfloor"]) - _close(np.fmax(0, x - floor - noise[:, None]), it1["X_thr"]) - - -def test_subproblem_baseline_fit_matches_matlab(sub: dict[str, Any]) -> None: - """FitB on a real subproblem, to quadprog's tolerance. - - Its trial is shorter than the lowess window of the high-pass split. - """ - y, it1 = sub["y"][0], sub["it1"] - b0 = sb.initial_baseline(y, PARAMS) - b, info = sb.fit_baseline( - b0, - y, - it1["X_thr"], - sub["init"]["H"], - sub["finv"], - sub["sel"], - PARAMS, - return_info=True, - ) - _close(b[:, :: sub["every"]], it1["B_out"], 1e-5) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - - -def test_subproblem_footprint_update_matches_matlab(sub: dict[str, Any]) -> None: - """H from MATLAB's fitted Hs through the footprint filter, and the normalization.""" - it1 = sub["it1"] - h = conv_operator(sub["sel"], PARAMS.hfilter) @ it1["Hs_out"] - norm = h.sum(0) - _close(norm, it1["normFac"]) - _close(h / norm, it1["H"]) - _close(it1["Hs_out"] / norm, it1["Hs"]) - _close(it1["S_out"] * norm[:, None], it1["S"]) - rows, _ = sel_coords(sub["sel"]) - assert h.shape == (rows.size, 2) - - -def test_subproblem_outputs_match_matlab(sub: dict[str, Any]) -> None: - """SNR, least squares and F0 from MATLAB's final activity.""" - y, out, it1 = sub["y"], sub["out"], sub["it1"] - h = out["H"] - b1 = sb.fit_baseline( - sb.initial_baseline(y[0], PARAMS), - y[0], - it1["X_thr"], - sub["init"]["H"], - sub["finv"], - sub["sel"], - PARAMS, - ) - x = _conv_same(out["S"][0], PARAMS.k) - _, _, snr = sb.activity_noise(y[0], sub["finv"], b1, h, x, PARAMS.tau_frames) - _close(snr, out["SNR"], 1e-5) - _close(np.linalg.lstsq(h, y[0] - b1, rcond=None)[0], out["LS"][0], 1e-5) - _close(sb.source_f0(h, b1), out["F0"][0], 1e-5) - b2 = sb.initial_baseline(y[1], PARAMS) - _close(np.linalg.lstsq(h, y[1] - b2, rcond=None)[0], out["LS"][1]) - _close(sb.source_f0(h, b2), out["F0"][1]) - - -def test_interp1_extrapolates() -> None: - """Linear interpolation of rows with linear extrapolation.""" - x = np.array([1.0, 2.0, 4.0]) - y = np.array([[0.0, 1.0, 5.0]]) - out = sb.interp1_extrap(x, y, np.array([0.0, 1.5, 3.0, 5.0])) - np.testing.assert_allclose(out, [[-1.0, 0.5, 3.0, 7.0]]) - - -def test_activity_noise_with_a_zero_footprint_is_matlabs() -> None: - """A source whose footprint is all zero makes the normal matrix singular. - - Noise Inf and SNR 0 for every source, with a warning, as MATLAB's inv - gives; other inputs give the plain inverse's result. - """ - rng = np.random.default_rng(5) - n_px, n_t = 40, 300 - h = np.abs(rng.standard_normal((n_px, 3))) - x = np.abs(rng.standard_normal((3, n_t))) - b = np.full((n_px, n_t), 5.0) - y = b + h @ x + 0.3 * rng.standard_normal((n_px, n_t)) - finv = np.ones((n_px, n_t)) # freshness per pixel and frame - var, noise, snr = sb.activity_noise(y, finv, b, h, x, 4.0) - cov = np.linalg.inv(h.T @ (h / var[:, None])) - np.testing.assert_array_equal(noise, np.sqrt(np.diag(cov) / 4.0)) - assert np.all(np.isfinite(noise)) and np.all(snr > 0) - h0 = h.copy() - h0[:, 1] = 0.0 - with pytest.warns(RuntimeWarning, match="singular"): - _, noise0, snr0 = sb.activity_noise(y, finv, b, h0, x, 4.0) - assert np.all(np.isinf(noise0)) and np.all(snr0 == 0) +"""Tests of the deterministic parts of the subproblem solver. + +The baseline (splitFreq, fitB and its helpers), the floor and the noise +estimate, against GIAnT-MATLAB's values. +""" + +import warnings +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +from numpy.typing import ArrayLike +from scipy import optimize + +from giant_python.extraction.raster import solver_baseline as sb +from giant_python.extraction.raster.localization import movmean_nan +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + conv_operator, + sel_coords, +) + +DATA = Path(__file__).parent / "data" +HELPERS = DATA / "matlab_solver_helpers.h5" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() # SILo's defaults for SLAP2, as the subproblem's +# parameters of the small fitB and getSurround references +SMALL = SolverParams( + sigma_px=1.33, + sel_radius=2, + tau_full=3, + tau2_s=0.05, + analyze_hz=100, + baseline_window_s=0.6, + denoise_window_s=0.1, +) + + +def _close(a: ArrayLike, b: ArrayLike, tol: float = 1e-12) -> None: + """Equal NaN patterns, and differences below tol of the largest value.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + assert a.shape == b.shape + assert np.array_equal(np.isnan(a), np.isnan(b)) + assert np.nanmax(np.abs(a - b)) <= tol * np.nanmax(np.abs(b)) + + +def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: + """MATLAB convn(x, k, 'same') along the rows. + + Returns + ------- + np.ndarray + Each row of `x` convolved with `k`, cropped to the length of the row. + """ + c = len(k) // 2 + return np.stack([np.convolve(r, k)[c : c + x.shape[1]] for r in x]) + + +def _read_tree(g: h5py.Group) -> dict[str, Any]: + """Read an HDF5 group as nested dicts of arrays. + + Returns + ------- + dict[str, Any] + The group's datasets as arrays (or scalars) and its subgroups as nested dicts. + """ + return {k: _read_tree(v) if isinstance(v, h5py.Group) else v[()] for k, v in g.items()} + + +@pytest.fixture(scope="module") +def helpers() -> dict[str, Any]: + """MATLAB's values for the helper functions. + + Returns + ------- + dict[str, Any] + The helper fixture file as nested dicts of arrays. + """ + with h5py.File(HELPERS, "r") as f: + return _read_tree(f) + + +@pytest.fixture(scope="module") +def sub() -> dict[str, Any]: + """Load the subproblem fixture: inputs as float64, MATLAB's intermediates. + + Returns + ------- + dict[str, Any] + The fixture file as nested dicts, plus every (the baseline step interval) and the + float64 y and finv and boolean sel copied from its inputs. + """ + with h5py.File(SUBPROBLEM, "r") as f: + d = _read_tree(f) + d["every"] = int(f.attrs["baseline_every"]) + d["y"] = d["in"]["y"].astype(np.float64) + d["finv"] = d["in"]["finv"].astype(np.float64) + d["sel"] = d["in"]["sel"].astype(bool) + return d + + +@pytest.mark.parametrize("window", [4, 7, 20, 50]) +def test_lowess_and_movmean_match_matlab(helpers: dict[str, Any], window: int) -> None: + """Smoothdata's lowess and movmean, for even, odd and too long windows.""" + s = helpers["smooth"] + _close(sb.smooth_lowess(s["A"], window), s[f"lowess_{window}"]) + _close(movmean_nan(s["A"].T, window).T, s[f"movmean_{window}"]) + + +@pytest.mark.parametrize("window", [7, 20]) +def test_lowess_omits_nan_as_matlab(helpers: dict[str, Any], window: int) -> None: + """NaN samples are left out of the local fits.""" + s = helpers["smooth"] + assert np.isnan(s["An"]).sum() == 10 + _close(sb.smooth_lowess(s["An"], window), s[f"lowess_nan_{window}"]) + + +def test_lowess_degenerate_windows() -> None: + """A window of one sample returns the data. + + A window whose only weighted sample is the centre returns it; all-NaN + windows give NaN. + """ + a = np.array([[1.0, 4.0, 2.0, np.nan, np.nan, np.nan, 7.0]]) + assert np.array_equal(sb.smooth_lowess(a[:, :3], 1), a[:, :3]) + out = sb.smooth_lowess(a, 3) + assert np.array_equal(out[0, :3], a[0, :3]) + assert np.isnan(out[0, 4]) + # the NaN next to a value takes it (zero weight, so the window's mean) + assert out[0, 3] == 2.0 and out[0, 5] == 7.0 + + +@pytest.mark.parametrize( + "name, order, n, pad", + [ + ("zeros_3_20", 3, 20, "zeros"), + ("zeros_2_5", 2, 5, "zeros"), + ("zeros_1_4", 1, 4, "zeros"), + ("sym_5_46", 5, 46, "symmetric"), + ("sym_3_7", 3, 7, "symmetric"), + ("sym_2_6", 2, 6, "symmetric"), + ("med_9", 5, 9, "symmetric"), + ], +) +def test_order_filters_match_matlab( + helpers: dict[str, Any], name: str, order: int, n: int, pad: str +) -> None: + """ordfilt2 and medfilt2 along rows, with both paddings. + + The window of 46 is longer than the 41 samples. + """ + o = helpers["ord"] + assert np.array_equal(sb.ordfilt_rows(o["a"], order, n, pad), o[name]) + + +def test_split_freq_matches_matlab(helpers: dict[str, Any]) -> None: + """splitFreq, also for a trial too short to interpolate.""" + s = helpers["split"] + lp, hp = sb.split_freq(s["A"], 10, 6) + _close(lp, s["LP"]) + assert np.array_equal(hp, s["A"] - lp) + short, _ = sb.split_freq(s["A"][:, :15], 10, 6) + _close(short, s["LP_short"]) + _close(sb.split_freq(s["D"], 10, 6)[0], s["LP_nan"]) + + +def test_initial_baseline_takes_min_where_nan(monkeypatch: pytest.MonkeyPatch) -> None: + """Where splitFreq's low-pass is NaN the baseline is min_baseline. + + As MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below. + """ + lp = np.array([[np.nan, 0.5, -1.0], [2.0, np.nan, 0.001]]) + monkeypatch.setattr(sb, "split_freq", lambda *a: (lp, None)) + b = sb.initial_baseline(np.zeros((2, 3)), PARAMS) + assert np.array_equal(b, [[0.01, 0.5, 0.01], [2.0, 0.01, 0.01]]) + + +def test_compute_floor_matches_matlab(helpers: dict[str, Any]) -> None: + """computeFloor, for integer and fractional windows.""" + f = helpers["floor"] + _close(sb.compute_floor(f["X"], 7, 45.5), f["out"]) + _close(sb.compute_floor(f["X"], 6, 40), f["out_int"]) + + +def test_bspline_basis_matches_matlab(helpers: dict[str, Any]) -> None: + """bsplineBasis: whole knot intervals tile the trial. + + One interval when the spacing exceeds it. The products are those of the + basis. + """ + s = helpers["spline"] + b = sb.bspline_basis(101, 17.3) + _close(b.toarray(), s["B"], 1e-14) + _close(sb.bspline_basis(40, 100).toarray(), s["B1"], 1e-14) + assert b.shape == (101, 9) and s["B1"].shape == (40, 4) + np.testing.assert_allclose(b.sum(1), 1.0, atol=1e-14) + dense = b.toarray() + prod = sb._bspline_products(101, 17.3).toarray().reshape(101, 9, 9) + np.testing.assert_allclose(prod, dense[:, :, None] * dense[:, None, :], atol=1e-15) + + +def test_curvature_penalty() -> None: + """Squared second differences per knot interval: constants and lines cost nothing.""" + pc = sb.curvature_penalty(7) + c = np.arange(7.0) + assert np.allclose(pc @ np.ones(7), 0) and np.allclose(pc @ c, 0) + quad = c**2 + assert quad @ pc @ quad == pytest.approx(5 * 2.0**2 / 4) + + +def test_surround_matches_matlab(helpers: dict[str, Any]) -> None: + """GetSurround on a map with a hole, dense and sparse operators.""" + sel = helpers["foot"]["selPix"].astype(bool) + s = helpers["surround"] + _close(SMALL.bfilter, s["Bfilter"].transpose(2, 0, 1)) + ops = sb.surround_operators(sel, SMALL) + assert all(isinstance(op, np.ndarray) for op in ops) # small: dense + ref = s["out"].transpose(2, 0, 1) + _close(sb.get_surround(s["HP"], ops), ref) + sparse_ops = [conv_operator(sel, f) for f in SMALL.bfilter] + _close(sb.get_surround(s["HP"], sparse_ops), ref) + + +def test_fit_baseline_matches_matlab(helpers: dict[str, Any]) -> None: + """FitB on a small synthetic problem. + + MATLAB's quadprog stops at its tolerance, so the baselines agree to about + 1e-8; Python's programs are solved to machine precision. + """ + sel = helpers["foot"]["selPix"].astype(bool) + f = helpers["fitB"] + y = f["Finv"] * f["counts"] + b0 = np.full(y.shape, 1.4) + b, info = sb.fit_baseline(b0, y, f["X"], f["H"], f["Finv"], sel, SMALL, return_info=True) + _close(b, f["B"], 1e-7) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + assert info["coef"].shape == (y.shape[0], 2 + 3 + 13) + # the sources' coefficients are not negative + assert info["coef"][:, :2].min() >= 0 + + +def _random_qp( + rng: np.random.Generator, m: int, n: int, rank: int | None = None +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Build a stack of random bounded quadratic programs. + + Returns + ------- + g : np.ndarray + Symmetric positive semidefinite matrices, (m, n, n). + c : np.ndarray + Linear terms, (m, n). + lb : np.ndarray + Lower bounds (at most 0), (m, n). + ub : np.ndarray + Upper bounds (at least 0), (m, n). + """ + a = rng.standard_normal((m, rank or n + 3, n)) + g = np.einsum("mki,mkj->mij", a, a) + c = rng.standard_normal((m, n)) * 3 + lb = -rng.random((m, n)) + ub = rng.random((m, n)) + return g, c, lb, ub + + +def test_box_qp_matches_scipy() -> None: + """The batched solver finds the minimum that a bounded least-squares solver finds. + + With many bounds active. + """ + rng = np.random.default_rng(3) + g, c, lb, ub = _random_qp(rng, 40, 6) + x, info = sb.solve_box_qp(g, c, lb, ub) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + assert (x >= lb).all() and (x <= ub).all() + assert ((x == lb) | (x == ub)).mean() > 0.2 + for i in range(40): + # min x'Gx/2 - c'x == min |R x - R^-T c|^2 with G = R'R + r = np.linalg.cholesky(g[i]).T + rhs = np.linalg.solve(r.T, c[i]) + ref = optimize.lsq_linear(r, rhs, bounds=(lb[i], ub[i]), method="bvls", tol=1e-13).x + np.testing.assert_allclose(x[i], ref, atol=1e-8) + + +def test_box_qp_zero_curvature_follows_the_linear_term() -> None: + """A variable without curvature goes to the bound that its linear term favours.""" + g = np.zeros((3, 1, 1)) + c = np.array([[1.0], [-1.0], [0.0]]) + lb, ub = np.full((3, 1), -3.0), np.full((3, 1), 2.0) + x, info = sb.solve_box_qp(g, c, lb, ub) + assert x.ravel().tolist() == [2.0, -3.0, 0.0] + assert info["converged"].all() + # beside variables with curvature, which do not depend on it + g = np.array([[[2.0, 0.0], [0.0, 0.0]]]) + x, _ = sb.solve_box_qp(g, np.array([[1.0, 5.0]]), np.full((1, 2), -4.0), np.full((1, 2), 3.0)) + assert x.ravel().tolist() == [0.5, 3.0] + + +def test_box_qp_fixed_variables() -> None: + """Bounds that coincide fix a variable, in the Newton iterations and in the fallback. + + The others are solved around it. + """ + one = np.ones((1, 1)) + for max_iter in (100, 0): + x, _ = sb.solve_box_qp(one[None], 0 * one, one, one, max_iter=max_iter) + assert x.tolist() == [[1.0]] + rng = np.random.default_rng(9) + g, c, lb, ub = _random_qp(rng, 8, 5) + lb[:, 1] = ub[:, 1] = 0.3 + lb[:, 4] = ub[:, 4] = -0.2 + x, info = sb.solve_box_qp(g, c, lb, ub) + assert info["converged"].all() + assert np.all(x[:, 1] == 0.3) and np.all(x[:, 4] == -0.2) + fallback, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert not info["converged"].any() + np.testing.assert_allclose(fallback, x, atol=1e-7) + # the free variables solve the program with the fixed ones moved into + # its linear term + keep = [0, 2, 3] + shift = g[:, keep][:, :, [1, 4]] @ np.array([0.3, -0.2]) + ref, _ = sb.solve_box_qp(g[:, keep][:, :, keep], c[:, keep] - shift, lb[:, keep], ub[:, keep]) + np.testing.assert_allclose(x[:, keep], ref, atol=1e-9) + + +def test_box_qp_fallback_keeps_the_objective() -> None: + """The fallback solves the program as given. + + A singular G whose linear term acts along the null direction ends on the + bounds, without a warning, as the Newton iterations do. + """ + g = np.array([[[1.0, 1.0], [1.0, 1.0]]]) + lb, ub = np.full((1, 2), -2.0), np.full((1, 2), 2.0) + for c in ([[1e-16, -1e-16]], [[0.5, -0.5]]): + c = np.array(c) + for max_iter in (100, 0): + with warnings.catch_warnings(): + warnings.simplefilter("error") + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=max_iter) + assert x.tolist() == [[2.0, -2.0]], (c, max_iter) + assert info["kkt"].max() < 1e-9 + # no linear term at all: the quadratic alone, pushed to the bounds + ones = np.ones((1, 4, 4)) + zero = np.zeros((1, 4)) + x, info = sb.solve_box_qp(ones, zero, np.full((1, 4), 1.0), np.full((1, 4), 2.0), max_iter=0) + assert x.tolist() == [[1.0] * 4] and np.isfinite(info["kkt"]).all() + # a positive semidefinite program with its minimum inside the bounds + c = np.array([[1.0, 1.0]]) + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert x.sum() == pytest.approx(1.0, abs=1e-9) and info["kkt"].max() < 1e-9 + + +def test_box_qp_zero_rows_and_fallback() -> None: + """A variable with a zero row is left at its bound nearest zero. + + A problem the Newton iterations do not finish goes to the fallback. + """ + rng = np.random.default_rng(4) + g, c, lb, ub = _random_qp(rng, 5, 4) + g[:, 2, :] = g[:, :, 2] = 0 + c[:, 2] = 0 + lb[:, 2], ub[:, 2] = 0.25, 3.0 + x, info = sb.solve_box_qp(g, c, lb, ub) + assert np.all(x[:, 2] == 0.25) and info["converged"].all() + ref, _ = sb.solve_box_qp( + np.delete(np.delete(g, 2, 1), 2, 2), + np.delete(c, 2, 1), + np.delete(lb, 2, 1), + np.delete(ub, 2, 1), + ) + np.testing.assert_allclose(np.delete(x, 2, 1), ref, atol=1e-10) + # no iterations: every problem is solved by the fallback + g, c, lb, ub = _random_qp(rng, 6, 5) + good, _ = sb.solve_box_qp(g, c, lb, ub) + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert not info["converged"].any() + np.testing.assert_allclose(x, good, atol=1e-7) + + +def test_subproblem_start_matches_matlab(sub: dict[str, Any]) -> None: + """Starting baseline, least squares and events of a real subproblem.""" + y, every = sub["y"][0], sub["every"] + b = sb.initial_baseline(y, PARAMS) + _close(b[:, ::every], sub["init"]["B"]) + ls = np.linalg.lstsq(sub["init"]["H"], y - b, rcond=None)[0] + _close(ls, sub["init"]["dFls"]) + prev = np.concatenate([np.zeros((2, 1)), ls[:, :-1]], axis=1) + k_peak = PARAMS.k[PARAMS.k.size // 2] + _close(np.fmax(0, ls - prev) / k_peak, sub["init"]["S"]) + b2 = sb.initial_baseline(sub["y"][1], PARAMS) + _close(b2[:, ::every], sub["ch2"]["B"]) + + +def test_subproblem_noise_and_floor_match_matlab(sub: dict[str, Any]) -> None: + """Noise, SNR and floor from MATLAB's first activity fit.""" + y, it1 = sub["y"][0], sub["it1"] + b = sb.initial_baseline(y, PARAMS) + x = _conv_same(it1["S_out"], PARAMS.k) + var, noise, snr = sb.activity_noise(y, sub["finv"], b, sub["init"]["H"], x, PARAMS.tau_frames) + _close(var, it1["residVar"]) + _close(noise, it1["Xnoise"]) + _close(snr, it1["Xsnr"]) + floor = sb.compute_floor(x, PARAMS.denoise_window, PARAMS.baseline_window) + _close(floor, it1["Xfloor"]) + _close(np.fmax(0, x - floor - noise[:, None]), it1["X_thr"]) + + +def test_subproblem_baseline_fit_matches_matlab(sub: dict[str, Any]) -> None: + """FitB on a real subproblem, to quadprog's tolerance. + + Its trial is shorter than the lowess window of the high-pass split. + """ + y, it1 = sub["y"][0], sub["it1"] + b0 = sb.initial_baseline(y, PARAMS) + b, info = sb.fit_baseline( + b0, + y, + it1["X_thr"], + sub["init"]["H"], + sub["finv"], + sub["sel"], + PARAMS, + return_info=True, + ) + _close(b[:, :: sub["every"]], it1["B_out"], 1e-5) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + + +def test_subproblem_footprint_update_matches_matlab(sub: dict[str, Any]) -> None: + """H from MATLAB's fitted Hs through the footprint filter, and the normalization.""" + it1 = sub["it1"] + h = conv_operator(sub["sel"], PARAMS.hfilter) @ it1["Hs_out"] + norm = h.sum(0) + _close(norm, it1["normFac"]) + _close(h / norm, it1["H"]) + _close(it1["Hs_out"] / norm, it1["Hs"]) + _close(it1["S_out"] * norm[:, None], it1["S"]) + rows, _ = sel_coords(sub["sel"]) + assert h.shape == (rows.size, 2) + + +def test_subproblem_outputs_match_matlab(sub: dict[str, Any]) -> None: + """SNR, least squares and F0 from MATLAB's final activity.""" + y, out, it1 = sub["y"], sub["out"], sub["it1"] + h = out["H"] + b1 = sb.fit_baseline( + sb.initial_baseline(y[0], PARAMS), + y[0], + it1["X_thr"], + sub["init"]["H"], + sub["finv"], + sub["sel"], + PARAMS, + ) + x = _conv_same(out["S"][0], PARAMS.k) + _, _, snr = sb.activity_noise(y[0], sub["finv"], b1, h, x, PARAMS.tau_frames) + _close(snr, out["SNR"], 1e-5) + _close(np.linalg.lstsq(h, y[0] - b1, rcond=None)[0], out["LS"][0], 1e-5) + _close(sb.source_f0(h, b1), out["F0"][0], 1e-5) + b2 = sb.initial_baseline(y[1], PARAMS) + _close(np.linalg.lstsq(h, y[1] - b2, rcond=None)[0], out["LS"][1]) + _close(sb.source_f0(h, b2), out["F0"][1]) + + +def test_interp1_extrapolates() -> None: + """Linear interpolation of rows with linear extrapolation.""" + x = np.array([1.0, 2.0, 4.0]) + y = np.array([[0.0, 1.0, 5.0]]) + out = sb.interp1_extrap(x, y, np.array([0.0, 1.5, 3.0, 5.0])) + np.testing.assert_allclose(out, [[-1.0, 0.5, 3.0, 7.0]]) + + +def test_activity_noise_with_a_zero_footprint_is_matlabs() -> None: + """A source whose footprint is all zero makes the normal matrix singular. + + Noise Inf and SNR 0 for every source, with a warning, as MATLAB's inv + gives; other inputs give the plain inverse's result. + """ + rng = np.random.default_rng(5) + n_px, n_t = 40, 300 + h = np.abs(rng.standard_normal((n_px, 3))) + x = np.abs(rng.standard_normal((3, n_t))) + b = np.full((n_px, n_t), 5.0) + y = b + h @ x + 0.3 * rng.standard_normal((n_px, n_t)) + finv = np.ones((n_px, n_t)) # freshness per pixel and frame + var, noise, snr = sb.activity_noise(y, finv, b, h, x, 4.0) + cov = np.linalg.inv(h.T @ (h / var[:, None])) + np.testing.assert_array_equal(noise, np.sqrt(np.diag(cov) / 4.0)) + assert np.all(np.isfinite(noise)) and np.all(snr > 0) + h0 = h.copy() + h0[:, 1] = 0.0 + with pytest.warns(RuntimeWarning, match="singular"): + _, noise0, snr0 = sb.activity_noise(y, finv, b, h0, x, 4.0) + assert np.all(np.isinf(noise0)) and np.all(snr0 == 0) diff --git a/tests/raster/test_raster_solver_baseline_modes.py b/tests/raster/test_raster_solver_baseline_modes.py index fdf7e43a..40a9d41a 100644 --- a/tests/raster/test_raster_solver_baseline_modes.py +++ b/tests/raster/test_raster_solver_baseline_modes.py @@ -1,479 +1,512 @@ -"""Tests of the solver's baseline modes. - -These are the variants R0, N0-N3 of the SILo port's baseline test: an external -baseline held, scaled per pixel, scaled by a shared time course, or corrected -by ``fitB``. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - conv_same, - solve_subproblem, -) -from giant_python.extraction.raster.solver_baseline import ( - fit_baseline, - fit_gain, - fit_network_gain, - gain_programs, - outside_halves, - shared_time_course, -) -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() -KEEP = SolverOptions(keep_baseline=True) - - -def _corr(a: np.ndarray, b: np.ndarray) -> float: - """Pearson correlation of two traces.""" - return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) - - -@pytest.fixture(scope="module") -def real() -> tuple[Subproblem, SubproblemResult]: - """Load a real two-source subproblem (activity channel only) and solve it. - - Returns it with the default solver's result on it, with its baseline. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - return sub, solve_subproblem(sub, PARAMS, KEEP) - - -def _synthetic( - seed: int = 0, - n_t: int = 1600, - shared: np.ndarray | None = None, - scale: float = 1.0, -) -> tuple[Subproblem, np.ndarray, np.ndarray]: - """Draw a one-source subproblem from a known baseline and events. - - The baseline is a bright stripe times a slow drift (and ``shared``, a - time course common to all pixels, if given); the data are ``F`` - times Poisson counts of mean ``T / F``, with the variance multiplier - ``F`` 0.2. Returns the subproblem (with the true - baseline times ``scale`` as its external baseline, without the shared - course), the true baseline and the true events. - """ - rng = np.random.default_rng(seed) - sel = np.ones((13, 13), bool) - rows, cols = np.nonzero(sel.T)[::-1] - t = np.arange(n_t) - slow = 1 + 0.1 * np.sin(2 * np.pi * t / n_t) - space = 2 + 3 * np.exp(-((cols - 6.0) ** 2) / 8) - b = space[:, None] * slow[None, :] - if shared is not None: - b_true = b * shared[None, :] - else: - b_true = b - h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h /= h.sum() - s = np.zeros(n_t) - s[rng.choice(np.arange(20, n_t - 40), 25, replace=False)] = 20 / 0.19 - x = conv_same(s[None], PARAMS.k)[0] - finv = np.full(b.shape, 0.2) - z = finv * rng.poisson((b_true + np.outer(h, x)) / finv) - sub = Subproblem( - y=z[None], - finv=finv, - sel=sel, - sources_rc=np.array([[6, 6]]), - baseline=b * scale, - ) - return sub, b_true, s - - -def test_params_and_subproblem_check_the_baseline() -> None: - """Unknown modes, a misfitting or non-finite baseline are refused.""" - with pytest.raises(ValueError, match="baseline_mode"): - SolverParams(baseline_mode="network") - for bad in (0.0, 1.0): - with pytest.raises(ValueError, match="outside_footprint"): - SolverParams(outside_footprint=bad) - sub, _, _ = _synthetic() - with pytest.raises(ValueError, match="pixels and frames"): - replace(sub, baseline=sub.baseline[:, :-1], _coords=None) - bad = sub.baseline.copy() - bad[0, 0] = np.nan - with pytest.raises(ValueError, match="NaN"): - replace(sub, baseline=bad, _coords=None) - - -def test_modes_other_than_fit_need_a_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """Without Subproblem.baseline only the default mode runs.""" - sub, _ = real - for mode in ("fixed", "gain", "gain_shared", "fit_from"): - with pytest.raises(ValueError, match="Subproblem.baseline"): - solve_subproblem(sub, replace(PARAMS, baseline_mode=mode)) - - -def test_fit_mode_ignores_an_external_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """R0 gives the same results with and without an external baseline.""" - sub, r0 = real - with_b = replace(sub, baseline=2 * r0.baseline[0], _coords=None) - again = solve_subproblem(with_b, PARAMS, KEEP) - for name in ("footprints", "events", "ls", "f0", "baseline"): - np.testing.assert_array_equal(getattr(again, name), getattr(r0, name)) - - -def test_fixed_mode_holds_the_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """N0 keeps the given baseline (bounded below). - - Given R0's final baseline, it finds R0's sources. - """ - sub, r0 = real - b = r0.baseline[0] - given = replace(sub, baseline=b, _coords=None) - n0 = solve_subproblem(given, replace(PARAMS, baseline_mode="fixed"), KEEP) - np.testing.assert_array_equal(n0.baseline[0], np.fmax(PARAMS.min_baseline, b)) - for j in range(2): - cos = n0.footprints[:, j] @ r0.footprints[:, j] - cos /= np.linalg.norm(n0.footprints[:, j]) - cos /= np.linalg.norm(r0.footprints[:, j]) - assert cos > 0.99 - x0 = conv_same(r0.events[0, j], PARAMS.k) - xn = conv_same(n0.events[0, j], PARAMS.k) - assert _corr(x0, xn) > 0.9 - assert 0.9 < xn.sum() / x0.sum() < 1.1 - assert "baseline_step" not in n0.info - - -def _mean_error(b: np.ndarray, truth: np.ndarray) -> float: - """Mean absolute error of the pixels' time means, over the truth's mean.""" - return float(np.abs(b.mean(1) - truth.mean(1)).mean() / truth.mean()) - - -def test_fit_from_mode_corrects_little_from_the_right_baseline() -> None: - """N3 given the true baseline stays near it, as R0 comes near it.""" - sub, b_true, _ = _synthetic(seed=7) - n3 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fit_from"), KEEP) - r0 = solve_subproblem(sub, PARAMS, KEEP) - assert _mean_error(n3.baseline[0], b_true) < 0.01 - assert _mean_error(r0.baseline[0], b_true) < 0.01 - - -def test_gain_mode_undoes_a_scale_error() -> None: - """N1 given the true baseline times 1.1 finds gains near 1 / 1.1. - - N0 keeps the error. - """ - sub, b_true, _ = _synthetic(seed=7, scale=1.1) - n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) - gain = n1.info["baseline_step"]["gain"] - assert gain.shape == (sub.n_pixels,) - assert abs(np.median(gain) - 1 / 1.1) < 0.01 - np.testing.assert_allclose( - n1.baseline[0], - np.fmax(PARAMS.min_baseline, gain[:, None] * sub.baseline), - ) - assert _mean_error(n1.baseline[0], b_true) < 0.01 - n0 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fixed"), KEEP) - assert abs(_mean_error(n0.baseline[0], b_true) - 0.1) < 1e-9 - - -def test_gain_programs_without_sources_are_weighted_ratios() -> None: - """With no activity the gain is the weighted ratio of data and predictor.""" - rng = np.random.default_rng(3) - y = rng.random((4, 50)) + 1 - q = rng.random((4, 50)) + 0.5 - finv = rng.random((4, 50)) + 0.5 - x = np.zeros((1, 50)) - h = np.full((4, 1), 0.25) - b, coef = fit_gain(q, y, x, h, finv, q, 0.01) - w = 1 / finv - want = (w * y * q).sum(1) / (w * q * q).sum(1) - np.testing.assert_allclose(coef[:, -1], want, rtol=1e-9) - np.testing.assert_allclose(b, want[:, None] * q, rtol=1e-9) - prog = gain_programs(q, y, x, h, finv, q) - assert prog["g"].shape == (4, 2, 2) and prog["n_sources"] == 1 - assert (prog["lb"] == 0).all() - - -def test_shared_time_course_shrinks_noise_to_its_mean() -> None: - """Without a shared change the factor is flat; with one it follows.""" - rng = np.random.default_rng(4) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - src = np.zeros((n_px, n_t)) - finv = np.ones((n_px, n_t)) - y = rng.poisson(q).astype(np.float64) - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] < 1e-4 - assert np.ptp(c) < 0.01 - assert abs(rec["mean"] - 1) < 0.01 - # Poisson of mean 3 against the loss's variance 3 + 1 - assert abs(rec["alpha"] - 0.75) < 0.03 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] > 0 - assert _corr(c, true) > 0.85 - raw_err = np.abs(rec["raw"] - true).mean() - assert np.abs(c - true).mean() < raw_err - - -def test_gain_shared_mode_finds_a_shared_change() -> None: - """N2 recovers a fast change shared by all pixels that the external baseline lacks. - - N1 does not. - """ - n_t = 1600 - shared = 1 + 0.08 * np.sign(np.sin(np.arange(n_t) / 3.0)) - sub, b_true, _ = _synthetic(seed=5, n_t=n_t, shared=shared) - n2 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain_shared"), KEEP) - step = n2.info["baseline_step"] - assert step["n_outside"] > 50 - assert _corr(step["shared"], shared) > 0.8 - n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) - err2 = np.abs(n2.baseline[0] - b_true).mean() - err1 = np.abs(n1.baseline[0] - b_true).mean() - assert err2 < 0.7 * err1 - - -def test_gain_shared_without_outside_pixels_is_gain() -> None: - """With too few pixels outside the footprints the factor is 1.""" - sub, _, _ = _synthetic(seed=6) - params = replace(PARAMS, baseline_mode="gain_shared") - rows, cols = np.nonzero(sub.sel) - b = sub.baseline - rng = np.random.default_rng(0) - h = rng.random((sub.n_pixels, 1)) + 1 # flat footprint: nothing outside - h /= h.sum() - x = np.zeros((1, sub.n_frames)) - bb, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) - assert info["n_outside"] == 0 - np.testing.assert_array_equal(info["shared"], 1.0) - b1, info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) - np.testing.assert_array_equal(bb, b1) - assert rows.size == cols.size == sub.n_pixels - - -def test_fit_baseline_offset() -> None: - """A zero offset changes nothing. - - With the true baseline as offset the fitted correction is small. - """ - sub, b_true, s = _synthetic(seed=7) - y = sub.y[0] - x = conv_same(s[None], PARAMS.k) - rows, cols = np.nonzero(sub.sel.T)[::-1] - h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h = (h / h.sum())[:, None] - b0 = sub.baseline - plain = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS) - zero = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=np.zeros_like(y)) - np.testing.assert_allclose(zero, plain, rtol=1e-12, atol=1e-12) - corr = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=b0) - err_from = np.abs(corr - b_true).mean() / b_true.mean() - assert err_from < 0.03 - - -def test_shared_variance_ignores_filled_frames() -> None: - """Filled-in frames (variance multiplier 1000 x) do not hide a shared change. - - They are left out of the shared variance and shrunk alone. - """ - rng = np.random.default_rng(8) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - src = np.zeros((n_px, n_t)) - finv = np.ones((n_px, n_t)) - filled = np.zeros(n_t, bool) - filled[100:160] = True - finv[:, filled] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[:, filled] = 3.0 # filled with a smooth value - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] > 0 - assert _corr(c[~filled], true[~filled]) > 0.85 - # the filled frames stay near the mean - assert np.abs(c[filled] - rec["mean"]).max() < 0.01 - - -def test_outside_pixels_ignore_a_source_without_footprint() -> None: - """A source whose footprint is all zero leaves the outside pixels to the other sources.""" - sub, _, _ = _synthetic(seed=9) - params = replace(PARAMS, baseline_mode="gain_shared") - rows, cols = np.nonzero(sub.sel.T)[::-1] - h1 = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h = np.column_stack([h1 / h1.sum(), np.zeros(sub.n_pixels)]) - x = np.zeros((2, sub.n_frames)) - b = sub.baseline - _, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) - assert info["n_outside"] > 100 - - -def test_filled_frames_do_not_fake_a_shared_change() -> None: - """With a constant baseline, many filled-in frames leave the residual scale unbiased. - - So no shared change is found. - """ - rng = np.random.default_rng(10) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - filled = rng.random(n_t) < 0.3 - finv[:, filled] = 1000.0 - y = rng.poisson(q).astype(np.float64) - y[:, filled] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert abs(rec["alpha"] - 0.75) < 0.03 - assert np.ptp(c) < 0.01 - - -def test_filled_samples_do_not_count_in_alpha() -> None: - """Pixels filled in at some frames do not bias the residual scale.""" - rng = np.random.default_rng(13) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - holes = rng.random((n_px, n_t)) < 0.3 - finv[holes] = 1000.0 - y = rng.poisson(q).astype(np.float64) - y[holes] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert abs(rec["alpha"] - 0.75) < 0.03 - assert np.ptp(c) < 0.01 - - -def test_shared_change_found_when_most_frames_are_filled() -> None: - """With 70% of the frames filled in, the shared change is still found. - - It is found on the other frames. - """ - rng = np.random.default_rng(12) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - filled = rng.random(n_t) < 0.7 - finv[:, filled] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[:, filled] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert rec["s2"] > 0 - assert _corr(c[~filled], true[~filled]) > 0.85 - - -def _paired_noise(rng: np.random.Generator, q: np.ndarray, true: np.ndarray) -> np.ndarray: - """Poisson data whose noise neighbouring pixel pairs share (as on resampled frames). - - Each pair's pixels are the mean of two draws. - """ - n_px, n_t = q.shape - draws = rng.poisson(q * true[None]).astype(np.float64) - pair = draws.reshape(n_px // 2, 2, n_t).mean(1) - return np.repeat(pair, 2, axis=0) - - -def test_halves_ignore_noise_shared_by_neighbours() -> None: - """Noise shared by neighbouring pixels is no shared change when the halves are apart. - - The independent-noise estimate mistakes it for one. - """ - rng = np.random.default_rng(14) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - src = np.zeros_like(q) - y = _paired_noise(rng, q, np.ones(n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - c1, r1 = shared_time_course(y, q, src, finv) - c2, r2 = shared_time_course(y, q, src, finv, (half_a, half_b)) - assert r1["s2"] > 0 and np.ptp(c1) > 0.05 - assert r2["s2"] < 0.1 * r2["var_raw"] - assert np.std(c2) < 0.3 * np.std(c1) - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = _paired_noise(rng, q, true) - c3, r3 = shared_time_course(y, q, src, finv, (half_a, half_b)) - assert r3["s2"] > 0 - assert _corr(c3, true) > 0.85 - small = np.zeros(n_px, bool) - small[:3] = True - _, r4 = shared_time_course(y, q, src, finv, (small, half_b)) - assert r4["s2"] == 0 - - -def test_outside_halves_are_apart() -> None: - """The halves split the outside pixels along their longer extent, with a gap.""" - sel = np.ones((5, 12), bool) - outside = np.ones(60, bool) - a, b = outside_halves(sel, outside) - rows, cols = np.nonzero(sel.T)[::-1] - assert cols[a].max() < cols[b].min() - 2 - assert a.sum() > 15 and b.sum() > 15 - - -def test_halves_skip_frames_where_one_half_is_filled() -> None: - """Frames where one half is filled in do not enter the halves' covariance. - - This holds for frames where the whole is not filled in. - """ - rng = np.random.default_rng(15) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - holes = rng.random(n_t) < 0.4 - finv[np.ix_(half_a, holes)] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[np.ix_(half_a, holes)] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) - assert rec["s2"] == pytest.approx(np.var(true), rel=0.25) - assert _corr(c, true) > 0.85 - - -def test_halves_do_not_shrink_noiseless_factors() -> None: - """Identical noiseless factors in both halves are kept as they are, also with few frames.""" - q = np.ones((20, 2)) - y = q * np.array([0.8, 1.2])[None] - halves = (np.arange(20) < 8, np.arange(20) >= 12) - for finv in (np.ones_like(q), np.ones_like(q) * np.array([1.0, 4.0])): - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) - np.testing.assert_allclose(c, [0.8, 1.2]) - - -def test_halves_use_the_same_frames_for_both_variances() -> None: - """The halves use the same frames for the shared and the factors' variance. - - When one half is filled in during the quiet part of a shared change, the - shared variance does not exceed the factors' variance on the same - frames, and the change is followed. - """ - rng = np.random.default_rng(16) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - quiet = true < 1 - finv[np.ix_(half_a, quiet)] = 1000.0 - y = rng.poisson(q * true[None]).astype(np.float64) - y[np.ix_(half_a, quiet)] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) - assert 0 < rec["s2"] <= rec["var_used"] - # on these frames the change is half a sine, a smaller variance - assert rec["s2"] == pytest.approx(np.var(true[~quiet]), rel=0.4) - assert _corr(c[~quiet], true[~quiet]) > 0.6 +"""Tests of the solver's baseline modes. + +These are the variants R0, N0-N3 of the SILo port's baseline test: an external +baseline held, scaled per pixel, scaled by a shared time course, or corrected +by fitB. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + conv_same, + solve_subproblem, +) +from giant_python.extraction.raster.solver_baseline import ( + fit_baseline, + fit_gain, + fit_network_gain, + gain_programs, + outside_halves, + shared_time_course, +) +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() +KEEP = SolverOptions(keep_baseline=True) + + +def _corr(a: np.ndarray, b: np.ndarray) -> float: + """Pearson correlation of two traces. + + Returns + ------- + float + The correlation coefficient of the flattened a and b. + """ + return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) + + +@pytest.fixture(scope="module") +def real() -> tuple[Subproblem, SubproblemResult]: + """Load a real two-source subproblem (activity channel only) and solve it. + + Returns it with the default solver's result on it, with its baseline. + + Returns + ------- + sub : Subproblem + The real subproblem. + result : SubproblemResult + The default solver's result on it, with its baseline kept. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + return sub, solve_subproblem(sub, PARAMS, KEEP) + + +def _synthetic( + seed: int = 0, + n_t: int = 1600, + shared: np.ndarray | None = None, + scale: float = 1.0, +) -> tuple[Subproblem, np.ndarray, np.ndarray]: + """Draw a one-source subproblem from a known baseline and events. + + The baseline is a bright stripe times a slow drift (and shared, a + time course common to all pixels, if given); the data are F + times Poisson counts of mean T / F, with the variance multiplier + F 0.2. Returns the subproblem (with the true + baseline times scale as its external baseline, without the shared + course), the true baseline and the true events. + + Returns + ------- + sub : Subproblem + The subproblem, with the true baseline times scale as its external baseline. + b_true : np.ndarray + The true baseline (including shared if given). + s : np.ndarray + The true events. + """ + rng = np.random.default_rng(seed) + sel = np.ones((13, 13), bool) + rows, cols = np.nonzero(sel.T)[::-1] + t = np.arange(n_t) + slow = 1 + 0.1 * np.sin(2 * np.pi * t / n_t) + space = 2 + 3 * np.exp(-((cols - 6.0) ** 2) / 8) + b = space[:, None] * slow[None, :] + if shared is not None: + b_true = b * shared[None, :] + else: + b_true = b + h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h /= h.sum() + s = np.zeros(n_t) + s[rng.choice(np.arange(20, n_t - 40), 25, replace=False)] = 20 / 0.19 + x = conv_same(s[None], PARAMS.k)[0] + finv = np.full(b.shape, 0.2) + z = finv * rng.poisson((b_true + np.outer(h, x)) / finv) + sub = Subproblem( + y=z[None], + finv=finv, + sel=sel, + sources_rc=np.array([[6, 6]]), + baseline=b * scale, + ) + return sub, b_true, s + + +def test_params_and_subproblem_check_the_baseline() -> None: + """Unknown modes, a misfitting or non-finite baseline are refused.""" + with pytest.raises(ValueError, match="baseline_mode"): + SolverParams(baseline_mode="network") + for bad in (0.0, 1.0): + with pytest.raises(ValueError, match="outside_footprint"): + SolverParams(outside_footprint=bad) + sub, _, _ = _synthetic() + with pytest.raises(ValueError, match="pixels and frames"): + replace(sub, baseline=sub.baseline[:, :-1], _coords=None) + bad = sub.baseline.copy() + bad[0, 0] = np.nan + with pytest.raises(ValueError, match="NaN"): + replace(sub, baseline=bad, _coords=None) + + +def test_modes_other_than_fit_need_a_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """Without Subproblem.baseline only the default mode runs.""" + sub, _ = real + for mode in ("fixed", "gain", "gain_shared", "fit_from"): + with pytest.raises(ValueError, match="Subproblem.baseline"): + solve_subproblem(sub, replace(PARAMS, baseline_mode=mode)) + + +def test_fit_mode_ignores_an_external_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """R0 gives the same results with and without an external baseline.""" + sub, r0 = real + with_b = replace(sub, baseline=2 * r0.baseline[0], _coords=None) + again = solve_subproblem(with_b, PARAMS, KEEP) + for name in ("footprints", "events", "ls", "f0", "baseline"): + np.testing.assert_array_equal(getattr(again, name), getattr(r0, name)) + + +def test_fixed_mode_holds_the_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """N0 keeps the given baseline (bounded below). + + Given R0's final baseline, it finds R0's sources. + """ + sub, r0 = real + b = r0.baseline[0] + given = replace(sub, baseline=b, _coords=None) + n0 = solve_subproblem(given, replace(PARAMS, baseline_mode="fixed"), KEEP) + np.testing.assert_array_equal(n0.baseline[0], np.fmax(PARAMS.min_baseline, b)) + for j in range(2): + cos = n0.footprints[:, j] @ r0.footprints[:, j] + cos /= np.linalg.norm(n0.footprints[:, j]) + cos /= np.linalg.norm(r0.footprints[:, j]) + assert cos > 0.99 + x0 = conv_same(r0.events[0, j], PARAMS.k) + xn = conv_same(n0.events[0, j], PARAMS.k) + assert _corr(x0, xn) > 0.9 + assert 0.9 < xn.sum() / x0.sum() < 1.1 + assert "baseline_step" not in n0.info + + +def _mean_error(b: np.ndarray, truth: np.ndarray) -> float: + """Mean absolute error of the pixels' time means, over the truth's mean. + + Returns + ------- + float + The relative error. + """ + return float(np.abs(b.mean(1) - truth.mean(1)).mean() / truth.mean()) + + +def test_fit_from_mode_corrects_little_from_the_right_baseline() -> None: + """N3 given the true baseline stays near it, as R0 comes near it.""" + sub, b_true, _ = _synthetic(seed=7) + n3 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fit_from"), KEEP) + r0 = solve_subproblem(sub, PARAMS, KEEP) + assert _mean_error(n3.baseline[0], b_true) < 0.01 + assert _mean_error(r0.baseline[0], b_true) < 0.01 + + +def test_gain_mode_undoes_a_scale_error() -> None: + """N1 given the true baseline times 1.1 finds gains near 1 / 1.1. + + N0 keeps the error. + """ + sub, b_true, _ = _synthetic(seed=7, scale=1.1) + n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) + gain = n1.info["baseline_step"]["gain"] + assert gain.shape == (sub.n_pixels,) + assert abs(np.median(gain) - 1 / 1.1) < 0.01 + np.testing.assert_allclose( + n1.baseline[0], + np.fmax(PARAMS.min_baseline, gain[:, None] * sub.baseline), + ) + assert _mean_error(n1.baseline[0], b_true) < 0.01 + n0 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fixed"), KEEP) + assert abs(_mean_error(n0.baseline[0], b_true) - 0.1) < 1e-9 + + +def test_gain_programs_without_sources_are_weighted_ratios() -> None: + """With no activity the gain is the weighted ratio of data and predictor.""" + rng = np.random.default_rng(3) + y = rng.random((4, 50)) + 1 + q = rng.random((4, 50)) + 0.5 + finv = rng.random((4, 50)) + 0.5 + x = np.zeros((1, 50)) + h = np.full((4, 1), 0.25) + b, coef = fit_gain(q, y, x, h, finv, q, 0.01) + w = 1 / finv + want = (w * y * q).sum(1) / (w * q * q).sum(1) + np.testing.assert_allclose(coef[:, -1], want, rtol=1e-9) + np.testing.assert_allclose(b, want[:, None] * q, rtol=1e-9) + prog = gain_programs(q, y, x, h, finv, q) + assert prog["g"].shape == (4, 2, 2) and prog["n_sources"] == 1 + assert (prog["lb"] == 0).all() + + +def test_shared_time_course_shrinks_noise_to_its_mean() -> None: + """Without a shared change the factor is flat; with one it follows.""" + rng = np.random.default_rng(4) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + src = np.zeros((n_px, n_t)) + finv = np.ones((n_px, n_t)) + y = rng.poisson(q).astype(np.float64) + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] < 1e-4 + assert np.ptp(c) < 0.01 + assert abs(rec["mean"] - 1) < 0.01 + # Poisson of mean 3 against the loss's variance 3 + 1 + assert abs(rec["alpha"] - 0.75) < 0.03 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] > 0 + assert _corr(c, true) > 0.85 + raw_err = np.abs(rec["raw"] - true).mean() + assert np.abs(c - true).mean() < raw_err + + +def test_gain_shared_mode_finds_a_shared_change() -> None: + """N2 recovers a fast change shared by all pixels that the external baseline lacks. + + N1 does not. + """ + n_t = 1600 + shared = 1 + 0.08 * np.sign(np.sin(np.arange(n_t) / 3.0)) + sub, b_true, _ = _synthetic(seed=5, n_t=n_t, shared=shared) + n2 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain_shared"), KEEP) + step = n2.info["baseline_step"] + assert step["n_outside"] > 50 + assert _corr(step["shared"], shared) > 0.8 + n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) + err2 = np.abs(n2.baseline[0] - b_true).mean() + err1 = np.abs(n1.baseline[0] - b_true).mean() + assert err2 < 0.7 * err1 + + +def test_gain_shared_without_outside_pixels_is_gain() -> None: + """With too few pixels outside the footprints the factor is 1.""" + sub, _, _ = _synthetic(seed=6) + params = replace(PARAMS, baseline_mode="gain_shared") + rows, cols = np.nonzero(sub.sel) + b = sub.baseline + rng = np.random.default_rng(0) + h = rng.random((sub.n_pixels, 1)) + 1 # flat footprint: nothing outside + h /= h.sum() + x = np.zeros((1, sub.n_frames)) + bb, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) + assert info["n_outside"] == 0 + np.testing.assert_array_equal(info["shared"], 1.0) + b1, info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) + np.testing.assert_array_equal(bb, b1) + assert rows.size == cols.size == sub.n_pixels + + +def test_fit_baseline_offset() -> None: + """A zero offset changes nothing. + + With the true baseline as offset the fitted correction is small. + """ + sub, b_true, s = _synthetic(seed=7) + y = sub.y[0] + x = conv_same(s[None], PARAMS.k) + rows, cols = np.nonzero(sub.sel.T)[::-1] + h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h = (h / h.sum())[:, None] + b0 = sub.baseline + plain = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS) + zero = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=np.zeros_like(y)) + np.testing.assert_allclose(zero, plain, rtol=1e-12, atol=1e-12) + corr = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=b0) + err_from = np.abs(corr - b_true).mean() / b_true.mean() + assert err_from < 0.03 + + +def test_shared_variance_ignores_filled_frames() -> None: + """Filled-in frames (variance multiplier 1000 x) do not hide a shared change. + + They are left out of the shared variance and shrunk alone. + """ + rng = np.random.default_rng(8) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + src = np.zeros((n_px, n_t)) + finv = np.ones((n_px, n_t)) + filled = np.zeros(n_t, bool) + filled[100:160] = True + finv[:, filled] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[:, filled] = 3.0 # filled with a smooth value + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] > 0 + assert _corr(c[~filled], true[~filled]) > 0.85 + # the filled frames stay near the mean + assert np.abs(c[filled] - rec["mean"]).max() < 0.01 + + +def test_outside_pixels_ignore_a_source_without_footprint() -> None: + """A source whose footprint is all zero leaves the outside pixels to the other sources.""" + sub, _, _ = _synthetic(seed=9) + params = replace(PARAMS, baseline_mode="gain_shared") + rows, cols = np.nonzero(sub.sel.T)[::-1] + h1 = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h = np.column_stack([h1 / h1.sum(), np.zeros(sub.n_pixels)]) + x = np.zeros((2, sub.n_frames)) + b = sub.baseline + _, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) + assert info["n_outside"] > 100 + + +def test_filled_frames_do_not_fake_a_shared_change() -> None: + """With a constant baseline, many filled-in frames leave the residual scale unbiased. + + So no shared change is found. + """ + rng = np.random.default_rng(10) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + filled = rng.random(n_t) < 0.3 + finv[:, filled] = 1000.0 + y = rng.poisson(q).astype(np.float64) + y[:, filled] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert abs(rec["alpha"] - 0.75) < 0.03 + assert np.ptp(c) < 0.01 + + +def test_filled_samples_do_not_count_in_alpha() -> None: + """Pixels filled in at some frames do not bias the residual scale.""" + rng = np.random.default_rng(13) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + holes = rng.random((n_px, n_t)) < 0.3 + finv[holes] = 1000.0 + y = rng.poisson(q).astype(np.float64) + y[holes] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert abs(rec["alpha"] - 0.75) < 0.03 + assert np.ptp(c) < 0.01 + + +def test_shared_change_found_when_most_frames_are_filled() -> None: + """With 70% of the frames filled in, the shared change is still found. + + It is found on the other frames. + """ + rng = np.random.default_rng(12) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + filled = rng.random(n_t) < 0.7 + finv[:, filled] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[:, filled] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert rec["s2"] > 0 + assert _corr(c[~filled], true[~filled]) > 0.85 + + +def _paired_noise(rng: np.random.Generator, q: np.ndarray, true: np.ndarray) -> np.ndarray: + """Poisson data whose noise neighbouring pixel pairs share (as on resampled frames). + + Each pair's pixels are the mean of two draws. + + Returns + ------- + np.ndarray + Data of shape (n_px, n_t) with each pixel pair sharing its values. + """ + n_px, n_t = q.shape + draws = rng.poisson(q * true[None]).astype(np.float64) + pair = draws.reshape(n_px // 2, 2, n_t).mean(1) + return np.repeat(pair, 2, axis=0) + + +def test_halves_ignore_noise_shared_by_neighbours() -> None: + """Noise shared by neighbouring pixels is no shared change when the halves are apart. + + The independent-noise estimate mistakes it for one. + """ + rng = np.random.default_rng(14) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + src = np.zeros_like(q) + y = _paired_noise(rng, q, np.ones(n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + c1, r1 = shared_time_course(y, q, src, finv) + c2, r2 = shared_time_course(y, q, src, finv, (half_a, half_b)) + assert r1["s2"] > 0 and np.ptp(c1) > 0.05 + assert r2["s2"] < 0.1 * r2["var_raw"] + assert np.std(c2) < 0.3 * np.std(c1) + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = _paired_noise(rng, q, true) + c3, r3 = shared_time_course(y, q, src, finv, (half_a, half_b)) + assert r3["s2"] > 0 + assert _corr(c3, true) > 0.85 + small = np.zeros(n_px, bool) + small[:3] = True + _, r4 = shared_time_course(y, q, src, finv, (small, half_b)) + assert r4["s2"] == 0 + + +def test_outside_halves_are_apart() -> None: + """The halves split the outside pixels along their longer extent, with a gap.""" + sel = np.ones((5, 12), bool) + outside = np.ones(60, bool) + a, b = outside_halves(sel, outside) + rows, cols = np.nonzero(sel.T)[::-1] + assert cols[a].max() < cols[b].min() - 2 + assert a.sum() > 15 and b.sum() > 15 + + +def test_halves_skip_frames_where_one_half_is_filled() -> None: + """Frames where one half is filled in do not enter the halves' covariance. + + This holds for frames where the whole is not filled in. + """ + rng = np.random.default_rng(15) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + holes = rng.random(n_t) < 0.4 + finv[np.ix_(half_a, holes)] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[np.ix_(half_a, holes)] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) + assert rec["s2"] == pytest.approx(np.var(true), rel=0.25) + assert _corr(c, true) > 0.85 + + +def test_halves_do_not_shrink_noiseless_factors() -> None: + """Identical noiseless factors in both halves are kept as they are, also with few frames.""" + q = np.ones((20, 2)) + y = q * np.array([0.8, 1.2])[None] + halves = (np.arange(20) < 8, np.arange(20) >= 12) + for finv in (np.ones_like(q), np.ones_like(q) * np.array([1.0, 4.0])): + c, rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) + np.testing.assert_allclose(c, [0.8, 1.2]) + + +def test_halves_use_the_same_frames_for_both_variances() -> None: + """The halves use the same frames for the shared and the factors' variance. + + When one half is filled in during the quiet part of a shared change, the + shared variance does not exceed the factors' variance on the same + frames, and the change is followed. + """ + rng = np.random.default_rng(16) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + quiet = true < 1 + finv[np.ix_(half_a, quiet)] = 1000.0 + y = rng.poisson(q * true[None]).astype(np.float64) + y[np.ix_(half_a, quiet)] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) + assert 0 < rec["s2"] <= rec["var_used"] + # on these frames the change is half a sine, a smaller variance + assert rec["s2"] == pytest.approx(np.var(true[~quiet]), rel=0.4) + assert _corr(c[~quiet], true[~quiet]) > 0.6 diff --git a/tests/raster/test_raster_solver_fits.py b/tests/raster/test_raster_solver_fits.py index e1bdb5e3..4973f439 100644 --- a/tests/raster/test_raster_solver_fits.py +++ b/tests/raster/test_raster_solver_fits.py @@ -1,431 +1,463 @@ -"""Tests of the iterative fits of the subproblem solver. - -The loss and its derivatives, the kernel, the bounded Newton solver, and the -fits against GIAnT-MATLAB's from the same inputs. -""" - -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -import torch -from numpy.typing import ArrayLike -from scipy import optimize - -from giant_python.extraction.raster import solver_baseline as sb -from giant_python.extraction.raster import solver_fits as sf -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - conv_operator, - temporal_kernel, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() -DT = torch.float64 - - -def _t(a: ArrayLike) -> torch.Tensor: - """Make a float64 tensor with a leading batch dimension of one.""" - return torch.as_tensor(np.ascontiguousarray(a), dtype=DT)[None] - - -def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: - """MATLAB convn(x, k, 'same') along the last axis.""" - c = len(k) // 2 - flat = x.reshape(-1, x.shape[-1]) - out = np.stack([np.convolve(r, k)[c : c + x.shape[-1]] for r in flat]) - return out.reshape(x.shape) - - -def _small_problem( - seed: int = 0, - n_px: int = 14, - n_src: int = 2, - n_t: int = 60, - batch: int = 1, - tau: float = 3.0, -) -> list[torch.Tensor]: - """Random data from overlapping footprints and sparse events.""" - rng = np.random.default_rng(seed) - k = temporal_kernel(tau) - h = rng.random((batch, n_px, n_src)) ** 3 - h /= h.sum(1, keepdims=True) - s = (rng.random((batch, n_src, n_t)) < 0.1) * rng.uniform(20, 80, (batch, n_src, n_t)) - b = 1.0 + rng.random((batch, n_px, 1)) + 0.2 * rng.random((1, 1, n_t)) - finv = 0.5 + rng.random((batch, n_px, n_t)) - mean = b + h @ _conv_same(s, k) - z = finv * rng.poisson(mean / finv) - tens = [torch.as_tensor(a, dtype=DT) for a in (z, h, b, 1 / finv, s)] - return tens + [torch.as_tensor(k, dtype=DT)] - - -@pytest.mark.parametrize("fixed", [False, True]) -def test_loss_derivatives(fixed: bool) -> None: - """First and second derivative of the loss in the model, by autograd.""" - rng = np.random.default_rng(0) - z = torch.as_tensor(rng.random((2, 3, 5)) * 4) - w = torch.as_tensor(0.5 + rng.random((2, 3, 5))) - s0 = torch.as_tensor(1 + rng.random((2, 3, 5))) if fixed else None - t = torch.as_tensor(rng.random((2, 3, 5)) * 3, dtype=DT).requires_grad_() - f, g, c = sf.variance_loss(z, t, w, s0) - var = s0 if fixed else t + 1 - expected = (w * (z - t) ** 2 / var).sum((-2, -1)) - assert torch.allclose(f, expected, rtol=1e-13) - (g_auto,) = torch.autograd.grad(expected.sum(), t, create_graph=True) - assert torch.allclose(g, g_auto, rtol=1e-12) - (c_auto,) = torch.autograd.grad(g_auto.sum(), t) - assert torch.allclose(c, c_auto, rtol=1e-12) - assert sf.variance_loss(z, t, w, s0, 0)[1:] == (None, None) - assert sf.variance_loss(z, t, w, s0, 1)[2] is None - - -@pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) -@pytest.mark.parametrize("n_t", [5, 40, 400]) -def test_time_kernel_matches_convolution(tau: float, n_t: int) -> None: - """The exponential kernels by shifted additions equal a 'same' convolution. - - This holds for trials shorter and longer than the kernel. - """ - rng = np.random.default_rng(1) - k = temporal_kernel(tau) - kern = sf.TimeKernel(torch.as_tensor(k)) - assert kern.decay == pytest.approx(np.exp(-1 / tau), rel=1e-9) - x = rng.standard_normal((2, 3, n_t)) - y = kern.conv(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-13) - ya = kern.conv_adj(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-13) - - -def test_time_kernel_general() -> None: - """Kernels that are not causal exponentials go through conv1d.""" - rng = np.random.default_rng(2) - x = rng.standard_normal((1, 2, 30)) - for k in ( - np.concatenate([np.zeros(4), [0.5, 0.3, 0.1, 0.07, 0.03]]), - np.array([0.2, 0.5, 0.3]), - np.array([0.0, 0.0, 0.0, 1.0, 0.5, 0.0, 0.25]), - ): - kern = sf.TimeKernel(torch.as_tensor(k)) - assert kern.decay is None - y = kern.conv(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-14) - ya = kern.conv_adj(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-14) - with pytest.raises(ValueError, match="odd"): - sf.TimeKernel(torch.ones(4)) - - -def _check_derivatives( - problem: sf.ActivityProblem | sf.FootprintProblem, x: torch.Tensor -) -> None: - """Gradient, Hessian products and diagonal against autograd.""" - x = x.clone().requires_grad_() - f = problem.value(x) - (g_auto,) = torch.autograd.grad(f.sum(), x, create_graph=True) - f2, g = problem.value_grad(x.detach()) - assert torch.allclose(f2, f.detach(), rtol=1e-13) - assert torch.allclose(g, g_auto.detach(), rtol=1e-9, atol=1e-10) - rng = np.random.default_rng(5) - v = torch.as_tensor(rng.standard_normal(x.shape)) - (hv_auto,) = torch.autograd.grad((g_auto * v).sum(), x, retain_graph=True) - hv = problem.hess_mult(v) - assert torch.allclose(hv, hv_auto, rtol=1e-9, atol=1e-9) - diag = torch.zeros_like(x) - flat = diag.view(-1) - for i in range(flat.numel()): - e = torch.zeros(flat.numel(), dtype=DT) - e[i] = 1 - flat[i] = problem.hess_mult(e.view(x.shape)).view(-1)[i] - assert torch.allclose(problem.hess_diag(), diag, rtol=1e-9, atol=1e-12) - - -@pytest.mark.parametrize("fixed", [False, True]) -def test_activity_problem_derivatives(fixed: bool) -> None: - """The activity fit's gradient and curvature, with either variance.""" - z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) - s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None - problem = sf.ActivityProblem(z, h, b, k, w, 0.9, s0) - _check_derivatives(problem, s * 0.5 + 1) - - -def test_footprint_problem_derivatives() -> None: - """The footprint fit's gradient and curvature.""" - z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) - rng = np.random.default_rng(6) - g = torch.as_tensor(rng.random((1, 6, 6)) * (rng.random((1, 6, 6)) < 0.6)) - x = sf.TimeKernel(k).conv(s) - support = torch.ones((1, 6, 2), dtype=torch.bool) - problem = sf.FootprintProblem(z, x, b, g, w, support) - _check_derivatives(problem, h.clone()) - - -def test_preconditioner_inverts_one_source() -> None: - """For one source the preconditioner is the inverse of the Hessian on the free events. - - Up to the kernel's truncation. - """ - z, h, b, w, s, k = _small_problem(n_px=8, n_src=1, n_t=200) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - problem.value_grad(s) - rng = np.random.default_rng(7) - free = torch.as_tensor(rng.random(s.shape) < 0.4) - free[..., 50:80] = True # a run of consecutive free events - fm = free.to(DT) - v = torch.as_tensor(rng.standard_normal(s.shape)) * fm - hv = fm * problem.hess_mult(v) - back = problem.preconditioner(free, problem.hess_diag())(hv) - assert float((back - v).norm() / v.norm()) < 0.02 - # the Hessian's diagonal alone is far from it - jacobi = fm / problem.hess_diag() * hv - assert float((jacobi - v).norm() / v.norm()) > 0.3 - - -def test_preconditioner_falls_back_to_diagonal() -> None: - """Kernels that are not exponential get the Hessian's diagonal.""" - z, h, b, w, s, _ = _small_problem(n_px=6, n_t=20) - k = torch.as_tensor([0.0, 0.0, 0.6, 0.1, 0.3], dtype=DT) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - problem.value_grad(s) - free = torch.ones_like(s, dtype=torch.bool) - r = torch.ones_like(s) - diag = problem.hess_diag() - assert torch.equal(problem.preconditioner(free, diag)(r), r / diag) - - -def test_activity_fit_reaches_scipy_optimum() -> None: - """The fit ends at the optimum that L-BFGS-B approaches. - - Many events are on their bound. - """ - z, h, b, w, s_true, k = _small_problem(seed=3, n_px=20, n_t=120) - start = torch.full_like(s_true, 5.0) - s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, history=True) - assert bool(info.converged[0]) and int(info.iterations[0]) < 30 - assert float(info.optimality[0]) < 1e-5 - assert float((s == 0).double().mean()) > 0.4 and float(s.min()) == 0 - losses = [float(f[0]) for f in info.history] - assert all(b2 <= a2 for a2, b2 in zip(losses, losses[1:])) - - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - - def fun(x: np.ndarray) -> tuple[float, np.ndarray]: - """Loss and gradient for scipy.""" - f, g = problem.value_grad(torch.as_tensor(x).view(s.shape)) - return float(f[0]), g.numpy().ravel() - - ref = optimize.minimize( - fun, - start.numpy().ravel(), - jac=True, - method="L-BFGS-B", - bounds=[(0, None)] * s.numel(), - options=dict(maxiter=20000, maxfun=50000, ftol=1e-15, gtol=1e-9), - ) - assert float(info.loss[0]) <= ref.fun + 1e-9 * abs(ref.fun) - np.testing.assert_allclose(s.numpy().ravel(), ref.x, atol=2e-2) - # the sparse events are recovered - found = _conv_same(s.numpy(), k.numpy()) - truth = _conv_same(s_true.numpy(), k.numpy()) - assert np.corrcoef(found.ravel(), truth.ravel())[0, 1] > 0.7 - - -def test_fit_does_not_depend_on_its_start() -> None: - """A convex fit has one optimum: two starts end at the same events.""" - z, h, b, w, s_true, k = _small_problem(seed=4, n_px=16, n_t=80) - a, _ = sf.fit_activity(z, h, b, k, w, 0.9, torch.zeros_like(s_true)) - c, _ = sf.fit_activity(z, h, b, k, w, 0.9, s_true * 3 + 10) - assert torch.allclose(a, c, atol=1e-4) - - -def test_batched_fit_equals_separate_fits() -> None: - """Members of a batch get the fits they get alone. - - They are padded with weightless pixels and a source held at zero. - """ - z, h, b, w, s_true, k = _small_problem(seed=5, n_px=12, n_t=70, batch=2) - # member 1: 9 pixels and one source; the rest is padding - w[1, 9:] = 0 - z[1, 9:] = 0 - b[1, 9:] = 1 - h[1, :, 1] = 0 - h[1, 9:] = 0 - free = torch.ones_like(s_true, dtype=torch.bool) - free[1, 1] = False - start = torch.full_like(s_true, 2.0) - s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, free=free) - assert bool(info.converged.all()) - assert torch.all(s[1, 1] == 0) - one, i0 = sf.fit_activity(z[:1], h[:1], b[:1], k, w[:1], 0.9, start[:1], free=free[:1]) - two, i1 = sf.fit_activity(z[1:, :9], h[1:, :9, :1], b[1:, :9], k, w[1:, :9], 0.9, start[1:, :1]) - assert torch.allclose(s[0], one[0], atol=1e-5) - assert torch.allclose(s[1, :1], two[0], atol=1e-5) - assert float(info.loss[0]) == pytest.approx(float(i0.loss[0]), rel=1e-10) - assert float(info.loss[1]) == pytest.approx(float(i1.loss[0]), rel=1e-10) - - -def test_iteration_cap_and_free_entries() -> None: - """A capped fit reports that it did not converge and still lowers the loss. - - Entries that are not free stay at zero. - """ - z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) - start = torch.full_like(s_true, 5.0) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) - assert not bool(info.converged[0]) and int(info.iterations[0]) == 1 - assert float(info.loss[0]) < float(problem.value(start)[0]) - full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) - assert float(done.loss[0]) < float(info.loss[0]) - free = s_true > 0 - s2, info2 = sf.fit_activity(z, h, b, k, w, 0.0, start, free=free) - assert bool(info2.converged[0]) - assert torch.all(s2[~free] == 0) and float(s2[free].min()) >= 0 - - -def test_fixed_variance_fit_is_weighted_least_squares() -> None: - """With the variance held, the fit of the free events is weighted least squares. - - It is the bounded weighted least-squares solution. - """ - z, h, b, w, s_true, k = _small_problem(seed=7, n_px=10, n_src=1, n_t=40) - kern = sf.TimeKernel(k) - s0 = h @ kern.conv(s_true) + b + 1 - free = torch.zeros_like(s_true, dtype=torch.bool) - free[..., ::4] = True - s, info = sf.fit_activity(z, h, b, k, w, 0.0, s_true, s0=s0, free=free, ftol=1e-15) - assert bool(info.converged[0]) - idx = np.nonzero(free.numpy().ravel())[0] - cols = [] - for i in idx: - e = torch.zeros_like(s_true) - e.view(-1)[i] = 1 - cols.append((h @ kern.conv(e)).numpy().ravel()) - sw = np.sqrt((w / s0).numpy().ravel()) - design = np.stack(cols, 1) * sw[:, None] - target = (z - b).numpy().ravel() * sw - ref = optimize.lsq_linear(design, target, bounds=(0, np.inf)).x - np.testing.assert_allclose(s.numpy().ravel()[idx], ref, atol=1e-5) - - -def test_footprint_fit_stays_on_its_support() -> None: - """Footprints are fitted within their support, not below zero. - - They reach a lower loss than the start. - """ - z, h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) - x = sf.TimeKernel(k).conv(s) - g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 - valid = torch.zeros((1, 12, 2), dtype=torch.bool) - valid[0, :6, 0] = True - valid[0, 5:, 1] = True - start = valid.to(DT) / 6 - hs, info = sf.fit_footprints(z, x, b, g, w, start, valid) - assert bool(info.converged[0]) - assert torch.all(hs[~valid] == 0) and float(hs.min()) >= 0 - problem = sf.FootprintProblem(z, x, b, g, w, valid) - assert float(info.loss[0]) < float(problem.value(start)[0]) - assert torch.allclose(problem.footprints(hs), g @ hs) - - -@pytest.fixture(scope="module") -def matlab() -> dict[str, Any]: - """MATLAB's fits of a real two-source subproblem, and its inputs.""" - with h5py.File(SUBPROBLEM, "r") as f: - d = { - g: {k: v[()] for k, v in f[g].items()} - for g in ("in", "init", "it1", "it2", "debias", "ch2", "out") - } - y = d["in"]["y"].astype(np.float64) - finv = d["in"]["finv"].astype(np.float64) - sel = d["in"]["sel"].astype(bool) - b0 = sb.initial_baseline(y[0], PARAMS) - b1 = sb.fit_baseline(b0, y[0], d["it1"]["X_thr"], d["init"]["H"], finv, sel, PARAMS) - d.update( - z=_t(y[0]), - z2=_t(y[1]), - w=_t(1 / finv), - b0=_t(b0), - b1=_t(b1), - b2=_t(sb.initial_baseline(y[1], PARAMS)), - g=_t(conv_operator(sel, PARAMS.hfilter).toarray()), - k=torch.as_tensor(PARAMS.k), - k2=torch.as_tensor(PARAMS.k2), - ) - return d - - -def test_loss_is_matlabs(matlab: dict[str, Any]) -> None: - """MATLAB's reported losses are this loss at MATLAB's solutions.""" - m = matlab - lam = PARAMS.lam - p1 = sf.ActivityProblem(m["z"], _t(m["init"]["H"]), m["b0"], m["k"], m["w"], lam) - assert float(p1.value(_t(m["it1"]["S_out"]))[0]) == pytest.approx(m["it1"]["loss_S"], rel=1e-10) - valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] - ph = sf.FootprintProblem(m["z"], _t(m["it1"]["X_thr"]), m["b1"], m["g"], m["w"], valid) - # the baseline differs from MATLAB's by quadprog's tolerance - assert float(ph.value(_t(m["it1"]["Hs_out"]))[0]) == pytest.approx(m["it1"]["loss_H"], rel=1e-6) - p2 = sf.ActivityProblem(m["z"], _t(m["it1"]["H"]), m["b1"], m["k"], m["w"], lam) - assert float(p2.value(_t(m["it2"]["S_out"]))[0]) == pytest.approx(m["it2"]["loss_S"], rel=1e-6) - pc = sf.ActivityProblem(m["z2"], _t(m["out"]["H"]), m["b2"], m["k2"], m["w"], lam) - assert float(pc.value(_t(m["ch2"]["S_l1"]))[0]) == pytest.approx(m["ch2"]["loss"], rel=1e-10) - - -def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: - """Each fit, started from MATLAB's inputs, ends at a loss no higher than MATLAB's. - - MATLAB's fits stop at iteration caps or tolerances. - """ - m = matlab - lam = PARAMS.lam - s, info = sf.fit_activity( - m["z"], - _t(m["init"]["H"]), - m["b0"], - m["k"], - m["w"], - lam, - _t(m["init"]["S"]), - ) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it1"]["loss_S"] - - valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] - x_thr = _t(m["it1"]["X_thr"]) - hs, info = sf.fit_footprints(m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it1"]["loss_H"] * (1 - 1e-5) - - h1 = _t(m["it1"]["H"]) - s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], lam, _t(m["it1"]["S"])) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it2"]["loss_S"] * (1 + 1e-6) - - # debias: MATLAB's refit of its own events, variance held at the start - free = torch.as_tensor(m["debias"]["free"].astype(bool))[None] - start = _t(m["debias"]["S_in"]) - s0 = h1 @ sf.TimeKernel(m["k"]).conv(start) + m["b1"] + 1 - problem = sf.ActivityProblem(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, s0) - f_matlab = float(problem.value(_t(m["debias"]["S_out"]))[0]) - s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, start, s0=s0, free=free) - assert bool(info.converged[0]) - assert float(info.loss[0]) <= f_matlab * (1 + 1e-9) - # MATLAB's refit stops near this optimum: the activity agrees - kern = sf.TimeKernel(m["k"]) - x, x_matlab = kern.conv(s), kern.conv(_t(m["debias"]["S_out"])) - assert float((x - x_matlab).norm() / x_matlab.norm()) < 0.02 - - s2, info = sf.fit_activity( - m["z2"], - _t(m["out"]["H"]), - m["b2"], - m["k2"], - m["w"], - lam, - _t(m["ch2"]["LS"]), - ) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["ch2"]["loss"] +"""Tests of the iterative fits of the subproblem solver. + +The loss and its derivatives, the kernel, the bounded Newton solver, and the +fits against GIAnT-MATLAB's from the same inputs. +""" + +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +import torch +from numpy.typing import ArrayLike +from scipy import optimize + +from giant_python.extraction.raster import solver_baseline as sb +from giant_python.extraction.raster import solver_fits as sf +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + conv_operator, + temporal_kernel, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() +DT = torch.float64 + + +def _t(a: ArrayLike) -> torch.Tensor: + """Make a float64 tensor with a leading batch dimension of one. + + Returns + ------- + torch.Tensor + a as a float64 tensor of shape ``(1, *a.shape)``. + """ + return torch.as_tensor(np.ascontiguousarray(a), dtype=DT)[None] + + +def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: + """MATLAB convn(x, k, 'same') along the last axis. + + Returns + ------- + np.ndarray + The convolution of each row of x with k, with the shape of x. + """ + c = len(k) // 2 + flat = x.reshape(-1, x.shape[-1]) + out = np.stack([np.convolve(r, k)[c : c + x.shape[-1]] for r in flat]) + return out.reshape(x.shape) + + +def _small_problem( + seed: int = 0, + n_px: int = 14, + n_src: int = 2, + n_t: int = 60, + batch: int = 1, + tau: float = 3.0, +) -> list[torch.Tensor]: + """Random data from overlapping footprints and sparse events. + + Returns + ------- + list[torch.Tensor] + The data z, footprints h, baseline b, weights 1 / finv, events s and + temporal kernel k, in that order. + """ + rng = np.random.default_rng(seed) + k = temporal_kernel(tau) + h = rng.random((batch, n_px, n_src)) ** 3 + h /= h.sum(1, keepdims=True) + s = (rng.random((batch, n_src, n_t)) < 0.1) * rng.uniform(20, 80, (batch, n_src, n_t)) + b = 1.0 + rng.random((batch, n_px, 1)) + 0.2 * rng.random((1, 1, n_t)) + finv = 0.5 + rng.random((batch, n_px, n_t)) + mean = b + h @ _conv_same(s, k) + z = finv * rng.poisson(mean / finv) + tens = [torch.as_tensor(a, dtype=DT) for a in (z, h, b, 1 / finv, s)] + return tens + [torch.as_tensor(k, dtype=DT)] + + +@pytest.mark.parametrize("fixed", [False, True]) +def test_loss_derivatives(fixed: bool) -> None: + """First and second derivative of the loss in the model, by autograd.""" + rng = np.random.default_rng(0) + z = torch.as_tensor(rng.random((2, 3, 5)) * 4) + w = torch.as_tensor(0.5 + rng.random((2, 3, 5))) + s0 = torch.as_tensor(1 + rng.random((2, 3, 5))) if fixed else None + t = torch.as_tensor(rng.random((2, 3, 5)) * 3, dtype=DT).requires_grad_() + f, g, c = sf.variance_loss(z, t, w, s0) + var = s0 if fixed else t + 1 + expected = (w * (z - t) ** 2 / var).sum((-2, -1)) + assert torch.allclose(f, expected, rtol=1e-13) + (g_auto,) = torch.autograd.grad(expected.sum(), t, create_graph=True) + assert torch.allclose(g, g_auto, rtol=1e-12) + (c_auto,) = torch.autograd.grad(g_auto.sum(), t) + assert torch.allclose(c, c_auto, rtol=1e-12) + assert sf.variance_loss(z, t, w, s0, 0)[1:] == (None, None) + assert sf.variance_loss(z, t, w, s0, 1)[2] is None + + +@pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) +@pytest.mark.parametrize("n_t", [5, 40, 400]) +def test_time_kernel_matches_convolution(tau: float, n_t: int) -> None: + """The exponential kernels by shifted additions equal a 'same' convolution. + + This holds for trials shorter and longer than the kernel. + """ + rng = np.random.default_rng(1) + k = temporal_kernel(tau) + kern = sf.TimeKernel(torch.as_tensor(k)) + assert kern.decay == pytest.approx(np.exp(-1 / tau), rel=1e-9) + x = rng.standard_normal((2, 3, n_t)) + y = kern.conv(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-13) + ya = kern.conv_adj(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-13) + + +def test_time_kernel_general() -> None: + """Kernels that are not causal exponentials go through conv1d.""" + rng = np.random.default_rng(2) + x = rng.standard_normal((1, 2, 30)) + for k in ( + np.concatenate([np.zeros(4), [0.5, 0.3, 0.1, 0.07, 0.03]]), + np.array([0.2, 0.5, 0.3]), + np.array([0.0, 0.0, 0.0, 1.0, 0.5, 0.0, 0.25]), + ): + kern = sf.TimeKernel(torch.as_tensor(k)) + assert kern.decay is None + y = kern.conv(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-14) + ya = kern.conv_adj(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-14) + with pytest.raises(ValueError, match="odd"): + sf.TimeKernel(torch.ones(4)) + + +def _check_derivatives(problem: sf.ActivityProblem | sf.FootprintProblem, x: torch.Tensor) -> None: + """Gradient, Hessian products and diagonal against autograd.""" + x = x.clone().requires_grad_() + f = problem.value(x) + (g_auto,) = torch.autograd.grad(f.sum(), x, create_graph=True) + f2, g = problem.value_grad(x.detach()) + assert torch.allclose(f2, f.detach(), rtol=1e-13) + assert torch.allclose(g, g_auto.detach(), rtol=1e-9, atol=1e-10) + rng = np.random.default_rng(5) + v = torch.as_tensor(rng.standard_normal(x.shape)) + (hv_auto,) = torch.autograd.grad((g_auto * v).sum(), x, retain_graph=True) + hv = problem.hess_mult(v) + assert torch.allclose(hv, hv_auto, rtol=1e-9, atol=1e-9) + diag = torch.zeros_like(x) + flat = diag.view(-1) + for i in range(flat.numel()): + e = torch.zeros(flat.numel(), dtype=DT) + e[i] = 1 + flat[i] = problem.hess_mult(e.view(x.shape)).view(-1)[i] + assert torch.allclose(problem.hess_diag(), diag, rtol=1e-9, atol=1e-12) + + +@pytest.mark.parametrize("fixed", [False, True]) +def test_activity_problem_derivatives(fixed: bool) -> None: + """The activity fit's gradient and curvature, with either variance.""" + z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) + s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None + problem = sf.ActivityProblem(z, h, b, k, w, 0.9, s0) + _check_derivatives(problem, s * 0.5 + 1) + + +def test_footprint_problem_derivatives() -> None: + """The footprint fit's gradient and curvature.""" + z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) + rng = np.random.default_rng(6) + g = torch.as_tensor(rng.random((1, 6, 6)) * (rng.random((1, 6, 6)) < 0.6)) + x = sf.TimeKernel(k).conv(s) + support = torch.ones((1, 6, 2), dtype=torch.bool) + problem = sf.FootprintProblem(z, x, b, g, w, support) + _check_derivatives(problem, h.clone()) + + +def test_preconditioner_inverts_one_source() -> None: + """For one source the preconditioner is the inverse of the Hessian on the free events. + + Up to the kernel's truncation. + """ + z, h, b, w, s, k = _small_problem(n_px=8, n_src=1, n_t=200) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + problem.value_grad(s) + rng = np.random.default_rng(7) + free = torch.as_tensor(rng.random(s.shape) < 0.4) + free[..., 50:80] = True # a run of consecutive free events + fm = free.to(DT) + v = torch.as_tensor(rng.standard_normal(s.shape)) * fm + hv = fm * problem.hess_mult(v) + back = problem.preconditioner(free, problem.hess_diag())(hv) + assert float((back - v).norm() / v.norm()) < 0.02 + # the Hessian's diagonal alone is far from it + jacobi = fm / problem.hess_diag() * hv + assert float((jacobi - v).norm() / v.norm()) > 0.3 + + +def test_preconditioner_falls_back_to_diagonal() -> None: + """Kernels that are not exponential get the Hessian's diagonal.""" + z, h, b, w, s, _ = _small_problem(n_px=6, n_t=20) + k = torch.as_tensor([0.0, 0.0, 0.6, 0.1, 0.3], dtype=DT) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + problem.value_grad(s) + free = torch.ones_like(s, dtype=torch.bool) + r = torch.ones_like(s) + diag = problem.hess_diag() + assert torch.equal(problem.preconditioner(free, diag)(r), r / diag) + + +def test_activity_fit_reaches_scipy_optimum() -> None: + """The fit ends at the optimum that L-BFGS-B approaches. + + Many events are on their bound. + """ + z, h, b, w, s_true, k = _small_problem(seed=3, n_px=20, n_t=120) + start = torch.full_like(s_true, 5.0) + s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, history=True) + assert bool(info.converged[0]) and int(info.iterations[0]) < 30 + assert float(info.optimality[0]) < 1e-5 + assert float((s == 0).double().mean()) > 0.4 and float(s.min()) == 0 + losses = [float(f[0]) for f in info.history] + assert all(b2 <= a2 for a2, b2 in zip(losses, losses[1:])) + + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + + def fun(x: np.ndarray) -> tuple[float, np.ndarray]: + """Loss and gradient for scipy. + + Returns + ------- + loss : float + The activity loss at x. + grad : np.ndarray + The flattened gradient of the loss at x. + """ + f, g = problem.value_grad(torch.as_tensor(x).view(s.shape)) + return float(f[0]), g.numpy().ravel() + + ref = optimize.minimize( + fun, + start.numpy().ravel(), + jac=True, + method="L-BFGS-B", + bounds=[(0, None)] * s.numel(), + options=dict(maxiter=20000, maxfun=50000, ftol=1e-15, gtol=1e-9), + ) + assert float(info.loss[0]) <= ref.fun + 1e-9 * abs(ref.fun) + np.testing.assert_allclose(s.numpy().ravel(), ref.x, atol=2e-2) + # the sparse events are recovered + found = _conv_same(s.numpy(), k.numpy()) + truth = _conv_same(s_true.numpy(), k.numpy()) + assert np.corrcoef(found.ravel(), truth.ravel())[0, 1] > 0.7 + + +def test_fit_does_not_depend_on_its_start() -> None: + """A convex fit has one optimum: two starts end at the same events.""" + z, h, b, w, s_true, k = _small_problem(seed=4, n_px=16, n_t=80) + a, _ = sf.fit_activity(z, h, b, k, w, 0.9, torch.zeros_like(s_true)) + c, _ = sf.fit_activity(z, h, b, k, w, 0.9, s_true * 3 + 10) + assert torch.allclose(a, c, atol=1e-4) + + +def test_batched_fit_equals_separate_fits() -> None: + """Members of a batch get the fits they get alone. + + They are padded with weightless pixels and a source held at zero. + """ + z, h, b, w, s_true, k = _small_problem(seed=5, n_px=12, n_t=70, batch=2) + # member 1: 9 pixels and one source; the rest is padding + w[1, 9:] = 0 + z[1, 9:] = 0 + b[1, 9:] = 1 + h[1, :, 1] = 0 + h[1, 9:] = 0 + free = torch.ones_like(s_true, dtype=torch.bool) + free[1, 1] = False + start = torch.full_like(s_true, 2.0) + s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, free=free) + assert bool(info.converged.all()) + assert torch.all(s[1, 1] == 0) + one, i0 = sf.fit_activity(z[:1], h[:1], b[:1], k, w[:1], 0.9, start[:1], free=free[:1]) + two, i1 = sf.fit_activity(z[1:, :9], h[1:, :9, :1], b[1:, :9], k, w[1:, :9], 0.9, start[1:, :1]) + assert torch.allclose(s[0], one[0], atol=1e-5) + assert torch.allclose(s[1, :1], two[0], atol=1e-5) + assert float(info.loss[0]) == pytest.approx(float(i0.loss[0]), rel=1e-10) + assert float(info.loss[1]) == pytest.approx(float(i1.loss[0]), rel=1e-10) + + +def test_iteration_cap_and_free_entries() -> None: + """A capped fit reports that it did not converge and still lowers the loss. + + Entries that are not free stay at zero. + """ + z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) + start = torch.full_like(s_true, 5.0) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) + assert not bool(info.converged[0]) and int(info.iterations[0]) == 1 + assert float(info.loss[0]) < float(problem.value(start)[0]) + full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) + assert float(done.loss[0]) < float(info.loss[0]) + free = s_true > 0 + s2, info2 = sf.fit_activity(z, h, b, k, w, 0.0, start, free=free) + assert bool(info2.converged[0]) + assert torch.all(s2[~free] == 0) and float(s2[free].min()) >= 0 + + +def test_fixed_variance_fit_is_weighted_least_squares() -> None: + """With the variance held, the fit of the free events is weighted least squares. + + It is the bounded weighted least-squares solution. + """ + z, h, b, w, s_true, k = _small_problem(seed=7, n_px=10, n_src=1, n_t=40) + kern = sf.TimeKernel(k) + s0 = h @ kern.conv(s_true) + b + 1 + free = torch.zeros_like(s_true, dtype=torch.bool) + free[..., ::4] = True + s, info = sf.fit_activity(z, h, b, k, w, 0.0, s_true, s0=s0, free=free, ftol=1e-15) + assert bool(info.converged[0]) + idx = np.nonzero(free.numpy().ravel())[0] + cols = [] + for i in idx: + e = torch.zeros_like(s_true) + e.view(-1)[i] = 1 + cols.append((h @ kern.conv(e)).numpy().ravel()) + sw = np.sqrt((w / s0).numpy().ravel()) + design = np.stack(cols, 1) * sw[:, None] + target = (z - b).numpy().ravel() * sw + ref = optimize.lsq_linear(design, target, bounds=(0, np.inf)).x + np.testing.assert_allclose(s.numpy().ravel()[idx], ref, atol=1e-5) + + +def test_footprint_fit_stays_on_its_support() -> None: + """Footprints are fitted within their support, not below zero. + + They reach a lower loss than the start. + """ + z, h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) + x = sf.TimeKernel(k).conv(s) + g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 + valid = torch.zeros((1, 12, 2), dtype=torch.bool) + valid[0, :6, 0] = True + valid[0, 5:, 1] = True + start = valid.to(DT) / 6 + hs, info = sf.fit_footprints(z, x, b, g, w, start, valid) + assert bool(info.converged[0]) + assert torch.all(hs[~valid] == 0) and float(hs.min()) >= 0 + problem = sf.FootprintProblem(z, x, b, g, w, valid) + assert float(info.loss[0]) < float(problem.value(start)[0]) + assert torch.allclose(problem.footprints(hs), g @ hs) + + +@pytest.fixture(scope="module") +def matlab() -> dict[str, Any]: + """MATLAB's fits of a real two-source subproblem, and its inputs. + + Returns + ------- + dict[str, Any] + MATLAB's stored groups (in, init, it1, it2, debias, ch2, out) + plus the tensors z, z2, w, b0, b1, b2, g, k and k2. + """ + with h5py.File(SUBPROBLEM, "r") as f: + d = { + g: {k: v[()] for k, v in f[g].items()} + for g in ("in", "init", "it1", "it2", "debias", "ch2", "out") + } + y = d["in"]["y"].astype(np.float64) + finv = d["in"]["finv"].astype(np.float64) + sel = d["in"]["sel"].astype(bool) + b0 = sb.initial_baseline(y[0], PARAMS) + b1 = sb.fit_baseline(b0, y[0], d["it1"]["X_thr"], d["init"]["H"], finv, sel, PARAMS) + d.update( + z=_t(y[0]), + z2=_t(y[1]), + w=_t(1 / finv), + b0=_t(b0), + b1=_t(b1), + b2=_t(sb.initial_baseline(y[1], PARAMS)), + g=_t(conv_operator(sel, PARAMS.hfilter).toarray()), + k=torch.as_tensor(PARAMS.k), + k2=torch.as_tensor(PARAMS.k2), + ) + return d + + +def test_loss_is_matlabs(matlab: dict[str, Any]) -> None: + """MATLAB's reported losses are this loss at MATLAB's solutions.""" + m = matlab + lam = PARAMS.lam + p1 = sf.ActivityProblem(m["z"], _t(m["init"]["H"]), m["b0"], m["k"], m["w"], lam) + assert float(p1.value(_t(m["it1"]["S_out"]))[0]) == pytest.approx(m["it1"]["loss_S"], rel=1e-10) + valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] + ph = sf.FootprintProblem(m["z"], _t(m["it1"]["X_thr"]), m["b1"], m["g"], m["w"], valid) + # the baseline differs from MATLAB's by quadprog's tolerance + assert float(ph.value(_t(m["it1"]["Hs_out"]))[0]) == pytest.approx(m["it1"]["loss_H"], rel=1e-6) + p2 = sf.ActivityProblem(m["z"], _t(m["it1"]["H"]), m["b1"], m["k"], m["w"], lam) + assert float(p2.value(_t(m["it2"]["S_out"]))[0]) == pytest.approx(m["it2"]["loss_S"], rel=1e-6) + pc = sf.ActivityProblem(m["z2"], _t(m["out"]["H"]), m["b2"], m["k2"], m["w"], lam) + assert float(pc.value(_t(m["ch2"]["S_l1"]))[0]) == pytest.approx(m["ch2"]["loss"], rel=1e-10) + + +def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: + """Each fit, started from MATLAB's inputs, ends at a loss no higher than MATLAB's. + + MATLAB's fits stop at iteration caps or tolerances. + """ + m = matlab + lam = PARAMS.lam + s, info = sf.fit_activity( + m["z"], + _t(m["init"]["H"]), + m["b0"], + m["k"], + m["w"], + lam, + _t(m["init"]["S"]), + ) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it1"]["loss_S"] + + valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] + x_thr = _t(m["it1"]["X_thr"]) + hs, info = sf.fit_footprints(m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it1"]["loss_H"] * (1 - 1e-5) + + h1 = _t(m["it1"]["H"]) + s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], lam, _t(m["it1"]["S"])) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it2"]["loss_S"] * (1 + 1e-6) + + # debias: MATLAB's refit of its own events, variance held at the start + free = torch.as_tensor(m["debias"]["free"].astype(bool))[None] + start = _t(m["debias"]["S_in"]) + s0 = h1 @ sf.TimeKernel(m["k"]).conv(start) + m["b1"] + 1 + problem = sf.ActivityProblem(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, s0) + f_matlab = float(problem.value(_t(m["debias"]["S_out"]))[0]) + s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, start, s0=s0, free=free) + assert bool(info.converged[0]) + assert float(info.loss[0]) <= f_matlab * (1 + 1e-9) + # MATLAB's refit stops near this optimum: the activity agrees + kern = sf.TimeKernel(m["k"]) + x, x_matlab = kern.conv(s), kern.conv(_t(m["debias"]["S_out"])) + assert float((x - x_matlab).norm() / x_matlab.norm()) < 0.02 + + s2, info = sf.fit_activity( + m["z2"], + _t(m["out"]["H"]), + m["b2"], + m["k2"], + m["w"], + lam, + _t(m["ch2"]["LS"]), + ) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["ch2"]["loss"] diff --git a/tests/raster/test_raster_solver_setup.py b/tests/raster/test_raster_solver_setup.py index 25f99316..4f2c5b2f 100644 --- a/tests/raster/test_raster_solver_setup.py +++ b/tests/raster/test_raster_solver_setup.py @@ -1,389 +1,395 @@ -"""Tests of the subproblem solver's parameters, filters and inputs.""" - -import warnings -from pathlib import Path - -import h5py -import numpy as np -import numpy.typing as npt -import pytest -from scipy import signal - -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, - conv_operator, - initial_footprints, - load_matlab_subproblem, - params_from_matlab, - sel_coords, - temporal_kernel, -) - -DATA = Path(__file__).parent / "data" -HELPERS = DATA / "matlab_solver_helpers.h5" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" - -# the two parameter sets of the MATLAB references (make_helper_refs.m) -PARAMS_A = SolverParams( - sigma_px=1.6, - sel_radius=4, - tau_full=3.7, - tau2_s=0.05, - analyze_hz=150, - baseline_window_s=2, - denoise_window_s=0.1, -) -PARAMS_B = SolverParams() - - -def _close(a: npt.ArrayLike, b: npt.ArrayLike, tol: float = 1e-13) -> None: - """Largest difference relative to the largest reference value.""" - a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) - assert a.shape == b.shape - assert np.abs(a - b).max() <= tol * np.abs(b).max() - - -@pytest.mark.parametrize("name, params", [("a", PARAMS_A), ("b", PARAMS_B)]) -def test_filters_match_matlab(name: str, params: SolverParams) -> None: - """Footprint filter, surround filters and kernels of setParamsExtractTrial.""" - with h5py.File(HELPERS, "r") as f: - g = f["params"][name] - _close(params.hfilter, g["Hfilter"][()]) - # MATLAB stores the three filters along the third dimension - _close(params.bfilter, g["Bfilter"][()].transpose(2, 0, 1)) - _close(params.k, g["k"][()].ravel()) - _close(params.k2, g["k2"][()].ravel()) - if "baselineWindow_samps" in g: - assert params.baseline_window == g["baselineWindow_samps"][()] - assert params.denoise_window == g["denoiseWindow_samps"][()] - - -def test_kernel_and_windows() -> None: - """The kernel is causal, sums to 1 and peaks at its centre. - - The windows follow MATLAB's rounding. - """ - k = temporal_kernel(4.8) - n = int(np.ceil(6 * 4.8)) - assert k.size == 2 * n + 1 - assert np.all(k[:n] == 0) and np.argmax(k) == n - assert k.sum() == pytest.approx(1.0, abs=1e-15) - assert k[n + 1] / k[n] == pytest.approx(np.exp(-1 / 4.8)) - p = SolverParams(analyze_hz=434.7826087, tau_s=0.024) - assert p.tau_frames == pytest.approx(10.4348, abs=1e-4) - assert p.denoise_window == 87 # ceil(86.96) - assert p.baseline_window == pytest.approx(1739.13, abs=1e-2) # not rounded - assert p.lp_factor == 20 - assert SolverParams(tau_full=7.0).tau_frames == 7.0 - - -def test_params_reject_bad_values() -> None: - """Values the solver cannot run with are refused.""" - with pytest.raises(ValueError, match="debias_variance"): - SolverParams(debias_variance="other") - with pytest.raises(ValueError, match="nmf_iter"): - SolverParams(nmf_iter=0) - with pytest.raises(ValueError, match="sigma_px"): - SolverParams(sigma_px=0) - # divisors: a zero would give a NaN kernel or an endless spline - with pytest.raises(ValueError, match="tau_full"): - SolverParams(tau_full=0) - with pytest.raises(ValueError, match="baseline_knot_factor"): - SolverParams(baseline_knot_factor=0) - with pytest.raises(ValueError, match="tau_s"): - SolverParams(tau_s=float("nan")) - with pytest.raises(ValueError, match="photon_scale"): - SolverParams(photon_scale=float("inf")) - with pytest.raises(ValueError, match="lam"): - SolverParams(lam=-0.1) - assert SolverParams(photon_scale=None, lam=0, phi=0).tau_full is None - # the baseline needs at least two denoise windows per baseline window - with pytest.raises(ValueError, match="baseline_window_s"): - SolverParams(baseline_window_s=0.1, denoise_window_s=0.1) - with pytest.raises(ValueError, match="baseline_window_s"): - SolverParams(baseline_window_s=0.2, denoise_window_s=0.196) - assert SolverParams(baseline_window_s=0.3, denoise_window_s=0.2).lp_factor == 2 - - -def test_initial_footprints_match_matlab() -> None: - """Starting footprints, also for sources at the map's edge and next to an unselected pixel.""" - with h5py.File(HELPERS, "r") as f: - g = f["foot"] - sel = g["selPix"][()].astype(bool) - rc = np.stack([g["R"][()].ravel(), g["C"][()].ravel()], 1) - 1 - hs, h, valid = initial_footprints(sel, rc, float(g["sigma"][()])) - assert np.array_equal(hs, g["Hs"][()]) - _close(h, g["H"][()]) - assert np.array_equal(valid, g["Hvalid"][()].astype(bool)) - - -def test_sel_coords_are_column_major() -> None: - """Pixels are listed as MATLAB's find(sel) lists them.""" - sel = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool) - rows, cols = sel_coords(sel) - assert rows.tolist() == [0, 1, 1, 0] - assert cols.tolist() == [0, 0, 1, 2] - - -def test_conv_operator_is_same_convolution() -> None: - """The operator equals a 'same' convolution of the map, zero outside the selected pixels. - - It is read at the selected pixels. - """ - rng = np.random.default_rng(0) - sel = rng.random((9, 11)) < 0.7 - rows, cols = sel_coords(sel) - values = rng.standard_normal(rows.size) - for shape in ((5, 5), (3, 7), (4, 5)): - filt = rng.standard_normal(shape) - filt[0, 0] = 0 # a zero tap is left out of the sparse matrix - image = np.zeros(sel.shape) - image[rows, cols] = values - # MATLAB's convn 'same': the centre is floor(size / 2) - full = signal.convolve2d(image, filt, mode="full") - r0, c0 = shape[0] // 2, shape[1] // 2 - same = full[r0 : r0 + sel.shape[0], c0 : c0 + sel.shape[1]] - got = conv_operator(sel, filt) @ values - np.testing.assert_allclose(got, same[rows, cols], atol=1e-13) - - -def test_subproblem_checks_its_arrays() -> None: - """A subproblem whose arrays do not fit together is refused.""" - sel = np.ones((3, 3), dtype=bool) - y = np.zeros((1, 9, 20), np.float32) - finv = np.ones((9, 20), np.float32) - sub = Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1]]) - assert (sub.n_pixels, sub.n_frames, sub.n_sources) == (9, 20, 1) - assert sub.coords[0].tolist() == [0, 1, 2] * 3 - with pytest.raises(ValueError, match="pixels"): - Subproblem(y=y[:, :8], finv=finv, sel=sel, sources_rc=[[1, 1]]) - with pytest.raises(ValueError, match="outside"): - Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 3]]) - with pytest.raises(ValueError, match="channels"): - Subproblem(y=y[0], finv=finv, sel=sel, sources_rc=[[1, 1]]) - with pytest.raises(ValueError, match="share a position"): - Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1], [1, 1]]) - - -def _write_matlab_params(g: h5py.Group, params: SolverParams, **extra: np.ndarray) -> None: - """Write a MATLAB params struct as a v7.3 file holds it.""" - fields = dict( - analyzeHz=params.analyze_hz, - tau_s=params.tau_s, - tau_full=params.tau_frames, - tau2_s=params.tau2_s, - sigma_px=params.sigma_px, - selRadius=params.sel_radius, - baselineWindow_Glu_s=params.baseline_window_s, - denoiseWindow_s=params.denoise_window_s, - minBaseline=params.min_baseline, - nmfIter=params.nmf_iter, - phi=params.phi, - ) - fields["lambda"] = params.lam - for name, v in fields.items(): - g.create_dataset(name, data=np.array([[float(v)]])) - g.create_dataset("k", data=params.k[None, :]) - g.create_dataset("Hfilter", data=params.hfilter.T) - # MATLAB's (rows, cols, 3) array, dimensions reversed in the file - g.create_dataset("Bfilter", data=params.bfilter.transpose(0, 2, 1)) - for name, v in extra.items(): - g.create_dataset(name, data=v) - - -def _write_matlab_subproblem( - folder: Path, - y: np.ndarray, - finv: np.ndarray, - sel: np.ndarray, - rc: np.ndarray, - params: SolverParams, - row0: int, - col0: int, -) -> Path: - """sub_001.mat and trial.mat as extractTrial saves them (v7.3).""" - full = np.zeros((sel.shape[0] + row0 + 2, sel.shape[1] + col0 + 1), bool) - full[0, 0] = full[1, 0] = True # two pixels of another subproblem - full[row0 : row0 + sel.shape[0], col0 : col0 + sel.shape[1]] = sel - with h5py.File(folder / "trial.mat", "w") as f: - f.create_dataset("selPix", data=full.T.astype(np.uint8)) - with h5py.File(folder / "sub_001.mat", "w") as f: - # MATLAB's pixels x frames x channels, dimensions reversed - f.create_dataset("Y_p", data=y.transpose(0, 2, 1)) - f.create_dataset("F_inv_p", data=finv.T) - f.create_dataset("selPix_p", data=sel.T.astype(np.uint8)) - g = f.create_group("sources_p") - g.create_dataset("R", data=rc[None, :, 0] + 1.0) - g.create_dataset("C", data=rc[None, :, 1] + 1.0) - f.create_dataset("rowSupport", data=np.array([[row0 + 1.0, 0]]).T) - f.create_dataset("colSupport", data=np.array([[col0 + 1.0, 0]]).T) - f.create_dataset("srcIdx", data=np.array([[4.0, 9.0]])) - debias = np.array([[ord(c)] for c in "Model"], dtype=np.uint16) - empty = f.create_group("params").create_dataset("photonScale", data=np.zeros(2, np.uint64)) - empty.attrs["MATLAB_empty"] = 1 - _write_matlab_params(f["params"], params, debiasVariance=debias) - return folder / "sub_001.mat" - - -def test_load_matlab_subproblem(tmp_path: Path) -> None: - """A saved subproblem is read in the port's convention. - - Channels x pixels x frames, zero-based sources, pixel indices in the - trial's list, and its parameters. - """ - rng = np.random.default_rng(1) - sel = np.ones((4, 5), dtype=bool) - sel[0, 0] = sel[3, 4] = False - n_px = int(sel.sum()) - y = rng.random((2, n_px, 30)) - finv = 0.5 + rng.random((n_px, 30)) - rc = np.array([[1, 1], [2, 3]]) - params = SolverParams(sigma_px=1.6, sel_radius=4, tau_s=0.03, lam=0.7) - path = _write_matlab_subproblem(tmp_path, y, finv, sel, rc, params, 3, 2) - with warnings.catch_warnings(): - warnings.simplefilter("error") - sub, p = load_matlab_subproblem(path) - assert sub.y.dtype == np.float64 - assert np.array_equal(sub.y, y) and np.array_equal(sub.finv, finv) - assert np.array_equal(sub.sel, sel) - assert np.array_equal(sub.sources_rc, rc) - assert (sub.row0, sub.col0) == (3, 2) - assert sub.sources.tolist() == [3, 8] - # the trial's map has two selected pixels before this crop's - assert np.array_equal(sub.pixels, 2 + np.arange(n_px)) - assert p.photon_scale is None and p.debias_variance == "model" - # not a MATLAB parameter: the default, unless the struct names it - assert p.footprint_variance == "fixed" - with h5py.File(path, "r+") as f: - f["params"].create_dataset( - "footprintVariance", - data=np.array([[ord(c)] for c in "Model"], dtype=np.uint16), - ) - assert load_matlab_subproblem(path)[1].footprint_variance == "model" - assert (p.sigma_px, p.sel_radius, p.lam) == (1.6, 4, 0.7) - assert p.tau_frames == pytest.approx(0.03 * 200) - assert load_matlab_subproblem(path, np.float32)[0].y.dtype == np.float32 - - -def test_trial_file_of_another_trial_is_refused(tmp_path: Path) -> None: - """A trial.mat that does not select every pixel of the subproblem is refused. - - It cannot give the subproblem's pixel indices. - """ - sel = np.ones((3, 3), dtype=bool) - path = _write_matlab_subproblem( - tmp_path, - np.zeros((1, 9, 5)), - np.ones((9, 5)), - sel, - np.array([[1, 1]]), - SolverParams(), - 2, - 1, - ) - with h5py.File(tmp_path / "trial.mat", "r+") as f: - full = f["selPix"][()] - full[2, 3] = 0 # one of the crop's pixels, in MATLAB's file order - f["selPix"][...] = full - with pytest.raises(ValueError, match="not from the same trial"): - load_matlab_subproblem(path) - with h5py.File(tmp_path / "trial.mat", "w") as f: - f.create_dataset("selPix", data=np.ones((2, 2), np.uint8)) - with pytest.raises(ValueError, match="not from the same trial"): - load_matlab_subproblem(path) - - -def test_single_channel_subproblem_without_trial_file(tmp_path: Path) -> None: - """One channel is saved as a 2-D array. - - Without trial.mat the pixel indices are unknown. - """ - sel = np.ones((2, 3), dtype=bool) - y = np.arange(6 * 7, dtype=np.float64).reshape(1, 6, 7) - path = _write_matlab_subproblem( - tmp_path, - y, - np.ones((6, 7)), - sel, - np.array([[0, 1]]), - SolverParams(), - 0, - 0, - ) - (tmp_path / "trial.mat").unlink() - with h5py.File(path, "r+") as f: - del f["Y_p"] - f.create_dataset("Y_p", data=y[0].T) - sub, _ = load_matlab_subproblem(path) - assert sub.y.shape == (1, 6, 7) and np.array_equal(sub.y, y) - assert sub.pixels is None - - -def test_params_warn_when_saved_filters_differ(tmp_path: Path) -> None: - """A saved kernel that the scalar parameters do not give is reported.""" - with h5py.File(tmp_path / "p.mat", "w") as f: - g = f.create_group("params") - _write_matlab_params(g, SolverParams()) - g["k"][...] = g["k"][()] * 1.01 - with pytest.warns(UserWarning, match="params.k differs"): - p = params_from_matlab(g) - # a struct without validKernel is MATLAB's 3 x 3 (not the default 5) - assert p == SolverParams(tau_full=4.8, photon_scale=None, valid_kernel=3) - - -def test_subproblem_fixture_starts_as_matlab() -> None: - """The fixture's starting footprints are MATLAB's.""" - with h5py.File(SUBPROBLEM, "r") as f: - sel = f["in/sel"][()].astype(bool) - hs, h, valid = initial_footprints(sel, f["in/sources_rc"][()], PARAMS_B.sigma_px) - assert np.array_equal(hs, f["init/Hs"][()]) - _close(h, f["init/H"][()]) - assert np.array_equal(valid, f["init/Hvalid"][()].astype(bool)) - - -def test_valid_kernel_widens_the_support_only() -> None: - """A larger validKernel widens where Hs may go, nothing else. - - A source at the crop's edge gets the part of the square inside it. - """ - sel = np.ones((15, 15), dtype=bool) - rc = np.array([[7, 7], [0, 1]]) - hs3, h3, v3 = initial_footprints(sel, rc, 1.33) - hs5, h5, v5 = initial_footprints(sel, rc, 1.33, valid_kernel=5) - assert np.array_equal(hs3, hs5) - assert np.array_equal(h3, h5) - assert v3.sum(0).tolist() == [9, 6] - assert v5.sum(0).tolist() == [25, 12] - assert (v3 <= v5).all() - rows, cols = sel_coords(sel) - inside = (np.abs(rows - 7) <= 2) & (np.abs(cols - 7) <= 2) - assert np.array_equal(v5[:, 0], inside) - - -@pytest.mark.parametrize("bad", [0, 2, 4, -3, 3.0, True]) -def test_valid_kernel_must_be_odd_and_positive(bad: float) -> None: - """An even, non-positive or non-integer side is rejected.""" - with pytest.raises(ValueError, match="valid_kernel"): - SolverParams(valid_kernel=bad) - - -def test_valid_kernel_from_matlab() -> None: - """params_from_matlab reads validKernel's side; 3 without one.""" - with h5py.File("vk.h5", "w", driver="core", backing_store=False) as f: - assert params_from_matlab(f.create_group("none")).valid_kernel == 3 - f.create_group("five")["validKernel"] = np.ones((5, 5), np.uint8) - assert params_from_matlab(f["five"]).valid_kernel == 5 - f.create_group("odd")["validKernel"] = np.ones((3, 2), np.uint8) - with pytest.raises(ValueError, match="validKernel"): - params_from_matlab(f["odd"]) - # entries other than 1 are rejected, not read as a full support - for name, value in (("twos", 2.0), ("minus", -1.0), ("nan", np.nan)): - f.create_group(name)["validKernel"] = np.full((5, 5), value) - with pytest.raises(ValueError, match="square of ones"): - params_from_matlab(f[name]) - f.create_group("plus")["validKernel"] = np.array( - [[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8 - ) - with pytest.raises(ValueError, match="5 ones"): - params_from_matlab(f["plus"]) +"""Tests of the subproblem solver's parameters, filters and inputs.""" + +import warnings +from pathlib import Path + +import h5py +import numpy as np +import numpy.typing as npt +import pytest +from scipy import signal + +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, + conv_operator, + initial_footprints, + load_matlab_subproblem, + params_from_matlab, + sel_coords, + temporal_kernel, +) + +DATA = Path(__file__).parent / "data" +HELPERS = DATA / "matlab_solver_helpers.h5" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" + +# the two parameter sets of the MATLAB references (make_helper_refs.m) +PARAMS_A = SolverParams( + sigma_px=1.6, + sel_radius=4, + tau_full=3.7, + tau2_s=0.05, + analyze_hz=150, + baseline_window_s=2, + denoise_window_s=0.1, +) +PARAMS_B = SolverParams() + + +def _close(a: npt.ArrayLike, b: npt.ArrayLike, tol: float = 1e-13) -> None: + """Largest difference relative to the largest reference value.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + assert a.shape == b.shape + assert np.abs(a - b).max() <= tol * np.abs(b).max() + + +@pytest.mark.parametrize("name, params", [("a", PARAMS_A), ("b", PARAMS_B)]) +def test_filters_match_matlab(name: str, params: SolverParams) -> None: + """Footprint filter, surround filters and kernels of setParamsExtractTrial.""" + with h5py.File(HELPERS, "r") as f: + g = f["params"][name] + _close(params.hfilter, g["Hfilter"][()]) + # MATLAB stores the three filters along the third dimension + _close(params.bfilter, g["Bfilter"][()].transpose(2, 0, 1)) + _close(params.k, g["k"][()].ravel()) + _close(params.k2, g["k2"][()].ravel()) + if "baselineWindow_samps" in g: + assert params.baseline_window == g["baselineWindow_samps"][()] + assert params.denoise_window == g["denoiseWindow_samps"][()] + + +def test_kernel_and_windows() -> None: + """The kernel is causal, sums to 1 and peaks at its centre. + + The windows follow MATLAB's rounding. + """ + k = temporal_kernel(4.8) + n = int(np.ceil(6 * 4.8)) + assert k.size == 2 * n + 1 + assert np.all(k[:n] == 0) and np.argmax(k) == n + assert k.sum() == pytest.approx(1.0, abs=1e-15) + assert k[n + 1] / k[n] == pytest.approx(np.exp(-1 / 4.8)) + p = SolverParams(analyze_hz=434.7826087, tau_s=0.024) + assert p.tau_frames == pytest.approx(10.4348, abs=1e-4) + assert p.denoise_window == 87 # ceil(86.96) + assert p.baseline_window == pytest.approx(1739.13, abs=1e-2) # not rounded + assert p.lp_factor == 20 + assert SolverParams(tau_full=7.0).tau_frames == 7.0 + + +def test_params_reject_bad_values() -> None: + """Values the solver cannot run with are refused.""" + with pytest.raises(ValueError, match="debias_variance"): + SolverParams(debias_variance="other") + with pytest.raises(ValueError, match="nmf_iter"): + SolverParams(nmf_iter=0) + with pytest.raises(ValueError, match="sigma_px"): + SolverParams(sigma_px=0) + # divisors: a zero would give a NaN kernel or an endless spline + with pytest.raises(ValueError, match="tau_full"): + SolverParams(tau_full=0) + with pytest.raises(ValueError, match="baseline_knot_factor"): + SolverParams(baseline_knot_factor=0) + with pytest.raises(ValueError, match="tau_s"): + SolverParams(tau_s=float("nan")) + with pytest.raises(ValueError, match="photon_scale"): + SolverParams(photon_scale=float("inf")) + with pytest.raises(ValueError, match="lam"): + SolverParams(lam=-0.1) + assert SolverParams(photon_scale=None, lam=0, phi=0).tau_full is None + # the baseline needs at least two denoise windows per baseline window + with pytest.raises(ValueError, match="baseline_window_s"): + SolverParams(baseline_window_s=0.1, denoise_window_s=0.1) + with pytest.raises(ValueError, match="baseline_window_s"): + SolverParams(baseline_window_s=0.2, denoise_window_s=0.196) + assert SolverParams(baseline_window_s=0.3, denoise_window_s=0.2).lp_factor == 2 + + +def test_initial_footprints_match_matlab() -> None: + """Starting footprints, also for sources at the map's edge and next to an unselected pixel.""" + with h5py.File(HELPERS, "r") as f: + g = f["foot"] + sel = g["selPix"][()].astype(bool) + rc = np.stack([g["R"][()].ravel(), g["C"][()].ravel()], 1) - 1 + hs, h, valid = initial_footprints(sel, rc, float(g["sigma"][()])) + assert np.array_equal(hs, g["Hs"][()]) + _close(h, g["H"][()]) + assert np.array_equal(valid, g["Hvalid"][()].astype(bool)) + + +def test_sel_coords_are_column_major() -> None: + """Pixels are listed as MATLAB's find(sel) lists them.""" + sel = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool) + rows, cols = sel_coords(sel) + assert rows.tolist() == [0, 1, 1, 0] + assert cols.tolist() == [0, 0, 1, 2] + + +def test_conv_operator_is_same_convolution() -> None: + """The operator equals a 'same' convolution of the map, zero outside the selected pixels. + + It is read at the selected pixels. + """ + rng = np.random.default_rng(0) + sel = rng.random((9, 11)) < 0.7 + rows, cols = sel_coords(sel) + values = rng.standard_normal(rows.size) + for shape in ((5, 5), (3, 7), (4, 5)): + filt = rng.standard_normal(shape) + filt[0, 0] = 0 # a zero tap is left out of the sparse matrix + image = np.zeros(sel.shape) + image[rows, cols] = values + # MATLAB's convn 'same': the centre is floor(size / 2) + full = signal.convolve2d(image, filt, mode="full") + r0, c0 = shape[0] // 2, shape[1] // 2 + same = full[r0 : r0 + sel.shape[0], c0 : c0 + sel.shape[1]] + got = conv_operator(sel, filt) @ values + np.testing.assert_allclose(got, same[rows, cols], atol=1e-13) + + +def test_subproblem_checks_its_arrays() -> None: + """A subproblem whose arrays do not fit together is refused.""" + sel = np.ones((3, 3), dtype=bool) + y = np.zeros((1, 9, 20), np.float32) + finv = np.ones((9, 20), np.float32) + sub = Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1]]) + assert (sub.n_pixels, sub.n_frames, sub.n_sources) == (9, 20, 1) + assert sub.coords[0].tolist() == [0, 1, 2] * 3 + with pytest.raises(ValueError, match="pixels"): + Subproblem(y=y[:, :8], finv=finv, sel=sel, sources_rc=[[1, 1]]) + with pytest.raises(ValueError, match="outside"): + Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 3]]) + with pytest.raises(ValueError, match="channels"): + Subproblem(y=y[0], finv=finv, sel=sel, sources_rc=[[1, 1]]) + with pytest.raises(ValueError, match="share a position"): + Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1], [1, 1]]) + + +def _write_matlab_params(g: h5py.Group, params: SolverParams, **extra: np.ndarray) -> None: + """Write a MATLAB params struct as a v7.3 file holds it.""" + fields = dict( + analyzeHz=params.analyze_hz, + tau_s=params.tau_s, + tau_full=params.tau_frames, + tau2_s=params.tau2_s, + sigma_px=params.sigma_px, + selRadius=params.sel_radius, + baselineWindow_Glu_s=params.baseline_window_s, + denoiseWindow_s=params.denoise_window_s, + minBaseline=params.min_baseline, + nmfIter=params.nmf_iter, + phi=params.phi, + ) + fields["lambda"] = params.lam + for name, v in fields.items(): + g.create_dataset(name, data=np.array([[float(v)]])) + g.create_dataset("k", data=params.k[None, :]) + g.create_dataset("Hfilter", data=params.hfilter.T) + # MATLAB's (rows, cols, 3) array, dimensions reversed in the file + g.create_dataset("Bfilter", data=params.bfilter.transpose(0, 2, 1)) + for name, v in extra.items(): + g.create_dataset(name, data=v) + + +def _write_matlab_subproblem( + folder: Path, + y: np.ndarray, + finv: np.ndarray, + sel: np.ndarray, + rc: np.ndarray, + params: SolverParams, + row0: int, + col0: int, +) -> Path: + """sub_001.mat and trial.mat as extractTrial saves them (v7.3). + + Returns + ------- + Path + The sub_001.mat file written in folder. + """ + full = np.zeros((sel.shape[0] + row0 + 2, sel.shape[1] + col0 + 1), bool) + full[0, 0] = full[1, 0] = True # two pixels of another subproblem + full[row0 : row0 + sel.shape[0], col0 : col0 + sel.shape[1]] = sel + with h5py.File(folder / "trial.mat", "w") as f: + f.create_dataset("selPix", data=full.T.astype(np.uint8)) + with h5py.File(folder / "sub_001.mat", "w") as f: + # MATLAB's pixels x frames x channels, dimensions reversed + f.create_dataset("Y_p", data=y.transpose(0, 2, 1)) + f.create_dataset("F_inv_p", data=finv.T) + f.create_dataset("selPix_p", data=sel.T.astype(np.uint8)) + g = f.create_group("sources_p") + g.create_dataset("R", data=rc[None, :, 0] + 1.0) + g.create_dataset("C", data=rc[None, :, 1] + 1.0) + f.create_dataset("rowSupport", data=np.array([[row0 + 1.0, 0]]).T) + f.create_dataset("colSupport", data=np.array([[col0 + 1.0, 0]]).T) + f.create_dataset("srcIdx", data=np.array([[4.0, 9.0]])) + debias = np.array([[ord(c)] for c in "Model"], dtype=np.uint16) + empty = f.create_group("params").create_dataset("photonScale", data=np.zeros(2, np.uint64)) + empty.attrs["MATLAB_empty"] = 1 + _write_matlab_params(f["params"], params, debiasVariance=debias) + return folder / "sub_001.mat" + + +def test_load_matlab_subproblem(tmp_path: Path) -> None: + """A saved subproblem is read in the port's convention. + + Channels x pixels x frames, zero-based sources, pixel indices in the + trial's list, and its parameters. + """ + rng = np.random.default_rng(1) + sel = np.ones((4, 5), dtype=bool) + sel[0, 0] = sel[3, 4] = False + n_px = int(sel.sum()) + y = rng.random((2, n_px, 30)) + finv = 0.5 + rng.random((n_px, 30)) + rc = np.array([[1, 1], [2, 3]]) + params = SolverParams(sigma_px=1.6, sel_radius=4, tau_s=0.03, lam=0.7) + path = _write_matlab_subproblem(tmp_path, y, finv, sel, rc, params, 3, 2) + with warnings.catch_warnings(): + warnings.simplefilter("error") + sub, p = load_matlab_subproblem(path) + assert sub.y.dtype == np.float64 + assert np.array_equal(sub.y, y) and np.array_equal(sub.finv, finv) + assert np.array_equal(sub.sel, sel) + assert np.array_equal(sub.sources_rc, rc) + assert (sub.row0, sub.col0) == (3, 2) + assert sub.sources.tolist() == [3, 8] + # the trial's map has two selected pixels before this crop's + assert np.array_equal(sub.pixels, 2 + np.arange(n_px)) + assert p.photon_scale is None and p.debias_variance == "model" + # not a MATLAB parameter: the default, unless the struct names it + assert p.footprint_variance == "fixed" + with h5py.File(path, "r+") as f: + f["params"].create_dataset( + "footprintVariance", + data=np.array([[ord(c)] for c in "Model"], dtype=np.uint16), + ) + assert load_matlab_subproblem(path)[1].footprint_variance == "model" + assert (p.sigma_px, p.sel_radius, p.lam) == (1.6, 4, 0.7) + assert p.tau_frames == pytest.approx(0.03 * 200) + assert load_matlab_subproblem(path, np.float32)[0].y.dtype == np.float32 + + +def test_trial_file_of_another_trial_is_refused(tmp_path: Path) -> None: + """A trial.mat that does not select every pixel of the subproblem is refused. + + It cannot give the subproblem's pixel indices. + """ + sel = np.ones((3, 3), dtype=bool) + path = _write_matlab_subproblem( + tmp_path, + np.zeros((1, 9, 5)), + np.ones((9, 5)), + sel, + np.array([[1, 1]]), + SolverParams(), + 2, + 1, + ) + with h5py.File(tmp_path / "trial.mat", "r+") as f: + full = f["selPix"][()] + full[2, 3] = 0 # one of the crop's pixels, in MATLAB's file order + f["selPix"][...] = full + with pytest.raises(ValueError, match="not from the same trial"): + load_matlab_subproblem(path) + with h5py.File(tmp_path / "trial.mat", "w") as f: + f.create_dataset("selPix", data=np.ones((2, 2), np.uint8)) + with pytest.raises(ValueError, match="not from the same trial"): + load_matlab_subproblem(path) + + +def test_single_channel_subproblem_without_trial_file(tmp_path: Path) -> None: + """One channel is saved as a 2-D array. + + Without trial.mat the pixel indices are unknown. + """ + sel = np.ones((2, 3), dtype=bool) + y = np.arange(6 * 7, dtype=np.float64).reshape(1, 6, 7) + path = _write_matlab_subproblem( + tmp_path, + y, + np.ones((6, 7)), + sel, + np.array([[0, 1]]), + SolverParams(), + 0, + 0, + ) + (tmp_path / "trial.mat").unlink() + with h5py.File(path, "r+") as f: + del f["Y_p"] + f.create_dataset("Y_p", data=y[0].T) + sub, _ = load_matlab_subproblem(path) + assert sub.y.shape == (1, 6, 7) and np.array_equal(sub.y, y) + assert sub.pixels is None + + +def test_params_warn_when_saved_filters_differ(tmp_path: Path) -> None: + """A saved kernel that the scalar parameters do not give is reported.""" + with h5py.File(tmp_path / "p.mat", "w") as f: + g = f.create_group("params") + _write_matlab_params(g, SolverParams()) + g["k"][...] = g["k"][()] * 1.01 + with pytest.warns(UserWarning, match="params.k differs"): + p = params_from_matlab(g) + # a struct without validKernel is MATLAB's 3 x 3 (not the default 5) + assert p == SolverParams(tau_full=4.8, photon_scale=None, valid_kernel=3) + + +def test_subproblem_fixture_starts_as_matlab() -> None: + """The fixture's starting footprints are MATLAB's.""" + with h5py.File(SUBPROBLEM, "r") as f: + sel = f["in/sel"][()].astype(bool) + hs, h, valid = initial_footprints(sel, f["in/sources_rc"][()], PARAMS_B.sigma_px) + assert np.array_equal(hs, f["init/Hs"][()]) + _close(h, f["init/H"][()]) + assert np.array_equal(valid, f["init/Hvalid"][()].astype(bool)) + + +def test_valid_kernel_widens_the_support_only() -> None: + """A larger validKernel widens where Hs may go, nothing else. + + A source at the crop's edge gets the part of the square inside it. + """ + sel = np.ones((15, 15), dtype=bool) + rc = np.array([[7, 7], [0, 1]]) + hs3, h3, v3 = initial_footprints(sel, rc, 1.33) + hs5, h5, v5 = initial_footprints(sel, rc, 1.33, valid_kernel=5) + assert np.array_equal(hs3, hs5) + assert np.array_equal(h3, h5) + assert v3.sum(0).tolist() == [9, 6] + assert v5.sum(0).tolist() == [25, 12] + assert (v3 <= v5).all() + rows, cols = sel_coords(sel) + inside = (np.abs(rows - 7) <= 2) & (np.abs(cols - 7) <= 2) + assert np.array_equal(v5[:, 0], inside) + + +@pytest.mark.parametrize("bad", [0, 2, 4, -3, 3.0, True]) +def test_valid_kernel_must_be_odd_and_positive(bad: float) -> None: + """An even, non-positive or non-integer side is rejected.""" + with pytest.raises(ValueError, match="valid_kernel"): + SolverParams(valid_kernel=bad) + + +def test_valid_kernel_from_matlab() -> None: + """params_from_matlab reads validKernel's side; 3 without one.""" + with h5py.File("vk.h5", "w", driver="core", backing_store=False) as f: + assert params_from_matlab(f.create_group("none")).valid_kernel == 3 + f.create_group("five")["validKernel"] = np.ones((5, 5), np.uint8) + assert params_from_matlab(f["five"]).valid_kernel == 5 + f.create_group("odd")["validKernel"] = np.ones((3, 2), np.uint8) + with pytest.raises(ValueError, match="validKernel"): + params_from_matlab(f["odd"]) + # entries other than 1 are rejected, not read as a full support + for name, value in (("twos", 2.0), ("minus", -1.0), ("nan", np.nan)): + f.create_group(name)["validKernel"] = np.full((5, 5), value) + with pytest.raises(ValueError, match="square of ones"): + params_from_matlab(f[name]) + f.create_group("plus")["validKernel"] = np.array( + [[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8 + ) + with pytest.raises(ValueError, match="5 ones"): + params_from_matlab(f["plus"]) diff --git a/tests/raster/test_raster_spots.py b/tests/raster/test_raster_spots.py index b60f8f1b..853d1706 100644 --- a/tests/raster/test_raster_spots.py +++ b/tests/raster/test_raster_spots.py @@ -1,394 +1,405 @@ -"""The spot annotation (GIAnT-Python#51 follow-up). - -Spots of linked sources, their tests and labels, and the annotation collect -writes. -""" - -import json -import warnings -from collections.abc import Sequence -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster import spots as sp -from giant_python.extraction.raster.alignment import TrialWarp -from giant_python.models.params import SiloParams -from giant_python.pipeline import silo -from giant_python.pipeline.silo_session import SiloSession -from giant_python.pipeline.silo_spots import SummaryWarp, read_spots - -from .test_raster_silo_stages import ( # noqa: F401 (fixture) - EX, - PARAMS, - fake, - make_session, - seeds_file, -) - - -def test_link_groups() -> None: - """Single linkage within link_px; sources without a position alone.""" - rc = np.array([[0, 0], [0, 2], [0, 4.2], [10, 10], [np.nan, np.nan], [30, 30]]) - lab = sp.link_groups(rc, 2.5) - assert lab[0] == lab[1] == lab[2] # a chain links - assert len({lab[0], lab[3], lab[4], lab[5]}) == 4 - assert lab.max() == 3 - assert sp.link_groups(np.zeros((0, 2)), 2.5).size == 0 - - -def test_event_train_corr() -> None: - """Shared events correlate; independent ones do not; one train: NaN.""" - rng = np.random.default_rng(0) - a = (rng.random(5000) < 0.01).astype(float) - b = (rng.random(5000) < 0.01).astype(float) - assert sp.event_train_corr(np.stack([a, a * 0.5])) == pytest.approx(1.0) - assert abs(sp.event_train_corr(np.stack([a, b]))) < 0.1 - assert np.isnan(sp.event_train_corr(a[None])) - - -def _movie( - pos: Sequence[tuple[float, float]], - n: int = 600, - rate: float = 0.03, - amp: float = 40.0, - noise: float = 2.0, - seed: int = 1, -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Simulate a 15 x 15 window of Gaussian events and white noise. - - Gaussian events (sigma 1.4) at positions ``pos`` (one drawn per event), - white noise; returns x (frames, pixels), rows, cols and the event frames. - """ - rng = np.random.default_rng(seed) - rr, cc = np.meshgrid(np.arange(15.0), np.arange(15.0), indexing="ij") - rr, cc = rr.ravel(), cc.ravel() - x = rng.normal(0, noise, (n, rr.size)) - frames = np.flatnonzero(rng.random(n) < rate) - frames = frames[np.r_[True, np.diff(frames) > 4]] - frames = frames[(frames > 2) & (frames < n - 3)] - for f in frames: - p = pos[rng.integers(len(pos))] - g = np.exp(-((rr - p[0]) ** 2 + (cc - p[1]) ** 2) / (2 * 1.4**2)) - x[f] += amp * g - x[f + 1] += amp * 0.6 * g - return x, rr, cc, frames - - -def test_localize_events_finds_and_places_events() -> None: - """Strong events are found at their frames and placed within a fraction of a pixel. - - Weak noise yields none. - """ - x, rr, cc, frames = _movie([(7.3, 6.6)]) - ev = sp.localize_events(x, rr, cc, (7.0, 7.0), 4.0, sp.SpotSettings()) - assert ev["frame"].size >= 0.9 * frames.size - assert np.median(np.abs(ev["r"] - 7.3)) < 0.15 - assert np.median(np.abs(ev["c"] - 6.6)) < 0.15 - assert (ev["se_r"] > 0).all() and (ev["snr"] >= 6).all() - quiet, _, _, _ = _movie([(7.3, 6.6)], amp=0.0) - none = sp.localize_events(quiet, rr, cc, (7, 7), 4.0, sp.SpotSettings()) - assert none["frame"].size <= 2 - - -def test_mixture_fit_counts_clusters() -> None: - """Two clusters 3 px apart give K = 2; one cluster K = 1.""" - rng = np.random.default_rng(2) - n = 80 - S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) - one = rng.normal([5, 5], 0.45, (n, 2)) - best, fits = sp.mixture_fit(one, S, (5, 5)) - assert best.K == 1 and fits[0].K == 1 - two = np.r_[ - rng.normal([5, 3.5], 0.45, (n // 2, 2)), - rng.normal([5, 6.5], 0.45, (n // 2, 2)), - ] - best, _ = sp.mixture_fit(two, S, (5, 5)) - assert best.K == 2 - assert np.sort(best.means[:, 1]) == pytest.approx([3.5, 6.5], abs=0.4) - - -def test_separation_power() -> None: - """Points far apart are always resolved; one point never is.""" - n = 60 - S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) - far = sp.separation_power([[5, 3], [5, 7]], S, 0.0, (5, 5), n_sim=6) - near = sp.separation_power([[5, 5], [5, 5.05]], S, 0.0, (5, 5), n_sim=6) - assert far == 1.0 and near <= 0.34 - assert np.isnan(sp.separation_power([[5, 5]], S, 0.0, (5, 5))) - - -def test_event_test_and_labels() -> None: - """The event test on canvas positions, and the labels' precedence.""" - st = sp.SpotSettings(n_sim=6) - rng = np.random.default_rng(3) - n = 60 - src = np.array([[10.0, 9.0], [10.0, 11.0]]) - ev = dict( - r=np.r_[rng.normal(10, 0.3, n), 50.0], # one event far away: left out - c=np.r_[rng.normal(9, 0.3, n // 2), rng.normal(11, 0.3, n // 2), 50.0], - se_r=np.full(n + 1, 0.15), - se_c=np.full(n + 1, 0.15), - ) - t = sp.event_test(ev, src, st) - assert t["n_events"] == n and t["K"] == 2 - assert sp.spot_label(2, 0.05, t, st) == "close_pair" - few = sp.event_test({k: v[:5] for k, v in ev.items()}, src, st) - assert few == {"n_events": 5} - assert sp.spot_label(2, 0.05, few, st) == "undecided" - assert sp.spot_label(2, 0.5, few, st) == "merge" - assert sp.spot_label(1, 0.9, t, st) == "single" - compact = dict(K=1, cloud_major=0.3, power=0.1) - assert sp.spot_label(2, 0.0, compact, st) == "merge" - wide = dict(K=1, cloud_major=0.8, power=0.9) - assert sp.spot_label(2, 0.0, wide, st) == "continuum" - assert sp.spot_label(2, 0.0, dict(wide, power=0.5), st) == "undecided" - - -def test_summary_warp_matches_the_plan() -> None: - """The maps a summary records give the plan's warp. - - Rigid, affine and patchwise (its displacement field sampled on the - canvas). - """ - a = np.array([[[1.0, 0, 0.5], [0, 1, -1.0]], [[1.0, 0.02, 0], [0, 0.98, 2]]]) - w = TrialWarp(a) - sw = SummaryWarp(a) - r, c = np.array([3.2, 10.0]), np.array([4.5, 7.25]) - for t in range(2): - np.testing.assert_allclose(sw.coords(t, r, c), w.coords(t, r, c)) - rr, cc = np.meshgrid(np.arange(20.0), np.arange(30.0), indexing="ij") - field = np.stack([0.1 * rr, -0.05 * cc])[None] # (1, 2, rows, cols) - sw = SummaryWarp(np.zeros((1, 2, 3)), field) - got = sw.coords(0, np.array([4.0, 9.5]), np.array([3.0, 12.25])) - np.testing.assert_allclose(got[0], [4.4, 9.5 * 1.1]) - np.testing.assert_allclose(got[1], [3.0 * 0.95, 12.25 * 0.95]) - - -def test_collect_writes_the_annotation(tmp_path: Path, fake: None) -> None: # noqa: F811 - """Every run's summary gets each kept source's spot and each spot's label. - - With empty movies the event test is skipped (a warning) and the spots - keep the correlation test; silo-spots writes it again. - """ - table = make_session(tmp_path / "s") - params = SiloParams(min_kinetic_score=0.0, spot_link_px=4.0) - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - silo.run_silo(table, params, EX, seeds_file=seeds_file(tmp_path)) - session = SiloSession.open(table) - summary = session.out_dir / "experiment_summary.h5" - for d in (1, 2): - a = read_spots(summary, d) - with h5py.File(summary, "r") as f: - n_kept = f[f"Path{d}/sources/spatial/coords"].shape[1] - assert a["spot_id"].size == n_kept - assert a["n_sources"].sum() == n_kept - assert set(a["label"]) <= set(sp.LABELS) - assert a["settings"]["link_px"] == 4.0 - multi = a["n_sources"] >= 2 - assert multi.any() # sources (6, 7) and (8, 9) are linked at 4 px - assert (a["label"][~multi] == "single").all() - assert (a["label"][multi] != "single").all() - assert (a["n_events"][multi] == 0).all() # no movie to test - assert any("event test skipped" in str(x.message) for x in w) - # again from the summary alone - from giant_python.pipeline.silo_spots import annotate_spots - - with h5py.File(summary, "a") as f: - del f["Path1/sources/spots"] - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - report = annotate_spots(session, params) - assert read_spots(summary, 1) is not None and "seconds" in report - with h5py.File(summary, "r") as f: - labels = json.loads(f["Path1/sources/spots"].attrs["labels"]) - assert tuple(labels) == sp.LABELS - - -def test_spot_params() -> None: - """Defaults and checks of the spot settings.""" - p = SiloParams() - assert (p.spot_link_px, p.spot_split_corr, p.spot_min_power) == ( - 2.5, - 0.3, - 0.8, - ) - assert p.spot_event_test and p.spot_compact_px == 0.45 - for bad in ( - dict(spot_link_px=0), - dict(spot_split_corr=1.5), - dict(spot_min_events=2.5), - dict(spot_event_test="yes"), - dict(spot_min_power=-0.1), - dict(spot_min_events=4), # a cloud's fit takes 5 - ): - with pytest.raises(ValueError): - SiloParams(**bad) - assert PARAMS.spot_event_test - - -def test_event_tests_in_a_pool_agree() -> None: - """Event tests in spawned workers give the serial results (one seed per spot).""" - from giant_python.pipeline.silo_spots import _event_tests, _pool - - rng = np.random.default_rng(5) - st = sp.SpotSettings(n_sim=4) - jobs = [] - for g in range(4): - n = 40 - ev = dict( - r=rng.normal(10, 0.5, n), - c=rng.normal(10, 0.5, n), - se_r=np.full(n, 0.2), - se_c=np.full(n, 0.2), - ) - jobs.append((ev, np.array([[10.0, 9.0], [10.0, 11.0]]), st, g)) - serial = _event_tests(jobs, None) - pool = _pool(2) - try: - parallel = _event_tests(jobs, pool) - finally: - pool.shutdown() - assert parallel == serial - assert _pool(1) is None - - -def test_few_events_are_not_fitted() -> None: - """Fewer than MIN_FIT_EVENTS events give no cloud, whatever min_events says.""" - st = sp.SpotSettings(min_events=1, n_sim=4) - one = dict(r=[10.0], c=[10.0], se_r=[0.2], se_c=[0.2]) - src = np.array([[10.0, 9.5], [10.0, 10.5]]) - assert sp.event_test(one, src, st) == {"n_events": 1} - - -def test_tiff_and_hdf5_pixels_agree(tmp_path: Path) -> None: - """A movie's pixels read from a TIFF (page by page) and from HDF5 are the same. - - They are NaN outside the image. - """ - import tifffile - - from giant_python.pipeline.silo_spots import _read_pixels - - rng = np.random.default_rng(6) - pages = rng.random((8, 5, 7)).astype(np.float32) # (pages, cols, rows) - tif = tmp_path / "m.tif" - tifffile.imwrite(tif, pages) - h5 = tmp_path / "m.h5" - with h5py.File(h5, "w") as f: - f["movie"] = pages - rows = np.array([0, 3, 6, 7, -1]) - cols = np.array([0, 4, 2, 1, 1]) - a = _read_pixels(tif, 2, 1, rows, cols) - b = _read_pixels(h5, 2, 1, rows, cols) - np.testing.assert_array_equal(a, b) - assert a.shape == (4, 5) and np.isnan(a[:, 3:]).all() - np.testing.assert_array_equal(a[:, 1], pages[1::2, 4, 3]) - assert _read_pixels(tif, 2, 1, rows, cols, n_frames=2).shape == (2, 5) - - -def test_missing_movies_warn() -> None: - """Trials to test without a movie are named in a warning.""" - from giant_python.pipeline.silo_spots import _spot_events - - class _Session: - """Two kept trials, no movies.""" - - n_trials = 2 - keep = np.ones((1, 2), bool) - - def movie(self, d: int, t: int) -> None: - """No movie.""" - return None - - warp = SummaryWarp(np.tile(np.eye(2, 3), (2, 1, 1))) - spots = [dict(g=0, center=np.array([5.0, 5.0]), extent=1.0)] - st = sp.SpotSettings() - with pytest.warns(UserWarning, match=r"trials \[1, 2\] have no"): - ev = _spot_events(_Session(), PARAMS, st, 0, warp, spots, None, False) - assert ev[0]["r"].size == 0 - - -def test_event_corr_uses_the_activity_channel(tmp_path: Path) -> None: - """The summary keeps physical channels. - - The correlation is the activity channel's. - """ - from giant_python.pipeline.silo_spots import _annotate_path - - rng = np.random.default_rng(7) - n = 4000 - shared = (rng.random(n) < 0.02).astype(float) - ev = np.zeros((n, 2, 2)) # (frames, channels, kept sources) - ev[:, 0, 0] = (rng.random(n) < 0.02).astype(float) - ev[:, 0, 1] = (rng.random(n) < 0.02).astype(float) - ev[:, 1, 0] = shared - ev[:, 1, 1] = shared - summary = tmp_path / "experiment_summary.h5" - with h5py.File(summary, "w") as f: - f["Path1/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) - f["Path1/sources/temporal/events"] = ev - st = sp.SpotSettings() - for ch, label in ((2, "merge"), (1, "undecided")): - params = SiloParams(activity_channel=ch, spot_event_test=False) - _annotate_path(None, params, st, summary, 0, None, None, False, None) - assert list(read_spots(summary, 1)["label"]) == [label] - - -def test_truncated_files_are_refused(tmp_path: Path) -> None: - """A baseline (or movie) without every frame asked for is an error. - - Frames are not left unfilled. - """ - import tifffile - - from giant_python.pipeline.silo_spots import _read_pixels - - pages = np.ones((6, 5, 7), np.float32) - h5 = tmp_path / "b.h5" - with h5py.File(h5, "w") as f: - f["baseline"] = pages - tif = tmp_path / "b.tif" - tifffile.imwrite(tif, pages) - for path in (h5, tif): - assert _read_pixels(path, 1, 0, [1], [1], n_frames=6).shape == (6, 1) - with pytest.raises(ValueError, match="too few"): - _read_pixels(path, 1, 0, [1], [1], n_frames=7) - - -def test_reannotation_uses_the_recorded_run(tmp_path: Path) -> None: - """silo-spots reads the run's own activity channel. - - It annotates the paths the summary has (here only Path2). - """ - from giant_python.pipeline.silo_spots import annotate_spots - - rng = np.random.default_rng(8) - n = 4000 - shared = (rng.random(n) < 0.02).astype(float) - ev = np.zeros((n, 2, 2)) - ev[:, 0] = (rng.random((n, 2)) < 0.02).astype(float) - ev[:, 1, 0] = shared - ev[:, 1, 1] = shared - summary = tmp_path / "experiment_summary.h5" - with h5py.File(summary, "w") as f: - f["Path2/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) - f["Path2/sources/temporal/events"] = ev - f["params/activityChannel"] = np.array([[2.0]]) - f["params/baselineMode"] = np.array([b"fit"]) - f["params/localizationBaseline"] = np.array([b"median"]) - - class _Session: - """The summary's folder; no movies.""" - - out_dir = tmp_path - n_paths = 2 - - params = SiloParams(spot_event_test=False) # activity channel 1 - report = annotate_spots(_Session(), params) - assert read_spots(summary, 1) is None - assert list(read_spots(summary, 2)["label"]) == ["merge"] - assert report["Path2"]["merge"] == 1 +"""The spot annotation (GIAnT-Python#51 follow-up). + +Spots of linked sources, their tests and labels, and the annotation collect +writes. +""" + +import json +import warnings +from collections.abc import Sequence +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster import spots as sp +from giant_python.extraction.raster.alignment import TrialWarp +from giant_python.models.params import SiloParams +from giant_python.pipeline import silo +from giant_python.pipeline.silo_session import SiloSession +from giant_python.pipeline.silo_spots import SummaryWarp, read_spots + +from .test_raster_silo_stages import ( # noqa: F401 (fixture) + EX, + PARAMS, + fake, + make_session, + seeds_file, +) + + +def test_link_groups() -> None: + """Single linkage within link_px; sources without a position alone.""" + rc = np.array([[0, 0], [0, 2], [0, 4.2], [10, 10], [np.nan, np.nan], [30, 30]]) + lab = sp.link_groups(rc, 2.5) + assert lab[0] == lab[1] == lab[2] # a chain links + assert len({lab[0], lab[3], lab[4], lab[5]}) == 4 + assert lab.max() == 3 + assert sp.link_groups(np.zeros((0, 2)), 2.5).size == 0 + + +def test_event_train_corr() -> None: + """Shared events correlate; independent ones do not; one train: NaN.""" + rng = np.random.default_rng(0) + a = (rng.random(5000) < 0.01).astype(float) + b = (rng.random(5000) < 0.01).astype(float) + assert sp.event_train_corr(np.stack([a, a * 0.5])) == pytest.approx(1.0) + assert abs(sp.event_train_corr(np.stack([a, b]))) < 0.1 + assert np.isnan(sp.event_train_corr(a[None])) + + +def _movie( + pos: Sequence[tuple[float, float]], + n: int = 600, + rate: float = 0.03, + amp: float = 40.0, + noise: float = 2.0, + seed: int = 1, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Simulate a 15 x 15 window of Gaussian events and white noise. + + Gaussian events (sigma 1.4) at positions pos (one drawn per event), + white noise; returns x (frames, pixels), rows, cols and the event frames. + + Returns + ------- + x : np.ndarray + Simulated samples of shape (frames, pixels). + rr : np.ndarray + Row coordinate of each pixel. + cc : np.ndarray + Column coordinate of each pixel. + frames : np.ndarray + Frame indices of the events. + """ + rng = np.random.default_rng(seed) + rr, cc = np.meshgrid(np.arange(15.0), np.arange(15.0), indexing="ij") + rr, cc = rr.ravel(), cc.ravel() + x = rng.normal(0, noise, (n, rr.size)) + frames = np.flatnonzero(rng.random(n) < rate) + frames = frames[np.r_[True, np.diff(frames) > 4]] + frames = frames[(frames > 2) & (frames < n - 3)] + for f in frames: + p = pos[rng.integers(len(pos))] + g = np.exp(-((rr - p[0]) ** 2 + (cc - p[1]) ** 2) / (2 * 1.4**2)) + x[f] += amp * g + x[f + 1] += amp * 0.6 * g + return x, rr, cc, frames + + +def test_localize_events_finds_and_places_events() -> None: + """Strong events are found at their frames and placed within a fraction of a pixel. + + Weak noise yields none. + """ + x, rr, cc, frames = _movie([(7.3, 6.6)]) + ev = sp.localize_events(x, rr, cc, (7.0, 7.0), 4.0, sp.SpotSettings()) + assert ev["frame"].size >= 0.9 * frames.size + assert np.median(np.abs(ev["r"] - 7.3)) < 0.15 + assert np.median(np.abs(ev["c"] - 6.6)) < 0.15 + assert (ev["se_r"] > 0).all() and (ev["snr"] >= 6).all() + quiet, _, _, _ = _movie([(7.3, 6.6)], amp=0.0) + none = sp.localize_events(quiet, rr, cc, (7, 7), 4.0, sp.SpotSettings()) + assert none["frame"].size <= 2 + + +def test_mixture_fit_counts_clusters() -> None: + """Two clusters 3 px apart give K = 2; one cluster K = 1.""" + rng = np.random.default_rng(2) + n = 80 + S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) + one = rng.normal([5, 5], 0.45, (n, 2)) + best, fits = sp.mixture_fit(one, S, (5, 5)) + assert best.K == 1 and fits[0].K == 1 + two = np.r_[ + rng.normal([5, 3.5], 0.45, (n // 2, 2)), + rng.normal([5, 6.5], 0.45, (n // 2, 2)), + ] + best, _ = sp.mixture_fit(two, S, (5, 5)) + assert best.K == 2 + assert np.sort(best.means[:, 1]) == pytest.approx([3.5, 6.5], abs=0.4) + + +def test_separation_power() -> None: + """Points far apart are always resolved; one point never is.""" + n = 60 + S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) + far = sp.separation_power([[5, 3], [5, 7]], S, 0.0, (5, 5), n_sim=6) + near = sp.separation_power([[5, 5], [5, 5.05]], S, 0.0, (5, 5), n_sim=6) + assert far == 1.0 and near <= 0.34 + assert np.isnan(sp.separation_power([[5, 5]], S, 0.0, (5, 5))) + + +def test_event_test_and_labels() -> None: + """The event test on canvas positions, and the labels' precedence.""" + st = sp.SpotSettings(n_sim=6) + rng = np.random.default_rng(3) + n = 60 + src = np.array([[10.0, 9.0], [10.0, 11.0]]) + ev = dict( + r=np.r_[rng.normal(10, 0.3, n), 50.0], # one event far away: left out + c=np.r_[rng.normal(9, 0.3, n // 2), rng.normal(11, 0.3, n // 2), 50.0], + se_r=np.full(n + 1, 0.15), + se_c=np.full(n + 1, 0.15), + ) + t = sp.event_test(ev, src, st) + assert t["n_events"] == n and t["K"] == 2 + assert sp.spot_label(2, 0.05, t, st) == "close_pair" + few = sp.event_test({k: v[:5] for k, v in ev.items()}, src, st) + assert few == {"n_events": 5} + assert sp.spot_label(2, 0.05, few, st) == "undecided" + assert sp.spot_label(2, 0.5, few, st) == "merge" + assert sp.spot_label(1, 0.9, t, st) == "single" + compact = dict(K=1, cloud_major=0.3, power=0.1) + assert sp.spot_label(2, 0.0, compact, st) == "merge" + wide = dict(K=1, cloud_major=0.8, power=0.9) + assert sp.spot_label(2, 0.0, wide, st) == "continuum" + assert sp.spot_label(2, 0.0, dict(wide, power=0.5), st) == "undecided" + + +def test_summary_warp_matches_the_plan() -> None: + """The maps a summary records give the plan's warp. + + Rigid, affine and patchwise (its displacement field sampled on the + canvas). + """ + a = np.array([[[1.0, 0, 0.5], [0, 1, -1.0]], [[1.0, 0.02, 0], [0, 0.98, 2]]]) + w = TrialWarp(a) + sw = SummaryWarp(a) + r, c = np.array([3.2, 10.0]), np.array([4.5, 7.25]) + for t in range(2): + np.testing.assert_allclose(sw.coords(t, r, c), w.coords(t, r, c)) + rr, cc = np.meshgrid(np.arange(20.0), np.arange(30.0), indexing="ij") + field = np.stack([0.1 * rr, -0.05 * cc])[None] # (1, 2, rows, cols) + sw = SummaryWarp(np.zeros((1, 2, 3)), field) + got = sw.coords(0, np.array([4.0, 9.5]), np.array([3.0, 12.25])) + np.testing.assert_allclose(got[0], [4.4, 9.5 * 1.1]) + np.testing.assert_allclose(got[1], [3.0 * 0.95, 12.25 * 0.95]) + + +def test_collect_writes_the_annotation(tmp_path: Path, fake: None) -> None: # noqa: F811 + """Every run's summary gets each kept source's spot and each spot's label. + + With empty movies the event test is skipped (a warning) and the spots + keep the correlation test; silo-spots writes it again. + """ + table = make_session(tmp_path / "s") + params = SiloParams(min_kinetic_score=0.0, spot_link_px=4.0) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + silo.run_silo(table, params, EX, seeds_file=seeds_file(tmp_path)) + session = SiloSession.open(table) + summary = session.out_dir / "experiment_summary.h5" + for d in (1, 2): + a = read_spots(summary, d) + with h5py.File(summary, "r") as f: + n_kept = f[f"Path{d}/sources/spatial/coords"].shape[1] + assert a["spot_id"].size == n_kept + assert a["n_sources"].sum() == n_kept + assert set(a["label"]) <= set(sp.LABELS) + assert a["settings"]["link_px"] == 4.0 + multi = a["n_sources"] >= 2 + assert multi.any() # sources (6, 7) and (8, 9) are linked at 4 px + assert (a["label"][~multi] == "single").all() + assert (a["label"][multi] != "single").all() + assert (a["n_events"][multi] == 0).all() # no movie to test + assert any("event test skipped" in str(x.message) for x in w) + # again from the summary alone + from giant_python.pipeline.silo_spots import annotate_spots + + with h5py.File(summary, "a") as f: + del f["Path1/sources/spots"] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + report = annotate_spots(session, params) + assert read_spots(summary, 1) is not None and "seconds" in report + with h5py.File(summary, "r") as f: + labels = json.loads(f["Path1/sources/spots"].attrs["labels"]) + assert tuple(labels) == sp.LABELS + + +def test_spot_params() -> None: + """Defaults and checks of the spot settings.""" + p = SiloParams() + assert (p.spot_link_px, p.spot_split_corr, p.spot_min_power) == ( + 2.5, + 0.3, + 0.8, + ) + assert p.spot_event_test and p.spot_compact_px == 0.45 + for bad in ( + dict(spot_link_px=0), + dict(spot_split_corr=1.5), + dict(spot_min_events=2.5), + dict(spot_event_test="yes"), + dict(spot_min_power=-0.1), + dict(spot_min_events=4), # a cloud's fit takes 5 + ): + with pytest.raises(ValueError): + SiloParams(**bad) + assert PARAMS.spot_event_test + + +def test_event_tests_in_a_pool_agree() -> None: + """Event tests in spawned workers give the serial results (one seed per spot).""" + from giant_python.pipeline.silo_spots import _event_tests, _pool + + rng = np.random.default_rng(5) + st = sp.SpotSettings(n_sim=4) + jobs = [] + for g in range(4): + n = 40 + ev = dict( + r=rng.normal(10, 0.5, n), + c=rng.normal(10, 0.5, n), + se_r=np.full(n, 0.2), + se_c=np.full(n, 0.2), + ) + jobs.append((ev, np.array([[10.0, 9.0], [10.0, 11.0]]), st, g)) + serial = _event_tests(jobs, None) + pool = _pool(2) + try: + parallel = _event_tests(jobs, pool) + finally: + pool.shutdown() + assert parallel == serial + assert _pool(1) is None + + +def test_few_events_are_not_fitted() -> None: + """Fewer than MIN_FIT_EVENTS events give no cloud, whatever min_events says.""" + st = sp.SpotSettings(min_events=1, n_sim=4) + one = dict(r=[10.0], c=[10.0], se_r=[0.2], se_c=[0.2]) + src = np.array([[10.0, 9.5], [10.0, 10.5]]) + assert sp.event_test(one, src, st) == {"n_events": 1} + + +def test_tiff_and_hdf5_pixels_agree(tmp_path: Path) -> None: + """A movie's pixels read from a TIFF (page by page) and from HDF5 are the same. + + They are NaN outside the image. + """ + import tifffile + + from giant_python.pipeline.silo_spots import _read_pixels + + rng = np.random.default_rng(6) + pages = rng.random((8, 5, 7)).astype(np.float32) # (pages, cols, rows) + tif = tmp_path / "m.tif" + tifffile.imwrite(tif, pages) + h5 = tmp_path / "m.h5" + with h5py.File(h5, "w") as f: + f["movie"] = pages + rows = np.array([0, 3, 6, 7, -1]) + cols = np.array([0, 4, 2, 1, 1]) + a = _read_pixels(tif, 2, 1, rows, cols) + b = _read_pixels(h5, 2, 1, rows, cols) + np.testing.assert_array_equal(a, b) + assert a.shape == (4, 5) and np.isnan(a[:, 3:]).all() + np.testing.assert_array_equal(a[:, 1], pages[1::2, 4, 3]) + assert _read_pixels(tif, 2, 1, rows, cols, n_frames=2).shape == (2, 5) + + +def test_missing_movies_warn() -> None: + """Trials to test without a movie are named in a warning.""" + from giant_python.pipeline.silo_spots import _spot_events + + class _Session: + """Two kept trials, no movies.""" + + n_trials = 2 + keep = np.ones((1, 2), bool) + + def movie(self, d: int, t: int) -> None: + """No movie.""" + return None + + warp = SummaryWarp(np.tile(np.eye(2, 3), (2, 1, 1))) + spots = [dict(g=0, center=np.array([5.0, 5.0]), extent=1.0)] + st = sp.SpotSettings() + with pytest.warns(UserWarning, match=r"trials \[1, 2\] have no"): + ev = _spot_events(_Session(), PARAMS, st, 0, warp, spots, None, False) + assert ev[0]["r"].size == 0 + + +def test_event_corr_uses_the_activity_channel(tmp_path: Path) -> None: + """The summary keeps physical channels. + + The correlation is the activity channel's. + """ + from giant_python.pipeline.silo_spots import _annotate_path + + rng = np.random.default_rng(7) + n = 4000 + shared = (rng.random(n) < 0.02).astype(float) + ev = np.zeros((n, 2, 2)) # (frames, channels, kept sources) + ev[:, 0, 0] = (rng.random(n) < 0.02).astype(float) + ev[:, 0, 1] = (rng.random(n) < 0.02).astype(float) + ev[:, 1, 0] = shared + ev[:, 1, 1] = shared + summary = tmp_path / "experiment_summary.h5" + with h5py.File(summary, "w") as f: + f["Path1/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) + f["Path1/sources/temporal/events"] = ev + st = sp.SpotSettings() + for ch, label in ((2, "merge"), (1, "undecided")): + params = SiloParams(activity_channel=ch, spot_event_test=False) + _annotate_path(None, params, st, summary, 0, None, None, False, None) + assert list(read_spots(summary, 1)["label"]) == [label] + + +def test_truncated_files_are_refused(tmp_path: Path) -> None: + """A baseline (or movie) without every frame asked for is an error. + + Frames are not left unfilled. + """ + import tifffile + + from giant_python.pipeline.silo_spots import _read_pixels + + pages = np.ones((6, 5, 7), np.float32) + h5 = tmp_path / "b.h5" + with h5py.File(h5, "w") as f: + f["baseline"] = pages + tif = tmp_path / "b.tif" + tifffile.imwrite(tif, pages) + for path in (h5, tif): + assert _read_pixels(path, 1, 0, [1], [1], n_frames=6).shape == (6, 1) + with pytest.raises(ValueError, match="too few"): + _read_pixels(path, 1, 0, [1], [1], n_frames=7) + + +def test_reannotation_uses_the_recorded_run(tmp_path: Path) -> None: + """silo-spots reads the run's own activity channel. + + It annotates the paths the summary has (here only Path2). + """ + from giant_python.pipeline.silo_spots import annotate_spots + + rng = np.random.default_rng(8) + n = 4000 + shared = (rng.random(n) < 0.02).astype(float) + ev = np.zeros((n, 2, 2)) + ev[:, 0] = (rng.random((n, 2)) < 0.02).astype(float) + ev[:, 1, 0] = shared + ev[:, 1, 1] = shared + summary = tmp_path / "experiment_summary.h5" + with h5py.File(summary, "w") as f: + f["Path2/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) + f["Path2/sources/temporal/events"] = ev + f["params/activityChannel"] = np.array([[2.0]]) + f["params/baselineMode"] = np.array([b"fit"]) + f["params/localizationBaseline"] = np.array([b"median"]) + + class _Session: + """The summary's folder; no movies.""" + + out_dir = tmp_path + n_paths = 2 + + params = SiloParams(spot_event_test=False) # activity channel 1 + report = annotate_spots(_Session(), params) + assert read_spots(summary, 1) is None + assert list(read_spots(summary, 2)["label"]) == ["merge"] + assert report["Path2"]["merge"] == 1 diff --git a/tests/raster/test_raster_stage_files.py b/tests/raster/test_raster_stage_files.py index 73e7b2b4..16948369 100644 --- a/tests/raster/test_raster_stage_files.py +++ b/tests/raster/test_raster_stage_files.py @@ -1,112 +1,112 @@ -"""Tests of the files SILo's stages hand to each other. - -These are per-trial localization files and seeds files. -""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.stage_files import ( - add_peaks, - localization_attrs, - read_localization, - read_seeds, - write_localization, - write_seeds, -) - - -def test_localization_round_trip(tmp_path: Path) -> None: - """Images, discards and peaks come back; peaks can be added later.""" - rng = np.random.default_rng(0) - mean_im = rng.random((6, 7, 2)).astype(np.float32) - act_im = rng.random((6, 7)) - act_im[0, 0] = np.nan - discard = rng.random(40) < 0.2 - path = tmp_path / "loc.h5" - write_localization(path, mean_im, act_im, act_im * 2, discard, None, {"trial": 3}) - rec = read_localization(path) - np.testing.assert_array_equal(rec.mean_im, mean_im) - assert rec.mean_im.dtype == np.float32 - np.testing.assert_array_equal(rec.act_im, act_im) - np.testing.assert_array_equal(rec.summary, act_im * 2) - np.testing.assert_array_equal(rec.discard, discard) - assert rec.peaks is None and rec.attrs["peaks_fitted"] == 0 - assert rec.attrs["trial"] == 3 - peaks = np.array([[1.0, 2.0, 3.0, 0.5]]) - side = add_peaks(path, peaks) - assert side.name == "loc.peaks.h5" # the localization file is not written - rec = read_localization(path) - np.testing.assert_array_equal(rec.peaks, peaks) - assert localization_attrs(path)["peaks_fitted"] == 1 - assert read_localization(path, peaks=False).peaks is None - images = rec.trial_images() - np.testing.assert_array_equal(images.act_im, act_im) - np.testing.assert_array_equal(images.peaks, peaks) - assert not list(tmp_path.glob("*.partial")) - # a new localization replaces the earlier one's peaks - write_localization(path, mean_im, act_im, act_im, discard, None, {"trial": 3}) - assert not side.exists() and read_localization(path).peaks is None - - -def test_localization_format_checks(tmp_path: Path) -> None: - """Other files are refused; a missing file has no attributes.""" - with h5py.File(tmp_path / "other.h5", "w") as f: - f.attrs["format"] = "other" - with pytest.raises(ValueError): - read_localization(tmp_path / "other.h5") - assert localization_attrs(tmp_path / "other.h5") is None - assert localization_attrs(tmp_path / "missing.h5") is None - path = tmp_path / "loc.h5" - write_localization( - path, - np.zeros((2, 2, 1)), - np.zeros((2, 2)), - np.zeros((2, 2)), - np.zeros(3, bool), - None, - {}, - ) - with h5py.File(path, "a") as f: - f.attrs["format_version"] = 99 - with pytest.raises(ValueError, match="99"): - read_localization(path) - - -def test_seeds(tmp_path: Path) -> None: - """Seeds per path, one-based (MATLAB's thetaf) or zero-based.""" - seeds = np.array([[2.0, 10.0, 20.0, 0.5], [1.0, 3.0, 4.0, 0.4]]) - write_seeds(tmp_path / "s1.h5", {2: seeds}, index_base=1) - got = read_seeds(tmp_path / "s1.h5", 3) - assert got[0] is None and got[2] is None - np.testing.assert_array_equal(got[1][:, 1:3], seeds[:, 1:3] - 1) - np.testing.assert_array_equal(got[1][:, [0, 3]], seeds[:, [0, 3]]) - write_seeds(tmp_path / "s0.h5", {1: seeds}) - np.testing.assert_array_equal(read_seeds(tmp_path / "s0.h5", 1)[0], seeds) - with pytest.raises(ValueError): - write_seeds(tmp_path / "bad.h5", {1: seeds}, index_base=2) - - -def test_recording_ids(tmp_path: Path) -> None: - """A recording's files: CYCLE segments and .meta; a missing one raises.""" - from giant_python.pipeline.silo_session import recording_ids - - for name in ( - "rec_DMD1-CYCLE-000000.dat", - "rec_DMD1-CYCLE-000100.dat", - "rec_DMD2-CYCLE-000000.dat", - "rec_DMD1.meta", - "other.meta", - ): - (tmp_path / name).write_bytes(b"x") - ids = recording_ids(tmp_path / "rec_DMD1-CYCLE-000100.dat") - assert [i["name"] for i in ids] == [ - "rec_DMD1-CYCLE-000000.dat", - "rec_DMD1-CYCLE-000100.dat", - "rec_DMD1.meta", - ] - with pytest.raises(FileNotFoundError): - recording_ids(tmp_path / "rec_DMD3-CYCLE-000000.dat") +"""Tests of the files SILo's stages hand to each other. + +These are per-trial localization files and seeds files. +""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.stage_files import ( + add_peaks, + localization_attrs, + read_localization, + read_seeds, + write_localization, + write_seeds, +) + + +def test_localization_round_trip(tmp_path: Path) -> None: + """Images, discards and peaks come back; peaks can be added later.""" + rng = np.random.default_rng(0) + mean_im = rng.random((6, 7, 2)).astype(np.float32) + act_im = rng.random((6, 7)) + act_im[0, 0] = np.nan + discard = rng.random(40) < 0.2 + path = tmp_path / "loc.h5" + write_localization(path, mean_im, act_im, act_im * 2, discard, None, {"trial": 3}) + rec = read_localization(path) + np.testing.assert_array_equal(rec.mean_im, mean_im) + assert rec.mean_im.dtype == np.float32 + np.testing.assert_array_equal(rec.act_im, act_im) + np.testing.assert_array_equal(rec.summary, act_im * 2) + np.testing.assert_array_equal(rec.discard, discard) + assert rec.peaks is None and rec.attrs["peaks_fitted"] == 0 + assert rec.attrs["trial"] == 3 + peaks = np.array([[1.0, 2.0, 3.0, 0.5]]) + side = add_peaks(path, peaks) + assert side.name == "loc.peaks.h5" # the localization file is not written + rec = read_localization(path) + np.testing.assert_array_equal(rec.peaks, peaks) + assert localization_attrs(path)["peaks_fitted"] == 1 + assert read_localization(path, peaks=False).peaks is None + images = rec.trial_images() + np.testing.assert_array_equal(images.act_im, act_im) + np.testing.assert_array_equal(images.peaks, peaks) + assert not list(tmp_path.glob("*.partial")) + # a new localization replaces the earlier one's peaks + write_localization(path, mean_im, act_im, act_im, discard, None, {"trial": 3}) + assert not side.exists() and read_localization(path).peaks is None + + +def test_localization_format_checks(tmp_path: Path) -> None: + """Other files are refused; a missing file has no attributes.""" + with h5py.File(tmp_path / "other.h5", "w") as f: + f.attrs["format"] = "other" + with pytest.raises(ValueError): + read_localization(tmp_path / "other.h5") + assert localization_attrs(tmp_path / "other.h5") is None + assert localization_attrs(tmp_path / "missing.h5") is None + path = tmp_path / "loc.h5" + write_localization( + path, + np.zeros((2, 2, 1)), + np.zeros((2, 2)), + np.zeros((2, 2)), + np.zeros(3, bool), + None, + {}, + ) + with h5py.File(path, "a") as f: + f.attrs["format_version"] = 99 + with pytest.raises(ValueError, match="99"): + read_localization(path) + + +def test_seeds(tmp_path: Path) -> None: + """Seeds per path, one-based (MATLAB's thetaf) or zero-based.""" + seeds = np.array([[2.0, 10.0, 20.0, 0.5], [1.0, 3.0, 4.0, 0.4]]) + write_seeds(tmp_path / "s1.h5", {2: seeds}, index_base=1) + got = read_seeds(tmp_path / "s1.h5", 3) + assert got[0] is None and got[2] is None + np.testing.assert_array_equal(got[1][:, 1:3], seeds[:, 1:3] - 1) + np.testing.assert_array_equal(got[1][:, [0, 3]], seeds[:, [0, 3]]) + write_seeds(tmp_path / "s0.h5", {1: seeds}) + np.testing.assert_array_equal(read_seeds(tmp_path / "s0.h5", 1)[0], seeds) + with pytest.raises(ValueError): + write_seeds(tmp_path / "bad.h5", {1: seeds}, index_base=2) + + +def test_recording_ids(tmp_path: Path) -> None: + """A recording's files: CYCLE segments and .meta; a missing one raises.""" + from giant_python.pipeline.silo_session import recording_ids + + for name in ( + "rec_DMD1-CYCLE-000000.dat", + "rec_DMD1-CYCLE-000100.dat", + "rec_DMD2-CYCLE-000000.dat", + "rec_DMD1.meta", + "other.meta", + ): + (tmp_path / name).write_bytes(b"x") + ids = recording_ids(tmp_path / "rec_DMD1-CYCLE-000100.dat") + assert [i["name"] for i in ids] == [ + "rec_DMD1-CYCLE-000000.dat", + "rec_DMD1-CYCLE-000100.dat", + "rec_DMD1.meta", + ] + with pytest.raises(FileNotFoundError): + recording_ids(tmp_path / "rec_DMD3-CYCLE-000000.dat") diff --git a/tests/raster/test_raster_summary.py b/tests/raster/test_raster_summary.py index 41775f7f..ba11ce8b 100644 --- a/tests/raster/test_raster_summary.py +++ b/tests/raster/test_raster_summary.py @@ -1,490 +1,520 @@ -"""Tests of SILo's summaries in GIAnT-MATLAB's schema. - -saveExperimentSummaryH5, savePerTrialSummaryH5. -""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import TrialWarp -from giant_python.extraction.raster.kinetics import KineticsTest -from giant_python.extraction.raster.plan import ( - ExtractionPlan, - PlanParams, - group_sources, -) -from giant_python.extraction.raster.results import TrialOutcome, TrialRecord -from giant_python.extraction.raster.solver import TrialActivity -from giant_python.extraction.raster.summary import ( - AlignmentRecord, - PathResult, - _nearest, - kinetics_test, - write_summaries, -) -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.models.params import SiloParams - -H, W, C = 14, 18, 2 -N_TRIALS = 3 -FRAMES = {1: 30, 2: 40} # trial 0 is not valid -SHIFTS = np.array([[np.nan, np.nan], [0.0, 0.0], [1.0, -2.0]]) - - -def make_plan() -> ExtractionPlan: - """Build a plan of four sources on a 14 x 18 frame, three trials.""" - rng = np.random.default_rng(0) - rows, cols = np.array([3, 4, 9, 10]), np.array([3, 5, 12, 15]) - sel = np.zeros((H, W), bool) - for r, c in zip(rows, cols): - sel[max(r - 2, 0) : r + 3, max(c - 2, 0) : c + 3] = True - groups = group_sources(rows, cols, sel, 3, 6) - mean_aligned = rng.random((N_TRIALS, H, W, C)) + 1 - act_aligned = rng.random((N_TRIALS, H, W)) - act_aligned[0] = np.nan - mean_aligned[0] = np.nan - sel_cols, sel_rows = np.nonzero(sel.T) - lists = [] - for r, c in zip(rows, cols): - near = (abs(sel_rows - r) <= 2) & (abs(sel_cols - c) <= 2) - lists.append(np.flatnonzero(near)) - return ExtractionPlan( - params=PlanParams(), - keep_trials=np.ones(N_TRIALS, bool), - template=np.zeros((H + 10, W + 10)), - template_trials=np.arange(N_TRIALS), - shifts=SHIFTS, - corr=np.array([np.nan, 0.9, 0.95]), - corr_thresh=0.5, - act_valid_pix=np.ones(N_TRIALS), - valid_trials=np.array([1, 2]), - warp=TrialWarp.from_shifts(SHIFTS), - mean_ims=mean_aligned.copy(), - act_ims=act_aligned.copy(), - mean_aligned=mean_aligned, - act_aligned=act_aligned, - mean_im=np.nanmean(mean_aligned[1:], axis=0), - act_im=rng.random((H, W)), - soma_mask=np.zeros((H, W), bool), - px_always_valid=np.ones((H, W), bool), - seeds=np.zeros((4, 4)), - source_rows=rows, - source_cols=cols, - source_values=np.ones(4), - sel=sel, - source_pixels=lists, - groups=groups, - trial_peaks=[None, None, None], - trial_discard=[None, None, None], - ) - - -def outcome(t: int, n_px: int, extracted: bool = True) -> TrialOutcome: - """Build a trial's outcome with distinct values per source and channel.""" - n = FRAMES[t] - rng = np.random.default_rng(t) - rec = TrialRecord( - frame_lines=100 * t + np.arange(n) * 8 + 1, - discard=np.arange(n) % 7 == 0, - global_f=rng.random((C, n)), - roi_f=rng.random((2, C, n)), - roi_fsvd=rng.random((2, C, n)), - ) - if not extracted: - return TrialOutcome(rec) - fp = rng.random((n_px, 4)).astype(np.float32) - fp[0, 1] = np.nan # a pixel outside source 1's subproblem - base = np.arange(4)[None, :, None] * 10 + np.arange(C)[:, None, None] - trace = base + rng.random((C, 4, n)) - act = TrialActivity( - footprints=fp, - events=trace + 0.1, - denoised=trace + 0.2, - ls=trace, - f0=trace + 0.3, - snr=np.array([1.0, 2.0, np.nan, 4.0]) * t, - ) - return TrialOutcome(rec, act) - - -def alignment(t: int) -> AlignmentRecord: - """Build a registration record with 5 registered frames over the trial.""" - ds = np.linspace(100 * t + 1, 100 * t + 1 + FRAMES[t] * 8, 5) - return AlignmentRecord( - ds_frames=ds, - motion_r=np.linspace(0, 1, 5), - motion_c=np.linspace(1, 0, 5), - online_x=np.arange(5.0), - online_y=-np.arange(5.0), - online_z=np.zeros(5), - z_depth=-18.75, - ) - - -@pytest.fixture -def written(tmp_path: Path) -> tuple[Path, Path, PathResult]: - """Both summaries of one path (activity channel 2).""" - plan = make_plan() - n_px = plan.n_pixels - result = PathResult( - plan=plan, - trials=[None, outcome(1, n_px), lambda: outcome(2, n_px)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=["spine01", "soma"], - roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], - z_depth=-18.75, - trial_peaks=[ - np.array([[1.0, 2.0, 3.0, 0.5]]), - None, - np.array([[1.0, 5.0, 6.0, 0.5], [2.0, 7.0, 8.0, 0.4]]), - ], - ) - result.kinetics = KineticsTest( - keep=np.array([True, False, True, True]), - score=np.array([0.9, 0.1, np.nan, 0.5]), - n_events=np.array([10, 7, 2, 6]), - ) - params = SiloParams( - activity_channel=2, - footprint_variance="model", - seed_fit="matlab", - seed_merge_px=0.0, - f0_im_trim_s=None, - ).to_matlab(C, 80.0, 4, "a", "b") - exp, per = tmp_path / "experiment_summary.h5", tmp_path / "per.h5" - write_summaries(exp, per, [result, None], params, N_TRIALS, C, 2) - return exp, per, result - - -def sizes(path: Path) -> dict[str, tuple[tuple[int, ...], str, int]]: - """Every dataset's MATLAB size and class.""" - out = {} - with h5py.File(path, "r") as f: - - def visit(name: str, obj: h5py.HLObject) -> None: - """Record a dataset.""" - if isinstance(obj, h5py.Dataset): - out[name] = ( - obj.shape[::-1], - obj.dtype.kind, - obj.dtype.itemsize, - ) - - f.visititems(visit) - return out - - -def test_experiment_summary_schema(written: tuple[Path, Path, PathResult]) -> None: - """Names, MATLAB sizes and classes of saveExperimentSummaryH5.""" - exp, _, _ = written - s = sizes(exp) - total = sum(FRAMES.values()) - want = { - "Path1/Z_depths": ((1, 1), "f", 8), - "Path1/frame_info/trial_num_frames": ((N_TRIALS, 1), "i", 4), - "Path1/frame_info/offlineXshifts": ((total, 1), "f", 8), - "Path1/frame_info/offlineYshifts": ((total, 1), "f", 8), - "Path1/frame_info/frame_line_idxs": ((total, 1), "i", 4), - "Path1/frame_info/discard_frames": ((total, 1), "i", 1), - "Path1/frame_info/onlineXshifts": ((total, 1), "f", 8), - "Path1/frame_info/onlineYshifts": ((total, 1), "f", 8), - "Path1/frame_info/onlineZshifts": ((total, 1), "f", 8), - "Path1/frame_info/trial_alignment_affine": ((N_TRIALS, 2, 3), "f", 8), - "Path1/visualizations/mean_im": ((C, 1, H, W), "f", 8), - "Path1/visualizations/act_im": ((1, H, W), "f", 8), - "Path1/visualizations/act_im_peaks": ((3, 3), "f", 8), - "Path1/global/F": ((C, total), "f", 8), - "Path1/user_rois/labels": ((2, 1), "O", 8), - "Path1/user_rois/mask": ((2, 1, H, W), "u", 1), - "Path1/user_rois/F": ((2, C, total), "f", 8), - "Path1/user_rois/Fsvd": ((2, C, total), "f", 8), - "Path1/sources/rejected/seed_coords": ((1, 3), "f", 8), - "Path1/sources/rejected/kinetic_score": ((1, 1), "f", 8), - "Path1/sources/rejected/kinetic_n_events": ((1, 1), "i", 4), - "Path1/sources/spatial/profiles": ((3, 1, H, W), "f", 4), - "Path1/sources/spatial/coords": ((3, 3), "f", 8), - "Path1/sources/temporal/dF_ls": ((3, C, total), "f", 8), - "Path1/sources/temporal/dF_denoised": ((3, C, total), "f", 8), - "Path1/sources/temporal/events": ((3, C, total), "f", 8), - "Path1/sources/temporal/F0": ((3, C, total), "f", 8), - "Path1/sources/temporal/SNR": ((3, 1), "f", 8), - "Path1/sources/temporal/kinetic_score": ((3, 1), "f", 8), - "Path1/sources/temporal/kinetic_n_events": ((3, 1), "i", 4), - "row_major": ((1, 1), "u", 1), - } - params = {k for k in s if k.startswith("params/")} - assert len(params) == 48 - assert {k: v for k, v in s.items() if k not in params} == want - - -def test_experiment_summary_values(written: tuple[Path, Path, PathResult]) -> None: - """Traces at their trials' frames in file channel order. - - Kept sources only; frame records; ROI traces reordered; profiles averaged. - """ - exp, _, result = written - e = load_struct_h5(exp)["Path1"] - o1, o2 = result.trials[1], result.trials[2]() - kept = [0, 2, 3] - ls = e["sources"]["temporal"]["dF_ls"] - # activity channel 2 is analysis channel 0 - np.testing.assert_array_equal(ls[:, 1, :30], o1.activity.ls[0][kept]) - np.testing.assert_array_equal(ls[:, 0, 30:], o2.activity.ls[1][kept]) - np.testing.assert_array_equal( - e["sources"]["temporal"]["F0"][:, 1, 30:], o2.activity.f0[0][kept] - ) - np.testing.assert_array_equal( - e["sources"]["temporal"]["kinetic_score"].ravel(), [0.9, np.nan, 0.5] - ) - np.testing.assert_array_equal(e["sources"]["temporal"]["SNR"].ravel(), [1.5, np.nan, 6.0]) - np.testing.assert_array_equal(e["sources"]["rejected"]["seed_coords"], [[0, 4, 5]]) - np.testing.assert_array_equal( - e["visualizations"]["act_im_peaks"], - [[0, 3, 3], [0, 9, 12], [0, 10, 15]], - ) - fi = e["frame_info"] - np.testing.assert_array_equal(fi["trial_num_frames"].ravel(), [0, 30, 40]) - np.testing.assert_array_equal( - fi["frame_line_idxs"].ravel(), - np.r_[o1.record.frame_lines, o2.record.frame_lines], - ) - np.testing.assert_array_equal( - fi["discard_frames"].ravel().astype(bool), - np.r_[o1.record.discard, o2.record.discard], - ) - # trial 2's shift is added to its offline motion - a = alignment(2) - first = np.interp(o2.record.frame_lines[0], a.ds_frames, a.motion_c) - assert fi["offlineXshifts"].ravel()[30] == pytest.approx(first - 2.0) - assert "offlineZshifts" not in fi - np.testing.assert_array_equal(fi["trial_alignment_affine"][2], [[1, 0, 1], [0, 1, -2]]) - np.testing.assert_array_equal(e["global"]["F"][:, :30], o1.record.global_f) - roi_f = e["user_rois"]["F"] - np.testing.assert_array_equal(roi_f[:, 1, :30], o1.record.roi_f[:, 0]) - np.testing.assert_array_equal(roi_f[:, 0, :30], o1.record.roi_f[:, 1]) - assert list(e["user_rois"]["labels"].ravel()) == ["spine01", "soma"] - # profiles: mean of the trials' footprints, NaN as 0 - rows, cols = result.plan.selected_pixels() - fp = ( - np.nan_to_num(o1.activity.footprints[:, kept]) - + np.nan_to_num(o2.activity.footprints[:, kept]) - ) / 2 - prof = e["sources"]["spatial"]["profiles"] - np.testing.assert_allclose(prof[:, 0, rows, cols].T, fp, rtol=1e-6) - np.testing.assert_allclose( - e["sources"]["spatial"]["coords"][:, 1], - (fp * rows[:, None]).sum(0) / fp.sum(0), - rtol=1e-5, - ) - np.testing.assert_array_equal( - e["visualizations"]["mean_im"][:, 0], - result.plan.mean_im.transpose(2, 0, 1), - ) - - -def test_per_trial_summary(written: tuple[Path, Path, PathResult]) -> None: - """Per-trial images, peaks in the consensus frame, footprints.""" - _, per, result = written - s = sizes(per) - assert s["Path1/visualizations/per_trial_mean_im"][0] == ( - N_TRIALS, - C, - 1, - H, - W, - ) - assert s["Path1/visualizations/per_trial_act_im"][0] == (N_TRIALS, 1, H, W) - assert s["Path1/visualizations/per_trial_act_im_peaks"][0] == ( - N_TRIALS, - 2, - 3, - ) - assert s["Path1/sources/spatial/per_trial_profiles"][0] == ( - N_TRIALS, - 3, - 1, - H, - W, - ) - assert s["Path1/sources/temporal/per_trial_SNR"][0] == (N_TRIALS, 3) - p = load_struct_h5(per)["Path1"] - v = p["visualizations"] - assert np.isnan(v["per_trial_mean_im"][0]).all() - np.testing.assert_array_equal( - v["per_trial_mean_im"][2, :, 0], - result.plan.mean_aligned[2].transpose(2, 0, 1), - ) - np.testing.assert_array_equal(v["per_trial_num_peaks"].ravel(), [1, 0, 2]) - peaks = v["per_trial_act_im_peaks"] - # trial 0 is not aligned (NaN shift); trial 2 moves by minus its shift - assert np.isnan(peaks[0, 0, 1:]).all() and peaks[0, 0, 0] == 0 - np.testing.assert_array_equal(peaks[2], [[0, 4, 8], [0, 6, 10]]) - assert np.isnan(peaks[1]).all() - prof = p["sources"]["spatial"]["per_trial_profiles"] - assert np.isnan(prof[0]).all() - rows, cols = result.plan.selected_pixels() - fp = np.nan_to_num(result.trials[1].activity.footprints[:, [0, 2, 3]]) - np.testing.assert_array_equal(prof[1, :, 0, rows, cols], fp) - snr = p["sources"]["temporal"]["per_trial_SNR"] - np.testing.assert_array_equal(snr[1], [1, np.nan, 4]) - coords = p["sources"]["spatial"]["per_trial_coords"] - assert (coords[:, :, 0] == 0).all() and np.isnan(coords[0, :, 1:]).all() - - -def test_short_trial_and_no_peaks(tmp_path: Path) -> None: - """A trial loaded but not extracted adds frames, no sources. - - Without per-trial peaks the peak fields are left out. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, outcome(1, plan.n_pixels, extracted=False), None], - alignment=[None, alignment(1), None], - ) - kinetics_test(result, 0.024, 200.0, 0.2) - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) - e = load_struct_h5(exp) - assert "sources" not in e["Path1"] - assert e["Path1"]["frame_info"]["trial_num_frames"].ravel().tolist() == [ - 0, - 30, - 0, - ] - assert e["Path1"]["global"]["F"].shape == (C, 30) - assert "user_rois" not in e["Path1"] - assert "Z_depths" not in e["Path1"] - p = load_struct_h5(per)["Path1"] - assert "per_trial_num_peaks" not in p["visualizations"] - assert "sources" not in p - - -def test_trial_without_sources_is_nan(tmp_path: Path) -> None: - """Frames of a trial loaded but not extracted are NaN in the sources' traces. - - When other trials have sources. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[ - None, - outcome(1, plan.n_pixels, extracted=False), - outcome(2, plan.n_pixels), - ], - alignment=[None, alignment(1), alignment(2)], - ) - kinetics_test(result, 0.024, 200.0, 0.0) - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) - temporal = load_struct_h5(exp)["Path1"]["sources"]["temporal"] - for key in ("dF_ls", "dF_denoised", "events", "F0"): - assert np.isnan(temporal[key][:, :, :30]).all() - assert not np.isnan(temporal[key][:, 0, 30:]).all() - snr = load_struct_h5(per)["Path1"]["sources"]["temporal"]["per_trial_SNR"] - assert np.isnan(snr[1]).all() - - -def test_nearest_interpolation() -> None: - """MATLAB's interp1 'nearest' with 'extrap': ties go right.""" - ds = np.array([1.0, 5.0, 9.0]) - v = np.array([10.0, 20.0, 30.0]) - np.testing.assert_array_equal(_nearest(ds, v, [0, 2, 3, 4, 7, 12]), [10, 10, 20, 20, 30, 30]) - np.testing.assert_array_equal(_nearest(ds[:1], v[:1], [0, 4]), [10, 10]) - - -def test_evidence_test_removes_weak_sources(tmp_path: Path) -> None: - """With min_snr the sources whose SNR averaged over trials is below it are removed. - - They are removed with the kinetics test's, and marked in the summary; the - SNR of a source without one (NaN) does not judge it. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], - alignment=[None, alignment(1), alignment(2)], - ) - kin = kinetics_test(result, 0.024, 200.0, 0.0, min_snr=3.5) - # SNR per trial [1, 2, nan, 4] * t: means 1.5, 3, nan, 6 - np.testing.assert_allclose(kin.snr, [1.5, 3.0, np.nan, 6.0]) - np.testing.assert_array_equal(kin.weak, [True, True, False, False]) - np.testing.assert_array_equal(kin.keep, [False, False, True, True]) - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) - rej = load_struct_h5(exp)["Path1"]["sources"]["rejected"] - np.testing.assert_array_equal(rej["weak"].ravel(), [1, 1]) - np.testing.assert_allclose(rej["SNR"].ravel(), [1.5, 3.0]) - off = kinetics_test(result, 0.024, 200.0, 0.0) - assert off.weak is None and off.keep.all() - - -def test_evidence_test_event_rate(tmp_path: Path) -> None: - """min_event_rate compares each source's kinetics events per minute with the rate. - - Events per minute of its frames; the summary records the rejected - sources' rates. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], - alignment=[None, alignment(1), alignment(2)], - ) - minutes = (FRAMES[1] + FRAMES[2]) / 200.0 / 60.0 - kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6) - np.testing.assert_allclose(kin.event_rate, kin.n_events / minutes) - assert kin.weak.all() and not kin.keep.any() - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) - rej = load_struct_h5(exp)["Path1"]["sources"]["rejected"] - np.testing.assert_allclose(rej["event_rate"].ravel(), kin.event_rate) - np.testing.assert_array_equal(rej["weak"].ravel(), [1, 1, 1, 1]) - kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e-9) - np.testing.assert_array_equal(kin.weak, kin.n_events == 0) - - -def test_evidence_test_judges_weak_seeds_only() -> None: - """With judge_below the evidence test judges only the sources seeded below it. - - The sources whose seed height in the plan's combined image is below it. - """ - from giant_python.extraction.raster.seeding import seed_heights - - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], - alignment=[None, alignment(1), alignment(2)], - ) - h = seed_heights(plan.act_im, plan.source_rows, plan.source_cols) - cut = float(np.median(h)) - kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6, judge_below=cut) - np.testing.assert_allclose(kin.seed_height, h) - np.testing.assert_array_equal(kin.weak, ~(h >= cut)) - assert kin.weak.any() and not kin.weak.all() - np.testing.assert_array_equal(kin.keep, h >= cut) - every = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6) - assert every.weak.all() and every.seed_height is None - - -def test_evidence_events_skipped_without_counts() -> None: - """The event criterion judges nothing when the kinetics test cannot count events. - - Decay under 3 frames; the SNR criterion still does. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], - alignment=[None, alignment(1), alignment(2)], - ) - kin = kinetics_test(result, 0.005, 200.0, 0.0, min_event_rate=3.0) - assert not kin.weak.any() and kin.keep.all() - assert np.isnan(kin.event_rate).all() - kin = kinetics_test(result, 0.005, 200.0, 0.0, 3.5, 3.0) - np.testing.assert_array_equal(kin.weak, [True, True, False, False]) +"""Tests of SILo's summaries in GIAnT-MATLAB's schema. + +saveExperimentSummaryH5, savePerTrialSummaryH5. +""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import TrialWarp +from giant_python.extraction.raster.kinetics import KineticsTest +from giant_python.extraction.raster.plan import ( + ExtractionPlan, + PlanParams, + group_sources, +) +from giant_python.extraction.raster.results import TrialOutcome, TrialRecord +from giant_python.extraction.raster.solver import TrialActivity +from giant_python.extraction.raster.summary import ( + AlignmentRecord, + PathResult, + _nearest, + kinetics_test, + write_summaries, +) +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.models.params import SiloParams + +H, W, C = 14, 18, 2 +N_TRIALS = 3 +FRAMES = {1: 30, 2: 40} # trial 0 is not valid +SHIFTS = np.array([[np.nan, np.nan], [0.0, 0.0], [1.0, -2.0]]) + + +def make_plan() -> ExtractionPlan: + """Build a plan of four sources on a 14 x 18 frame, three trials. + + Returns + ------- + ExtractionPlan + The plan, with trial 0 not valid. + """ + rng = np.random.default_rng(0) + rows, cols = np.array([3, 4, 9, 10]), np.array([3, 5, 12, 15]) + sel = np.zeros((H, W), bool) + for r, c in zip(rows, cols): + sel[max(r - 2, 0) : r + 3, max(c - 2, 0) : c + 3] = True + groups = group_sources(rows, cols, sel, 3, 6) + mean_aligned = rng.random((N_TRIALS, H, W, C)) + 1 + act_aligned = rng.random((N_TRIALS, H, W)) + act_aligned[0] = np.nan + mean_aligned[0] = np.nan + sel_cols, sel_rows = np.nonzero(sel.T) + lists = [] + for r, c in zip(rows, cols): + near = (abs(sel_rows - r) <= 2) & (abs(sel_cols - c) <= 2) + lists.append(np.flatnonzero(near)) + return ExtractionPlan( + params=PlanParams(), + keep_trials=np.ones(N_TRIALS, bool), + template=np.zeros((H + 10, W + 10)), + template_trials=np.arange(N_TRIALS), + shifts=SHIFTS, + corr=np.array([np.nan, 0.9, 0.95]), + corr_thresh=0.5, + act_valid_pix=np.ones(N_TRIALS), + valid_trials=np.array([1, 2]), + warp=TrialWarp.from_shifts(SHIFTS), + mean_ims=mean_aligned.copy(), + act_ims=act_aligned.copy(), + mean_aligned=mean_aligned, + act_aligned=act_aligned, + mean_im=np.nanmean(mean_aligned[1:], axis=0), + act_im=rng.random((H, W)), + soma_mask=np.zeros((H, W), bool), + px_always_valid=np.ones((H, W), bool), + seeds=np.zeros((4, 4)), + source_rows=rows, + source_cols=cols, + source_values=np.ones(4), + sel=sel, + source_pixels=lists, + groups=groups, + trial_peaks=[None, None, None], + trial_discard=[None, None, None], + ) + + +def outcome(t: int, n_px: int, extracted: bool = True) -> TrialOutcome: + """Build a trial's outcome with distinct values per source and channel. + + Returns + ------- + TrialOutcome + The trial's record and activity; the activity is None when extracted is False. + """ + n = FRAMES[t] + rng = np.random.default_rng(t) + rec = TrialRecord( + frame_lines=100 * t + np.arange(n) * 8 + 1, + discard=np.arange(n) % 7 == 0, + global_f=rng.random((C, n)), + roi_f=rng.random((2, C, n)), + roi_fsvd=rng.random((2, C, n)), + ) + if not extracted: + return TrialOutcome(rec) + fp = rng.random((n_px, 4)).astype(np.float32) + fp[0, 1] = np.nan # a pixel outside source 1's subproblem + base = np.arange(4)[None, :, None] * 10 + np.arange(C)[:, None, None] + trace = base + rng.random((C, 4, n)) + act = TrialActivity( + footprints=fp, + events=trace + 0.1, + denoised=trace + 0.2, + ls=trace, + f0=trace + 0.3, + snr=np.array([1.0, 2.0, np.nan, 4.0]) * t, + ) + return TrialOutcome(rec, act) + + +def alignment(t: int) -> AlignmentRecord: + """Build a registration record with 5 registered frames over the trial. + + Returns + ------- + AlignmentRecord + The trial's registration record. + """ + ds = np.linspace(100 * t + 1, 100 * t + 1 + FRAMES[t] * 8, 5) + return AlignmentRecord( + ds_frames=ds, + motion_r=np.linspace(0, 1, 5), + motion_c=np.linspace(1, 0, 5), + online_x=np.arange(5.0), + online_y=-np.arange(5.0), + online_z=np.zeros(5), + z_depth=-18.75, + ) + + +@pytest.fixture +def written(tmp_path: Path) -> tuple[Path, Path, PathResult]: + """Both summaries of one path (activity channel 2). + + Returns + ------- + tuple[Path, Path, PathResult] + The experiment summary file, the per-path summary file and the path's result. + """ + plan = make_plan() + n_px = plan.n_pixels + result = PathResult( + plan=plan, + trials=[None, outcome(1, n_px), lambda: outcome(2, n_px)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=["spine01", "soma"], + roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], + z_depth=-18.75, + trial_peaks=[ + np.array([[1.0, 2.0, 3.0, 0.5]]), + None, + np.array([[1.0, 5.0, 6.0, 0.5], [2.0, 7.0, 8.0, 0.4]]), + ], + ) + result.kinetics = KineticsTest( + keep=np.array([True, False, True, True]), + score=np.array([0.9, 0.1, np.nan, 0.5]), + n_events=np.array([10, 7, 2, 6]), + ) + params = SiloParams( + activity_channel=2, + footprint_variance="model", + seed_fit="matlab", + seed_merge_px=0.0, + f0_im_trim_s=None, + ).to_matlab(C, 80.0, 4, "a", "b") + exp, per = tmp_path / "experiment_summary.h5", tmp_path / "per.h5" + write_summaries(exp, per, [result, None], params, N_TRIALS, C, 2) + return exp, per, result + + +def sizes(path: Path) -> dict[str, tuple[tuple[int, ...], str, int]]: + """Every dataset's MATLAB size and class. + + Returns + ------- + dict[str, tuple[tuple[int, ...], str, int]] + For each dataset name, its MATLAB-order shape, dtype kind and item size. + """ + out = {} + with h5py.File(path, "r") as f: + + def visit(name: str, obj: h5py.HLObject) -> None: + """Record a dataset.""" + if isinstance(obj, h5py.Dataset): + out[name] = ( + obj.shape[::-1], + obj.dtype.kind, + obj.dtype.itemsize, + ) + + f.visititems(visit) + return out + + +def test_experiment_summary_schema(written: tuple[Path, Path, PathResult]) -> None: + """Names, MATLAB sizes and classes of saveExperimentSummaryH5.""" + exp, _, _ = written + s = sizes(exp) + total = sum(FRAMES.values()) + want = { + "Path1/Z_depths": ((1, 1), "f", 8), + "Path1/frame_info/trial_num_frames": ((N_TRIALS, 1), "i", 4), + "Path1/frame_info/offlineXshifts": ((total, 1), "f", 8), + "Path1/frame_info/offlineYshifts": ((total, 1), "f", 8), + "Path1/frame_info/frame_line_idxs": ((total, 1), "i", 4), + "Path1/frame_info/discard_frames": ((total, 1), "i", 1), + "Path1/frame_info/onlineXshifts": ((total, 1), "f", 8), + "Path1/frame_info/onlineYshifts": ((total, 1), "f", 8), + "Path1/frame_info/onlineZshifts": ((total, 1), "f", 8), + "Path1/frame_info/trial_alignment_affine": ((N_TRIALS, 2, 3), "f", 8), + "Path1/visualizations/mean_im": ((C, 1, H, W), "f", 8), + "Path1/visualizations/act_im": ((1, H, W), "f", 8), + "Path1/visualizations/act_im_peaks": ((3, 3), "f", 8), + "Path1/global/F": ((C, total), "f", 8), + "Path1/user_rois/labels": ((2, 1), "O", 8), + "Path1/user_rois/mask": ((2, 1, H, W), "u", 1), + "Path1/user_rois/F": ((2, C, total), "f", 8), + "Path1/user_rois/Fsvd": ((2, C, total), "f", 8), + "Path1/sources/rejected/seed_coords": ((1, 3), "f", 8), + "Path1/sources/rejected/kinetic_score": ((1, 1), "f", 8), + "Path1/sources/rejected/kinetic_n_events": ((1, 1), "i", 4), + "Path1/sources/spatial/profiles": ((3, 1, H, W), "f", 4), + "Path1/sources/spatial/coords": ((3, 3), "f", 8), + "Path1/sources/temporal/dF_ls": ((3, C, total), "f", 8), + "Path1/sources/temporal/dF_denoised": ((3, C, total), "f", 8), + "Path1/sources/temporal/events": ((3, C, total), "f", 8), + "Path1/sources/temporal/F0": ((3, C, total), "f", 8), + "Path1/sources/temporal/SNR": ((3, 1), "f", 8), + "Path1/sources/temporal/kinetic_score": ((3, 1), "f", 8), + "Path1/sources/temporal/kinetic_n_events": ((3, 1), "i", 4), + "row_major": ((1, 1), "u", 1), + } + params = {k for k in s if k.startswith("params/")} + assert len(params) == 48 + assert {k: v for k, v in s.items() if k not in params} == want + + +def test_experiment_summary_values(written: tuple[Path, Path, PathResult]) -> None: + """Traces at their trials' frames in file channel order. + + Kept sources only; frame records; ROI traces reordered; profiles averaged. + """ + exp, _, result = written + e = load_struct_h5(exp)["Path1"] + o1, o2 = result.trials[1], result.trials[2]() + kept = [0, 2, 3] + ls = e["sources"]["temporal"]["dF_ls"] + # activity channel 2 is analysis channel 0 + np.testing.assert_array_equal(ls[:, 1, :30], o1.activity.ls[0][kept]) + np.testing.assert_array_equal(ls[:, 0, 30:], o2.activity.ls[1][kept]) + np.testing.assert_array_equal( + e["sources"]["temporal"]["F0"][:, 1, 30:], o2.activity.f0[0][kept] + ) + np.testing.assert_array_equal( + e["sources"]["temporal"]["kinetic_score"].ravel(), [0.9, np.nan, 0.5] + ) + np.testing.assert_array_equal(e["sources"]["temporal"]["SNR"].ravel(), [1.5, np.nan, 6.0]) + np.testing.assert_array_equal(e["sources"]["rejected"]["seed_coords"], [[0, 4, 5]]) + np.testing.assert_array_equal( + e["visualizations"]["act_im_peaks"], + [[0, 3, 3], [0, 9, 12], [0, 10, 15]], + ) + fi = e["frame_info"] + np.testing.assert_array_equal(fi["trial_num_frames"].ravel(), [0, 30, 40]) + np.testing.assert_array_equal( + fi["frame_line_idxs"].ravel(), + np.r_[o1.record.frame_lines, o2.record.frame_lines], + ) + np.testing.assert_array_equal( + fi["discard_frames"].ravel().astype(bool), + np.r_[o1.record.discard, o2.record.discard], + ) + # trial 2's shift is added to its offline motion + a = alignment(2) + first = np.interp(o2.record.frame_lines[0], a.ds_frames, a.motion_c) + assert fi["offlineXshifts"].ravel()[30] == pytest.approx(first - 2.0) + assert "offlineZshifts" not in fi + np.testing.assert_array_equal(fi["trial_alignment_affine"][2], [[1, 0, 1], [0, 1, -2]]) + np.testing.assert_array_equal(e["global"]["F"][:, :30], o1.record.global_f) + roi_f = e["user_rois"]["F"] + np.testing.assert_array_equal(roi_f[:, 1, :30], o1.record.roi_f[:, 0]) + np.testing.assert_array_equal(roi_f[:, 0, :30], o1.record.roi_f[:, 1]) + assert list(e["user_rois"]["labels"].ravel()) == ["spine01", "soma"] + # profiles: mean of the trials' footprints, NaN as 0 + rows, cols = result.plan.selected_pixels() + fp = ( + np.nan_to_num(o1.activity.footprints[:, kept]) + + np.nan_to_num(o2.activity.footprints[:, kept]) + ) / 2 + prof = e["sources"]["spatial"]["profiles"] + np.testing.assert_allclose(prof[:, 0, rows, cols].T, fp, rtol=1e-6) + np.testing.assert_allclose( + e["sources"]["spatial"]["coords"][:, 1], + (fp * rows[:, None]).sum(0) / fp.sum(0), + rtol=1e-5, + ) + np.testing.assert_array_equal( + e["visualizations"]["mean_im"][:, 0], + result.plan.mean_im.transpose(2, 0, 1), + ) + + +def test_per_trial_summary(written: tuple[Path, Path, PathResult]) -> None: + """Per-trial images, peaks in the consensus frame, footprints.""" + _, per, result = written + s = sizes(per) + assert s["Path1/visualizations/per_trial_mean_im"][0] == ( + N_TRIALS, + C, + 1, + H, + W, + ) + assert s["Path1/visualizations/per_trial_act_im"][0] == (N_TRIALS, 1, H, W) + assert s["Path1/visualizations/per_trial_act_im_peaks"][0] == ( + N_TRIALS, + 2, + 3, + ) + assert s["Path1/sources/spatial/per_trial_profiles"][0] == ( + N_TRIALS, + 3, + 1, + H, + W, + ) + assert s["Path1/sources/temporal/per_trial_SNR"][0] == (N_TRIALS, 3) + p = load_struct_h5(per)["Path1"] + v = p["visualizations"] + assert np.isnan(v["per_trial_mean_im"][0]).all() + np.testing.assert_array_equal( + v["per_trial_mean_im"][2, :, 0], + result.plan.mean_aligned[2].transpose(2, 0, 1), + ) + np.testing.assert_array_equal(v["per_trial_num_peaks"].ravel(), [1, 0, 2]) + peaks = v["per_trial_act_im_peaks"] + # trial 0 is not aligned (NaN shift); trial 2 moves by minus its shift + assert np.isnan(peaks[0, 0, 1:]).all() and peaks[0, 0, 0] == 0 + np.testing.assert_array_equal(peaks[2], [[0, 4, 8], [0, 6, 10]]) + assert np.isnan(peaks[1]).all() + prof = p["sources"]["spatial"]["per_trial_profiles"] + assert np.isnan(prof[0]).all() + rows, cols = result.plan.selected_pixels() + fp = np.nan_to_num(result.trials[1].activity.footprints[:, [0, 2, 3]]) + np.testing.assert_array_equal(prof[1, :, 0, rows, cols], fp) + snr = p["sources"]["temporal"]["per_trial_SNR"] + np.testing.assert_array_equal(snr[1], [1, np.nan, 4]) + coords = p["sources"]["spatial"]["per_trial_coords"] + assert (coords[:, :, 0] == 0).all() and np.isnan(coords[0, :, 1:]).all() + + +def test_short_trial_and_no_peaks(tmp_path: Path) -> None: + """A trial loaded but not extracted adds frames, no sources. + + Without per-trial peaks the peak fields are left out. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, outcome(1, plan.n_pixels, extracted=False), None], + alignment=[None, alignment(1), None], + ) + kinetics_test(result, 0.024, 200.0, 0.2) + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) + e = load_struct_h5(exp) + assert "sources" not in e["Path1"] + assert e["Path1"]["frame_info"]["trial_num_frames"].ravel().tolist() == [ + 0, + 30, + 0, + ] + assert e["Path1"]["global"]["F"].shape == (C, 30) + assert "user_rois" not in e["Path1"] + assert "Z_depths" not in e["Path1"] + p = load_struct_h5(per)["Path1"] + assert "per_trial_num_peaks" not in p["visualizations"] + assert "sources" not in p + + +def test_trial_without_sources_is_nan(tmp_path: Path) -> None: + """Frames of a trial loaded but not extracted are NaN in the sources' traces. + + When other trials have sources. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[ + None, + outcome(1, plan.n_pixels, extracted=False), + outcome(2, plan.n_pixels), + ], + alignment=[None, alignment(1), alignment(2)], + ) + kinetics_test(result, 0.024, 200.0, 0.0) + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) + temporal = load_struct_h5(exp)["Path1"]["sources"]["temporal"] + for key in ("dF_ls", "dF_denoised", "events", "F0"): + assert np.isnan(temporal[key][:, :, :30]).all() + assert not np.isnan(temporal[key][:, 0, 30:]).all() + snr = load_struct_h5(per)["Path1"]["sources"]["temporal"]["per_trial_SNR"] + assert np.isnan(snr[1]).all() + + +def test_nearest_interpolation() -> None: + """MATLAB's interp1 'nearest' with 'extrap': ties go right.""" + ds = np.array([1.0, 5.0, 9.0]) + v = np.array([10.0, 20.0, 30.0]) + np.testing.assert_array_equal(_nearest(ds, v, [0, 2, 3, 4, 7, 12]), [10, 10, 20, 20, 30, 30]) + np.testing.assert_array_equal(_nearest(ds[:1], v[:1], [0, 4]), [10, 10]) + + +def test_evidence_test_removes_weak_sources(tmp_path: Path) -> None: + """With min_snr the sources whose SNR averaged over trials is below it are removed. + + They are removed with the kinetics test's, and marked in the summary; the + SNR of a source without one (NaN) does not judge it. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], + alignment=[None, alignment(1), alignment(2)], + ) + kin = kinetics_test(result, 0.024, 200.0, 0.0, min_snr=3.5) + # SNR per trial [1, 2, nan, 4] * t: means 1.5, 3, nan, 6 + np.testing.assert_allclose(kin.snr, [1.5, 3.0, np.nan, 6.0]) + np.testing.assert_array_equal(kin.weak, [True, True, False, False]) + np.testing.assert_array_equal(kin.keep, [False, False, True, True]) + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) + rej = load_struct_h5(exp)["Path1"]["sources"]["rejected"] + np.testing.assert_array_equal(rej["weak"].ravel(), [1, 1]) + np.testing.assert_allclose(rej["SNR"].ravel(), [1.5, 3.0]) + off = kinetics_test(result, 0.024, 200.0, 0.0) + assert off.weak is None and off.keep.all() + + +def test_evidence_test_event_rate(tmp_path: Path) -> None: + """min_event_rate compares each source's kinetics events per minute with the rate. + + Events per minute of its frames; the summary records the rejected + sources' rates. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], + alignment=[None, alignment(1), alignment(2)], + ) + minutes = (FRAMES[1] + FRAMES[2]) / 200.0 / 60.0 + kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6) + np.testing.assert_allclose(kin.event_rate, kin.n_events / minutes) + assert kin.weak.all() and not kin.keep.any() + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], {"x": 1.0}, N_TRIALS, C, 1) + rej = load_struct_h5(exp)["Path1"]["sources"]["rejected"] + np.testing.assert_allclose(rej["event_rate"].ravel(), kin.event_rate) + np.testing.assert_array_equal(rej["weak"].ravel(), [1, 1, 1, 1]) + kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e-9) + np.testing.assert_array_equal(kin.weak, kin.n_events == 0) + + +def test_evidence_test_judges_weak_seeds_only() -> None: + """With judge_below the evidence test judges only the sources seeded below it. + + The sources whose seed height in the plan's combined image is below it. + """ + from giant_python.extraction.raster.seeding import seed_heights + + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], + alignment=[None, alignment(1), alignment(2)], + ) + h = seed_heights(plan.act_im, plan.source_rows, plan.source_cols) + cut = float(np.median(h)) + kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6, judge_below=cut) + np.testing.assert_allclose(kin.seed_height, h) + np.testing.assert_array_equal(kin.weak, ~(h >= cut)) + assert kin.weak.any() and not kin.weak.all() + np.testing.assert_array_equal(kin.keep, h >= cut) + every = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6) + assert every.weak.all() and every.seed_height is None + + +def test_evidence_events_skipped_without_counts() -> None: + """The event criterion judges nothing when the kinetics test cannot count events. + + Decay under 3 frames; the SNR criterion still does. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, outcome(1, plan.n_pixels), outcome(2, plan.n_pixels)], + alignment=[None, alignment(1), alignment(2)], + ) + kin = kinetics_test(result, 0.005, 200.0, 0.0, min_event_rate=3.0) + assert not kin.weak.any() and kin.keep.all() + assert np.isnan(kin.event_rate).all() + kin = kinetics_test(result, 0.005, 200.0, 0.0, 3.5, 3.0) + np.testing.assert_array_equal(kin.weak, [True, True, False, False]) diff --git a/tests/raster/test_raster_summary_model.py b/tests/raster/test_raster_summary_model.py index dce5d4b7..131e474a 100644 --- a/tests/raster/test_raster_summary_model.py +++ b/tests/raster/test_raster_summary_model.py @@ -1,461 +1,479 @@ -"""``ExperimentSummary.from_h5`` / ``to_h5`` on raster SILo's and BandSILo's summaries. - -Raster SILo's experiment summary is column-major (GIAnT-MATLAB's layout); -BandSILo's schema is also covered. -""" - -import dataclasses -import json -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster import spots as sp -from giant_python.extraction.raster.kinetics import KineticsTest -from giant_python.extraction.raster.summary import ( - PathResult, - _Writer, - write_summaries, -) -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.models.experiment_summary import ( - ExperimentSummary, - FrameInfo, - PathSummary, - Source, - Visualizations, -) -from giant_python.models.params import SiloParams -from giant_python.pipeline.silo_spots import _write as write_spots - -from .test_raster_summary import ( # noqa: F401 (fixture) - FRAMES, - N_TRIALS, - C, - H, - W, - alignment, - make_plan, - outcome, - written, -) - -TOTAL = sum(FRAMES.values()) - - -def _children(a: object, b: object, where: str) -> list[tuple[object, object, str]]: - """Pairs of the members of two containers (dataclass, dict, list).""" - if dataclasses.is_dataclass(a): - assert type(a) is type(b), where - return [ - (getattr(a, f.name), getattr(b, f.name), f"{where}.{f.name}") - for f in dataclasses.fields(a) - if not f.name.startswith("_") - ] - if isinstance(a, dict): - assert set(a) == set(b), where - return [(a[k], b[k], f"{where}[{k}]") for k in a] - assert len(a) == len(b), where - return [(x, y, f"{where}[{i}]") for i, (x, y) in enumerate(zip(a, b))] - - -def _equal(a: object, b: object, where: str = "summary") -> None: - """Two models hold the same values (NaN equal to NaN).""" - if dataclasses.is_dataclass(a) or isinstance(a, (dict, list, tuple)): - for x, y, w in _children(a, b, where): - _equal(x, y, w) - elif a is None or b is None: - assert a is None and b is None, where - elif isinstance(a, str): - assert a == b, where - else: - x, y = np.asarray(a), np.asarray(b) - assert x.shape == y.shape, where - if x.dtype.kind in "fc" or y.dtype.kind in "fc": - np.testing.assert_array_equal(x, y, err_msg=where) - else: - assert np.array_equal(x, y), where - - -def test_from_h5_reads_a_raster_summary(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 - """A raster summary loads with the dimension order of the README. - - It loads with its values, its kinetics and rejected sources, and no - offlineZshifts. - """ - exp, _, result = written - s = ExperimentSummary.from_h5(exp) - raw = load_struct_h5(exp)["Path1"] - assert [p.path_index for p in s.paths] == [0] # Path2 was None - p = s.paths[0] - assert len(p.sources) == 3 - src = p.sources[1] - assert src.profile.shape == (1, H, W) - assert src.df_ls.shape == src.events.shape == (C, TOTAL) - np.testing.assert_array_equal(src.f0, raw["sources"]["temporal"]["F0"][1]) - np.testing.assert_array_equal([x.snr for x in p.sources], [1.5, np.nan, 6.0]) - np.testing.assert_array_equal([x.kinetic_score for x in p.sources], [0.9, np.nan, 0.5]) - assert [x.kinetic_n_events for x in p.sources] == [10, 2, 6] - assert all(x.spot_id is None for x in p.sources) - assert p.frame_info.offlineZshifts is None - assert p.frame_info.offlineXshifts.shape == (TOTAL, 1) - np.testing.assert_array_equal(p.frame_info.trial_alignment_affine[2], [[1, 0, 1], [0, 1, -2]]) - assert p.frame_info.trial_alignment_displacement is None - np.testing.assert_array_equal(p.rejected["seed_coords"], [[0, 4, 5]]) - assert p.rejected["kinetic_score"].shape == (1, 1) - assert [r.label for r in p.user_rois] == ["spine01", "soma"] - assert p.annotation_enabled - assert p.user_rois[0].mask.shape == (1, H, W) - assert p.user_rois[1].f.shape == (C, TOTAL) - assert p.visualizations.mean_im.shape == (C, 1, H, W) - assert p.visualizations.act_im.shape == (1, H, W) - np.testing.assert_array_equal( - p.visualizations.act_im_peaks, [[0, 3, 3], [0, 9, 12], [0, 10, 15]] - ) - assert p.visualizations.f0_im is None - assert p.global_f.shape == (C, TOTAL) - np.testing.assert_array_equal(p.z_depths, [[-18.75]]) - assert p.spots is None - assert s.params["activityChannel"] == 2 - assert s.attrs == {} - - -def test_paths_without_sources_rois_or_depth(tmp_path: Path) -> None: - """A path whose sources were all removed, without annotations and an unknown depth. - - It sits beside one with sources (in Path2). - """ - plan = make_plan() - n_px = plan.n_pixels - - def result(keep: list[bool]) -> PathResult: - """One path of the plan, with the kinetics' keep.""" - r = PathResult( - plan=plan, - trials=[None, outcome(1, n_px), outcome(2, n_px)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=[], - roi_masks=[], - ) - r.kinetics = KineticsTest( - keep=np.asarray(keep), - score=np.array([0.9, 0.1, 0.4, 0.5]), - n_events=np.array([10, 7, 2, 6]), - ) - return r - - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") - exp = tmp_path / "experiment_summary.h5" - write_summaries( - exp, - tmp_path / "per.h5", - [result([False] * 4), result([True, True, False, True])], - params, - N_TRIALS, - C, - 1, - ) - s = ExperimentSummary.from_h5(exp) - none, some = s.paths - assert (none.path_index, some.path_index) == (0, 1) - assert none.sources == [] and none.user_rois == [] - assert not none.annotation_enabled - assert none.visualizations.act_im_peaks is None - assert none.z_depths is None - assert none.rejected["seed_coords"].shape == (4, 3) - assert none.global_f.shape == (C, TOTAL) - assert len(some.sources) == 3 - assert [x.kinetic_n_events for x in some.sources] == [10, 7, 6] - # a model without sources is written in the band schema and read back - out = tmp_path / "band.h5" - s.to_h5(out) - back = ExperimentSummary.from_h5(out) - assert back.paths[0].sources == [] - assert back.paths[0].z_depths is None - _equal(back.paths[1], some) - - -def _annotated(exp: Path) -> None: - """Add raster extras to the written summary, as raster SILo writes them. - - The extras are a spot annotation, a baseline image, a displacement field - and root attributes. - """ - lab = np.array([0, 1, 0]) # sources 1 and 3 form a spot - out = [ - sp.SpotResult( - np.array([0, 2]), - "merge", - event_corr=0.6, - n_events=20, - K=1, - power=0.4, - cloud_major=0.3, - cloud_minor=0.2, - bic_gain=-3.0, - center=np.array([6.0, 7.5]), - ), - sp.SpotResult(np.array([1]), "single", center=np.array([9.0, 12.0])), - ] - write_spots(exp, "Path1", lab, out, sp.SpotSettings()) - rng = np.random.default_rng(4) - with h5py.File(exp, "a") as f: - ew = _Writer(f) - ew.put("Path1/visualizations/F0_im", rng.random((C, 1, H, W))) - ew.put( - "Path1/frame_info/trial_alignment_displacement", - rng.random((N_TRIALS, 2, H, W)).astype(np.float32), - ) - f.attrs["baseline_source"] = "network" - f.attrs["network_baseline"] = json.dumps({"path1_trial0002": {}}) - - -def test_spot_annotation_and_raster_extras(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 - """The spot annotation with its attributes, and the summary's raster extras. - - These are each source's spot, the baseline image, the displacement field - and the root attributes. - """ - exp, _, _ = written - _annotated(exp) - s = ExperimentSummary.from_h5(exp) - p = s.paths[0] - assert [x.spot_id for x in p.sources] == [1, 2, 1] - spots = p.spots - assert spots["labels"] == list(sp.LABELS) - assert spots["settings"]["link_px"] == 2.5 - assert spots["label"].shape == (2, 1) - names = [spots["labels"][i] for i in spots["label"].ravel()] - assert names == ["merge", "single"] - np.testing.assert_array_equal(spots["n_sources"].ravel(), [2, 1]) - np.testing.assert_array_equal(spots["event_corr"].ravel()[:1], [0.6]) - assert p.visualizations.f0_im.shape == (C, 1, H, W) - assert p.frame_info.trial_alignment_displacement.shape == ( - N_TRIALS, - 2, - H, - W, - ) - assert s.attrs["baseline_source"] == "network" - assert json.loads(s.attrs["network_baseline"]) == {"path1_trial0002": {}} - - -def test_raster_round_trip( - written: tuple[Path, Path, PathResult], # noqa: F811 - tmp_path: Path, -) -> None: - """A raster model written with to_h5 reads back as the same model. - - to_h5 writes BandSILo's row-major schema plus the raster fields, and - refuses to add paths to the column-major file. - """ - exp, _, _ = written - _annotated(exp) - s = ExperimentSummary.from_h5(exp) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 - assert "offlineZshifts" not in f["Path1/frame_info"] - assert f["Path1/sources/spots"].attrs["labels"] - _equal(ExperimentSummary.from_h5(out), s) - with pytest.raises(ValueError, match="column-major"): - s.to_h5(exp) - - -def _band_summary() -> ExperimentSummary: - """Build a BandSILo-like model: every band field, no raster field.""" - rng = np.random.default_rng(9) - n, frames, ch = 2, 12, 2 - sources = [ - Source( - profile=rng.random((1, H, W)).astype(np.float32), - coords=np.array([0, 3 + j, 4 + j], np.int32), - df_ls=rng.random((ch, frames)), - df_denoised=rng.random((ch, frames)), - events=rng.random((ch, frames)), - f0=rng.random((ch, frames)), - snr=np.float64(2.0 + j), - ) - for j in range(n) - ] - col = np.arange(frames, dtype=float).reshape(-1, 1) - frame_info = FrameInfo( - trial_num_frames=np.array([[5], [7]]), - discard_frames=np.zeros((frames, 1), bool), - frame_line_idxs=np.arange(1, frames + 1).reshape(-1, 1), - offlineXshifts=col, - offlineYshifts=-col, - offlineZshifts=0 * col, - onlineXshifts=col, - onlineYshifts=col, - onlineZshifts=col, - ) - path = PathSummary( - path_index=0, - sources=sources, - visualizations=Visualizations( - mean_im=rng.random((ch, 1, H, W)), - act_im=rng.random((1, H, W)), - act_im_peaks=np.array([[0, 3, 4], [0, 4, 5], [0, 9, 9]]), - ), - frame_info=frame_info, - global_f=rng.random((ch, frames)), - z_depths=np.array([12.5]), - ) - return ExperimentSummary(paths=[path], params={"analyzeHz": 100.0}) - - -BAND_DATASETS = { - "row_major", - "params/analyzeHz", - "Path1/Z_depths", - "Path1/sources/spatial/profiles", - "Path1/sources/spatial/coords", - "Path1/sources/temporal/dF_ls", - "Path1/sources/temporal/dF_denoised", - "Path1/sources/temporal/events", - "Path1/sources/temporal/F0", - "Path1/sources/temporal/SNR", - "Path1/frame_info/trial_num_frames", - "Path1/frame_info/discard_frames", - "Path1/frame_info/frame_line_idxs", - "Path1/frame_info/offlineXshifts", - "Path1/frame_info/offlineYshifts", - "Path1/frame_info/offlineZshifts", - "Path1/frame_info/onlineXshifts", - "Path1/frame_info/onlineYshifts", - "Path1/frame_info/onlineZshifts", - "Path1/global/F", - "Path1/visualizations/act_im", - "Path1/visualizations/mean_im", - "Path1/visualizations/act_im_peaks", - "Path1/user_rois/mask", - "Path1/user_rois/F", - "Path1/user_rois/Fsvd", - "Path1/user_rois/labels", -} - - -def test_band_schema_unchanged(tmp_path: Path) -> None: - """A BandSILo model writes exactly the band datasets and reads back unchanged. - - It writes no raster field and no root attribute. - """ - s = _band_summary() - out = tmp_path / "band.h5" - s.to_h5(out) - names = set() - with h5py.File(out, "r") as f: - f.visititems(lambda name, obj: names.add(name) if isinstance(obj, h5py.Dataset) else None) - assert dict(f.attrs) == {} - assert dict(f["Path1/user_rois"].attrs) == {"annotation_enabled": False} - assert names == BAND_DATASETS - back = ExperimentSummary.from_h5(out) - p = back.paths[0] - assert p.rejected == {} and p.spots is None and back.attrs == {} - assert p.visualizations.f0_im is None - assert all(x.kinetic_score is None for x in p.sources) - _equal(p.sources, s.paths[0].sources) - _equal(p.frame_info, s.paths[0].frame_info) - np.testing.assert_array_equal(p.z_depths, [[12.5]]) - - -def test_partial_raster_scalars_are_refused(tmp_path: Path) -> None: - """A raster field set for some sources only cannot be written.""" - s = _band_summary() - s.paths[0].sources[0].kinetic_score = 0.5 - with pytest.raises(ValueError, match="kinetic_score"): - s.to_h5(tmp_path / "x.h5") - - -def test_raster_round_trip_without_snr( - written: tuple[Path, Path, PathResult], # noqa: F811 - tmp_path: Path, -) -> None: - """A raster file without SNR (no trial gave one) stays without it.""" - exp, _, _ = written - with h5py.File(exp, "a") as f: - del f["Path1/sources/temporal/SNR"] - s = ExperimentSummary.from_h5(exp) - assert all(x.snr is None for x in s.paths[0].sources) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert "SNR" not in f["Path1/sources/temporal"] - _equal(ExperimentSummary.from_h5(out), s) - # a model built in memory with no SNR still gets NaN, as before - band = _band_summary() - for x in band.paths[0].sources: - x.snr = None - band.to_h5(tmp_path / "band.h5") - with h5py.File(tmp_path / "band.h5", "r") as f: - assert np.isnan(f["Path1/sources/temporal/SNR"][()]).all() - - -def test_raster_path_without_frames(tmp_path: Path) -> None: - """A raster path without frames (no trial loaded) is written back and reads the same. - - It has no global trace, no sources and ROI masks without traces. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, None, None], - alignment=[None, None, None], - roi_labels=["soma"], - roi_masks=[np.ones((H, W), bool)], - ) - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") - exp = tmp_path / "experiment_summary.h5" - write_summaries(exp, tmp_path / "per.h5", [result], params, N_TRIALS, C, 1) - s = ExperimentSummary.from_h5(exp) - p = s.paths[0] - assert p.global_f is None and p.sources == [] - assert [r.label for r in p.user_rois] == ["soma"] - assert p.user_rois[0].f is None and p.user_rois[0].fsvd is None - assert p.user_rois[0].mask.shape == (1, H, W) - np.testing.assert_array_equal(p.frame_info.trial_num_frames.ravel(), 0) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert f["Path1/sources/temporal/dF_ls"].shape == (0, C, 0) - assert "F" not in f["Path1/user_rois"] - assert f["Path1/user_rois/mask"].shape == (1, 1, H, W) - assert "global" not in f["Path1"] - _equal(ExperimentSummary.from_h5(out), s) - - -def test_files_without_the_flag_are_refused(tmp_path: Path) -> None: - """A nonempty file without /row_major reads as column-major: refused. - - A new (empty) file is made row-major. - """ - old = tmp_path / "old.h5" - with h5py.File(old, "w") as f: - f["Path1/Z_depths"] = np.zeros((1, 1)) - with pytest.raises(ValueError, match="no /row_major"): - _band_summary().to_h5(old) - new = tmp_path / "new.h5" - h5py.File(new, "w").close() - _band_summary().to_h5(new) - with h5py.File(new, "r") as f: - assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 - - -def test_partial_roi_traces_are_refused(tmp_path: Path) -> None: - """ROIs of which only some have a trace cannot be written.""" - from giant_python.models.experiment_summary import UserRoi - - s = _band_summary() - p = s.paths[0] - p.annotation_enabled = True - mask = np.ones((1, H, W), bool) - p.user_rois = [ - UserRoi(label="a", mask=mask, f=p.global_f.copy()), - UserRoi(label="b", mask=mask), - ] - with pytest.raises(ValueError, match="UserRoi.f"): - s.to_h5(tmp_path / "x.h5") +"""ExperimentSummary.from_h5 / to_h5 on raster SILo's and BandSILo's summaries. + +Raster SILo's experiment summary is column-major (GIAnT-MATLAB's layout); +BandSILo's schema is also covered. +""" + +import dataclasses +import json +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster import spots as sp +from giant_python.extraction.raster.kinetics import KineticsTest +from giant_python.extraction.raster.summary import ( + PathResult, + _Writer, + write_summaries, +) +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.models.experiment_summary import ( + ExperimentSummary, + FrameInfo, + PathSummary, + Source, + Visualizations, +) +from giant_python.models.params import SiloParams +from giant_python.pipeline.silo_spots import _write as write_spots + +from .test_raster_summary import ( # noqa: F401 (fixture) + FRAMES, + N_TRIALS, + C, + H, + W, + alignment, + make_plan, + outcome, + written, +) + +TOTAL = sum(FRAMES.values()) + + +def _children(a: object, b: object, where: str) -> list[tuple[object, object, str]]: + """Pairs of the members of two containers (dataclass, dict, list). + + Returns + ------- + list[tuple[object, object, str]] + One (member of a, member of b, location) triple per member. + """ + if dataclasses.is_dataclass(a): + assert type(a) is type(b), where + return [ + (getattr(a, f.name), getattr(b, f.name), f"{where}.{f.name}") + for f in dataclasses.fields(a) + if not f.name.startswith("_") + ] + if isinstance(a, dict): + assert set(a) == set(b), where + return [(a[k], b[k], f"{where}[{k}]") for k in a] + assert len(a) == len(b), where + return [(x, y, f"{where}[{i}]") for i, (x, y) in enumerate(zip(a, b))] + + +def _equal(a: object, b: object, where: str = "summary") -> None: + """Two models hold the same values (NaN equal to NaN).""" + if dataclasses.is_dataclass(a) or isinstance(a, (dict, list, tuple)): + for x, y, w in _children(a, b, where): + _equal(x, y, w) + elif a is None or b is None: + assert a is None and b is None, where + elif isinstance(a, str): + assert a == b, where + else: + x, y = np.asarray(a), np.asarray(b) + assert x.shape == y.shape, where + if x.dtype.kind in "fc" or y.dtype.kind in "fc": + np.testing.assert_array_equal(x, y, err_msg=where) + else: + assert np.array_equal(x, y), where + + +def test_from_h5_reads_a_raster_summary(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 + """A raster summary loads with the dimension order of the README. + + It loads with its values, its kinetics and rejected sources, and no + offlineZshifts. + """ + exp, _, result = written + s = ExperimentSummary.from_h5(exp) + raw = load_struct_h5(exp)["Path1"] + assert [p.path_index for p in s.paths] == [0] # Path2 was None + p = s.paths[0] + assert len(p.sources) == 3 + src = p.sources[1] + assert src.profile.shape == (1, H, W) + assert src.df_ls.shape == src.events.shape == (C, TOTAL) + np.testing.assert_array_equal(src.f0, raw["sources"]["temporal"]["F0"][1]) + np.testing.assert_array_equal([x.snr for x in p.sources], [1.5, np.nan, 6.0]) + np.testing.assert_array_equal([x.kinetic_score for x in p.sources], [0.9, np.nan, 0.5]) + assert [x.kinetic_n_events for x in p.sources] == [10, 2, 6] + assert all(x.spot_id is None for x in p.sources) + assert p.frame_info.offlineZshifts is None + assert p.frame_info.offlineXshifts.shape == (TOTAL, 1) + np.testing.assert_array_equal(p.frame_info.trial_alignment_affine[2], [[1, 0, 1], [0, 1, -2]]) + assert p.frame_info.trial_alignment_displacement is None + np.testing.assert_array_equal(p.rejected["seed_coords"], [[0, 4, 5]]) + assert p.rejected["kinetic_score"].shape == (1, 1) + assert [r.label for r in p.user_rois] == ["spine01", "soma"] + assert p.annotation_enabled + assert p.user_rois[0].mask.shape == (1, H, W) + assert p.user_rois[1].f.shape == (C, TOTAL) + assert p.visualizations.mean_im.shape == (C, 1, H, W) + assert p.visualizations.act_im.shape == (1, H, W) + np.testing.assert_array_equal( + p.visualizations.act_im_peaks, [[0, 3, 3], [0, 9, 12], [0, 10, 15]] + ) + assert p.visualizations.f0_im is None + assert p.global_f.shape == (C, TOTAL) + np.testing.assert_array_equal(p.z_depths, [[-18.75]]) + assert p.spots is None + assert s.params["activityChannel"] == 2 + assert s.attrs == {} + + +def test_paths_without_sources_rois_or_depth(tmp_path: Path) -> None: + """A path whose sources were all removed, without annotations and an unknown depth. + + It sits beside one with sources (in Path2). + """ + plan = make_plan() + n_px = plan.n_pixels + + def result(keep: list[bool]) -> PathResult: + """One path of the plan, with the kinetics' keep. + + Returns + ------- + PathResult + The path's result, with a kinetics test whose keep is keep. + """ + r = PathResult( + plan=plan, + trials=[None, outcome(1, n_px), outcome(2, n_px)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=[], + roi_masks=[], + ) + r.kinetics = KineticsTest( + keep=np.asarray(keep), + score=np.array([0.9, 0.1, 0.4, 0.5]), + n_events=np.array([10, 7, 2, 6]), + ) + return r + + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") + exp = tmp_path / "experiment_summary.h5" + write_summaries( + exp, + tmp_path / "per.h5", + [result([False] * 4), result([True, True, False, True])], + params, + N_TRIALS, + C, + 1, + ) + s = ExperimentSummary.from_h5(exp) + none, some = s.paths + assert (none.path_index, some.path_index) == (0, 1) + assert none.sources == [] and none.user_rois == [] + assert not none.annotation_enabled + assert none.visualizations.act_im_peaks is None + assert none.z_depths is None + assert none.rejected["seed_coords"].shape == (4, 3) + assert none.global_f.shape == (C, TOTAL) + assert len(some.sources) == 3 + assert [x.kinetic_n_events for x in some.sources] == [10, 7, 6] + # a model without sources is written in the band schema and read back + out = tmp_path / "band.h5" + s.to_h5(out) + back = ExperimentSummary.from_h5(out) + assert back.paths[0].sources == [] + assert back.paths[0].z_depths is None + _equal(back.paths[1], some) + + +def _annotated(exp: Path) -> None: + """Add raster extras to the written summary, as raster SILo writes them. + + The extras are a spot annotation, a baseline image, a displacement field + and root attributes. + """ + lab = np.array([0, 1, 0]) # sources 1 and 3 form a spot + out = [ + sp.SpotResult( + np.array([0, 2]), + "merge", + event_corr=0.6, + n_events=20, + K=1, + power=0.4, + cloud_major=0.3, + cloud_minor=0.2, + bic_gain=-3.0, + center=np.array([6.0, 7.5]), + ), + sp.SpotResult(np.array([1]), "single", center=np.array([9.0, 12.0])), + ] + write_spots(exp, "Path1", lab, out, sp.SpotSettings()) + rng = np.random.default_rng(4) + with h5py.File(exp, "a") as f: + ew = _Writer(f) + ew.put("Path1/visualizations/F0_im", rng.random((C, 1, H, W))) + ew.put( + "Path1/frame_info/trial_alignment_displacement", + rng.random((N_TRIALS, 2, H, W)).astype(np.float32), + ) + f.attrs["baseline_source"] = "network" + f.attrs["network_baseline"] = json.dumps({"path1_trial0002": {}}) + + +def test_spot_annotation_and_raster_extras(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 + """The spot annotation with its attributes, and the summary's raster extras. + + These are each source's spot, the baseline image, the displacement field + and the root attributes. + """ + exp, _, _ = written + _annotated(exp) + s = ExperimentSummary.from_h5(exp) + p = s.paths[0] + assert [x.spot_id for x in p.sources] == [1, 2, 1] + spots = p.spots + assert spots["labels"] == list(sp.LABELS) + assert spots["settings"]["link_px"] == 2.5 + assert spots["label"].shape == (2, 1) + names = [spots["labels"][i] for i in spots["label"].ravel()] + assert names == ["merge", "single"] + np.testing.assert_array_equal(spots["n_sources"].ravel(), [2, 1]) + np.testing.assert_array_equal(spots["event_corr"].ravel()[:1], [0.6]) + assert p.visualizations.f0_im.shape == (C, 1, H, W) + assert p.frame_info.trial_alignment_displacement.shape == ( + N_TRIALS, + 2, + H, + W, + ) + assert s.attrs["baseline_source"] == "network" + assert json.loads(s.attrs["network_baseline"]) == {"path1_trial0002": {}} + + +def test_raster_round_trip( + written: tuple[Path, Path, PathResult], # noqa: F811 + tmp_path: Path, +) -> None: + """A raster model written with to_h5 reads back as the same model. + + to_h5 writes BandSILo's row-major schema plus the raster fields, and + refuses to add paths to the column-major file. + """ + exp, _, _ = written + _annotated(exp) + s = ExperimentSummary.from_h5(exp) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 + assert "offlineZshifts" not in f["Path1/frame_info"] + assert f["Path1/sources/spots"].attrs["labels"] + _equal(ExperimentSummary.from_h5(out), s) + with pytest.raises(ValueError, match="column-major"): + s.to_h5(exp) + + +def _band_summary() -> ExperimentSummary: + """Build a BandSILo-like model: every band field, no raster field. + + Returns + ------- + ExperimentSummary + A summary of one path with two sources and random values. + """ + rng = np.random.default_rng(9) + n, frames, ch = 2, 12, 2 + sources = [ + Source( + profile=rng.random((1, H, W)).astype(np.float32), + coords=np.array([0, 3 + j, 4 + j], np.int32), + df_ls=rng.random((ch, frames)), + df_denoised=rng.random((ch, frames)), + events=rng.random((ch, frames)), + f0=rng.random((ch, frames)), + snr=np.float64(2.0 + j), + ) + for j in range(n) + ] + col = np.arange(frames, dtype=float).reshape(-1, 1) + frame_info = FrameInfo( + trial_num_frames=np.array([[5], [7]]), + discard_frames=np.zeros((frames, 1), bool), + frame_line_idxs=np.arange(1, frames + 1).reshape(-1, 1), + offlineXshifts=col, + offlineYshifts=-col, + offlineZshifts=0 * col, + onlineXshifts=col, + onlineYshifts=col, + onlineZshifts=col, + ) + path = PathSummary( + path_index=0, + sources=sources, + visualizations=Visualizations( + mean_im=rng.random((ch, 1, H, W)), + act_im=rng.random((1, H, W)), + act_im_peaks=np.array([[0, 3, 4], [0, 4, 5], [0, 9, 9]]), + ), + frame_info=frame_info, + global_f=rng.random((ch, frames)), + z_depths=np.array([12.5]), + ) + return ExperimentSummary(paths=[path], params={"analyzeHz": 100.0}) + + +BAND_DATASETS = { + "row_major", + "params/analyzeHz", + "Path1/Z_depths", + "Path1/sources/spatial/profiles", + "Path1/sources/spatial/coords", + "Path1/sources/temporal/dF_ls", + "Path1/sources/temporal/dF_denoised", + "Path1/sources/temporal/events", + "Path1/sources/temporal/F0", + "Path1/sources/temporal/SNR", + "Path1/frame_info/trial_num_frames", + "Path1/frame_info/discard_frames", + "Path1/frame_info/frame_line_idxs", + "Path1/frame_info/offlineXshifts", + "Path1/frame_info/offlineYshifts", + "Path1/frame_info/offlineZshifts", + "Path1/frame_info/onlineXshifts", + "Path1/frame_info/onlineYshifts", + "Path1/frame_info/onlineZshifts", + "Path1/global/F", + "Path1/visualizations/act_im", + "Path1/visualizations/mean_im", + "Path1/visualizations/act_im_peaks", + "Path1/user_rois/mask", + "Path1/user_rois/F", + "Path1/user_rois/Fsvd", + "Path1/user_rois/labels", +} + + +def test_band_schema_unchanged(tmp_path: Path) -> None: + """A BandSILo model writes exactly the band datasets and reads back unchanged. + + It writes no raster field and no root attribute. + """ + s = _band_summary() + out = tmp_path / "band.h5" + s.to_h5(out) + names = set() + with h5py.File(out, "r") as f: + f.visititems(lambda name, obj: names.add(name) if isinstance(obj, h5py.Dataset) else None) + assert dict(f.attrs) == {} + assert dict(f["Path1/user_rois"].attrs) == {"annotation_enabled": False} + assert names == BAND_DATASETS + back = ExperimentSummary.from_h5(out) + p = back.paths[0] + assert p.rejected == {} and p.spots is None and back.attrs == {} + assert p.visualizations.f0_im is None + assert all(x.kinetic_score is None for x in p.sources) + _equal(p.sources, s.paths[0].sources) + _equal(p.frame_info, s.paths[0].frame_info) + np.testing.assert_array_equal(p.z_depths, [[12.5]]) + + +def test_partial_raster_scalars_are_refused(tmp_path: Path) -> None: + """A raster field set for some sources only cannot be written.""" + s = _band_summary() + s.paths[0].sources[0].kinetic_score = 0.5 + with pytest.raises(ValueError, match="kinetic_score"): + s.to_h5(tmp_path / "x.h5") + + +def test_raster_round_trip_without_snr( + written: tuple[Path, Path, PathResult], # noqa: F811 + tmp_path: Path, +) -> None: + """A raster file without SNR (no trial gave one) stays without it.""" + exp, _, _ = written + with h5py.File(exp, "a") as f: + del f["Path1/sources/temporal/SNR"] + s = ExperimentSummary.from_h5(exp) + assert all(x.snr is None for x in s.paths[0].sources) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert "SNR" not in f["Path1/sources/temporal"] + _equal(ExperimentSummary.from_h5(out), s) + # a model built in memory with no SNR still gets NaN, as before + band = _band_summary() + for x in band.paths[0].sources: + x.snr = None + band.to_h5(tmp_path / "band.h5") + with h5py.File(tmp_path / "band.h5", "r") as f: + assert np.isnan(f["Path1/sources/temporal/SNR"][()]).all() + + +def test_raster_path_without_frames(tmp_path: Path) -> None: + """A raster path without frames (no trial loaded) is written back and reads the same. + + It has no global trace, no sources and ROI masks without traces. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, None, None], + alignment=[None, None, None], + roi_labels=["soma"], + roi_masks=[np.ones((H, W), bool)], + ) + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") + exp = tmp_path / "experiment_summary.h5" + write_summaries(exp, tmp_path / "per.h5", [result], params, N_TRIALS, C, 1) + s = ExperimentSummary.from_h5(exp) + p = s.paths[0] + assert p.global_f is None and p.sources == [] + assert [r.label for r in p.user_rois] == ["soma"] + assert p.user_rois[0].f is None and p.user_rois[0].fsvd is None + assert p.user_rois[0].mask.shape == (1, H, W) + np.testing.assert_array_equal(p.frame_info.trial_num_frames.ravel(), 0) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert f["Path1/sources/temporal/dF_ls"].shape == (0, C, 0) + assert "F" not in f["Path1/user_rois"] + assert f["Path1/user_rois/mask"].shape == (1, 1, H, W) + assert "global" not in f["Path1"] + _equal(ExperimentSummary.from_h5(out), s) + + +def test_files_without_the_flag_are_refused(tmp_path: Path) -> None: + """A nonempty file without /row_major reads as column-major: refused. + + A new (empty) file is made row-major. + """ + old = tmp_path / "old.h5" + with h5py.File(old, "w") as f: + f["Path1/Z_depths"] = np.zeros((1, 1)) + with pytest.raises(ValueError, match="no /row_major"): + _band_summary().to_h5(old) + new = tmp_path / "new.h5" + h5py.File(new, "w").close() + _band_summary().to_h5(new) + with h5py.File(new, "r") as f: + assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 + + +def test_partial_roi_traces_are_refused(tmp_path: Path) -> None: + """ROIs of which only some have a trace cannot be written.""" + from giant_python.models.experiment_summary import UserRoi + + s = _band_summary() + p = s.paths[0] + p.annotation_enabled = True + mask = np.ones((1, H, W), bool) + p.user_rois = [ + UserRoi(label="a", mask=mask, f=p.global_f.copy()), + UserRoi(label="b", mask=mask), + ] + with pytest.raises(ValueError, match="UserRoi.f"): + s.to_h5(tmp_path / "x.h5") diff --git a/tests/raster/test_raster_trial.py b/tests/raster/test_raster_trial.py index ed3f19e0..9a0ca9da 100644 --- a/tests/raster/test_raster_trial.py +++ b/tests/raster/test_raster_trial.py @@ -1,260 +1,271 @@ -"""Tests of loading a registered SLAP2 trial for raster localization.""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.trial import ( - discard_frames, - half_mean_images, - load_registered_trial, - trial_halves, -) - -PLAN_FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" - - -def test_discard_frames_around_a_motion_event() -> None: - """A jump of recNegErr discards it and neighbours above half the threshold. - - MATLAB: dilate by ~50 ms, keep above half, close. - """ - rne = -0.5 + 0.01 * np.random.default_rng(0).standard_normal(800) - rne[400:402] += 0.2 # registration error jumps for two frames - d = discard_frames(rne, 80.0, motion_thresh=2.0) - assert d[400:402].all() - assert d.sum() <= 8 and not d[:395].any() and not d[408:].any() - d0 = discard_frames(rne, 80.0, discard_initial_s=0.5) - assert d0[:40].all() and not d0[40:395].any() - - -@pytest.mark.parametrize("layout", ["one_series", "page_by_page"]) -def test_load_registered_trial(tmp_path: Path, layout: str) -> None: - """Channels are deinterleaved, pages transposed to MATLAB's rows and columns. - - Discards are set to NaN, the variance factor read. The TIFF may hold one - series of all pages (MATLAB's Fast_BigTiff_Write) or one per page - (GIAnT-Python's registration writes each page on its own). - """ - tifffile = pytest.importorskip("tifffile") - n, rows, cols = 400, 6, 9 # MATLAB rows x cols; n > the 4 s median - rng = np.random.default_rng(0) - act = rng.poisson(5, (n, rows, cols)).astype(np.float32) - other = np.full((n, rows, cols), 100, np.float32) - pages = np.empty((2 * n, cols, rows), np.float32) # pages: (col, row) - pages[0::2] = act.transpose(0, 2, 1) - pages[1::2] = other.transpose(0, 2, 1) - stem = "E1T1DMD1" - tif = tmp_path / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" - if layout == "one_series": - tifffile.imwrite(tif, pages) - else: # as giant_python.registration.outputs writes it - with tifffile.TiffWriter(tif, bigtiff=True) as tw: - for page in pages: - tw.write(page, photometric="minisblack") - with tifffile.TiffFile(tif) as tf: - assert len(tf.series) == 2 * n # imread would read one page - rne = -0.5 + 0.01 * rng.standard_normal(n) - rne[200] += 0.2 - vf = rng.uniform(1, 2, (n, cols, rows)).astype(np.float32) - with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = rne[None, :] - f["slap2/varFacDS"] = vf # MATLAB rows x cols x frames, reversed - tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) - assert tr.movie.shape == (n, rows, cols) and tr.align_hz == 80.0 - keep = ~tr.discard - assert tr.discard[200] and keep.sum() > n - 8 - np.testing.assert_array_equal(tr.movie[keep], act[keep]) - assert np.isnan(tr.movie[tr.discard]).all() - np.testing.assert_allclose(tr.mean_im[..., 1], 100) - np.testing.assert_allclose(tr.var_factor, vf.transpose(0, 2, 1)) - - -@pytest.mark.parametrize("save_tif", [False, True]) -def test_load_registration_movie(tmp_path: Path, save_tif: bool) -> None: - """Movies written by GIAnT-Python's registration, HDF5 or TIFF, load alike. - - HDF5 (the default) or TIFF load as the same frames in MATLAB's rows and - columns. - """ - if save_tif: - pytest.importorskip("tifffile") - from giant_python.registration.outputs import MovieWriter - - n, rows, cols = 50, 6, 9 - rng = np.random.default_rng(1) - act = rng.poisson(5, (n, rows, cols)).astype(np.float32) - act[3, 2, 4] = np.nan - other = np.full((n, rows, cols), 100, np.float32) - stem = "E1T1DMD1" - name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz" + (".tif" if save_tif else ".h5") - movie = MovieWriter(tmp_path / name, (rows, cols), 2 * n, save_tif) - for a, o in zip(act, other): - movie.write(a) - movie.write(o) - movie.close() - movie.tmp.rename(movie.path) - with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = np.full((1, n), -0.5) - tr = load_registered_trial(tmp_path, name, 2) - np.testing.assert_array_equal(tr.movie, act) - np.testing.assert_allclose(tr.mean_im[..., 1], 100) - - -def test_localize_trial_retries_numerical_failures(monkeypatch: pytest.MonkeyPatch) -> None: - """Any failure of the localization itself is retried with the outer rows and columns NaN. - - MATLAB's catch; invalid inputs are not. - """ - import giant_python.extraction.raster.trial as trial_mod - from giant_python.extraction.raster.localization import ( - RasterLocalizationParams, - ) - - movie = np.ones((20, 6, 7), np.float32) - fake = trial_mod.RegisteredTrial(movie, None, np.ones((6, 7, 1)), np.zeros(20, bool), 80.0) - monkeypatch.setattr(trial_mod, "load_registered_trial", lambda *a: fake) - seen = [] - - def flaky(mov: np.ndarray, *args: object, **kwargs: object) -> str: - """Fails like a numerical error unless the edges are NaN.""" - seen.append(bool(np.isnan(mov[:, 0, :]).all())) - if not seen[-1]: - raise ValueError("non-finite residuals") - return "ok" - - monkeypatch.setattr(trial_mod, "localize_sources", flaky) - loc, _ = trial_mod.localize_trial("dir", "x_REGISTERED.tif", 1) - assert loc == "ok" and seen == [False, True] - seen.clear() - p = RasterLocalizationParams(variance_floor=False) - with pytest.raises(ValueError, match="external baseline"): - trial_mod.localize_trial("dir", "x_REGISTERED.tif", 1, p) - assert seen == [] - - -@pytest.mark.parametrize( - "num_channels, activity_channel", - [(2, 0), (2, 3), (0, 1), (2.0, 1), (2, True), (1, -1)], -) -def test_channel_arguments_checked( - tmp_path: Path, num_channels: float, activity_channel: float -) -> None: - """Channel arguments outside 1..num_channels, or not integers, raise before anything is read. - - 0 would select the last channel. - """ - with pytest.raises(ValueError, match="channel"): - load_registered_trial( - tmp_path, - "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", - num_channels, - activity_channel, - ) - - -def test_page_count_not_a_multiple_of_channels(tmp_path: Path) -> None: - """An incomplete last frame is left out, with a warning.""" - tifffile = pytest.importorskip("tifffile") - n, rows, cols = 400, 4, 5 - pages = np.ones((2 * n + 1, cols, rows), np.float32) - stem = "E1T1DMD1" - tifffile.imwrite( - tmp_path / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", - pages, - photometric="minisblack", - ) - with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = np.full((1, n), -0.5) - with pytest.warns(UserWarning, match="not a multiple"): - tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) - assert tr.movie.shape == (n, rows, cols) - - -def test_trial_halves_match_matlab() -> None: - """trialHalves.m of GIAnT-MATLAB: alternating blocks. - - Then the larger half's last frames move over until the halves are equal - to a frame. - """ - cases = { - (10, 3): [1, 1, 1, 2, 2, 2, 1, 1, 2, 2], - (7, 2): [1, 1, 2, 2, 1, 1, 2], - (12, 4): [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2], - (9, 40): [1, 1, 1, 1, 1, 2, 2, 2, 2], - (5, 1): [1, 2, 1, 2, 1], - (1, 3): [1], - (23, 5): [1] * 5 + [2] * 5 + [1] * 5 + [2] * 5 + [1, 1, 2], - } - for (n, block), matlab in cases.items(): - half = trial_halves(n, block) - np.testing.assert_array_equal(half + 1, matlab) - assert abs(int((half == 0).sum()) - int((half == 1).sum())) <= 1 - - -def test_half_mean_images_match_matlab() -> None: - """The half-trial mean images of MATLAB's loadAndProcessTrialAsync. - - On a small movie with missing pixels (exactly: sums of whole counts). - """ - with h5py.File(PLAN_FIXTURE, "r") as f: - g = f["halves"] - stack, half, ref = g["stack"][()], g["half"][()], g["half_ims"][()] - nan_thresh, block = g.attrs["nanThresh"], int(g.attrs["block_len"]) - np.testing.assert_array_equal(trial_halves(stack.shape[0], block), half) - out = half_mean_images(stack, half, nan_thresh) - assert out.dtype == np.float32 and np.isnan(ref).any() - np.testing.assert_array_equal(out, ref) - - -def test_load_registered_trial_half_images(tmp_path: Path) -> None: - """Half images are returned only when asked for. - - Their mean is the trial's mean image where nothing is missing. - """ - n, rows, cols = 120, 5, 6 - rng = np.random.default_rng(3) - data = rng.poisson(20, (2 * n, cols, rows)).astype(np.float32) - stem = "E1T1DMD1" - name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" - with h5py.File(tmp_path / name, "w") as f: - f["data"] = data - with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = np.full((1, n), -0.5) - assert load_registered_trial(tmp_path, name, 2).half_ims is None - tr = load_registered_trial(tmp_path, name, 2, half_ims=True) - assert tr.half_ims.shape == (2, rows, cols, 2) - # 40-frame blocks of 120 frames: the halves hold 60 frames each - np.testing.assert_allclose(tr.half_ims.mean(axis=0), tr.mean_im, rtol=1e-6) - stack = data.transpose(0, 2, 1).reshape(n, 2, rows, cols) - first = np.r_[0:40, 80:100] - np.testing.assert_allclose(tr.half_ims[0, :, :, 1], stack[first, 1].mean(axis=0), rtol=1e-6) - - -def test_channel_means_equal_the_joint_nanmean() -> None: - """The mean image and the missing pixels, one channel at a time, match the joint ones. - - They are those of ``nanmean`` and ``isnan(...).mean`` over all channels - at once, bit for bit (pixels without samples included). - """ - from giant_python.extraction.raster.trial import _channel_means - - rng = np.random.default_rng(3) - stack = rng.gamma(2.0, 30.0, (97, 3, 11, 13)).astype(np.float32) - stack[rng.random(stack.shape) < 0.3] = np.nan - stack[:, :, 2, 5] = np.nan # no sample in any channel - stack[:, 1, 4, 4] = np.nan # none in one channel - with np.errstate(invalid="ignore"), pytest.warns(RuntimeWarning): - want = np.nanmean(stack, axis=0).transpose(1, 2, 0) - gaps = np.isnan(stack).mean(axis=(0, 1)) - with pytest.warns(RuntimeWarning): - got, missing = _channel_means(stack, 0.33) - assert got.dtype == want.dtype - np.testing.assert_array_equal(got, want) - np.testing.assert_array_equal(missing, gaps > 0.33) +"""Tests of loading a registered SLAP2 trial for raster localization.""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.trial import ( + discard_frames, + half_mean_images, + load_registered_trial, + trial_halves, +) + +PLAN_FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" + + +def test_discard_frames_around_a_motion_event() -> None: + """A jump of recNegErr discards it and neighbours above half the threshold. + + MATLAB: dilate by ~50 ms, keep above half, close. + """ + rne = -0.5 + 0.01 * np.random.default_rng(0).standard_normal(800) + rne[400:402] += 0.2 # registration error jumps for two frames + d = discard_frames(rne, 80.0, motion_thresh=2.0) + assert d[400:402].all() + assert d.sum() <= 8 and not d[:395].any() and not d[408:].any() + d0 = discard_frames(rne, 80.0, discard_initial_s=0.5) + assert d0[:40].all() and not d0[40:395].any() + + +@pytest.mark.parametrize("layout", ["one_series", "page_by_page"]) +def test_load_registered_trial(tmp_path: Path, layout: str) -> None: + """Channels are deinterleaved, pages transposed to MATLAB's rows and columns. + + Discards are set to NaN, the variance factor read. The TIFF may hold one + series of all pages (MATLAB's Fast_BigTiff_Write) or one per page + (GIAnT-Python's registration writes each page on its own). + """ + tifffile = pytest.importorskip("tifffile") + n, rows, cols = 400, 6, 9 # MATLAB rows x cols; n > the 4 s median + rng = np.random.default_rng(0) + act = rng.poisson(5, (n, rows, cols)).astype(np.float32) + other = np.full((n, rows, cols), 100, np.float32) + pages = np.empty((2 * n, cols, rows), np.float32) # pages: (col, row) + pages[0::2] = act.transpose(0, 2, 1) + pages[1::2] = other.transpose(0, 2, 1) + stem = "E1T1DMD1" + tif = tmp_path / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif" + if layout == "one_series": + tifffile.imwrite(tif, pages) + else: # as giant_python.registration.outputs writes it + with tifffile.TiffWriter(tif, bigtiff=True) as tw: + for page in pages: + tw.write(page, photometric="minisblack") + with tifffile.TiffFile(tif) as tf: + assert len(tf.series) == 2 * n # imread would read one page + rne = -0.5 + 0.01 * rng.standard_normal(n) + rne[200] += 0.2 + vf = rng.uniform(1, 2, (n, cols, rows)).astype(np.float32) + with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = rne[None, :] + f["slap2/varFacDS"] = vf # MATLAB rows x cols x frames, reversed + tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) + assert tr.movie.shape == (n, rows, cols) and tr.align_hz == 80.0 + keep = ~tr.discard + assert tr.discard[200] and keep.sum() > n - 8 + np.testing.assert_array_equal(tr.movie[keep], act[keep]) + assert np.isnan(tr.movie[tr.discard]).all() + np.testing.assert_allclose(tr.mean_im[..., 1], 100) + np.testing.assert_allclose(tr.var_factor, vf.transpose(0, 2, 1)) + + +@pytest.mark.parametrize("save_tif", [False, True]) +def test_load_registration_movie(tmp_path: Path, save_tif: bool) -> None: + """Movies written by GIAnT-Python's registration, HDF5 or TIFF, load alike. + + HDF5 (the default) or TIFF load as the same frames in MATLAB's rows and + columns. + """ + if save_tif: + pytest.importorskip("tifffile") + from giant_python.registration.outputs import MovieWriter + + n, rows, cols = 50, 6, 9 + rng = np.random.default_rng(1) + act = rng.poisson(5, (n, rows, cols)).astype(np.float32) + act[3, 2, 4] = np.nan + other = np.full((n, rows, cols), 100, np.float32) + stem = "E1T1DMD1" + name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz" + (".tif" if save_tif else ".h5") + movie = MovieWriter(tmp_path / name, (rows, cols), 2 * n, save_tif) + for a, o in zip(act, other): + movie.write(a) + movie.write(o) + movie.close() + movie.tmp.rename(movie.path) + with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = np.full((1, n), -0.5) + tr = load_registered_trial(tmp_path, name, 2) + np.testing.assert_array_equal(tr.movie, act) + np.testing.assert_allclose(tr.mean_im[..., 1], 100) + + +def test_localize_trial_retries_numerical_failures(monkeypatch: pytest.MonkeyPatch) -> None: + """Any failure of the localization itself is retried with the outer rows and columns NaN. + + MATLAB's catch; invalid inputs are not. + """ + import giant_python.extraction.raster.trial as trial_mod + from giant_python.extraction.raster.localization import ( + RasterLocalizationParams, + ) + + movie = np.ones((20, 6, 7), np.float32) + fake = trial_mod.RegisteredTrial(movie, None, np.ones((6, 7, 1)), np.zeros(20, bool), 80.0) + monkeypatch.setattr(trial_mod, "load_registered_trial", lambda *a: fake) + seen = [] + + def flaky(mov: np.ndarray, *args: object, **kwargs: object) -> str: + """Fails like a numerical error unless the edges are NaN. + + Returns + ------- + str + "ok", when the movie's edge columns are all NaN. + + Raises + ------ + ValueError + If the movie's edge columns are not all NaN. + """ + seen.append(bool(np.isnan(mov[:, 0, :]).all())) + if not seen[-1]: + raise ValueError("non-finite residuals") + return "ok" + + monkeypatch.setattr(trial_mod, "localize_sources", flaky) + loc, _ = trial_mod.localize_trial("dir", "x_REGISTERED.tif", 1) + assert loc == "ok" and seen == [False, True] + seen.clear() + p = RasterLocalizationParams(variance_floor=False) + with pytest.raises(ValueError, match="external baseline"): + trial_mod.localize_trial("dir", "x_REGISTERED.tif", 1, p) + assert seen == [] + + +@pytest.mark.parametrize( + "num_channels, activity_channel", + [(2, 0), (2, 3), (0, 1), (2.0, 1), (2, True), (1, -1)], +) +def test_channel_arguments_checked( + tmp_path: Path, num_channels: float, activity_channel: float +) -> None: + """Channel arguments outside 1..num_channels, or not integers, raise before anything is read. + + 0 would select the last channel. + """ + with pytest.raises(ValueError, match="channel"): + load_registered_trial( + tmp_path, + "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", + num_channels, + activity_channel, + ) + + +def test_page_count_not_a_multiple_of_channels(tmp_path: Path) -> None: + """An incomplete last frame is left out, with a warning.""" + tifffile = pytest.importorskip("tifffile") + n, rows, cols = 400, 4, 5 + pages = np.ones((2 * n + 1, cols, rows), np.float32) + stem = "E1T1DMD1" + tifffile.imwrite( + tmp_path / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", + pages, + photometric="minisblack", + ) + with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = np.full((1, n), -0.5) + with pytest.warns(UserWarning, match="not a multiple"): + tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) + assert tr.movie.shape == (n, rows, cols) + + +def test_trial_halves_match_matlab() -> None: + """trialHalves.m of GIAnT-MATLAB: alternating blocks. + + Then the larger half's last frames move over until the halves are equal + to a frame. + """ + cases = { + (10, 3): [1, 1, 1, 2, 2, 2, 1, 1, 2, 2], + (7, 2): [1, 1, 2, 2, 1, 1, 2], + (12, 4): [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2], + (9, 40): [1, 1, 1, 1, 1, 2, 2, 2, 2], + (5, 1): [1, 2, 1, 2, 1], + (1, 3): [1], + (23, 5): [1] * 5 + [2] * 5 + [1] * 5 + [2] * 5 + [1, 1, 2], + } + for (n, block), matlab in cases.items(): + half = trial_halves(n, block) + np.testing.assert_array_equal(half + 1, matlab) + assert abs(int((half == 0).sum()) - int((half == 1).sum())) <= 1 + + +def test_half_mean_images_match_matlab() -> None: + """The half-trial mean images of MATLAB's loadAndProcessTrialAsync. + + On a small movie with missing pixels (exactly: sums of whole counts). + """ + with h5py.File(PLAN_FIXTURE, "r") as f: + g = f["halves"] + stack, half, ref = g["stack"][()], g["half"][()], g["half_ims"][()] + nan_thresh, block = g.attrs["nanThresh"], int(g.attrs["block_len"]) + np.testing.assert_array_equal(trial_halves(stack.shape[0], block), half) + out = half_mean_images(stack, half, nan_thresh) + assert out.dtype == np.float32 and np.isnan(ref).any() + np.testing.assert_array_equal(out, ref) + + +def test_load_registered_trial_half_images(tmp_path: Path) -> None: + """Half images are returned only when asked for. + + Their mean is the trial's mean image where nothing is missing. + """ + n, rows, cols = 120, 5, 6 + rng = np.random.default_rng(3) + data = rng.poisson(20, (2 * n, cols, rows)).astype(np.float32) + stem = "E1T1DMD1" + name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" + with h5py.File(tmp_path / name, "w") as f: + f["data"] = data + with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = np.full((1, n), -0.5) + assert load_registered_trial(tmp_path, name, 2).half_ims is None + tr = load_registered_trial(tmp_path, name, 2, half_ims=True) + assert tr.half_ims.shape == (2, rows, cols, 2) + # 40-frame blocks of 120 frames: the halves hold 60 frames each + np.testing.assert_allclose(tr.half_ims.mean(axis=0), tr.mean_im, rtol=1e-6) + stack = data.transpose(0, 2, 1).reshape(n, 2, rows, cols) + first = np.r_[0:40, 80:100] + np.testing.assert_allclose(tr.half_ims[0, :, :, 1], stack[first, 1].mean(axis=0), rtol=1e-6) + + +def test_channel_means_equal_the_joint_nanmean() -> None: + """The mean image and the missing pixels, one channel at a time, match the joint ones. + + They are those of nanmean and isnan(...).mean over all channels + at once, bit for bit (pixels without samples included). + """ + from giant_python.extraction.raster.trial import _channel_means + + rng = np.random.default_rng(3) + stack = rng.gamma(2.0, 30.0, (97, 3, 11, 13)).astype(np.float32) + stack[rng.random(stack.shape) < 0.3] = np.nan + stack[:, :, 2, 5] = np.nan # no sample in any channel + stack[:, 1, 4, 4] = np.nan # none in one channel + with np.errstate(invalid="ignore"), pytest.warns(RuntimeWarning): + want = np.nanmean(stack, axis=0).transpose(1, 2, 0) + gaps = np.isnan(stack).mean(axis=(0, 1)) + with pytest.warns(RuntimeWarning): + got, missing = _channel_means(stack, 0.33) + assert got.dtype == want.dtype + np.testing.assert_array_equal(got, want) + np.testing.assert_array_equal(missing, gaps > 0.33) diff --git a/tests/raster/test_raster_trial_data.py b/tests/raster/test_raster_trial_data.py index 5cee65a3..b0d579ea 100644 --- a/tests/raster/test_raster_trial_data.py +++ b/tests/raster/test_raster_trial_data.py @@ -1,1223 +1,1351 @@ -"""Tests of the SLAP2 trial loader (SILo's loadTrial and its helpers). - -The helpers are checked against values computed by MATLAB R2024b -(``data/matlab_trial_data.mat``, made by ``data/make_matlab_trial_data.m``), -the frames against slow loops written from the definition, and the whole -loader on small synthetic recordings of a static scene under known motion. -""" - -from collections.abc import Callable, Iterable, Sequence -from pathlib import Path -from typing import Any - -import numpy as np -import pytest -import scipy.io -import torch -from scipy.ndimage import map_coordinates - -from giant_python.extraction.raster import trial_data -from giant_python.extraction.raster.trial_data import ( - OnlineCompensation, - RigidShift, - TrialAlignment, - TrialData, - TrialLoadParams, - block_compensation, - block_edges, - compensation_pad, - finish_pixels, - frame_lines, - frames_at, - labeled_pixels, - load_trial, - medfilt3, - movmean, - nansvd, - online_compensation, - read_alignment, - roi_svd_trace, - upsample_discard, - upsample_motion, -) -from giant_python.io.slap2_raster import RasterLayout, read_raster_samples -from giant_python.registration import multiroi -from giant_python.registration.compensation import MAPPING, line_offsets -from giant_python.registration.frames import FrameFormer, PixelFormer -from tests.registration.synthetic import ( - make_layout, - online_offsets, - scene, - write_recording, -) - -DATA = Path(__file__).parent / "data" / "matlab_trial_data.mat" -MARGIN = 3 # rows and columns of the registered frame around the raster - -Recording = tuple[RasterLayout, np.ndarray, np.ndarray] -"""The ``recording`` fixture: layout, samples and true motion.""" -OnlineRecording = tuple[ - RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray] -] -"""The ``online_recording`` fixture: layout, samples, true motion and online offsets.""" - - -@pytest.fixture(scope="module") -def ref() -> dict[str, Any]: - """Values computed by MATLAB.""" - return scipy.io.loadmat(DATA) - - -@pytest.fixture(scope="module") -def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: - """Layout, samples and true motion of a short recording.""" - path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=500, seed=3) - truth = write_recording(layout, seed=4, invalid=0.02) - samples = read_raster_samples(layout, (0, layout.num_cycles)) - return layout, samples, truth - - -@pytest.fixture(scope="module") -def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: - """Make a recording whose online offsets move the DMD pattern.""" - path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400, seed=5) - online = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=online) - samples = read_raster_samples(layout, (0, layout.num_cycles)) - return layout, samples, truth, online - - -class Noiseless: - """Stands in for the generator of ``write_recording``. - - Samples are 20 times their expected count instead of Poisson draws. - """ - - def __init__(self, seed: int) -> None: - """Keep a real generator for the other draws.""" - self._rng = np.random.Generator(np.random.PCG64(seed)) - - def poisson(self, lam: np.ndarray) -> np.ndarray: - """Return the expected count, scaled to keep whole-number rounding small.""" - return np.round(20 * lam) - - def random(self, n: int) -> np.ndarray: - """Uniform draws (which samples are invalid).""" - return self._rng.random(n) - - -@pytest.fixture(scope="module") -def quiet_online_recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: - """Make a noise-free recording whose online offsets move the DMD pattern. - - What varies in its motion-corrected samples is motion-correction error - (as GIAnT-MATLAB's TestCompensatedExtraction). - """ - from tests.registration import synthetic - - path = tmp_path_factory.mktemp("rec") / "quiet_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=900, seed=5) - online = online_offsets(layout.total_lines) - with pytest.MonkeyPatch.context() as patch: - patch.setattr(synthetic.np.random, "default_rng", Noiseless) - write_recording(layout, seed=6, online=online) - return layout - - -# ---------------------------------------------------------------- MATLAB - - -def test_movmean_matches_smoothdata(ref: dict[str, Any]) -> None: - """Even, odd and fractional windows are placed as smoothdata's.""" - x = ref["mm_x"] - for w, want in zip(ref["mm_w"].ravel(), ref["mm_y"]): - np.testing.assert_allclose(movmean(x, w)[0], want, rtol=1e-13) - full = np.arange(12.0)[None, :] ** 2 # the branch without gaps - gap = full.copy() - gap[0, 3] = np.nan - want = movmean(gap, 4)[0] - keep = np.r_[0:2, 6:12] # windows that do not hold the gap - np.testing.assert_allclose(movmean(full, 4)[0][keep], want[keep]) - assert np.isnan(movmean(np.full((1, 5), np.nan), 3)).all() - - -def test_medfilt3_and_labeled_pixels(ref: dict[str, Any]) -> None: - """medfilt2 is NaN wherever its window holds a NaN; zero padding.""" - got = medfilt3(ref["med_in"]) - np.testing.assert_array_equal(got, ref["med_out"]) - np.testing.assert_array_equal(labeled_pixels(ref["med_in"]), ref["labeled"].astype(bool)) - assert not labeled_pixels(np.full((4, 4), np.nan)).any() - - -def test_upsample_motion_matches_interp1_pchip(ref: dict[str, Any]) -> None: - """Pchip with extrapolation, as interp1. - - Frames without motion left out; one frame's motion used throughout. - """ - x, y = ref["pchip_x"].ravel(), ref["pchip_y"].ravel() - q = ref["pchip_q"].ravel() - got = upsample_motion(x, y, q) - np.testing.assert_allclose(got, ref["pchip_v"].ravel(), rtol=1e-12) - y_gap = y.copy() - y_gap[3] = np.nan # a registered frame without samples - keep = np.arange(y.size) != 3 - np.testing.assert_array_equal( - upsample_motion(x, y_gap, q), upsample_motion(x[keep], y[keep], q) - ) - one = upsample_motion(x[:1], y[:1], q) - np.testing.assert_array_equal(one, np.full(q.size, y[0])) - with pytest.raises(ValueError, match="no motion"): - upsample_motion(x, np.full(x.size, np.nan), q) - - -def test_upsample_discard_and_block_edges(ref: dict[str, Any]) -> None: - """A frame is discarded if either registered frame around it is.""" - d = ref["disc_in"].ravel() > 0 - want = ref["disc_out"].ravel() > 0 - np.testing.assert_array_equal(upsample_discard(d, want.size), want) - assert upsample_discard(np.array([True]), 4).all() - assert not upsample_discard(np.array([False]), 4).any() - np.testing.assert_array_equal(block_edges(5633, 600), ref["blocks"].ravel() - 1) - np.testing.assert_array_equal(block_edges(10, 600), [0, 10]) - - -def test_frame_lines_are_ceil_of_matlab_colon() -> None: - """``ceil(first:dt:last)``, with fractional line ranges.""" - lines = frame_lines(1.0, 300974.0, 53.43333333333334) - assert lines.size == 5633 and lines[0] == 1 - assert lines[-1] <= 300974 < lines[-1] + 54 - np.testing.assert_array_equal(frame_lines(2.5, 20.0, 4.0)[:3], [3, 7, 11]) - - -def test_roi_svd_trace_matches_matlab(ref: dict[str, Any]) -> None: - """Nansvd and the component choice of loadTrial.""" - d = ref["svd_d"] - u, s, v, bg = nansvd(d, 3, 10, 0.33) - np.testing.assert_allclose(s, ref["svd_s"].ravel(), rtol=1e-8) - np.testing.assert_allclose(bg, ref["svd_bg"], rtol=1e-12) - np.testing.assert_allclose((u * s) @ v.T, ref["svd_recon"], rtol=1e-6, atol=1e-8) - np.testing.assert_allclose(roi_svd_trace(d, 0.33), ref["svd_trace"].ravel(), rtol=1e-8) - # a one-pixel ROI has one component; the others are padded - np.testing.assert_allclose(roi_svd_trace(d[4:5], 0.33), ref["svd1_trace"].ravel(), rtol=1e-8) - u1, s1, _, _ = nansvd(d[4:5], 3, 10, 0.33) - assert np.isnan(u1[:, 1:]).all() and np.all(s1[1:] == 0) - # nothing usable: every pixel misses too many frames, or no data - assert np.isnan(roi_svd_trace(np.full((3, 20), np.nan), 0.33)).all() - assert np.isnan(roi_svd_trace(np.zeros((0, 20)), 0.33)).all() - sparse = np.full((3, 20), np.nan) - sparse[:, ::2] = 1.0 - assert np.isnan(roi_svd_trace(sparse, 0.33)).all() - - -def test_nansvd_selects_until_the_choice_is_stable() -> None: - """Rows and columns are left out until the choice no longer changes. - - Leaving a column out can bring a row back, and the rows and columns - kept each miss less than the threshold among the other kept ones. - """ - rng = np.random.default_rng(3) - d = rng.standard_normal((8, 30)) + 5 - d[0, :12] = np.nan # misses 40%: out, until ... - d[:5, :6] = np.nan # ... columns 0-5, missing in most rows, go - u, s, v, bg = nansvd(d, 3, 10, 0.33) - rows, cols = ~np.isnan(u[:, 0]), ~np.isnan(v[:, 0]) - assert not cols[:6].any() and cols[6:].all() - gaps = np.isnan(d) - assert (gaps[np.ix_(rows, cols)].mean(1) < 0.33).all() - assert (gaps[np.ix_(rows, cols)].mean(0) < 0.33).all() - assert (gaps[~rows][:, cols].mean(1) >= 0.33).all() or rows.all() - assert np.isfinite(s).all() and np.isnan(bg[:, :6]).all() - - -@pytest.mark.parametrize("dtype, rtol", [(np.float64, 1e-12), (np.float32, 2e-6)]) -@pytest.mark.parametrize("rows", [2, 512]) -def test_finish_pixels_matches_matlab( - ref: dict[str, Any], dtype: type[np.floating], rtol: float, rows: int -) -> None: - """Discards, outliers and gap filling as at the end of loadTrial. - - A pixel without samples, gaps longer than the window (15 passes over - everything), and the variance multiplier of filled samples. - """ - y = ref["fin_y_in"].transpose(1, 0, 2).astype(dtype) # channels first - finv = ref["fin_finv_in"].astype(dtype) - discard = upsample_discard(ref["fin_discard_in"].ravel() > 0, y.shape[2]) - np.testing.assert_array_equal(discard, ref["fin_discard"].ravel() > 0) - assert int(ref["fin_passes"].ravel()[0]) == 15 - finish_pixels(y, finv, discard, float(ref["fin_window"].ravel()[0]), rows) - np.testing.assert_allclose(y, ref["fin_y"].transpose(1, 0, 2), rtol=rtol, atol=rtol) - np.testing.assert_allclose(finv, ref["fin_finv"], rtol=rtol) - assert not np.isnan(y).any() and not np.isnan(finv).any() - - -def test_finish_pixels_without_gaps_changes_nothing() -> None: - """No discards and no missing samples: data and multiplier are kept.""" - rng = np.random.default_rng(0) - y = 5 + rng.random((2, 7, 40)) - finv = 1 + rng.random((7, 40)) - y0, f0 = y.copy(), finv.copy() - finish_pixels(y, finv, np.zeros(40, bool), 8.0) - np.testing.assert_array_equal(y, y0) - np.testing.assert_array_equal(finv, f0) - - -def test_finish_pixels_rejects_what_it_cannot_fill() -> None: - """A window that reaches no frame ahead never fills a gap at the start. - - MATLAB's loop would not end; and without any sample there is no variance - multiplier to give: both are errors. No pixels: nothing to do. - """ - rng = np.random.default_rng(0) - y = 5 + rng.random((2, 4, 30)) - finv = 1 + rng.random((4, 30)) - discard = np.zeros(30, dtype=bool) - discard[0] = True - with pytest.raises(ValueError, match="cannot fill"): - finish_pixels(y.copy(), finv.copy(), discard, 2.0) - with pytest.raises(ValueError, match="cannot fill"): - finish_pixels(y.copy(), finv.copy(), discard, 0.5) - finish_pixels(y, finv, discard, 3.0) # one frame ahead is enough - assert np.isfinite(y).all() - gap = np.full((1, 2, 30), np.nan) - with pytest.raises(ValueError, match="none of the selected pixels"): - finish_pixels(gap, np.full((2, 30), np.nan), ~discard, 8.0) - empty = np.zeros((2, 0, 30)) - finish_pixels(empty, np.zeros((0, 30)), discard, 2.0) - assert empty.shape == (2, 0, 30) - - -# ------------------------------------------------- frames, by definition - - -def raw_reference( - layout: RasterLayout, - samples: np.ndarray, - times: np.ndarray, - dt: int, - channels: Sequence[int], - shift: Callable[[int], tuple[int, int]] | None = None, -) -> tuple[np.ndarray, np.ndarray]: - """Num and Den images by the definition (slow loops). - - getImages' kernel without the lines exactly ``max(3 dt, P)`` from the - frame, invalid samples left out; ``shift(line) -> (dr, dc)`` moves a - line's samples. Returns ``(channels, frames, rows, cols)`` arrays. - """ - p, total = layout.lines_per_cycle, layout.total_lines - reach = max(3 * dt, p) - shape = (len(channels), len(times), layout.n_rows, layout.n_cols) - num, den = np.zeros(shape), np.zeros(shape) - pr = (layout.slot_pixel - 1) // layout.n_cols - pc = (layout.slot_pixel - 1) % layout.n_cols - for f, t in enumerate(times): - for ln in range(max(1, t - reach + 1), min(total, t + reach - 1) + 1): - wt = np.exp(-abs(t - ln) / dt) - sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) - dr, dc = shift(ln) if shift else (0, 0) - r, c = pr[sel] + dr, pc[sel] + dc - ok = (r >= 0) & (r < layout.n_rows) & (c >= 0) & (c < layout.n_cols) - for k, ch in enumerate(channels): - x = samples[ch, sel, (ln - 1) // p].astype(float) - use = ok & (x != -32768) - np.add.at(num[k, f], (r[use], c[use]), wt * x[use]) - np.add.at(den[k, f], (r[use], c[use]), wt) - return num, den - - -def frames_reference( - num: np.ndarray, - den: np.ndarray, - trim_rows: np.ndarray, - trim_cols: np.ndarray, - r_d: np.ndarray, - c_d: np.ndarray, - m_r: np.ndarray, - m_c: np.ndarray, -) -> tuple[np.ndarray, np.ndarray]: - """slap2FramesAt's interpolation by the definition. - - ``num`` and ``den`` are whole-DMD sums. Returns ``(channels, points, - frames)`` values and ``(points, frames)`` variance multipliers. - """ - rows = slice(trim_rows[0] - 1, trim_rows[-1]) - cols = slice(trim_cols[0] - 1, trim_cols[-1]) - with np.errstate(invalid="ignore", divide="ignore"): - v = (num / den)[:, :, rows, cols] - w = den[0][:, rows, cols] - n1, n2 = w.shape[1:] - n_ch, n_f = v.shape[:2] - y = np.zeros((n_ch, r_d.size, n_f)) - fq = np.zeros((r_d.size, n_f)) - for f in range(n_f): - rr, cc = r_d + m_r[f], c_d + m_c[f] - rf, cf = np.floor(rr), np.floor(cc) - fr, fc = rr - rf, cc - cf - acc_n, acc_d = np.zeros((n_ch, r_d.size)), np.zeros(r_d.size) - for rk, ck, wt in ( - (rf, cf, (1 - fc) * (1 - fr)), - (rf, np.ceil(cc), fc * (1 - fr)), - (np.ceil(rr), cf, (1 - fc) * fr), - (np.ceil(rr), np.ceil(cc), fc * fr), - ): - ok = (rk >= 1) & (rk <= n1) & (ck >= 1) & (ck <= n2) - ri = np.where(ok, rk, 1).astype(int) - 1 - ci = np.where(ok, ck, 1).astype(int) - 1 - fw = np.where(ok, w[f, ri, ci], np.nan) - acc_d += wt * fw - acc_n += wt * fw * np.where(ok, v[:, f, ri, ci], np.nan) - with np.errstate(invalid="ignore", divide="ignore"): - y[:, :, f] = acc_n / acc_d - inv = 1 / acc_d - inv[np.isinf(inv)] = np.nan - fq[:, f] = inv - return y, fq - - -def collect( - parts: Iterable[tuple[slice, torch.Tensor, torch.Tensor]], -) -> tuple[np.ndarray, np.ndarray]: - """All parts of :func:`frames_at` as NumPy arrays.""" - ys, fqs = [], [] - for _, y, fq in parts: - ys.append(y.numpy()) - fqs.append(fq.numpy()) - return np.concatenate(ys, 2), np.concatenate(fqs, 1) - - -def raster_window(layout: RasterLayout) -> tuple[np.ndarray, np.ndarray]: - """One-based DMD rows and columns of the raster's bounding box.""" - rows = (layout.slot_pixel - 1) // layout.n_cols + 1 - cols = (layout.slot_pixel - 1) % layout.n_cols + 1 - return ( - np.arange(rows.min(), rows.max() + 1), - np.arange(cols.min(), cols.max() + 1), - ) - - -def test_exclusive_boundary_and_pixel_sums(recording: Recording) -> None: - """The exclusive kernel leaves out the lines exactly max(3 dt, P) from a frame. - - PixelFormer's sums are FrameFormer's, pixel by pixel. - """ - layout, samples, _ = recording - times, dt = np.array([30, 500, 1777, 3480]), 8 - num, den = raw_reference(layout, samples, times, dt, [1, 0]) - former = FrameFormer(layout, samples, 0, exclusive=True) - s_num, s_den = former.sums(times, dt, [1, 0]) - r, c = former.rows, former.cols - np.testing.assert_allclose(s_num.numpy(), num[:, :, r, c], rtol=1e-12) - np.testing.assert_allclose(s_den.numpy(), den[:, :, r, c], rtol=1e-12) - inclusive = FrameFormer(layout, samples, 0).sums(times, dt, [1, 0])[1] - assert (inclusive.numpy() > s_den.numpy()).any() - for band in (2, 16): - pixel = PixelFormer(layout, samples, 0, exclusive=True, band=band) - ((shift, frames, p_num, p_den),) = pixel.pixel_sums(times, dt, [1, 0]) - assert shift == (0, 0) and list(frames) == [0, 1, 2, 3] - np.testing.assert_allclose(p_num.numpy(), s_num.numpy().transpose(0, 2, 1), rtol=1e-12) - np.testing.assert_allclose(p_den.numpy(), s_den.numpy().transpose(0, 2, 1), rtol=1e-12) - assert (samples == -32768).any() # some sums leave samples out - - -def test_pixel_sums_with_shifts_match_shifted_sums(online_recording: OnlineRecording) -> None: - """Grouped by displacement, as FrameFormer.shifted_sums.""" - layout, samples, _, _ = online_recording - offsets = line_offsets(layout, (1, layout.total_lines)) - comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) - times, dt = np.arange(900, 1500, 97), 8 - args = (times, dt, comp.displacement) - want = list(FrameFormer(layout, samples, 0, exclusive=True).shifted_sums(*args)) - got = list( - PixelFormer(layout, samples, 0, exclusive=True).pixel_sums( - times, dt, None, comp.displacement - ) - ) - assert len(got) == len(want) > 1 - for (s0, f0, n0, d0), (s1, f1, n1, d1) in zip(want, got): - assert s0 == s1 - np.testing.assert_array_equal(f0, f1) - np.testing.assert_allclose(n1.numpy(), n0.numpy().transpose(0, 2, 1), rtol=1e-12) - np.testing.assert_allclose(d1.numpy(), d0.numpy().transpose(0, 2, 1), rtol=1e-12) - - -def view_points( - layout: RasterLayout, step: int = 1 -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Whole-pixel points of a registered frame around the raster.""" - trim_rows, trim_cols = raster_window(layout) - r, c = np.meshgrid( - np.arange(1 - MARGIN, trim_rows.size + MARGIN + 1, step), - np.arange(1 - MARGIN, trim_cols.size + MARGIN + 1, step), - indexing="ij", - ) - return ( - trim_rows, - trim_cols, - r.ravel().astype(float), - c.ravel().astype(float), - ) - - -def test_frames_at_matches_definition(recording: Recording) -> None: - """Frames at whole-pixel and at fractional points. - - With motion that crosses whole pixels and takes points off the image. - """ - layout, samples, _ = recording - trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) - times, dt = np.arange(200, 3300, 61), 8 - rng = np.random.default_rng(1) - m_r = 1.5 * np.sin(np.arange(times.size) / 4) + 0.2 - m_c = rng.uniform(-2.2, 2.2, times.size) - m_r[3], m_c[3] = 1.0, -2.0 # whole-pixel motion: ceil equals floor - m_r[5] = 1 - 1e-12 # within rounding of a whole pixel - num, den = raw_reference(layout, samples, times, dt, [0, 1]) - args = (layout, [0, 1], times, dt, trim_rows, trim_cols) - for dr, dc in ((0.0, 0.0), (0.37, -0.21)): - rq, cq = r_d + dr, c_d + dc - want = frames_reference(num, den, trim_rows, trim_cols, rq, cq, m_r, m_c) - for whole in (True, False): - got = collect(frames_at(*args, rq, cq, m_r, m_c, chunk=7, whole_pixels=whole)) - for g, w in zip(got, want): - np.testing.assert_array_equal(np.isnan(g), np.isnan(w)) - np.testing.assert_allclose(g, w, rtol=1e-10, atol=1e-12) - assert np.isnan(want[0]).any() and not np.isnan(want[0]).all() - - -def test_frames_at_points_off_the_raster(recording: Recording) -> None: - """Points whose neighbours are all outside the image need no sample. - - Every value is missing. - """ - layout, _, _ = recording - trim_rows, trim_cols = raster_window(layout) - r_d = np.array([-40.0, -41.0, trim_rows.size + 30.0]) - c_d = np.array([5.0, -7.0, 3.0]) - times = np.arange(300, 900, 50) - motion = np.linspace(-1.5, 1.5, times.size) - y, fq = collect( - frames_at( - layout, - [0], - times, - 8, - trim_rows, - trim_cols, - r_d, - c_d, - motion, - motion, - ) - ) - assert y.shape == (1, 3, times.size) and fq.shape == (3, times.size) - assert np.isnan(y).all() and np.isnan(fq).all() - none = np.zeros(0) - for whole in (True, False): # no points at all - y, fq = collect( - frames_at( - layout, - [0, 1], - times, - 8, - trim_rows, - trim_cols, - none, - none, - motion, - motion, - whole_pixels=whole, - ) - ) - assert y.shape == (2, 0, times.size) and fq.shape == (0, times.size) - - -def test_frames_at_compensated_matches_definition(online_recording: OnlineRecording) -> None: - """With compensation, each line's samples move by its online offset. - - The offset is relative to the block's reference; samples move also past - the trimmed raster. - """ - layout, samples, _, _ = online_recording - offsets = line_offsets(layout, (1, layout.total_lines)) - comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) - trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) - times, dt = np.arange(3000, 4500, 53), 8 - m_r = 0.8 * np.cos(np.arange(times.size) / 3) - m_c = 0.6 * np.sin(np.arange(times.size) / 5) - 0.3 - comp_b, d_b = block_compensation(comp, times) - assert np.ptp(offsets.x[times - 1]) > 0 # offsets change in the block - pad = compensation_pad(comp_b, layout, times, dt) - assert pad >= 1 and compensation_pad(None, layout, times, dt) == 0 - - def shift(line: int) -> tuple[int, int]: - """Return a line's displacement around the block's reference.""" - return ( - int(offsets.y_eff[line - 1] - comp_b.ref_offset[1]), - int(offsets.x[line - 1] - comp_b.ref_offset[0]), - ) - - num, den = raw_reference(layout, samples, times, dt, [0, 1], shift) - rows = np.arange(trim_rows[0] - pad, trim_rows[-1] + pad + 1) - cols = np.arange(trim_cols[0] - pad, trim_cols[-1] + pad + 1) - want = frames_reference(num, den, rows, cols, r_d + pad, c_d + pad, m_r - d_b[0], m_c - d_b[1]) - got = collect( - frames_at( - layout, - [0, 1], - times, - dt, - trim_rows, - trim_cols, - r_d, - c_d, - m_r - d_b[0], - m_c - d_b[1], - comp_b, - chunk=9, - ) - ) - for g, w in zip(got, want): - np.testing.assert_array_equal(np.isnan(g), np.isnan(w)) - np.testing.assert_allclose(g, w, rtol=1e-10, atol=1e-12) - # the block's reference only moves the frame: around the trial's - # reference, the same points give the same samples - other = collect( - frames_at( - layout, - [0, 1], - times, - dt, - trim_rows, - trim_cols, - r_d, - c_d, - m_r, - m_c, - comp, - chunk=64, - ) - ) - inner = ~np.isnan(got[0]) & ~np.isnan(other[0]) - assert inner.mean() > 0.5 - np.testing.assert_allclose(got[0][inner], other[0][inner], rtol=1e-9) - - -def test_compensation_helpers(online_recording: OnlineRecording) -> None: - """The helpers of onlineCompensation. - - The motion to interpolate is the saved motion plus each registered - frame's offset; blocks take their median. - """ - layout, _, _, (x, y, y_dmd) = online_recording - ds = np.arange(100.0, 9000.0, 20.0) - ref = np.array([2.0, 0.0]) - fx = x[ds.astype(int) - 1].astype(float) - fy = y_dmd[ds.astype(int) - 1].astype(float) - alignment = TrialAlignment( - ds_frames=ds, - motion_r=np.linspace(0, 1, ds.size), - motion_c=np.linspace(1, 0, ds.size), - align_hz=80.0, - view_r=np.arange(1.0, 5.0), - view_c=np.arange(1.0, 5.0), - trim_rows=np.arange(9, 13), - trim_cols=np.arange(11, 15), - compensation={ - "refOffset": ref, - "frameRefX": fx, - "frameRefY": fy, - "mapping": MAPPING, - "yLead": np.array([2.0, 6.0]), - }, - ) - comp, mot_r, mot_c = online_compensation(alignment, layout, (100, 9000), 20) - np.testing.assert_allclose(mot_r, alignment.motion_r + fy - ref[1]) - np.testing.assert_allclose(mot_c, alignment.motion_c + fx - ref[0]) - np.testing.assert_array_equal(comp.offsets.y_eff[99:9000], y_dmd[99:9000]) - dr, dc = comp.displacement(np.array([[150, 4000], [8000, 20_000_000]])) - assert dr.shape == (2, 2) and dr.dtype == np.int64 - assert dr[0, 1] == y_dmd[3999] - 0 and dc[0, 1] == x[3999] - 2 - lines = np.arange(4000, 4400) - comp_b, shift = block_compensation(comp, lines) - med = [np.median(x[lines - 1]), np.median(y_dmd[lines - 1])] - np.testing.assert_array_equal(comp_b.ref_offset, np.round(med)) - assert shift == (comp_b.ref_offset[1] - 0.0, comp_b.ref_offset[0] - 2.0) - assert block_compensation(None, lines) == (None, (0.0, 0.0)) - # without the record: the saved motion, and no compensation - alignment.compensation = None - none, mot_r, _ = online_compensation(alignment, layout, (100, 9000), 20) - assert none is None - np.testing.assert_array_equal(mot_r, alignment.motion_r) - bad = OnlineCompensation(comp.offsets, ref, 0.5 * MAPPING) - with pytest.raises(ValueError, match="integer"): - bad.displacement(lines) - - -# ------------------------------------------------------- the whole loader - - -def loader_inputs( - layout: RasterLayout, - truth: np.ndarray, - shift: tuple[float, float] = (0.0, 0.0), - ds_step: int = 20, -) -> tuple[TrialAlignment, np.ndarray, np.ndarray, list[np.ndarray], np.ndarray, np.ndarray]: - """Alignment, maps and masks for loading a synthetic recording. - - The registered frame is the raster's bounding box with MARGIN pixels - around it; registration's motion is the true motion at its frames. - Returns also the scene where the trial's ``shift`` reads each pixel of - the consensus canvas (``truth``); the mean image is its square / 20 - (and half that in channel 2), so that it has dim and bright parts as a - recording's, and differs from the data it normalizes. - """ - trim_rows, trim_cols = raster_window(layout) - shape = (trim_rows.size + 2 * MARGIN, trim_cols.size + 2 * MARGIN) - ds = np.arange(float(ds_step), layout.total_lines - ds_step, ds_step) - alignment = TrialAlignment( - ds_frames=ds, - motion_r=truth[ds.astype(int) - 1, 0], - motion_c=truth[ds.astype(int) - 1, 1], - align_hz=80.0, - view_r=np.arange(1.0 - MARGIN, trim_rows.size + MARGIN + 1), - view_c=np.arange(1.0 - MARGIN, trim_cols.size + MARGIN + 1), - trim_rows=trim_rows, - trim_cols=trim_cols, - ) - # consensus canvas: two rows and a column larger than this trial's frame - canvas = (shape[0] + 2, shape[1] + 1) - sel = np.zeros(canvas, dtype=bool) - sel[8:15, 9:21] = True - sel[18:21, 25:31] = True - sel[1, 2] = True # in the margin: never sampled - sel[shape[0] + 1, 5] = True # outside this trial's frame - rows = trim_rows[0] - 1 - MARGIN + np.arange(canvas[0]) - cols = trim_cols[0] - 1 - MARGIN + np.arange(canvas[1]) - rr, cc = np.meshgrid(rows + shift[0], cols + shift[1], indexing="ij") - inside = ( - (rr >= trim_rows[0] - 1) - & (rr <= trim_rows[-1] - 1) - & (cc >= trim_cols[0] - 1) - & (cc <= trim_cols[-1] - 1) - ) - image = np.full(canvas, np.nan) - image[inside] = map_coordinates(scene(layout), [rr[inside], cc[inside]], order=1) - mean = np.stack([image**2 / 20, image**2 / 40], 2) - roi_a = np.zeros(canvas, dtype=bool) - roi_a[10:14, 12:17] = True - roi_b = np.zeros(canvas, dtype=bool) - roi_b[0:6, 0:8] = True # partly in the margin - roi_c = np.zeros(canvas, dtype=bool) - roi_c[shape[0] :, :] = True # outside this trial's frame - discard = np.zeros(ds.size, dtype=bool) - discard[40:44] = True - return alignment, sel, mean, [roi_a, roi_b, roi_c], discard, image - - -def test_load_trial_follows_the_scene( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """Motion-corrected samples of a static scene are steady and equal the scene. - - The scene is taken at each pixel's position; traces, discards and filled - samples are as loadTrial makes them. - """ - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - shift = (0.3, -0.4) - alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) - params = TrialLoadParams(block_frames=37, baseline_window_s=0.2) - first, last = 10.0, layout.total_lines - 30.5 - td = load_trial( - layout.files[0], - first, - last, - alignment, - sel, - RigidShift(*shift), - discard, - mean, - rois, - params, - ) - n_f = td.frame_lines.size - assert td.y.shape == (2, sel.sum(), n_f) and td.y.dtype == np.float32 - assert td.finv.shape == (sel.sum(), n_f) and td.photon_scale == 25.0 - np.testing.assert_array_equal(td.frame_lines, frame_lines(first, last, 8.0)) - np.testing.assert_array_equal(td.discard, upsample_discard(discard, n_f)) - assert 0 < td.discard.sum() < 20 - # pixels in MATLAB's column-major order of the map - np.testing.assert_array_equal(td.pixel_rc, np.argwhere(sel.T)[:, ::-1]) - np.testing.assert_allclose(td.trial_rc, td.pixel_rc + np.array(shift)) - want_r = upsample_motion(alignment.ds_frames, alignment.motion_r, td.frame_lines) - np.testing.assert_allclose(td.motion_r, want_r + shift[0]) - assert np.isfinite(td.y).all() and np.isfinite(td.finv).all() - - never = (td.pixel_rc[:, 0] == 1) | (td.pixel_rc[:, 0] == sel.shape[0] - 1) - assert never.sum() == 2 - assert np.all(td.y[:, never] == 0) # no sample: filled from 0 - filled = td.finv > 100 * np.median(td.finv) - assert filled[never].all() and filled[:, td.discard].all() - assert not filled[~never][:, ~td.discard].any() - # 1000 times the mean over all samples, those of discarded frames too - assert np.ptp(td.finv[filled]) == 0 - np.testing.assert_allclose(td.finv[filled][0], 1000 * td.finv[~filled].mean(), rtol=5e-3) - - keep = ~td.discard - got = td.y[:, ~never][:, :, keep].astype(np.float64) * 25.0 - want = image[tuple(td.pixel_rc[~never].T)] - mean_0, mean_1 = got[0].mean(1), got[1].mean(1) - assert np.corrcoef(mean_0, want)[0, 1] > 0.995 - assert np.median(np.abs(mean_0 / want - 1)) < 0.03 - assert np.median(np.abs(mean_1 / (0.5 * want) - 1)) < 0.05 - # steady: temporal SD near Poisson's, far below the spatial SD - assert np.median(got[0].std(1)) < 0.35 * want.std() - - # traces: NaN at discards. Global: the labeled pixels' summed data - # over their summed mean image, times the whole mean image's sum. ROI: - # the same over the ROI's pixels, which is their summed data - shape = alignment.view_shape - view, mean_v = image[: shape[0], : shape[1]], mean[: shape[0], : shape[1]] - lab = labeled_pixels(mean_v[..., 0]) - assert lab.sum() > 20 - assert np.isnan(td.global_f[:, td.discard]).all() - assert np.isfinite(td.global_f[:, keep]).all() - assert td.roi_f.shape == td.roi_fsvd.shape == (3, 2, n_f) - assert np.isnan(td.roi_f[2]).all() and np.isnan(td.roi_fsvd[2]).all() - assert np.isfinite(td.roi_f[1][:, keep]).all() - for k, gain in enumerate((1.0, 0.5)): - m = mean_v[..., k] - want_g = gain * view[lab].sum() / m[lab].sum() * np.nansum(m) - np.testing.assert_allclose(td.global_f[k, keep].mean(), want_g, rtol=0.05) - want_r = gain * view[: shape[0], : shape[1]][rois[0][: shape[0], : shape[1]]].sum() - np.testing.assert_allclose(td.roi_f[0, k, keep].mean(), want_r, rtol=0.03) - np.testing.assert_allclose( - td.roi_fsvd[0, k, keep].mean(), want_r / rois[0].sum(), rtol=0.03 - ) - - # the blocks do not show: one block of all frames gives the same, and - # so does double precision - one = load_trial( - layout.files[0], - first, - last, - alignment, - sel, - RigidShift(*shift), - discard, - mean, - rois, - TrialLoadParams(block_frames=100000, baseline_window_s=0.2), - dtype=np.float64, - ) - np.testing.assert_allclose(td.y, one.y, rtol=2e-6, atol=1e-6) - np.testing.assert_allclose(td.finv, one.finv, rtol=2e-6) - np.testing.assert_allclose(td.global_f, one.global_f, rtol=1e-9, equal_nan=True) - np.testing.assert_allclose(td.roi_fsvd, one.roi_fsvd, rtol=1e-7, equal_nan=True) - - -def test_load_trial_with_a_general_warp( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """A callable warp is evaluated at every pixel. - - The same shift given as a function gives the same data, and an affine - map samples the scene at the mapped positions. - """ - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth) - trim_rows, trim_cols = raster_window(layout) - origin = (trim_rows[0] - 1 - MARGIN, trim_cols[0] - 1 - MARGIN) - args = (layout.files[0], 10.0, 3000.0, alignment, sel) - rest = (discard, mean, rois, TrialLoadParams(baseline_window_s=0.2)) - shift = (0.3, -0.4) - rigid = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) - - def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Apply the shift as a general coordinate map.""" - return r + shift[0], c + shift[1] - - general = load_trial(*args, as_function, *rest, dtype=np.float64) - np.testing.assert_allclose(general.y, rigid.y, rtol=1e-8, atol=1e-10) - np.testing.assert_allclose(general.finv, rigid.finv, rtol=1e-8) - np.testing.assert_allclose(general.motion_r, rigid.motion_r, atol=1e-12) - np.testing.assert_allclose(general.trial_rc, rigid.trial_rc) - - a = np.array([[1.02, 0.015], [-0.01, 0.98]]) - x0 = np.array([12.0, 17.0]) - - def affine(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Apply a stretch and shear about the field's centre, plus a shift.""" - p = a @ (np.stack([r, c]) - x0[:, None]) + x0[:, None] - return p[0] + 0.25, p[1] - 0.15 - - warped = load_trial(*args, affine, *rest, dtype=np.float64) - r_t, c_t = affine(*warped.pixel_rc.T.astype(float)) - np.testing.assert_allclose(warped.trial_rc, np.stack([r_t, c_t], 1)) - img = scene(layout) - want = map_coordinates(img, [origin[0] + r_t, origin[1] + c_t], order=1) - used = np.median(warped.finv, 1) < 100 * np.median(warped.finv) - got = warped.y[0][:, ~warped.discard].mean(1) * 25.0 - assert used.sum() > 80 - assert np.corrcoef(got[used], want[used])[0, 1] > 0.995 - ignored = image[tuple(warped.pixel_rc.T)] # as if the map did nothing - err = np.abs(got[used] - want[used]).mean() - assert err < 0.5 * np.abs(got[used] - ignored[used]).mean() - - -def test_load_trial_reads_selected_pixels_beyond_the_frame( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """The consensus frame may be larger than a trial's registered frame. - - A selected pixel beyond the frame is read where the warp puts it: with a - shift of nine rows up it stays on the raster under the motion, and has - data. - """ - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - shift = (-9.3, 0.2) - alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) - beyond = (alignment.view_shape[0] + 1, 5) - assert sel[beyond] and np.isfinite(image[beyond]) - args = (layout.files[0], 10.0, 3000.0, alignment, sel) - rest = (discard, mean, rois[:1], TrialLoadParams(baseline_window_s=0.2)) - td = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) - k = np.flatnonzero((td.pixel_rc == beyond).all(1))[0] - np.testing.assert_allclose(td.trial_rc[k], np.add(beyond, shift)) - keep = ~td.discard - assert (td.finv[k, keep] < 100 * np.median(td.finv[k])).all() - np.testing.assert_allclose(td.y[0, k, keep].mean() * 25.0, image[beyond], rtol=0.1) - - def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Apply the shift as a general coordinate map.""" - return r + shift[0], c + shift[1] - - general = load_trial(*args, as_function, *rest, dtype=np.float64) - np.testing.assert_allclose(general.y, td.y, rtol=1e-8, atol=1e-10) - np.testing.assert_allclose(general.finv, td.finv, rtol=1e-8) - - -def test_recording_layout_is_read_once_per_file( - recording: Recording, monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Trials of one recording file read its layout once, also when loaded at the same time. - - The trials are a continuous recording's line ranges. A changed file, - another file or a missing one is read again; the loads are the same as - with a layout read every time. - """ - import os - import threading - from concurrent.futures import ThreadPoolExecutor - - layout, _, truth = recording - calls = [] - lock = threading.Lock() - - def counted(path: str | Path) -> RasterLayout: - """Return the fake layout, counting reads.""" - with lock: - calls.append(str(path)) - return layout - - monkeypatch.setattr(trial_data, "raster_layout", counted) - alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) - rest = (discard, mean, rois, TrialLoadParams(baseline_window_s=0.2)) - path = layout.files[0] - - def load(first: float, last: float) -> TrialData: - """One line range of the recording.""" - return load_trial(path, first, last, alignment, sel, RigidShift(), - *rest, dtype=np.float64) # fmt: skip - - a = load(10.0, 2000.0) - b = load(1500.0, 3000.0) - assert calls == [trial_data._layout_path(path)] # read once, absolute - assert a.timings["layout"] <= a.timings["setup"] - # concurrent loads of a new key read it once - other = tmp_path / "copy_DMD1-TRIAL000001.dat" - other.write_bytes(Path(path).read_bytes()) - calls.clear() - with ThreadPoolExecutor(3) as pool: - got = list(pool.map(lambda k: trial_data.recording_layout(other), - range(3))) # fmt: skip - assert calls == [trial_data._layout_path(other)] - assert all(g is layout for g in got) - # a changed file is read again; a missing one every time - stat = other.stat() - os.utime(other, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10**9)) - trial_data.recording_layout(other) - assert calls == [trial_data._layout_path(other)] * 2 - # a relative path is read through its absolute path (and is the same - # key as the absolute one) - rel = tmp_path / "rel_DMD1-TRIAL000001.dat" - rel.write_bytes(b"r") - calls.clear() - here = os.getcwd() - try: - os.chdir(tmp_path) - trial_data.recording_layout(rel.name) - finally: - os.chdir(here) - trial_data.recording_layout(rel) - assert calls == [trial_data._layout_path(rel)] - assert os.path.isabs(calls[0]) - calls.clear() - for _ in range(2): - trial_data.recording_layout(tmp_path / "missing.dat") - assert len(calls) == 2 - # the same loads as reading the layout every time - monkeypatch.setattr(trial_data, "recording_layout", lambda p: layout) - for got, first, last in ((a, 10.0, 2000.0), (b, 1500.0, 3000.0)): - ref = load(first, last) - np.testing.assert_array_equal(got.y, ref.y) - np.testing.assert_array_equal(got.finv, ref.finv) - - -def test_recording_layout_follows_segments_and_metadata( - recording: Recording, monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """A CYCLE-split recording's layout is read again when its segments change. - - That is, when a segment is added or removed or its metadata changes. The - path as given is part of the key (its name decides how the reader opens - it). - """ - import os - - layout = recording[0] - calls = [] - monkeypatch.setattr(trial_data, "raster_layout", lambda path: calls.append(path) or layout) - folder = tmp_path / "split" - folder.mkdir() - first = folder / "rec_DMD1-TRIAL000001-CYCLE-000000.dat" - first.write_bytes(b"x") - meta = folder / "rec_DMD1.meta" - meta.write_bytes(b"m") - (folder / "rec_DMD2-TRIAL000001-CYCLE-000000.dat").write_bytes(b"y") - read = trial_data.recording_layout - read(first), read(first) - assert len(calls) == 1 - names = [n for n, _, _ in trial_data._layout_inputs(first)] - assert names == [first.name, meta.name] # not the other DMD's - second = folder / "rec_DMD1-TRIAL000001-CYCLE-000100.dat" - second.write_bytes(b"z") # a segment added - read(first), read(first) - assert len(calls) == 2 - st = meta.stat() # the metadata changed - os.utime(meta, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - read(first) - assert len(calls) == 3 - second.unlink() # a segment removed - read(first) - assert len(calls) == 4 - # a missing segment of an existing group is read every time - for _ in range(2): - read(second) - assert len(calls) == 6 - # the same absolute path is the same key; a link to the file is not - (folder / "sub").mkdir() - read(str(folder / "sub" / ".." / first.name)) - assert len(calls) == 6 - link = folder / "link_DMD1-TRIAL000001.dat" - try: - os.symlink(first, link) - except (OSError, NotImplementedError): - return # no symbolic links here - read(link) - assert len(calls) == 7 - # a directory link followed by ".." is resolved before the key - elsewhere = tmp_path / "elsewhere" / "deep" - elsewhere.mkdir(parents=True) - (tmp_path / "elsewhere" / first.name).write_bytes(b"other") - dir_link = folder / "dlink" - try: - os.symlink(elsewhere, dir_link, target_is_directory=True) - except (OSError, NotImplementedError): - return - via = str(dir_link) + os.sep + ".." + os.sep + first.name - assert trial_data._layout_path(via) == os.path.join( - os.path.realpath(tmp_path / "elsewhere"), first.name - ) - read(via) - assert len(calls) == 8 # not the cached layout of folder/first - - -def test_load_trial_without_selected_pixels( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """No selected pixel, no ROI and no labeled pixel: empty data, and the traces are missing. - - A selection that is never sampled is an error. - """ - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - alignment, sel, mean, _, discard, _ = loader_inputs(layout, truth) - args = (layout.files[0], 10.0, 2000.0, alignment) - dark = np.full(mean.shape, np.nan) - td = load_trial(*args, np.zeros_like(sel), RigidShift(), discard, dark) - n_f = td.frame_lines.size - assert td.y.shape == (2, 0, n_f) and td.finv.shape == (0, n_f) - assert td.pixel_rc.shape == td.trial_rc.shape == (0, 2) - assert np.isnan(td.global_f).all() and td.roi_f.shape == (0, 2, n_f) - margin = np.zeros_like(sel) - margin[0, :3] = True # never on the raster - with pytest.raises(ValueError, match="none of the selected pixels"): - load_trial(*args, margin, RigidShift(), discard, mean) - - -def test_load_trial_rejects_bad_inputs( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """The activity channel and the mean image must fit the recording.""" - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) - args = (layout.files[0], 10.0, 3000.0, alignment, sel, RigidShift()) - with pytest.raises(ValueError, match="activity_channel"): - load_trial(*args, discard, mean, rois, TrialLoadParams(activity_channel=3)) - with pytest.raises(ValueError, match="2 channels"): - load_trial(*args, discard, mean[..., :1], rois) - for bad in (2.9, 1.0, True, "1"): # not cut to a channel below - with pytest.raises(ValueError, match="must be an integer"): - TrialLoadParams(activity_channel=bad).ordered_channels(2) - assert TrialLoadParams(activity_channel=np.int64(2)).ordered_channels(2) == [1, 0] - - -def test_load_trial_second_activity_channel( - recording: Recording, monkeypatch: pytest.MonkeyPatch -) -> None: - """With activityChannel 2, channel 0 of the data is the file's second channel. - - The global trace stays in the file's order. - """ - layout, _, truth = recording - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) - args = (layout.files[0], 10.0, 2000.0, alignment, sel, RigidShift()) - one = load_trial(*args, discard, mean, rois[:1], dtype=np.float64) - two = load_trial( - *args, - discard, - mean, - rois[:1], - TrialLoadParams(activity_channel=2), - dtype=np.float64, - ) - keep = ~one.discard - np.testing.assert_allclose(two.global_f[:, keep], one.global_f[:, keep], rtol=0.02) - # (the channels' invalid samples differ, and with them the shares of - # the neighbours: equal on average, not sample by sample) - np.testing.assert_allclose( - two.roi_f[0, ::-1][:, keep].mean(1), - one.roi_f[0][:, keep].mean(1), - rtol=0.01, - ) - used = np.median(one.finv, 1) < 100 * np.median(one.finv) - ratio = two.y[0][used][:, keep].mean() / one.y[0][used][:, keep].mean() - assert 0.45 < ratio < 0.55 # channel 2 sees half the scene - - -def test_load_trial_after_compensated_registration( - quiet_online_recording: RasterLayout, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Registered with compensateOnline, the loader undoes the online correction too. - - Samples of the static, noise-free scene vary less than after an - uncompensated registration, none is filled in, and the block size does - not show. - """ - layout = quiet_online_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) - spread, loaded = {}, {} - for comp in (False, True): - params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) - adata = tmp_path / f"{comp}_ALIGNMENTDATA.h5" - multiroi.register_trial(layout.files[0], 1, 6000, tmp_path / f"{comp}.tif", adata, params) - alignment = read_alignment(adata) - assert (alignment.compensation is not None) == comp - assert alignment.view_shape == (20 + 12, 30 + 12) - sel = np.zeros(alignment.view_shape, dtype=bool) - sel[12:20, 14:28] = True - mean = np.ones(alignment.view_shape + (2,)) - discard = np.zeros(alignment.ds_frames.size, dtype=bool) - args = (layout.files[0], 1, 6000, alignment, sel, RigidShift()) - td = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=60)) - y = td.y[0].astype(np.float64) - spread[comp] = np.median(y.std(1)) / y.mean(1).std() - loaded[comp] = (td, args, discard, mean) - assert np.isfinite(td.y).all() - assert (td.finv < 100 * np.median(td.finv)).all() # nothing filled - # temporal SD of a pixel over the spatial SD of the pixels' means - # (measured: 0.044 compensated, 0.074 uncompensated; part of it is - # interpolation error common to both) - assert spread[True] < 0.8 * spread[False] - assert spread[True] < 0.06 - td, args, discard, mean = loaded[True] - other = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=100000)) - np.testing.assert_allclose(td.y, other.y, rtol=1e-5, atol=1e-6) - np.testing.assert_allclose(td.finv, other.finv, rtol=1e-5) - - -def test_read_alignment_orientation(tmp_path: Path) -> None: - """ViewR and viewC are read in MATLAB's orientation. - - This holds for files written column-major (MATLAB, GIAnT-Python) or - row-major. - """ - import h5py - - view_r = np.repeat(np.arange(-2.0, 5.0)[:, None], 4, 1) # 7 x 4 - view_c = np.repeat(np.arange(-1.0, 3.0)[None, :], 7, 0) - for row_major in (False, True): - path = tmp_path / f"{row_major}_ALIGNMENTDATA.h5" - with h5py.File(path, "w") as f: - f["DSframes"] = np.arange(5.0)[None, :] - f["motionDSr"] = np.zeros((1, 5)) - f["motionDSc"] = np.ones((5, 1)) - f["alignHz"] = np.array([[80.0]]) - f["slap2/viewR"] = view_r if row_major else view_r.T - f["slap2/viewC"] = view_c if row_major else view_c.T - f["slap2/trimRows"] = np.arange(3.0, 6.0)[:, None] - f["slap2/trimCols"] = np.arange(8.0, 10.0)[:, None] - f["slap2/onlineCompensation/enabled"] = np.zeros((1, 1), np.int8) - f["row_major"] = np.array([[int(row_major)]], np.uint8) - a = read_alignment(path) - np.testing.assert_array_equal(a.view_r, view_r[:, 0]) - np.testing.assert_array_equal(a.view_c, view_c[0]) - assert a.view_shape == (7, 4) and a.compensation is None - np.testing.assert_array_equal(a.trim_rows, [3, 4, 5]) - assert a.align_hz == 80.0 and a.motion_c.shape == (5,) - - -def test_cuda_matches_cpu(recording: Recording) -> None: - """Frames agree on CUDA and CPU (skipped without a GPU).""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - layout, _, _ = recording - trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) - times = np.arange(200, 3300, 61) - m_r = np.sin(np.arange(times.size) / 4) - out = [] - for dev in ("cpu", "cuda"): - parts = frames_at( - layout, - [0, 1], - times, - 8, - trim_rows, - trim_cols, - r_d, - c_d, - m_r, - m_r, - device=dev, - ) - out.append([(y.cpu().numpy(), f.cpu().numpy()) for _, y, f in parts]) - for (y0, f0), (y1, f1) in zip(*out): - np.testing.assert_allclose(y0, y1, rtol=1e-9, equal_nan=True) - np.testing.assert_allclose(f0, f1, rtol=1e-9, equal_nan=True) +"""Tests of the SLAP2 trial loader (SILo's loadTrial and its helpers). + +The helpers are checked against values computed by MATLAB R2024b +(data/matlab_trial_data.mat, made by data/make_matlab_trial_data.m), +the frames against slow loops written from the definition, and the whole +loader on small synthetic recordings of a static scene under known motion. +""" + +from collections.abc import Callable, Iterable, Sequence +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +import scipy.io +import torch +from scipy.ndimage import map_coordinates + +from giant_python.extraction.raster import trial_data +from giant_python.extraction.raster.trial_data import ( + OnlineCompensation, + RigidShift, + TrialAlignment, + TrialData, + TrialLoadParams, + block_compensation, + block_edges, + compensation_pad, + finish_pixels, + frame_lines, + frames_at, + labeled_pixels, + load_trial, + medfilt3, + movmean, + nansvd, + online_compensation, + read_alignment, + roi_svd_trace, + upsample_discard, + upsample_motion, +) +from giant_python.io.slap2_raster import RasterLayout, read_raster_samples +from giant_python.registration import multiroi +from giant_python.registration.compensation import MAPPING, line_offsets +from giant_python.registration.frames import FrameFormer, PixelFormer +from tests.registration.synthetic import ( + make_layout, + online_offsets, + scene, + write_recording, +) + +DATA = Path(__file__).parent / "data" / "matlab_trial_data.mat" +MARGIN = 3 # rows and columns of the registered frame around the raster + +Recording = tuple[RasterLayout, np.ndarray, np.ndarray] +"""The recording fixture: layout, samples and true motion.""" +OnlineRecording = tuple[ + RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray] +] +"""The online_recording fixture: layout, samples, true motion and online offsets.""" + + +@pytest.fixture(scope="module") +def ref() -> dict[str, Any]: + """Values computed by MATLAB. + + Returns + ------- + dict[str, Any] + The variables of MATLAB's reference file. + """ + return scipy.io.loadmat(DATA) + + +@pytest.fixture(scope="module") +def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: + """Layout, samples and true motion of a short recording. + + Returns + ------- + Recording + The layout, the raster samples and the true motion of the recording. + """ + path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=500, seed=3) + truth = write_recording(layout, seed=4, invalid=0.02) + samples = read_raster_samples(layout, (0, layout.num_cycles)) + return layout, samples, truth + + +@pytest.fixture(scope="module") +def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: + """Make a recording whose online offsets move the DMD pattern. + + Returns + ------- + OnlineRecording + The layout, the raster samples, the true motion and the online offsets. + """ + path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400, seed=5) + online = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=online) + samples = read_raster_samples(layout, (0, layout.num_cycles)) + return layout, samples, truth, online + + +class Noiseless: + """Stands in for the generator of write_recording. + + Samples are 20 times their expected count instead of Poisson draws. + """ + + def __init__(self, seed: int) -> None: + """Keep a real generator for the other draws.""" + self._rng = np.random.Generator(np.random.PCG64(seed)) + + def poisson(self, lam: np.ndarray) -> np.ndarray: + """Return the expected count, scaled to keep whole-number rounding small. + + Returns + ------- + np.ndarray + 20 * lam rounded to whole numbers. + """ + return np.round(20 * lam) + + def random(self, n: int) -> np.ndarray: + """Uniform draws (which samples are invalid). + + Returns + ------- + np.ndarray + n uniform random numbers from the kept generator. + """ + return self._rng.random(n) + + +@pytest.fixture(scope="module") +def quiet_online_recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: + """Make a noise-free recording whose online offsets move the DMD pattern. + + What varies in its motion-corrected samples is motion-correction error + (as GIAnT-MATLAB's TestCompensatedExtraction). + + Returns + ------- + RasterLayout + The layout of the noise-free recording. + """ + from tests.registration import synthetic + + path = tmp_path_factory.mktemp("rec") / "quiet_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=900, seed=5) + online = online_offsets(layout.total_lines) + with pytest.MonkeyPatch.context() as patch: + patch.setattr(synthetic.np.random, "default_rng", Noiseless) + write_recording(layout, seed=6, online=online) + return layout + + +# ---------------------------------------------------------------- MATLAB + + +def test_movmean_matches_smoothdata(ref: dict[str, Any]) -> None: + """Even, odd and fractional windows are placed as smoothdata's.""" + x = ref["mm_x"] + for w, want in zip(ref["mm_w"].ravel(), ref["mm_y"]): + np.testing.assert_allclose(movmean(x, w)[0], want, rtol=1e-13) + full = np.arange(12.0)[None, :] ** 2 # the branch without gaps + gap = full.copy() + gap[0, 3] = np.nan + want = movmean(gap, 4)[0] + keep = np.r_[0:2, 6:12] # windows that do not hold the gap + np.testing.assert_allclose(movmean(full, 4)[0][keep], want[keep]) + assert np.isnan(movmean(np.full((1, 5), np.nan), 3)).all() + + +def test_medfilt3_and_labeled_pixels(ref: dict[str, Any]) -> None: + """medfilt2 is NaN wherever its window holds a NaN; zero padding.""" + got = medfilt3(ref["med_in"]) + np.testing.assert_array_equal(got, ref["med_out"]) + np.testing.assert_array_equal(labeled_pixels(ref["med_in"]), ref["labeled"].astype(bool)) + assert not labeled_pixels(np.full((4, 4), np.nan)).any() + + +def test_upsample_motion_matches_interp1_pchip(ref: dict[str, Any]) -> None: + """Pchip with extrapolation, as interp1. + + Frames without motion left out; one frame's motion used throughout. + """ + x, y = ref["pchip_x"].ravel(), ref["pchip_y"].ravel() + q = ref["pchip_q"].ravel() + got = upsample_motion(x, y, q) + np.testing.assert_allclose(got, ref["pchip_v"].ravel(), rtol=1e-12) + y_gap = y.copy() + y_gap[3] = np.nan # a registered frame without samples + keep = np.arange(y.size) != 3 + np.testing.assert_array_equal( + upsample_motion(x, y_gap, q), upsample_motion(x[keep], y[keep], q) + ) + one = upsample_motion(x[:1], y[:1], q) + np.testing.assert_array_equal(one, np.full(q.size, y[0])) + with pytest.raises(ValueError, match="no motion"): + upsample_motion(x, np.full(x.size, np.nan), q) + + +def test_upsample_discard_and_block_edges(ref: dict[str, Any]) -> None: + """A frame is discarded if either registered frame around it is.""" + d = ref["disc_in"].ravel() > 0 + want = ref["disc_out"].ravel() > 0 + np.testing.assert_array_equal(upsample_discard(d, want.size), want) + assert upsample_discard(np.array([True]), 4).all() + assert not upsample_discard(np.array([False]), 4).any() + np.testing.assert_array_equal(block_edges(5633, 600), ref["blocks"].ravel() - 1) + np.testing.assert_array_equal(block_edges(10, 600), [0, 10]) + + +def test_frame_lines_are_ceil_of_matlab_colon() -> None: + """ceil(first:dt:last), with fractional line ranges.""" + lines = frame_lines(1.0, 300974.0, 53.43333333333334) + assert lines.size == 5633 and lines[0] == 1 + assert lines[-1] <= 300974 < lines[-1] + 54 + np.testing.assert_array_equal(frame_lines(2.5, 20.0, 4.0)[:3], [3, 7, 11]) + + +def test_roi_svd_trace_matches_matlab(ref: dict[str, Any]) -> None: + """Nansvd and the component choice of loadTrial.""" + d = ref["svd_d"] + u, s, v, bg = nansvd(d, 3, 10, 0.33) + np.testing.assert_allclose(s, ref["svd_s"].ravel(), rtol=1e-8) + np.testing.assert_allclose(bg, ref["svd_bg"], rtol=1e-12) + np.testing.assert_allclose((u * s) @ v.T, ref["svd_recon"], rtol=1e-6, atol=1e-8) + np.testing.assert_allclose(roi_svd_trace(d, 0.33), ref["svd_trace"].ravel(), rtol=1e-8) + # a one-pixel ROI has one component; the others are padded + np.testing.assert_allclose(roi_svd_trace(d[4:5], 0.33), ref["svd1_trace"].ravel(), rtol=1e-8) + u1, s1, _, _ = nansvd(d[4:5], 3, 10, 0.33) + assert np.isnan(u1[:, 1:]).all() and np.all(s1[1:] == 0) + # nothing usable: every pixel misses too many frames, or no data + assert np.isnan(roi_svd_trace(np.full((3, 20), np.nan), 0.33)).all() + assert np.isnan(roi_svd_trace(np.zeros((0, 20)), 0.33)).all() + sparse = np.full((3, 20), np.nan) + sparse[:, ::2] = 1.0 + assert np.isnan(roi_svd_trace(sparse, 0.33)).all() + + +def test_nansvd_selects_until_the_choice_is_stable() -> None: + """Rows and columns are left out until the choice no longer changes. + + Leaving a column out can bring a row back, and the rows and columns + kept each miss less than the threshold among the other kept ones. + """ + rng = np.random.default_rng(3) + d = rng.standard_normal((8, 30)) + 5 + d[0, :12] = np.nan # misses 40%: out, until ... + d[:5, :6] = np.nan # ... columns 0-5, missing in most rows, go + u, s, v, bg = nansvd(d, 3, 10, 0.33) + rows, cols = ~np.isnan(u[:, 0]), ~np.isnan(v[:, 0]) + assert not cols[:6].any() and cols[6:].all() + gaps = np.isnan(d) + assert (gaps[np.ix_(rows, cols)].mean(1) < 0.33).all() + assert (gaps[np.ix_(rows, cols)].mean(0) < 0.33).all() + assert (gaps[~rows][:, cols].mean(1) >= 0.33).all() or rows.all() + assert np.isfinite(s).all() and np.isnan(bg[:, :6]).all() + + +@pytest.mark.parametrize("dtype, rtol", [(np.float64, 1e-12), (np.float32, 2e-6)]) +@pytest.mark.parametrize("rows", [2, 512]) +def test_finish_pixels_matches_matlab( + ref: dict[str, Any], dtype: type[np.floating], rtol: float, rows: int +) -> None: + """Discards, outliers and gap filling as at the end of loadTrial. + + A pixel without samples, gaps longer than the window (15 passes over + everything), and the variance multiplier of filled samples. + """ + y = ref["fin_y_in"].transpose(1, 0, 2).astype(dtype) # channels first + finv = ref["fin_finv_in"].astype(dtype) + discard = upsample_discard(ref["fin_discard_in"].ravel() > 0, y.shape[2]) + np.testing.assert_array_equal(discard, ref["fin_discard"].ravel() > 0) + assert int(ref["fin_passes"].ravel()[0]) == 15 + finish_pixels(y, finv, discard, float(ref["fin_window"].ravel()[0]), rows) + np.testing.assert_allclose(y, ref["fin_y"].transpose(1, 0, 2), rtol=rtol, atol=rtol) + np.testing.assert_allclose(finv, ref["fin_finv"], rtol=rtol) + assert not np.isnan(y).any() and not np.isnan(finv).any() + + +def test_finish_pixels_without_gaps_changes_nothing() -> None: + """No discards and no missing samples: data and multiplier are kept.""" + rng = np.random.default_rng(0) + y = 5 + rng.random((2, 7, 40)) + finv = 1 + rng.random((7, 40)) + y0, f0 = y.copy(), finv.copy() + finish_pixels(y, finv, np.zeros(40, bool), 8.0) + np.testing.assert_array_equal(y, y0) + np.testing.assert_array_equal(finv, f0) + + +def test_finish_pixels_rejects_what_it_cannot_fill() -> None: + """A window that reaches no frame ahead never fills a gap at the start. + + MATLAB's loop would not end; and without any sample there is no variance + multiplier to give: both are errors. No pixels: nothing to do. + """ + rng = np.random.default_rng(0) + y = 5 + rng.random((2, 4, 30)) + finv = 1 + rng.random((4, 30)) + discard = np.zeros(30, dtype=bool) + discard[0] = True + with pytest.raises(ValueError, match="cannot fill"): + finish_pixels(y.copy(), finv.copy(), discard, 2.0) + with pytest.raises(ValueError, match="cannot fill"): + finish_pixels(y.copy(), finv.copy(), discard, 0.5) + finish_pixels(y, finv, discard, 3.0) # one frame ahead is enough + assert np.isfinite(y).all() + gap = np.full((1, 2, 30), np.nan) + with pytest.raises(ValueError, match="none of the selected pixels"): + finish_pixels(gap, np.full((2, 30), np.nan), ~discard, 8.0) + empty = np.zeros((2, 0, 30)) + finish_pixels(empty, np.zeros((0, 30)), discard, 2.0) + assert empty.shape == (2, 0, 30) + + +# ------------------------------------------------- frames, by definition + + +def raw_reference( + layout: RasterLayout, + samples: np.ndarray, + times: np.ndarray, + dt: int, + channels: Sequence[int], + shift: Callable[[int], tuple[int, int]] | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Num and Den images by the definition (slow loops). + + getImages' kernel without the lines exactly max(3 dt, P) from the + frame, invalid samples left out; shift(line) -> (dr, dc) moves a + line's samples. Returns (channels, frames, rows, cols) arrays. + + Returns + ------- + num : np.ndarray + The Num images, (channels, frames, rows, cols). + den : np.ndarray + The Den images, (channels, frames, rows, cols). + """ + p, total = layout.lines_per_cycle, layout.total_lines + reach = max(3 * dt, p) + shape = (len(channels), len(times), layout.n_rows, layout.n_cols) + num, den = np.zeros(shape), np.zeros(shape) + pr = (layout.slot_pixel - 1) // layout.n_cols + pc = (layout.slot_pixel - 1) % layout.n_cols + for f, t in enumerate(times): + for ln in range(max(1, t - reach + 1), min(total, t + reach - 1) + 1): + wt = np.exp(-abs(t - ln) / dt) + sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) + dr, dc = shift(ln) if shift else (0, 0) + r, c = pr[sel] + dr, pc[sel] + dc + ok = (r >= 0) & (r < layout.n_rows) & (c >= 0) & (c < layout.n_cols) + for k, ch in enumerate(channels): + x = samples[ch, sel, (ln - 1) // p].astype(float) + use = ok & (x != -32768) + np.add.at(num[k, f], (r[use], c[use]), wt * x[use]) + np.add.at(den[k, f], (r[use], c[use]), wt) + return num, den + + +def frames_reference( + num: np.ndarray, + den: np.ndarray, + trim_rows: np.ndarray, + trim_cols: np.ndarray, + r_d: np.ndarray, + c_d: np.ndarray, + m_r: np.ndarray, + m_c: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """slap2FramesAt's interpolation by the definition. + + num and den are whole-DMD sums. Returns (channels, points, + frames) values and (points, frames) variance multipliers. + + Returns + ------- + y : np.ndarray + The interpolated values, (channels, points, frames). + fq : np.ndarray + The variance multipliers, (points, frames). + """ + rows = slice(trim_rows[0] - 1, trim_rows[-1]) + cols = slice(trim_cols[0] - 1, trim_cols[-1]) + with np.errstate(invalid="ignore", divide="ignore"): + v = (num / den)[:, :, rows, cols] + w = den[0][:, rows, cols] + n1, n2 = w.shape[1:] + n_ch, n_f = v.shape[:2] + y = np.zeros((n_ch, r_d.size, n_f)) + fq = np.zeros((r_d.size, n_f)) + for f in range(n_f): + rr, cc = r_d + m_r[f], c_d + m_c[f] + rf, cf = np.floor(rr), np.floor(cc) + fr, fc = rr - rf, cc - cf + acc_n, acc_d = np.zeros((n_ch, r_d.size)), np.zeros(r_d.size) + for rk, ck, wt in ( + (rf, cf, (1 - fc) * (1 - fr)), + (rf, np.ceil(cc), fc * (1 - fr)), + (np.ceil(rr), cf, (1 - fc) * fr), + (np.ceil(rr), np.ceil(cc), fc * fr), + ): + ok = (rk >= 1) & (rk <= n1) & (ck >= 1) & (ck <= n2) + ri = np.where(ok, rk, 1).astype(int) - 1 + ci = np.where(ok, ck, 1).astype(int) - 1 + fw = np.where(ok, w[f, ri, ci], np.nan) + acc_d += wt * fw + acc_n += wt * fw * np.where(ok, v[:, f, ri, ci], np.nan) + with np.errstate(invalid="ignore", divide="ignore"): + y[:, :, f] = acc_n / acc_d + inv = 1 / acc_d + inv[np.isinf(inv)] = np.nan + fq[:, f] = inv + return y, fq + + +def collect( + parts: Iterable[tuple[slice, torch.Tensor, torch.Tensor]], +) -> tuple[np.ndarray, np.ndarray]: + """All parts of :func:`frames_at` as NumPy arrays. + + Returns + ------- + y : np.ndarray + The values of all parts, joined along the frame axis. + fq : np.ndarray + The variance multipliers of all parts, joined along the frame axis. + """ + ys, fqs = [], [] + for _, y, fq in parts: + ys.append(y.numpy()) + fqs.append(fq.numpy()) + return np.concatenate(ys, 2), np.concatenate(fqs, 1) + + +def raster_window(layout: RasterLayout) -> tuple[np.ndarray, np.ndarray]: + """One-based DMD rows and columns of the raster's bounding box. + + Returns + ------- + rows : np.ndarray + The one-based DMD rows of the bounding box. + cols : np.ndarray + The one-based DMD columns of the bounding box. + """ + rows = (layout.slot_pixel - 1) // layout.n_cols + 1 + cols = (layout.slot_pixel - 1) % layout.n_cols + 1 + return ( + np.arange(rows.min(), rows.max() + 1), + np.arange(cols.min(), cols.max() + 1), + ) + + +def test_exclusive_boundary_and_pixel_sums(recording: Recording) -> None: + """The exclusive kernel leaves out the lines exactly max(3 dt, P) from a frame. + + PixelFormer's sums are FrameFormer's, pixel by pixel. + """ + layout, samples, _ = recording + times, dt = np.array([30, 500, 1777, 3480]), 8 + num, den = raw_reference(layout, samples, times, dt, [1, 0]) + former = FrameFormer(layout, samples, 0, exclusive=True) + s_num, s_den = former.sums(times, dt, [1, 0]) + r, c = former.rows, former.cols + np.testing.assert_allclose(s_num.numpy(), num[:, :, r, c], rtol=1e-12) + np.testing.assert_allclose(s_den.numpy(), den[:, :, r, c], rtol=1e-12) + inclusive = FrameFormer(layout, samples, 0).sums(times, dt, [1, 0])[1] + assert (inclusive.numpy() > s_den.numpy()).any() + for band in (2, 16): + pixel = PixelFormer(layout, samples, 0, exclusive=True, band=band) + ((shift, frames, p_num, p_den),) = pixel.pixel_sums(times, dt, [1, 0]) + assert shift == (0, 0) and list(frames) == [0, 1, 2, 3] + np.testing.assert_allclose(p_num.numpy(), s_num.numpy().transpose(0, 2, 1), rtol=1e-12) + np.testing.assert_allclose(p_den.numpy(), s_den.numpy().transpose(0, 2, 1), rtol=1e-12) + assert (samples == -32768).any() # some sums leave samples out + + +def test_pixel_sums_with_shifts_match_shifted_sums(online_recording: OnlineRecording) -> None: + """Grouped by displacement, as FrameFormer.shifted_sums.""" + layout, samples, _, _ = online_recording + offsets = line_offsets(layout, (1, layout.total_lines)) + comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) + times, dt = np.arange(900, 1500, 97), 8 + args = (times, dt, comp.displacement) + want = list(FrameFormer(layout, samples, 0, exclusive=True).shifted_sums(*args)) + got = list( + PixelFormer(layout, samples, 0, exclusive=True).pixel_sums( + times, dt, None, comp.displacement + ) + ) + assert len(got) == len(want) > 1 + for (s0, f0, n0, d0), (s1, f1, n1, d1) in zip(want, got): + assert s0 == s1 + np.testing.assert_array_equal(f0, f1) + np.testing.assert_allclose(n1.numpy(), n0.numpy().transpose(0, 2, 1), rtol=1e-12) + np.testing.assert_allclose(d1.numpy(), d0.numpy().transpose(0, 2, 1), rtol=1e-12) + + +def view_points( + layout: RasterLayout, step: int = 1 +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Whole-pixel points of a registered frame around the raster. + + Returns + ------- + trim_rows : np.ndarray + The one-based DMD rows of the raster's bounding box. + trim_cols : np.ndarray + The one-based DMD columns of the raster's bounding box. + r : np.ndarray + The row of each point, in the registered frame. + c : np.ndarray + The column of each point, in the registered frame. + """ + trim_rows, trim_cols = raster_window(layout) + r, c = np.meshgrid( + np.arange(1 - MARGIN, trim_rows.size + MARGIN + 1, step), + np.arange(1 - MARGIN, trim_cols.size + MARGIN + 1, step), + indexing="ij", + ) + return ( + trim_rows, + trim_cols, + r.ravel().astype(float), + c.ravel().astype(float), + ) + + +def test_frames_at_matches_definition(recording: Recording) -> None: + """Frames at whole-pixel and at fractional points. + + With motion that crosses whole pixels and takes points off the image. + """ + layout, samples, _ = recording + trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) + times, dt = np.arange(200, 3300, 61), 8 + rng = np.random.default_rng(1) + m_r = 1.5 * np.sin(np.arange(times.size) / 4) + 0.2 + m_c = rng.uniform(-2.2, 2.2, times.size) + m_r[3], m_c[3] = 1.0, -2.0 # whole-pixel motion: ceil equals floor + m_r[5] = 1 - 1e-12 # within rounding of a whole pixel + num, den = raw_reference(layout, samples, times, dt, [0, 1]) + args = (layout, [0, 1], times, dt, trim_rows, trim_cols) + for dr, dc in ((0.0, 0.0), (0.37, -0.21)): + rq, cq = r_d + dr, c_d + dc + want = frames_reference(num, den, trim_rows, trim_cols, rq, cq, m_r, m_c) + for whole in (True, False): + got = collect(frames_at(*args, rq, cq, m_r, m_c, chunk=7, whole_pixels=whole)) + for g, w in zip(got, want): + np.testing.assert_array_equal(np.isnan(g), np.isnan(w)) + np.testing.assert_allclose(g, w, rtol=1e-10, atol=1e-12) + assert np.isnan(want[0]).any() and not np.isnan(want[0]).all() + + +def test_frames_at_points_off_the_raster(recording: Recording) -> None: + """Points whose neighbours are all outside the image need no sample. + + Every value is missing. + """ + layout, _, _ = recording + trim_rows, trim_cols = raster_window(layout) + r_d = np.array([-40.0, -41.0, trim_rows.size + 30.0]) + c_d = np.array([5.0, -7.0, 3.0]) + times = np.arange(300, 900, 50) + motion = np.linspace(-1.5, 1.5, times.size) + y, fq = collect( + frames_at( + layout, + [0], + times, + 8, + trim_rows, + trim_cols, + r_d, + c_d, + motion, + motion, + ) + ) + assert y.shape == (1, 3, times.size) and fq.shape == (3, times.size) + assert np.isnan(y).all() and np.isnan(fq).all() + none = np.zeros(0) + for whole in (True, False): # no points at all + y, fq = collect( + frames_at( + layout, + [0, 1], + times, + 8, + trim_rows, + trim_cols, + none, + none, + motion, + motion, + whole_pixels=whole, + ) + ) + assert y.shape == (2, 0, times.size) and fq.shape == (0, times.size) + + +def test_frames_at_compensated_matches_definition(online_recording: OnlineRecording) -> None: + """With compensation, each line's samples move by its online offset. + + The offset is relative to the block's reference; samples move also past + the trimmed raster. + """ + layout, samples, _, _ = online_recording + offsets = line_offsets(layout, (1, layout.total_lines)) + comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) + trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) + times, dt = np.arange(3000, 4500, 53), 8 + m_r = 0.8 * np.cos(np.arange(times.size) / 3) + m_c = 0.6 * np.sin(np.arange(times.size) / 5) - 0.3 + comp_b, d_b = block_compensation(comp, times) + assert np.ptp(offsets.x[times - 1]) > 0 # offsets change in the block + pad = compensation_pad(comp_b, layout, times, dt) + assert pad >= 1 and compensation_pad(None, layout, times, dt) == 0 + + def shift(line: int) -> tuple[int, int]: + """Return a line's displacement around the block's reference. + + Returns + ------- + tuple[int, int] + The row and column displacement of the line's samples. + """ + return ( + int(offsets.y_eff[line - 1] - comp_b.ref_offset[1]), + int(offsets.x[line - 1] - comp_b.ref_offset[0]), + ) + + num, den = raw_reference(layout, samples, times, dt, [0, 1], shift) + rows = np.arange(trim_rows[0] - pad, trim_rows[-1] + pad + 1) + cols = np.arange(trim_cols[0] - pad, trim_cols[-1] + pad + 1) + want = frames_reference(num, den, rows, cols, r_d + pad, c_d + pad, m_r - d_b[0], m_c - d_b[1]) + got = collect( + frames_at( + layout, + [0, 1], + times, + dt, + trim_rows, + trim_cols, + r_d, + c_d, + m_r - d_b[0], + m_c - d_b[1], + comp_b, + chunk=9, + ) + ) + for g, w in zip(got, want): + np.testing.assert_array_equal(np.isnan(g), np.isnan(w)) + np.testing.assert_allclose(g, w, rtol=1e-10, atol=1e-12) + # the block's reference only moves the frame: around the trial's + # reference, the same points give the same samples + other = collect( + frames_at( + layout, + [0, 1], + times, + dt, + trim_rows, + trim_cols, + r_d, + c_d, + m_r, + m_c, + comp, + chunk=64, + ) + ) + inner = ~np.isnan(got[0]) & ~np.isnan(other[0]) + assert inner.mean() > 0.5 + np.testing.assert_allclose(got[0][inner], other[0][inner], rtol=1e-9) + + +def test_compensation_helpers(online_recording: OnlineRecording) -> None: + """The helpers of onlineCompensation. + + The motion to interpolate is the saved motion plus each registered + frame's offset; blocks take their median. + """ + layout, _, _, (x, y, y_dmd) = online_recording + ds = np.arange(100.0, 9000.0, 20.0) + ref = np.array([2.0, 0.0]) + fx = x[ds.astype(int) - 1].astype(float) + fy = y_dmd[ds.astype(int) - 1].astype(float) + alignment = TrialAlignment( + ds_frames=ds, + motion_r=np.linspace(0, 1, ds.size), + motion_c=np.linspace(1, 0, ds.size), + align_hz=80.0, + view_r=np.arange(1.0, 5.0), + view_c=np.arange(1.0, 5.0), + trim_rows=np.arange(9, 13), + trim_cols=np.arange(11, 15), + compensation={ + "refOffset": ref, + "frameRefX": fx, + "frameRefY": fy, + "mapping": MAPPING, + "yLead": np.array([2.0, 6.0]), + }, + ) + comp, mot_r, mot_c = online_compensation(alignment, layout, (100, 9000), 20) + np.testing.assert_allclose(mot_r, alignment.motion_r + fy - ref[1]) + np.testing.assert_allclose(mot_c, alignment.motion_c + fx - ref[0]) + np.testing.assert_array_equal(comp.offsets.y_eff[99:9000], y_dmd[99:9000]) + dr, dc = comp.displacement(np.array([[150, 4000], [8000, 20_000_000]])) + assert dr.shape == (2, 2) and dr.dtype == np.int64 + assert dr[0, 1] == y_dmd[3999] - 0 and dc[0, 1] == x[3999] - 2 + lines = np.arange(4000, 4400) + comp_b, shift = block_compensation(comp, lines) + med = [np.median(x[lines - 1]), np.median(y_dmd[lines - 1])] + np.testing.assert_array_equal(comp_b.ref_offset, np.round(med)) + assert shift == (comp_b.ref_offset[1] - 0.0, comp_b.ref_offset[0] - 2.0) + assert block_compensation(None, lines) == (None, (0.0, 0.0)) + # without the record: the saved motion, and no compensation + alignment.compensation = None + none, mot_r, _ = online_compensation(alignment, layout, (100, 9000), 20) + assert none is None + np.testing.assert_array_equal(mot_r, alignment.motion_r) + bad = OnlineCompensation(comp.offsets, ref, 0.5 * MAPPING) + with pytest.raises(ValueError, match="integer"): + bad.displacement(lines) + + +# ------------------------------------------------------- the whole loader + + +def loader_inputs( + layout: RasterLayout, + truth: np.ndarray, + shift: tuple[float, float] = (0.0, 0.0), + ds_step: int = 20, +) -> tuple[TrialAlignment, np.ndarray, np.ndarray, list[np.ndarray], np.ndarray, np.ndarray]: + """Alignment, maps and masks for loading a synthetic recording. + + The registered frame is the raster's bounding box with MARGIN pixels + around it; registration's motion is the true motion at its frames. + Returns also the scene where the trial's shift reads each pixel of + the consensus canvas (truth); the mean image is its square / 20 + (and half that in channel 2), so that it has dim and bright parts as a + recording's, and differs from the data it normalizes. + + Returns + ------- + alignment : TrialAlignment + The trial's alignment. + sel : np.ndarray + The bool mask of the selected pixels of the consensus canvas. + mean : np.ndarray + The mean image of the consensus canvas, with a channel in its last axis. + rois : list[np.ndarray] + The ROI masks of the consensus canvas. + discard : np.ndarray + The bool array of discarded frames. + image : np.ndarray + The scene where the trial's shift reads each pixel of the consensus canvas. + """ + trim_rows, trim_cols = raster_window(layout) + shape = (trim_rows.size + 2 * MARGIN, trim_cols.size + 2 * MARGIN) + ds = np.arange(float(ds_step), layout.total_lines - ds_step, ds_step) + alignment = TrialAlignment( + ds_frames=ds, + motion_r=truth[ds.astype(int) - 1, 0], + motion_c=truth[ds.astype(int) - 1, 1], + align_hz=80.0, + view_r=np.arange(1.0 - MARGIN, trim_rows.size + MARGIN + 1), + view_c=np.arange(1.0 - MARGIN, trim_cols.size + MARGIN + 1), + trim_rows=trim_rows, + trim_cols=trim_cols, + ) + # consensus canvas: two rows and a column larger than this trial's frame + canvas = (shape[0] + 2, shape[1] + 1) + sel = np.zeros(canvas, dtype=bool) + sel[8:15, 9:21] = True + sel[18:21, 25:31] = True + sel[1, 2] = True # in the margin: never sampled + sel[shape[0] + 1, 5] = True # outside this trial's frame + rows = trim_rows[0] - 1 - MARGIN + np.arange(canvas[0]) + cols = trim_cols[0] - 1 - MARGIN + np.arange(canvas[1]) + rr, cc = np.meshgrid(rows + shift[0], cols + shift[1], indexing="ij") + inside = ( + (rr >= trim_rows[0] - 1) + & (rr <= trim_rows[-1] - 1) + & (cc >= trim_cols[0] - 1) + & (cc <= trim_cols[-1] - 1) + ) + image = np.full(canvas, np.nan) + image[inside] = map_coordinates(scene(layout), [rr[inside], cc[inside]], order=1) + mean = np.stack([image**2 / 20, image**2 / 40], 2) + roi_a = np.zeros(canvas, dtype=bool) + roi_a[10:14, 12:17] = True + roi_b = np.zeros(canvas, dtype=bool) + roi_b[0:6, 0:8] = True # partly in the margin + roi_c = np.zeros(canvas, dtype=bool) + roi_c[shape[0] :, :] = True # outside this trial's frame + discard = np.zeros(ds.size, dtype=bool) + discard[40:44] = True + return alignment, sel, mean, [roi_a, roi_b, roi_c], discard, image + + +def test_load_trial_follows_the_scene( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """Motion-corrected samples of a static scene are steady and equal the scene. + + The scene is taken at each pixel's position; traces, discards and filled + samples are as loadTrial makes them. + """ + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + shift = (0.3, -0.4) + alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) + params = TrialLoadParams(block_frames=37, baseline_window_s=0.2) + first, last = 10.0, layout.total_lines - 30.5 + td = load_trial( + layout.files[0], + first, + last, + alignment, + sel, + RigidShift(*shift), + discard, + mean, + rois, + params, + ) + n_f = td.frame_lines.size + assert td.y.shape == (2, sel.sum(), n_f) and td.y.dtype == np.float32 + assert td.finv.shape == (sel.sum(), n_f) and td.photon_scale == 25.0 + np.testing.assert_array_equal(td.frame_lines, frame_lines(first, last, 8.0)) + np.testing.assert_array_equal(td.discard, upsample_discard(discard, n_f)) + assert 0 < td.discard.sum() < 20 + # pixels in MATLAB's column-major order of the map + np.testing.assert_array_equal(td.pixel_rc, np.argwhere(sel.T)[:, ::-1]) + np.testing.assert_allclose(td.trial_rc, td.pixel_rc + np.array(shift)) + want_r = upsample_motion(alignment.ds_frames, alignment.motion_r, td.frame_lines) + np.testing.assert_allclose(td.motion_r, want_r + shift[0]) + assert np.isfinite(td.y).all() and np.isfinite(td.finv).all() + + never = (td.pixel_rc[:, 0] == 1) | (td.pixel_rc[:, 0] == sel.shape[0] - 1) + assert never.sum() == 2 + assert np.all(td.y[:, never] == 0) # no sample: filled from 0 + filled = td.finv > 100 * np.median(td.finv) + assert filled[never].all() and filled[:, td.discard].all() + assert not filled[~never][:, ~td.discard].any() + # 1000 times the mean over all samples, those of discarded frames too + assert np.ptp(td.finv[filled]) == 0 + np.testing.assert_allclose(td.finv[filled][0], 1000 * td.finv[~filled].mean(), rtol=5e-3) + + keep = ~td.discard + got = td.y[:, ~never][:, :, keep].astype(np.float64) * 25.0 + want = image[tuple(td.pixel_rc[~never].T)] + mean_0, mean_1 = got[0].mean(1), got[1].mean(1) + assert np.corrcoef(mean_0, want)[0, 1] > 0.995 + assert np.median(np.abs(mean_0 / want - 1)) < 0.03 + assert np.median(np.abs(mean_1 / (0.5 * want) - 1)) < 0.05 + # steady: temporal SD near Poisson's, far below the spatial SD + assert np.median(got[0].std(1)) < 0.35 * want.std() + + # traces: NaN at discards. Global: the labeled pixels' summed data + # over their summed mean image, times the whole mean image's sum. ROI: + # the same over the ROI's pixels, which is their summed data + shape = alignment.view_shape + view, mean_v = image[: shape[0], : shape[1]], mean[: shape[0], : shape[1]] + lab = labeled_pixels(mean_v[..., 0]) + assert lab.sum() > 20 + assert np.isnan(td.global_f[:, td.discard]).all() + assert np.isfinite(td.global_f[:, keep]).all() + assert td.roi_f.shape == td.roi_fsvd.shape == (3, 2, n_f) + assert np.isnan(td.roi_f[2]).all() and np.isnan(td.roi_fsvd[2]).all() + assert np.isfinite(td.roi_f[1][:, keep]).all() + for k, gain in enumerate((1.0, 0.5)): + m = mean_v[..., k] + want_g = gain * view[lab].sum() / m[lab].sum() * np.nansum(m) + np.testing.assert_allclose(td.global_f[k, keep].mean(), want_g, rtol=0.05) + want_r = gain * view[: shape[0], : shape[1]][rois[0][: shape[0], : shape[1]]].sum() + np.testing.assert_allclose(td.roi_f[0, k, keep].mean(), want_r, rtol=0.03) + np.testing.assert_allclose( + td.roi_fsvd[0, k, keep].mean(), want_r / rois[0].sum(), rtol=0.03 + ) + + # the blocks do not show: one block of all frames gives the same, and + # so does double precision + one = load_trial( + layout.files[0], + first, + last, + alignment, + sel, + RigidShift(*shift), + discard, + mean, + rois, + TrialLoadParams(block_frames=100000, baseline_window_s=0.2), + dtype=np.float64, + ) + np.testing.assert_allclose(td.y, one.y, rtol=2e-6, atol=1e-6) + np.testing.assert_allclose(td.finv, one.finv, rtol=2e-6) + np.testing.assert_allclose(td.global_f, one.global_f, rtol=1e-9, equal_nan=True) + np.testing.assert_allclose(td.roi_fsvd, one.roi_fsvd, rtol=1e-7, equal_nan=True) + + +def test_load_trial_with_a_general_warp( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """A callable warp is evaluated at every pixel. + + The same shift given as a function gives the same data, and an affine + map samples the scene at the mapped positions. + """ + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth) + trim_rows, trim_cols = raster_window(layout) + origin = (trim_rows[0] - 1 - MARGIN, trim_cols[0] - 1 - MARGIN) + args = (layout.files[0], 10.0, 3000.0, alignment, sel) + rest = (discard, mean, rois, TrialLoadParams(baseline_window_s=0.2)) + shift = (0.3, -0.4) + rigid = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) + + def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Apply the shift as a general coordinate map. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The shifted rows and columns. + """ + return r + shift[0], c + shift[1] + + general = load_trial(*args, as_function, *rest, dtype=np.float64) + np.testing.assert_allclose(general.y, rigid.y, rtol=1e-8, atol=1e-10) + np.testing.assert_allclose(general.finv, rigid.finv, rtol=1e-8) + np.testing.assert_allclose(general.motion_r, rigid.motion_r, atol=1e-12) + np.testing.assert_allclose(general.trial_rc, rigid.trial_rc) + + a = np.array([[1.02, 0.015], [-0.01, 0.98]]) + x0 = np.array([12.0, 17.0]) + + def affine(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Apply a stretch and shear about the field's centre, plus a shift. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The mapped rows and columns. + """ + p = a @ (np.stack([r, c]) - x0[:, None]) + x0[:, None] + return p[0] + 0.25, p[1] - 0.15 + + warped = load_trial(*args, affine, *rest, dtype=np.float64) + r_t, c_t = affine(*warped.pixel_rc.T.astype(float)) + np.testing.assert_allclose(warped.trial_rc, np.stack([r_t, c_t], 1)) + img = scene(layout) + want = map_coordinates(img, [origin[0] + r_t, origin[1] + c_t], order=1) + used = np.median(warped.finv, 1) < 100 * np.median(warped.finv) + got = warped.y[0][:, ~warped.discard].mean(1) * 25.0 + assert used.sum() > 80 + assert np.corrcoef(got[used], want[used])[0, 1] > 0.995 + ignored = image[tuple(warped.pixel_rc.T)] # as if the map did nothing + err = np.abs(got[used] - want[used]).mean() + assert err < 0.5 * np.abs(got[used] - ignored[used]).mean() + + +def test_load_trial_reads_selected_pixels_beyond_the_frame( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """The consensus frame may be larger than a trial's registered frame. + + A selected pixel beyond the frame is read where the warp puts it: with a + shift of nine rows up it stays on the raster under the motion, and has + data. + """ + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + shift = (-9.3, 0.2) + alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) + beyond = (alignment.view_shape[0] + 1, 5) + assert sel[beyond] and np.isfinite(image[beyond]) + args = (layout.files[0], 10.0, 3000.0, alignment, sel) + rest = (discard, mean, rois[:1], TrialLoadParams(baseline_window_s=0.2)) + td = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) + k = np.flatnonzero((td.pixel_rc == beyond).all(1))[0] + np.testing.assert_allclose(td.trial_rc[k], np.add(beyond, shift)) + keep = ~td.discard + assert (td.finv[k, keep] < 100 * np.median(td.finv[k])).all() + np.testing.assert_allclose(td.y[0, k, keep].mean() * 25.0, image[beyond], rtol=0.1) + + def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Apply the shift as a general coordinate map. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The shifted rows and columns. + """ + return r + shift[0], c + shift[1] + + general = load_trial(*args, as_function, *rest, dtype=np.float64) + np.testing.assert_allclose(general.y, td.y, rtol=1e-8, atol=1e-10) + np.testing.assert_allclose(general.finv, td.finv, rtol=1e-8) + + +def test_recording_layout_is_read_once_per_file( + recording: Recording, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Trials of one recording file read its layout once, also when loaded at the same time. + + The trials are a continuous recording's line ranges. A changed file, + another file or a missing one is read again; the loads are the same as + with a layout read every time. + """ + import os + import threading + from concurrent.futures import ThreadPoolExecutor + + layout, _, truth = recording + calls = [] + lock = threading.Lock() + + def counted(path: str | Path) -> RasterLayout: + """Return the fake layout, counting reads. + + Returns + ------- + RasterLayout + The recording's layout. + """ + with lock: + calls.append(str(path)) + return layout + + monkeypatch.setattr(trial_data, "raster_layout", counted) + alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) + rest = (discard, mean, rois, TrialLoadParams(baseline_window_s=0.2)) + path = layout.files[0] + + def load(first: float, last: float) -> TrialData: + """One line range of the recording. + + Returns + ------- + TrialData + The trial loaded from the line range. + """ + return load_trial(path, first, last, alignment, sel, RigidShift(), + *rest, dtype=np.float64) # fmt: skip + + a = load(10.0, 2000.0) + b = load(1500.0, 3000.0) + assert calls == [trial_data._layout_path(path)] # read once, absolute + assert a.timings["layout"] <= a.timings["setup"] + # concurrent loads of a new key read it once + other = tmp_path / "copy_DMD1-TRIAL000001.dat" + other.write_bytes(Path(path).read_bytes()) + calls.clear() + with ThreadPoolExecutor(3) as pool: + got = list(pool.map(lambda k: trial_data.recording_layout(other), + range(3))) # fmt: skip + assert calls == [trial_data._layout_path(other)] + assert all(g is layout for g in got) + # a changed file is read again; a missing one every time + stat = other.stat() + os.utime(other, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10**9)) + trial_data.recording_layout(other) + assert calls == [trial_data._layout_path(other)] * 2 + # a relative path is read through its absolute path (and is the same + # key as the absolute one) + rel = tmp_path / "rel_DMD1-TRIAL000001.dat" + rel.write_bytes(b"r") + calls.clear() + here = os.getcwd() + try: + os.chdir(tmp_path) + trial_data.recording_layout(rel.name) + finally: + os.chdir(here) + trial_data.recording_layout(rel) + assert calls == [trial_data._layout_path(rel)] + assert os.path.isabs(calls[0]) + calls.clear() + for _ in range(2): + trial_data.recording_layout(tmp_path / "missing.dat") + assert len(calls) == 2 + # the same loads as reading the layout every time + monkeypatch.setattr(trial_data, "recording_layout", lambda p: layout) + for got, first, last in ((a, 10.0, 2000.0), (b, 1500.0, 3000.0)): + ref = load(first, last) + np.testing.assert_array_equal(got.y, ref.y) + np.testing.assert_array_equal(got.finv, ref.finv) + + +def test_recording_layout_follows_segments_and_metadata( + recording: Recording, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """A CYCLE-split recording's layout is read again when its segments change. + + That is, when a segment is added or removed or its metadata changes. The + path as given is part of the key (its name decides how the reader opens + it). + """ + import os + + layout = recording[0] + calls = [] + monkeypatch.setattr(trial_data, "raster_layout", lambda path: calls.append(path) or layout) + folder = tmp_path / "split" + folder.mkdir() + first = folder / "rec_DMD1-TRIAL000001-CYCLE-000000.dat" + first.write_bytes(b"x") + meta = folder / "rec_DMD1.meta" + meta.write_bytes(b"m") + (folder / "rec_DMD2-TRIAL000001-CYCLE-000000.dat").write_bytes(b"y") + read = trial_data.recording_layout + read(first), read(first) + assert len(calls) == 1 + names = [n for n, _, _ in trial_data._layout_inputs(first)] + assert names == [first.name, meta.name] # not the other DMD's + second = folder / "rec_DMD1-TRIAL000001-CYCLE-000100.dat" + second.write_bytes(b"z") # a segment added + read(first), read(first) + assert len(calls) == 2 + st = meta.stat() # the metadata changed + os.utime(meta, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + read(first) + assert len(calls) == 3 + second.unlink() # a segment removed + read(first) + assert len(calls) == 4 + # a missing segment of an existing group is read every time + for _ in range(2): + read(second) + assert len(calls) == 6 + # the same absolute path is the same key; a link to the file is not + (folder / "sub").mkdir() + read(str(folder / "sub" / ".." / first.name)) + assert len(calls) == 6 + link = folder / "link_DMD1-TRIAL000001.dat" + try: + os.symlink(first, link) + except (OSError, NotImplementedError): + return # no symbolic links here + read(link) + assert len(calls) == 7 + # a directory link followed by ".." is resolved before the key + elsewhere = tmp_path / "elsewhere" / "deep" + elsewhere.mkdir(parents=True) + (tmp_path / "elsewhere" / first.name).write_bytes(b"other") + dir_link = folder / "dlink" + try: + os.symlink(elsewhere, dir_link, target_is_directory=True) + except (OSError, NotImplementedError): + return + via = str(dir_link) + os.sep + ".." + os.sep + first.name + assert trial_data._layout_path(via) == os.path.join( + os.path.realpath(tmp_path / "elsewhere"), first.name + ) + read(via) + assert len(calls) == 8 # not the cached layout of folder/first + + +def test_load_trial_without_selected_pixels( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """No selected pixel, no ROI and no labeled pixel: empty data, and the traces are missing. + + A selection that is never sampled is an error. + """ + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + alignment, sel, mean, _, discard, _ = loader_inputs(layout, truth) + args = (layout.files[0], 10.0, 2000.0, alignment) + dark = np.full(mean.shape, np.nan) + td = load_trial(*args, np.zeros_like(sel), RigidShift(), discard, dark) + n_f = td.frame_lines.size + assert td.y.shape == (2, 0, n_f) and td.finv.shape == (0, n_f) + assert td.pixel_rc.shape == td.trial_rc.shape == (0, 2) + assert np.isnan(td.global_f).all() and td.roi_f.shape == (0, 2, n_f) + margin = np.zeros_like(sel) + margin[0, :3] = True # never on the raster + with pytest.raises(ValueError, match="none of the selected pixels"): + load_trial(*args, margin, RigidShift(), discard, mean) + + +def test_load_trial_rejects_bad_inputs( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """The activity channel and the mean image must fit the recording.""" + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) + args = (layout.files[0], 10.0, 3000.0, alignment, sel, RigidShift()) + with pytest.raises(ValueError, match="activity_channel"): + load_trial(*args, discard, mean, rois, TrialLoadParams(activity_channel=3)) + with pytest.raises(ValueError, match="2 channels"): + load_trial(*args, discard, mean[..., :1], rois) + for bad in (2.9, 1.0, True, "1"): # not cut to a channel below + with pytest.raises(ValueError, match="must be an integer"): + TrialLoadParams(activity_channel=bad).ordered_channels(2) + assert TrialLoadParams(activity_channel=np.int64(2)).ordered_channels(2) == [1, 0] + + +def test_load_trial_second_activity_channel( + recording: Recording, monkeypatch: pytest.MonkeyPatch +) -> None: + """With activityChannel 2, channel 0 of the data is the file's second channel. + + The global trace stays in the file's order. + """ + layout, _, truth = recording + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) + args = (layout.files[0], 10.0, 2000.0, alignment, sel, RigidShift()) + one = load_trial(*args, discard, mean, rois[:1], dtype=np.float64) + two = load_trial( + *args, + discard, + mean, + rois[:1], + TrialLoadParams(activity_channel=2), + dtype=np.float64, + ) + keep = ~one.discard + np.testing.assert_allclose(two.global_f[:, keep], one.global_f[:, keep], rtol=0.02) + # (the channels' invalid samples differ, and with them the shares of + # the neighbours: equal on average, not sample by sample) + np.testing.assert_allclose( + two.roi_f[0, ::-1][:, keep].mean(1), + one.roi_f[0][:, keep].mean(1), + rtol=0.01, + ) + used = np.median(one.finv, 1) < 100 * np.median(one.finv) + ratio = two.y[0][used][:, keep].mean() / one.y[0][used][:, keep].mean() + assert 0.45 < ratio < 0.55 # channel 2 sees half the scene + + +def test_load_trial_after_compensated_registration( + quiet_online_recording: RasterLayout, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Registered with compensateOnline, the loader undoes the online correction too. + + Samples of the static, noise-free scene vary less than after an + uncompensated registration, none is filled in, and the block size does + not show. + """ + layout = quiet_online_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) + spread, loaded = {}, {} + for comp in (False, True): + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) + adata = tmp_path / f"{comp}_ALIGNMENTDATA.h5" + multiroi.register_trial(layout.files[0], 1, 6000, tmp_path / f"{comp}.tif", adata, params) + alignment = read_alignment(adata) + assert (alignment.compensation is not None) == comp + assert alignment.view_shape == (20 + 12, 30 + 12) + sel = np.zeros(alignment.view_shape, dtype=bool) + sel[12:20, 14:28] = True + mean = np.ones(alignment.view_shape + (2,)) + discard = np.zeros(alignment.ds_frames.size, dtype=bool) + args = (layout.files[0], 1, 6000, alignment, sel, RigidShift()) + td = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=60)) + y = td.y[0].astype(np.float64) + spread[comp] = np.median(y.std(1)) / y.mean(1).std() + loaded[comp] = (td, args, discard, mean) + assert np.isfinite(td.y).all() + assert (td.finv < 100 * np.median(td.finv)).all() # nothing filled + # temporal SD of a pixel over the spatial SD of the pixels' means + # (measured: 0.044 compensated, 0.074 uncompensated; part of it is + # interpolation error common to both) + assert spread[True] < 0.8 * spread[False] + assert spread[True] < 0.06 + td, args, discard, mean = loaded[True] + other = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=100000)) + np.testing.assert_allclose(td.y, other.y, rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(td.finv, other.finv, rtol=1e-5) + + +def test_read_alignment_orientation(tmp_path: Path) -> None: + """ViewR and viewC are read in MATLAB's orientation. + + This holds for files written column-major (MATLAB, GIAnT-Python) or + row-major. + """ + import h5py + + view_r = np.repeat(np.arange(-2.0, 5.0)[:, None], 4, 1) # 7 x 4 + view_c = np.repeat(np.arange(-1.0, 3.0)[None, :], 7, 0) + for row_major in (False, True): + path = tmp_path / f"{row_major}_ALIGNMENTDATA.h5" + with h5py.File(path, "w") as f: + f["DSframes"] = np.arange(5.0)[None, :] + f["motionDSr"] = np.zeros((1, 5)) + f["motionDSc"] = np.ones((5, 1)) + f["alignHz"] = np.array([[80.0]]) + f["slap2/viewR"] = view_r if row_major else view_r.T + f["slap2/viewC"] = view_c if row_major else view_c.T + f["slap2/trimRows"] = np.arange(3.0, 6.0)[:, None] + f["slap2/trimCols"] = np.arange(8.0, 10.0)[:, None] + f["slap2/onlineCompensation/enabled"] = np.zeros((1, 1), np.int8) + f["row_major"] = np.array([[int(row_major)]], np.uint8) + a = read_alignment(path) + np.testing.assert_array_equal(a.view_r, view_r[:, 0]) + np.testing.assert_array_equal(a.view_c, view_c[0]) + assert a.view_shape == (7, 4) and a.compensation is None + np.testing.assert_array_equal(a.trim_rows, [3, 4, 5]) + assert a.align_hz == 80.0 and a.motion_c.shape == (5,) + + +def test_cuda_matches_cpu(recording: Recording) -> None: + """Frames agree on CUDA and CPU (skipped without a GPU).""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + layout, _, _ = recording + trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) + times = np.arange(200, 3300, 61) + m_r = np.sin(np.arange(times.size) / 4) + out = [] + for dev in ("cpu", "cuda"): + parts = frames_at( + layout, + [0, 1], + times, + 8, + trim_rows, + trim_cols, + r_d, + c_d, + m_r, + m_r, + device=dev, + ) + out.append([(y.cpu().numpy(), f.cpu().numpy()) for _, y, f in parts]) + for (y0, f0), (y1, f1) in zip(*out): + np.testing.assert_allclose(y0, y1, rtol=1e-9, equal_nan=True) + np.testing.assert_allclose(f0, f1, rtol=1e-9, equal_nan=True) diff --git a/tests/registration/__init__.py b/tests/registration/__init__.py index 8733c905..ff03927e 100644 --- a/tests/registration/__init__.py +++ b/tests/registration/__init__.py @@ -1 +1 @@ -"""Tests of SLAP2 raster registration.""" +"""Tests of SLAP2 raster registration.""" diff --git a/tests/registration/synthetic.py b/tests/registration/synthetic.py index d50589d6..c6b5bfc7 100644 --- a/tests/registration/synthetic.py +++ b/tests/registration/synthetic.py @@ -1,208 +1,230 @@ -"""A small synthetic SLAP2 raster recording with known motion. - -The file mimics the raw layout that ``giant_python.io.slap2_raster`` reads: -a header, then cycles of ``P`` lines, each line a header (with online-motion -fields) followed by its samples, channel by channel. The parse-plan side is -given directly as a :class:`RasterLayout`. -""" - -from pathlib import Path - -import numpy as np -from numpy.typing import ArrayLike -from scipy.ndimage import gaussian_filter, map_coordinates - -from giant_python.io.slap2_raster import RasterLayout, lit_mirrors - -HEADER_WORDS = 68 -LINE_HEADER_BYTES = 40 - - -def make_layout( - path: Path, - n_cycles: int, - seed: int = 0, - p: int = 7, - curtain: ArrayLike | None = None, - shear: ArrayLike | None = None, -) -> RasterLayout: - """Layout of a synthetic recording (the data file is not written). - - Pixels of the raster block (rows 8-27, columns 10-39 of a 36 x 50 DMD) - are each assigned to 1-3 of the lines 2..p (line 1 has no samples), in - random order within a line. ``curtain`` ([c1, c2]) and ``shear`` (per - DMD row, default zeros) set the layout's DMD curtain. - """ - rng = np.random.default_rng(seed) - n_rows, n_cols, n_ch = 36, 50, 2 - rr, cc = np.meshgrid(np.arange(8, 28), np.arange(10, 40), indexing="ij") - pix = (rr * n_cols + cc).ravel() + 1 - lines = {line: [] for line in range(1, p + 1)} - for px in pix: - for line in rng.choice(np.arange(2, p + 1), rng.integers(1, 4), False): - lines[int(line)].append(px) - slot_line, slot_pos, slot_pixel, n_per = [], [], [], [] - for line in range(1, p + 1): - ids = np.array(lines[line], dtype=np.int64) - rng.shuffle(ids) - slot_line += [line] * ids.size - slot_pos += list(range(ids.size)) - slot_pixel += list(ids) - n_per.append(ids.size) - n_per = np.array(n_per) - header_words = LINE_HEADER_BYTES // 2 - line_words = header_words + n_ch * n_per - line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) - return RasterLayout( - files=(str(path),), - file_cycles=np.array([n_cycles]), - file_offset_words=np.array([HEADER_WORDS]), - words_per_cycle=int(line_words.sum()), - lines_per_cycle=p, - n_rows=n_rows, - n_cols=n_cols, - num_channels=n_ch, - line_period_s=1 / 1600.0, - line_header_bytes=LINE_HEADER_BYTES, - line_header_words=line_header, - row_base=line_header + header_words, - n_per_channel=n_per, - line_fast_z=np.ones(p, dtype=np.int64), - fast_zs=np.array([-20.0]), - slot_line=np.array(slot_line), - slot_pos=np.array(slot_pos), - slot_pixel=np.array(slot_pixel), - dmd_curtain=None if curtain is None else np.asarray(curtain, float), - line_shear=( - None if curtain is None else np.zeros(n_rows) if shear is None else np.asarray(shear) - ), - ) - - -def scene(layout: RasterLayout, seed: int = 1) -> np.ndarray: - """Smooth random brightness pattern over the DMD (photons/sample).""" - rng = np.random.default_rng(seed) - img = gaussian_filter(rng.random((layout.n_rows, layout.n_cols)), 1.5) - img = (img - img.min()) / (img.max() - img.min()) - return 2.0 + 60.0 * img**2 - - -def motion(n_lines: int, seed: int = 2) -> np.ndarray: - """Known tissue motion ``(lines, 2)`` [rows, cols], within +-2 px.""" - t = np.arange(n_lines) / n_lines - rng = np.random.default_rng(seed) - ph = rng.random(2) * 2 * np.pi - return np.stack( - [ - 1.6 * np.sin(2 * np.pi * 1.3 * t + ph[0]), - 1.2 * np.sin(2 * np.pi * 0.7 * t + ph[1]), - ], - 1, - ) - - -def online_offsets(n_lines: int, seed: int = 4) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Piecewise-constant online offsets and the y they put on the DMD. - - The correction switches every 37-80 lines; at a switch x, y or both - change. The header records both on the switch line; x reaches the DMD - then, y 2 lines earlier (6 when x changes too), as measured on SLAP2. - - Returns - ------- - x, y_header, y_dmd : ndarray of int - Per line (index ``line - 1``). - """ - rng = np.random.default_rng(seed) - x = np.zeros(n_lines, dtype=np.int64) - y = np.zeros(n_lines, dtype=np.int64) - switches = [] - s, cur = 0, (2, 0) - while s < n_lines: - nxt = s + int(rng.integers(37, 81)) - kind = int(rng.integers(3)) # 0: x changes, 1: y changes, 2: both - new = cur - if s: - new = ( - int(rng.integers(1, 4)) if kind != 1 else cur[0], - int(rng.integers(-1, 2)) if kind != 0 else cur[1], - ) - switches.append((s, new[0] != cur[0], new[1] != cur[1])) - x[s:nxt], y[s:nxt] = new - cur, s = new, nxt - y_dmd = y.copy() - for s, x_changed, y_changed in switches: - if y_changed: - lead = 6 if x_changed else 2 - y_dmd[s - lead : s] = y[s] - return x, y, y_dmd - - -def write_recording( - layout: RasterLayout, - seed: int = 3, - invalid: float = 0.0, - online: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None, -) -> np.ndarray: - """Write Poisson samples of the moving scene; return the true motion. - - The sample of pixel (r, c) on line l is the scene at - ``(r - m_r(l), c - m_c(l))``; channel 2 sees 0.5 x the scene. Line - headers record online offsets x = cycle % 3, y = -(cycle % 2) and - z = 0.25 * cycle. A fraction ``invalid`` of samples is -32768. - - With ``online = (x, y_header, y_dmd)`` (see :func:`online_offsets`) the - headers record those offsets and the DMD pattern moves with them, as in - GIAnT-MATLAB's transplant recordings: the sample is the scene at - ``(r + y_dmd(l) - m_r(l), c + x(l) - m_c(l))``. With a DMD curtain in - the layout, samples whose mirror ``(r + y_dmd(l), c + x(l))`` is - behind it get no light (expected count 0). - """ - rng = np.random.default_rng(seed) - p = layout.lines_per_cycle - n_c = layout.num_cycles - n_lines = n_c * p - m = motion(n_lines) - if online is None: - cyc = np.arange(n_lines) // p - x_h, y_h, y_d = cyc % 3, -(cyc % 2), np.zeros(n_lines, np.int64) - shift_x = np.zeros(n_lines, np.int64) - else: - x_h, y_h, y_d = online - shift_x = x_h - img = scene(layout) - words = np.zeros((n_c, layout.words_per_cycle), dtype=np.int16) - pr = (layout.slot_pixel - 1) // layout.n_cols - pc = (layout.slot_pixel - 1) % layout.n_cols - for c in range(n_c): - for line in range(1, p + 1): - hdr = layout.line_header_words[line - 1] - raw = np.zeros(LINE_HEADER_BYTES, dtype=np.uint8) - ln = c * p + line - 1 - raw[20:22] = np.array([x_h[ln]], np.int16).view(np.uint8) - raw[22:24] = np.array([y_h[ln]], np.int16).view(np.uint8) - raw[32:36] = np.array([0.25 * c], np.float32).view(np.uint8) - words[c, hdr : hdr + LINE_HEADER_BYTES // 2] = raw.view(np.int16) - sel = np.flatnonzero(layout.slot_line == line) - if sel.size == 0: - continue - lam = map_coordinates( - img, - [ - pr[sel] + y_d[ln] - m[ln, 0], - pc[sel] + shift_x[ln] - m[ln, 1], - ], - order=1, - mode="nearest", - ) - if layout.dmd_curtain is not None: - lam = lam * lit_mirrors(layout, pr[sel] + y_d[ln], pc[sel] + x_h[ln]) - for ch, gain in enumerate((1.0, 0.5)): - x = rng.poisson(gain * lam).astype(np.int16) - x[rng.random(x.size) < invalid] = -32768 - base = layout.row_base[line - 1] + ch * layout.n_per_channel[line - 1] - words[c, base + layout.slot_pos[sel]] = x - with open(layout.files[0], "wb") as f: - f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) - f.write(words.tobytes()) - return m +"""A small synthetic SLAP2 raster recording with known motion. + +The file mimics the raw layout that giant_python.io.slap2_raster reads: +a header, then cycles of P lines, each line a header (with online-motion +fields) followed by its samples, channel by channel. The parse-plan side is +given directly as a :class:`RasterLayout`. +""" + +from pathlib import Path + +import numpy as np +from numpy.typing import ArrayLike +from scipy.ndimage import gaussian_filter, map_coordinates + +from giant_python.io.slap2_raster import RasterLayout, lit_mirrors + +HEADER_WORDS = 68 +LINE_HEADER_BYTES = 40 + + +def make_layout( + path: Path, + n_cycles: int, + seed: int = 0, + p: int = 7, + curtain: ArrayLike | None = None, + shear: ArrayLike | None = None, +) -> RasterLayout: + """Layout of a synthetic recording (the data file is not written). + + Pixels of the raster block (rows 8-27, columns 10-39 of a 36 x 50 DMD) + are each assigned to 1-3 of the lines 2..p (line 1 has no samples), in + random order within a line. curtain ([c1, c2]) and shear (per + DMD row, default zeros) set the layout's DMD curtain. + + Returns + ------- + RasterLayout + The layout of the synthetic recording. + """ + rng = np.random.default_rng(seed) + n_rows, n_cols, n_ch = 36, 50, 2 + rr, cc = np.meshgrid(np.arange(8, 28), np.arange(10, 40), indexing="ij") + pix = (rr * n_cols + cc).ravel() + 1 + lines = {line: [] for line in range(1, p + 1)} + for px in pix: + for line in rng.choice(np.arange(2, p + 1), rng.integers(1, 4), False): + lines[int(line)].append(px) + slot_line, slot_pos, slot_pixel, n_per = [], [], [], [] + for line in range(1, p + 1): + ids = np.array(lines[line], dtype=np.int64) + rng.shuffle(ids) + slot_line += [line] * ids.size + slot_pos += list(range(ids.size)) + slot_pixel += list(ids) + n_per.append(ids.size) + n_per = np.array(n_per) + header_words = LINE_HEADER_BYTES // 2 + line_words = header_words + n_ch * n_per + line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) + return RasterLayout( + files=(str(path),), + file_cycles=np.array([n_cycles]), + file_offset_words=np.array([HEADER_WORDS]), + words_per_cycle=int(line_words.sum()), + lines_per_cycle=p, + n_rows=n_rows, + n_cols=n_cols, + num_channels=n_ch, + line_period_s=1 / 1600.0, + line_header_bytes=LINE_HEADER_BYTES, + line_header_words=line_header, + row_base=line_header + header_words, + n_per_channel=n_per, + line_fast_z=np.ones(p, dtype=np.int64), + fast_zs=np.array([-20.0]), + slot_line=np.array(slot_line), + slot_pos=np.array(slot_pos), + slot_pixel=np.array(slot_pixel), + dmd_curtain=None if curtain is None else np.asarray(curtain, float), + line_shear=( + None if curtain is None else np.zeros(n_rows) if shear is None else np.asarray(shear) + ), + ) + + +def scene(layout: RasterLayout, seed: int = 1) -> np.ndarray: + """Smooth random brightness pattern over the DMD (photons/sample). + + Returns + ------- + np.ndarray + The brightness of each DMD pixel, of shape (n_rows, n_cols), from 2 to 62. + """ + rng = np.random.default_rng(seed) + img = gaussian_filter(rng.random((layout.n_rows, layout.n_cols)), 1.5) + img = (img - img.min()) / (img.max() - img.min()) + return 2.0 + 60.0 * img**2 + + +def motion(n_lines: int, seed: int = 2) -> np.ndarray: + """Known tissue motion (lines, 2) [rows, cols], within +-2 px. + + Returns + ------- + np.ndarray + The motion of each line, of shape (n_lines, 2): rows, then columns. + """ + t = np.arange(n_lines) / n_lines + rng = np.random.default_rng(seed) + ph = rng.random(2) * 2 * np.pi + return np.stack( + [ + 1.6 * np.sin(2 * np.pi * 1.3 * t + ph[0]), + 1.2 * np.sin(2 * np.pi * 0.7 * t + ph[1]), + ], + 1, + ) + + +def online_offsets(n_lines: int, seed: int = 4) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Piecewise-constant online offsets and the y they put on the DMD. + + The correction switches every 37-80 lines; at a switch x, y or both + change. The header records both on the switch line; x reaches the DMD + then, y 2 lines earlier (6 when x changes too), as measured on SLAP2. + + Returns + ------- + x, y_header, y_dmd : ndarray of int + Per line (index line - 1). + """ + rng = np.random.default_rng(seed) + x = np.zeros(n_lines, dtype=np.int64) + y = np.zeros(n_lines, dtype=np.int64) + switches = [] + s, cur = 0, (2, 0) + while s < n_lines: + nxt = s + int(rng.integers(37, 81)) + kind = int(rng.integers(3)) # 0: x changes, 1: y changes, 2: both + new = cur + if s: + new = ( + int(rng.integers(1, 4)) if kind != 1 else cur[0], + int(rng.integers(-1, 2)) if kind != 0 else cur[1], + ) + switches.append((s, new[0] != cur[0], new[1] != cur[1])) + x[s:nxt], y[s:nxt] = new + cur, s = new, nxt + y_dmd = y.copy() + for s, x_changed, y_changed in switches: + if y_changed: + lead = 6 if x_changed else 2 + y_dmd[s - lead : s] = y[s] + return x, y, y_dmd + + +def write_recording( + layout: RasterLayout, + seed: int = 3, + invalid: float = 0.0, + online: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None, +) -> np.ndarray: + """Write Poisson samples of the moving scene; return the true motion. + + The sample of pixel (r, c) on line l is the scene at + (r - m_r(l), c - m_c(l)); channel 2 sees 0.5 x the scene. Line + headers record online offsets x = cycle % 3, y = -(cycle % 2) and + z = 0.25 * cycle. A fraction invalid of samples is -32768. + + With online = (x, y_header, y_dmd) (see :func:`online_offsets`) the + headers record those offsets and the DMD pattern moves with them, as in + GIAnT-MATLAB's transplant recordings: the sample is the scene at + (r + y_dmd(l) - m_r(l), c + x(l) - m_c(l)). With a DMD curtain in + the layout, samples whose mirror (r + y_dmd(l), c + x(l)) is + behind it get no light (expected count 0). + + Returns + ------- + np.ndarray + The true motion of each line, of shape (lines, 2) [rows, cols]. + """ + rng = np.random.default_rng(seed) + p = layout.lines_per_cycle + n_c = layout.num_cycles + n_lines = n_c * p + m = motion(n_lines) + if online is None: + cyc = np.arange(n_lines) // p + x_h, y_h, y_d = cyc % 3, -(cyc % 2), np.zeros(n_lines, np.int64) + shift_x = np.zeros(n_lines, np.int64) + else: + x_h, y_h, y_d = online + shift_x = x_h + img = scene(layout) + words = np.zeros((n_c, layout.words_per_cycle), dtype=np.int16) + pr = (layout.slot_pixel - 1) // layout.n_cols + pc = (layout.slot_pixel - 1) % layout.n_cols + for c in range(n_c): + for line in range(1, p + 1): + hdr = layout.line_header_words[line - 1] + raw = np.zeros(LINE_HEADER_BYTES, dtype=np.uint8) + ln = c * p + line - 1 + raw[20:22] = np.array([x_h[ln]], np.int16).view(np.uint8) + raw[22:24] = np.array([y_h[ln]], np.int16).view(np.uint8) + raw[32:36] = np.array([0.25 * c], np.float32).view(np.uint8) + words[c, hdr : hdr + LINE_HEADER_BYTES // 2] = raw.view(np.int16) + sel = np.flatnonzero(layout.slot_line == line) + if sel.size == 0: + continue + lam = map_coordinates( + img, + [ + pr[sel] + y_d[ln] - m[ln, 0], + pc[sel] + shift_x[ln] - m[ln, 1], + ], + order=1, + mode="nearest", + ) + if layout.dmd_curtain is not None: + lam = lam * lit_mirrors(layout, pr[sel] + y_d[ln], pc[sel] + x_h[ln]) + for ch, gain in enumerate((1.0, 0.5)): + x = rng.poisson(gain * lam).astype(np.int16) + x[rng.random(x.size) < invalid] = -32768 + base = layout.row_base[line - 1] + ch * layout.n_per_channel[line - 1] + words[c, base + layout.slot_pos[sel]] = x + with open(layout.files[0], "wb") as f: + f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) + f.write(words.tobytes()) + return m diff --git a/tests/registration/test_cli.py b/tests/registration/test_cli.py index 083f1ee4..4f2bf651 100644 --- a/tests/registration/test_cli.py +++ b/tests/registration/test_cli.py @@ -1,89 +1,96 @@ -"""The ``giant register`` command's summary and exit code.""" - -import numpy as np -import pytest - -from giant_python import cli -from giant_python.models.params import MultiRoiRegistrationParams - - -@pytest.mark.parametrize( - "failed,names,recorded,code", - [ - ([[False, False]], [["a.h5", "b.h5"]], [["x", "y"]], 0), - ([[False, True]], [["a.h5", "b.h5"]], [["x", "y"]], 0), - ([[True, True]], [["a.h5", ""]], [["x", "y"]], 1), - ([[False, True]], [["a.h5", ""]], [["x", ""]], 0), - ], -) -def test_register_reports_failed_trials( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - failed: list[list[bool]], - names: list[list[str]], - recorded: list[list[str]], - code: int, -) -> None: - """Flagged trials are listed. - - A trial that raised makes the exit code nonzero; a cell without a - recording is listed as skipped. - """ - from types import SimpleNamespace - - from giant_python.io import trial_table - from giant_python.pipeline import register - - fields = { - "registration_failed": np.array(failed), - "fn_reg_ds": np.array(names, dtype=object), - "fn_adata": np.array(names, dtype=object), - "align_params": {}, - } - monkeypatch.setattr(register, "register_multiroi", lambda *a, **k: fields) - table = SimpleNamespace(filename=np.array(recorded, dtype=object)) - monkeypatch.setattr(trial_table, "read_trial_table", lambda path: table) - assert cli.main(["register", "trial_table.h5"]) == code - out, err = capsys.readouterr() - n_rec = sum(r != "" for r in recorded[0]) - registered = sum(n != "" for n in names[0]) - assert f"{registered} of {n_rec} trials registered" in out - flagged = any(f and n for f, n in zip(failed[0], names[0])) - assert ("registrationFailed" in out) == flagged - assert ("trial 2 (path 1)" in err) == (code == 1) - assert ("No recording (skipped): trial 2 (path 1)" in out) == (n_rec == 1) - - -@pytest.mark.parametrize("flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)]) -def test_register_movie_format( - monkeypatch: pytest.MonkeyPatch, flags: list[str], save_tif: bool -) -> None: - """Registered movies are HDF5 unless ``--tif`` asks for TIFF.""" - from types import SimpleNamespace - - from giant_python.io import trial_table - from giant_python.pipeline import register - - seen = {} - - def fake(table: str, params: MultiRoiRegistrationParams, **kwargs: object) -> dict[str, object]: - """Fake a registration that records its parameters and writes nothing.""" - seen["params"] = params - return { - "registration_failed": np.array([[False]]), - "fn_reg_ds": np.array([["a"]], dtype=object), - "fn_adata": np.array([["a"]], dtype=object), - "align_params": {}, - } - - monkeypatch.setattr(register, "register_multiroi", fake) - table = SimpleNamespace(filename=np.array([["x"]], dtype=object)) - monkeypatch.setattr(trial_table, "read_trial_table", lambda path: table) - assert cli.main(["register", "trial_table.h5", *flags]) == 0 - assert seen["params"].save_tif is save_tif - - -def test_register_movie_formats_exclusive() -> None: - """``--tif`` and ``--h5`` cannot be combined.""" - with pytest.raises(SystemExit): - cli.main(["register", "trial_table.h5", "--tif", "--h5"]) +"""The giant register command's summary and exit code.""" + +import numpy as np +import pytest + +from giant_python import cli +from giant_python.models.params import MultiRoiRegistrationParams + + +@pytest.mark.parametrize( + "failed,names,recorded,code", + [ + ([[False, False]], [["a.h5", "b.h5"]], [["x", "y"]], 0), + ([[False, True]], [["a.h5", "b.h5"]], [["x", "y"]], 0), + ([[True, True]], [["a.h5", ""]], [["x", "y"]], 1), + ([[False, True]], [["a.h5", ""]], [["x", ""]], 0), + ], +) +def test_register_reports_failed_trials( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + failed: list[list[bool]], + names: list[list[str]], + recorded: list[list[str]], + code: int, +) -> None: + """Flagged trials are listed. + + A trial that raised makes the exit code nonzero; a cell without a + recording is listed as skipped. + """ + from types import SimpleNamespace + + from giant_python.io import trial_table + from giant_python.pipeline import register + + fields = { + "registration_failed": np.array(failed), + "fn_reg_ds": np.array(names, dtype=object), + "fn_adata": np.array(names, dtype=object), + "align_params": {}, + } + monkeypatch.setattr(register, "register_multiroi", lambda *a, **k: fields) + table = SimpleNamespace(filename=np.array(recorded, dtype=object)) + monkeypatch.setattr(trial_table, "read_trial_table", lambda path: table) + assert cli.main(["register", "trial_table.h5"]) == code + out, err = capsys.readouterr() + n_rec = sum(r != "" for r in recorded[0]) + registered = sum(n != "" for n in names[0]) + assert f"{registered} of {n_rec} trials registered" in out + flagged = any(f and n for f, n in zip(failed[0], names[0])) + assert ("registrationFailed" in out) == flagged + assert ("trial 2 (path 1)" in err) == (code == 1) + assert ("No recording (skipped): trial 2 (path 1)" in out) == (n_rec == 1) + + +@pytest.mark.parametrize("flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)]) +def test_register_movie_format( + monkeypatch: pytest.MonkeyPatch, flags: list[str], save_tif: bool +) -> None: + """Registered movies are HDF5 unless --tif asks for TIFF.""" + from types import SimpleNamespace + + from giant_python.io import trial_table + from giant_python.pipeline import register + + seen = {} + + def fake(table: str, params: MultiRoiRegistrationParams, **kwargs: object) -> dict[str, object]: + """Fake a registration that records its parameters and writes nothing. + + Returns + ------- + dict[str, object] + A registration result for one trial: registration_failed (False), + fn_reg_ds, fn_adata and empty align_params. + """ + seen["params"] = params + return { + "registration_failed": np.array([[False]]), + "fn_reg_ds": np.array([["a"]], dtype=object), + "fn_adata": np.array([["a"]], dtype=object), + "align_params": {}, + } + + monkeypatch.setattr(register, "register_multiroi", fake) + table = SimpleNamespace(filename=np.array([["x"]], dtype=object)) + monkeypatch.setattr(trial_table, "read_trial_table", lambda path: table) + assert cli.main(["register", "trial_table.h5", *flags]) == 0 + assert seen["params"].save_tif is save_tif + + +def test_register_movie_formats_exclusive() -> None: + """--tif and --h5 cannot be combined.""" + with pytest.raises(SystemExit): + cli.main(["register", "trial_table.h5", "--tif", "--h5"]) diff --git a/tests/registration/test_compensation.py b/tests/registration/test_compensation.py index 66dc91fb..7389f024 100644 --- a/tests/registration/test_compensation.py +++ b/tests/registration/test_compensation.py @@ -1,206 +1,229 @@ -"""Online-motion compensation (compensateOnline) on synthetic data.""" - -from collections.abc import Sequence -from pathlib import Path - -import numpy as np -import pytest -import torch - -from giant_python.io.slap2_raster import RasterLayout -from giant_python.registration import multiroi -from giant_python.registration.compensation import ( - LineOffsets, - dmd_y, - frame_offsets, - line_offsets, -) -from giant_python.registration.sources import make_source - -from .synthetic import make_layout, online_offsets, write_recording - -# the layout, its online offsets (x, y_header, y_dmd) and the true motion -OnlineRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] - - -def test_dmd_y_leads_header_switches() -> None: - """Y switches 2 lines early, 6 with x, never before the last switch.""" - x = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) - y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 7, 7]) - sw = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 - got = dmd_y(x, y, sw) - # y switch at line index 8 (x unchanged): lines 6-7 take it; the - # switch at 14 (x unchanged): lines 12-13; none before index 10 (x) - want = y.copy() - want[6:8] = 5 - want[12:14] = 7 - np.testing.assert_array_equal(got, want) - x2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 3, 3]) - y2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 4, 4]) - sw2 = np.array([9]) - np.testing.assert_array_equal(dmd_y(x2, y2, sw2), [0, 0, 4, 4, 4, 4, 4, 4, 4, 4]) - - -@pytest.fixture(scope="module") -def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: - """Synthetic recording whose online offsets move the DMD pattern.""" - path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400, seed=5) - online = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=online) - return layout, online, truth - - -def test_line_offsets_reproduce_dmd_timing(online_recording: OnlineRecording) -> None: - """Headers decode, y_eff equals the generator's DMD y.""" - layout, (x, y, y_dmd), _ = online_recording - off = line_offsets(layout, (1, layout.total_lines)) - np.testing.assert_array_equal(off.x, x) - np.testing.assert_array_equal(off.y, y) - np.testing.assert_array_equal(off.y_eff, y_dmd) - part = line_offsets(layout, (2000, 3000)) - lo, hi = part.lines_read - assert lo <= 2000 - 7 and hi >= 3000 + 7 - # exact on the requested lines - np.testing.assert_array_equal(part.y_eff[1999:3000], y_dmd[1999:3000]) - assert part.x[0] == x[lo - 1] and part.x[-1] == x[hi - 1] - - -def frames_reference( - layout: RasterLayout, - former_samples: np.ndarray, - offsets: LineOffsets, - times: np.ndarray, - dt: int, - box: Sequence[int], -) -> tuple[np.ndarray, np.ndarray]: - """Compensated weighted means by the definition (slow loops).""" - p, total = layout.lines_per_cycle, layout.total_lines - r0, r1, c0, c1 = box - h, w = r1 - r0 + 1, c1 - c0 + 1 - refs = frame_offsets(offsets, times, dt, p) - dt_read = max(3 * dt, p) - num = np.zeros((layout.num_channels, len(times), h, w)) - den = np.zeros_like(num) - pr = (layout.slot_pixel - 1) // layout.n_cols - pc = (layout.slot_pixel - 1) % layout.n_cols - for f, t in enumerate(times): - for ln in range(max(1, t - dt_read), min(total, t + dt_read) + 1): - wt = np.exp(-abs(t - ln) / dt) - sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) - r = pr[sel] + offsets.y_eff[ln - 1] - refs[f, 1] - r0 - c = pc[sel] + offsets.x[ln - 1] - refs[f, 0] - c0 - ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) - for ch in range(layout.num_channels): - xv = former_samples[ch, sel, (ln - 1) // p].astype(float) - np.add.at(num[ch, f], (r[ok], c[ok]), wt * xv[ok]) - np.add.at(den[ch, f], (r[ok], c[ok]), wt) - return num, den - - -def test_compensated_frames_match_definition(online_recording: OnlineRecording) -> None: - """Each sample moves by its line's offset minus the frame's.""" - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.registration.frames import FrameFormer - - layout, _, _ = online_recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - former = FrameFormer(layout, samples, 0) - times = np.array([400, 1210, 3333, 5000]) - src = make_source(layout, former, 300, 6000, times, times, 20, True) - vals, fresh = src.frames(times) - box = ( - former.rows.min(), - former.rows.max(), - former.cols.min(), - former.cols.max(), - ) - num, den = frames_reference(layout, samples, src.compensation, times, 20, box) - with np.errstate(invalid="ignore"): - want = (num / den).astype(np.float32) - got = src.window.image(vals, float("nan")).numpy() - np.testing.assert_array_equal(np.isnan(got), np.isnan(want)) - np.testing.assert_allclose(got, want, rtol=1e-6) - np.testing.assert_allclose(src.window.image(fresh, 0.0).numpy(), den[0], rtol=1e-6) - - -def total_motion_error( - res: multiroi.TrialRegistration, - adata: dict, - truth: np.ndarray, - header: tuple[np.ndarray, np.ndarray], -) -> float: - """RMS error of the total motion against the kernel-averaged truth. - - Compensated: motion plus each frame's reference offset (relative to - ``refOffset``). Uncompensated: motion plus the header offsets at the - frame's line (``header = (x, y)``), as GIAnT-MATLAB's transplant - evaluation adds them. - """ - dt = 20 - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - true = np.stack([np.convolve(truth[:, i], kernel, "same") for i in (0, 1)])[ - :, res.ds_frames - 1 - ] - est = np.stack([res.motion_r, res.motion_c]) - oc = adata["slap2"]["onlineCompensation"] - if oc["enabled"].item(): - ref = oc["refOffset"].ravel() - est = est + np.stack([ - oc["frameRefY"].ravel() - ref[1], - oc["frameRefX"].ravel() - ref[0], - ]) - else: - x, y = header - est = est + np.stack([y[res.ds_frames - 1], x[res.ds_frames - 1]]) - err = est - true - err -= np.median(err, axis=1, keepdims=True) - return float(np.sqrt(np.mean(err**2))) - - -def test_compensated_registration_recovers_motion( - online_recording: OnlineRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Total motion follows the truth with compensation, not without.""" - from giant_python.io.hdf5 import load_struct_h5 - - layout, (x, y, _), truth = online_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - errors = {} - for comp in (True, False): - params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) - res = multiroi.register_trial( - layout.files[0], - 1, - 9000, - tmp_path / f"{comp}.tif", - tmp_path / f"{comp}.h5", - params, - ) - adata = load_struct_h5(tmp_path / f"{comp}.h5") - errors[comp] = total_motion_error(res, adata, truth, (x, y)) - oc = adata["slap2"]["onlineCompensation"] - assert oc["enabled"].item() == int(comp) - oc = load_struct_h5(tmp_path / "True.h5")["slap2"]["onlineCompensation"] - assert np.ptp(oc["frameRefX"]) >= 1 and np.ptp(oc["frameRefY"]) >= 1 - assert errors[True] < 0.1 - assert errors[True] < errors[False] / 3 - - -def test_compensation_on_cuda_matches_cpu(online_recording: OnlineRecording) -> None: - """Compensated frames agree on CUDA and CPU (skipped without a GPU).""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.registration.frames import FrameFormer - - layout, _, _ = online_recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - times = np.array([500, 2500, 4100]) - out = [] - for dev in ("cpu", "cuda"): - former = FrameFormer(layout, samples, 0, device=dev) - src = make_source(layout, former, 300, 6000, times, times, 20, True) - out.append(src.frames(times)[0].cpu().numpy()) - np.testing.assert_allclose(out[0], out[1], rtol=1e-6, equal_nan=True) +"""Online-motion compensation (compensateOnline) on synthetic data.""" + +from collections.abc import Sequence +from pathlib import Path + +import numpy as np +import pytest +import torch + +from giant_python.io.slap2_raster import RasterLayout +from giant_python.registration import multiroi +from giant_python.registration.compensation import ( + LineOffsets, + dmd_y, + frame_offsets, + line_offsets, +) +from giant_python.registration.sources import make_source + +from .synthetic import make_layout, online_offsets, write_recording + +# the layout, its online offsets (x, y_header, y_dmd) and the true motion +OnlineRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] + + +def test_dmd_y_leads_header_switches() -> None: + """Y switches 2 lines early, 6 with x, never before the last switch.""" + x = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) + y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 7, 7]) + sw = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 + got = dmd_y(x, y, sw) + # y switch at line index 8 (x unchanged): lines 6-7 take it; the + # switch at 14 (x unchanged): lines 12-13; none before index 10 (x) + want = y.copy() + want[6:8] = 5 + want[12:14] = 7 + np.testing.assert_array_equal(got, want) + x2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 3, 3]) + y2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 4, 4]) + sw2 = np.array([9]) + np.testing.assert_array_equal(dmd_y(x2, y2, sw2), [0, 0, 4, 4, 4, 4, 4, 4, 4, 4]) + + +@pytest.fixture(scope="module") +def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: + """Synthetic recording whose online offsets move the DMD pattern. + + Returns + ------- + OnlineRecording + The raster layout, its online offsets (x, y_header, y_dmd) and the true + motion. + """ + path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400, seed=5) + online = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=online) + return layout, online, truth + + +def test_line_offsets_reproduce_dmd_timing(online_recording: OnlineRecording) -> None: + """Headers decode, y_eff equals the generator's DMD y.""" + layout, (x, y, y_dmd), _ = online_recording + off = line_offsets(layout, (1, layout.total_lines)) + np.testing.assert_array_equal(off.x, x) + np.testing.assert_array_equal(off.y, y) + np.testing.assert_array_equal(off.y_eff, y_dmd) + part = line_offsets(layout, (2000, 3000)) + lo, hi = part.lines_read + assert lo <= 2000 - 7 and hi >= 3000 + 7 + # exact on the requested lines + np.testing.assert_array_equal(part.y_eff[1999:3000], y_dmd[1999:3000]) + assert part.x[0] == x[lo - 1] and part.x[-1] == x[hi - 1] + + +def frames_reference( + layout: RasterLayout, + former_samples: np.ndarray, + offsets: LineOffsets, + times: np.ndarray, + dt: int, + box: Sequence[int], +) -> tuple[np.ndarray, np.ndarray]: + """Compensated weighted means by the definition (slow loops). + + Returns + ------- + num : np.ndarray + (channels, frames, h, w) sums of the weighted, compensated samples + landing on each pixel of box. + den : np.ndarray + Same shape as num: the sums of the weights, so num / den is the + compensated weighted mean. + """ + p, total = layout.lines_per_cycle, layout.total_lines + r0, r1, c0, c1 = box + h, w = r1 - r0 + 1, c1 - c0 + 1 + refs = frame_offsets(offsets, times, dt, p) + dt_read = max(3 * dt, p) + num = np.zeros((layout.num_channels, len(times), h, w)) + den = np.zeros_like(num) + pr = (layout.slot_pixel - 1) // layout.n_cols + pc = (layout.slot_pixel - 1) % layout.n_cols + for f, t in enumerate(times): + for ln in range(max(1, t - dt_read), min(total, t + dt_read) + 1): + wt = np.exp(-abs(t - ln) / dt) + sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) + r = pr[sel] + offsets.y_eff[ln - 1] - refs[f, 1] - r0 + c = pc[sel] + offsets.x[ln - 1] - refs[f, 0] - c0 + ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) + for ch in range(layout.num_channels): + xv = former_samples[ch, sel, (ln - 1) // p].astype(float) + np.add.at(num[ch, f], (r[ok], c[ok]), wt * xv[ok]) + np.add.at(den[ch, f], (r[ok], c[ok]), wt) + return num, den + + +def test_compensated_frames_match_definition(online_recording: OnlineRecording) -> None: + """Each sample moves by its line's offset minus the frame's.""" + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.registration.frames import FrameFormer + + layout, _, _ = online_recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + former = FrameFormer(layout, samples, 0) + times = np.array([400, 1210, 3333, 5000]) + src = make_source(layout, former, 300, 6000, times, times, 20, True) + vals, fresh = src.frames(times) + box = ( + former.rows.min(), + former.rows.max(), + former.cols.min(), + former.cols.max(), + ) + num, den = frames_reference(layout, samples, src.compensation, times, 20, box) + with np.errstate(invalid="ignore"): + want = (num / den).astype(np.float32) + got = src.window.image(vals, float("nan")).numpy() + np.testing.assert_array_equal(np.isnan(got), np.isnan(want)) + np.testing.assert_allclose(got, want, rtol=1e-6) + np.testing.assert_allclose(src.window.image(fresh, 0.0).numpy(), den[0], rtol=1e-6) + + +def total_motion_error( + res: multiroi.TrialRegistration, + adata: dict, + truth: np.ndarray, + header: tuple[np.ndarray, np.ndarray], +) -> float: + """RMS error of the total motion against the kernel-averaged truth. + + Compensated: motion plus each frame's reference offset (relative to + refOffset). Uncompensated: motion plus the header offsets at the + frame's line (header = (x, y)), as GIAnT-MATLAB's transplant + evaluation adds them. + + Returns + ------- + float + Root-mean-square error of the motion estimate after removing its median + offset from the truth. + """ + dt = 20 + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + true = np.stack([np.convolve(truth[:, i], kernel, "same") for i in (0, 1)])[ + :, res.ds_frames - 1 + ] + est = np.stack([res.motion_r, res.motion_c]) + oc = adata["slap2"]["onlineCompensation"] + if oc["enabled"].item(): + ref = oc["refOffset"].ravel() + est = est + np.stack([ + oc["frameRefY"].ravel() - ref[1], + oc["frameRefX"].ravel() - ref[0], + ]) + else: + x, y = header + est = est + np.stack([y[res.ds_frames - 1], x[res.ds_frames - 1]]) + err = est - true + err -= np.median(err, axis=1, keepdims=True) + return float(np.sqrt(np.mean(err**2))) + + +def test_compensated_registration_recovers_motion( + online_recording: OnlineRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Total motion follows the truth with compensation, not without.""" + from giant_python.io.hdf5 import load_struct_h5 + + layout, (x, y, _), truth = online_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + errors = {} + for comp in (True, False): + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) + res = multiroi.register_trial( + layout.files[0], + 1, + 9000, + tmp_path / f"{comp}.tif", + tmp_path / f"{comp}.h5", + params, + ) + adata = load_struct_h5(tmp_path / f"{comp}.h5") + errors[comp] = total_motion_error(res, adata, truth, (x, y)) + oc = adata["slap2"]["onlineCompensation"] + assert oc["enabled"].item() == int(comp) + oc = load_struct_h5(tmp_path / "True.h5")["slap2"]["onlineCompensation"] + assert np.ptp(oc["frameRefX"]) >= 1 and np.ptp(oc["frameRefY"]) >= 1 + assert errors[True] < 0.1 + assert errors[True] < errors[False] / 3 + + +def test_compensation_on_cuda_matches_cpu(online_recording: OnlineRecording) -> None: + """Compensated frames agree on CUDA and CPU (skipped without a GPU).""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.registration.frames import FrameFormer + + layout, _, _ = online_recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + times = np.array([500, 2500, 4100]) + out = [] + for dev in ("cpu", "cuda"): + former = FrameFormer(layout, samples, 0, device=dev) + src = make_source(layout, former, 300, 6000, times, times, 20, True) + out.append(src.frames(times)[0].cpu().numpy()) + np.testing.assert_allclose(out[0], out[1], rtol=1e-6, equal_nan=True) diff --git a/tests/registration/test_curtain.py b/tests/registration/test_curtain.py index eaf1b468..9343f569 100644 --- a/tests/registration/test_curtain.py +++ b/tests/registration/test_curtain.py @@ -1,354 +1,382 @@ -"""Samples taken behind the DMD curtain (GIAnT-Python#66). - -The synthetic recording's online offsets move the pattern by x in 1..3 -columns; the curtain's last lit column is 41 at the raster's top row and 39 -at its bottom row (the line shear), so the raster's right columns (up to 39) -move behind it at the larger offsets, and column 39 of rows 25-27 at all of -them. -""" - -import dataclasses -import types -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.trial_data import RasterPixelFrames -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2_raster import ( - INVALID_SAMPLE, - RasterLayout, - _dmd_curtain, - lit_mirrors, - read_raster_samples, - unlit_samples, -) -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer - -from .synthetic import make_layout, online_offsets, write_recording - -# the layout, its online offsets (x, y_header, y_dmd) and the tissue's motion -# as the pattern sees it -CurtainRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] - -N_ROWS = 36 -CURTAIN = (0.05, 40.5 / 49 + 1 / 50) # last lit column 40 at zero shear -SHEAR = np.linspace(1.5, -1.5, N_ROWS) -STRIP = (np.array([25, 26, 27]), 39) # zero-based rows and column always unlit - - -@pytest.fixture(scope="module") -def curtain_recording(tmp_path_factory: pytest.TempPathFactory) -> CurtainRecording: - """Layout and online offsets of a recording with a DMD curtain.""" - path = tmp_path_factory.mktemp("rec") / "curtain_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=900, seed=5, curtain=CURTAIN, shear=SHEAR) - online = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=online) - # the tissue's motion as the pattern sees it: the pattern follows the - # online offsets - seen = np.stack([truth[:, 0] - online[2], truth[:, 1] - online[0]], 1) - return layout, online, seen - - -def plain(layout: RasterLayout) -> RasterLayout: - """Return the same layout without a curtain.""" - return dataclasses.replace(layout, dmd_curtain=None, line_shear=None) - - -def unlit_by_definition( - layout: RasterLayout, online: tuple[np.ndarray, np.ndarray, np.ndarray], dmd_y: bool = True -) -> np.ndarray: - """``(slots, cycles)``: True where the slot's mirror is behind the curtain. - - The line's offsets (header x, DMD y; the header's y with ``dmd_y=False``) - put the slot's mirror there. - """ - x, y = online[0], online[2] if dmd_y else online[1] - p = layout.lines_per_cycle - lines = np.arange(layout.num_cycles)[None, :] * p + layout.slot_line[:, None] - rows = (layout.slot_pixel - 1) // layout.n_cols - cols = (layout.slot_pixel - 1) % layout.n_cols - return ~lit_mirrors(layout, rows[:, None] + y[lines - 1], cols[:, None] + x[lines - 1]) - - -def test_curtain_from_metadata() -> None: - """The acquisition path's curtain and its DMD's line shear.""" - shear = np.arange(4.0) - meta = types.SimpleNamespace( - acquisitionPathName="Path2", - machineConfiguration=[ - { - "instanceName": "Path1", - "configuration": {"dmdCurtain": [0.0, 1.0], "hDmd": "DMD1"}, - }, - { - "instanceName": "Path2", - "configuration": { - "dmdCurtain": np.array([[0.1], [0.9]]), - # slap2_utils gives some strings as character codes - "hDmd": np.array([68, 77, 68, 50], dtype=np.uint16), - }, - }, - {"instanceName": "DMD2", "configuration": {"lineShear": shear}}, - ], - ) - curtain, got = _dmd_curtain(meta, 4) - np.testing.assert_array_equal(curtain, [0.1, 0.9]) - np.testing.assert_array_equal(got, shear) - # a shear without one value per DMD row is taken as none - np.testing.assert_array_equal(_dmd_curtain(meta, 5)[1], np.zeros(5)) - meta.acquisitionPathName = "Path3" - assert _dmd_curtain(meta, 4) == (None, None) - assert _dmd_curtain(types.SimpleNamespace(), 4) == (None, None) - - -def test_lit_mirrors_is_the_softwares_mask(curtain_recording: CurtainRecording) -> None: - """The acquisition software's curtain mask (``makeDmdCurtainMask``). - - Written out mirror by mirror. - """ - layout = curtain_recording[0] - n = layout.n_cols - want = np.zeros((layout.n_rows, n), dtype=bool) - for r in range(layout.n_rows): - for m in range(n): - frac = m / (n - 1) - SHEAR[r] / n - want[r, m] = CURTAIN[0] + 1 / n <= frac <= CURTAIN[1] - 1 / n - got = lit_mirrors(layout, np.arange(layout.n_rows)[:, None], np.arange(n)[None, :]) - np.testing.assert_array_equal(got, want) - last = n - 1 - np.argmax(got[:, ::-1], 1) - assert last[8] == 41 and last[27] == 39 - - -def test_unlit_samples_follow_the_offsets(curtain_recording: CurtainRecording) -> None: - """Exactly the samples behind the curtain are found. - - They hold no light, and only they are marked invalid. - """ - layout, online, _ = curtain_recording - n_c = layout.num_cycles - want = unlit_by_definition(layout, online) - assert 0 < want.mean() < 0.1 - s, c = unlit_samples(layout, (0, n_c)) - got = np.zeros_like(want) - got[s, c] = True - np.testing.assert_array_equal(got, want) - # the shear follows the y on the DMD, which switches 2-6 lines before - # the header records it - assert np.any(unlit_by_definition(layout, online, dmd_y=False) != want) - raw = read_raster_samples(layout, (0, n_c)) - assert np.all(raw[:, want] == 0) - masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) - assert np.all(masked[:, want] == INVALID_SAMPLE) - np.testing.assert_array_equal(masked[:, ~want], raw[:, ~want]) - # a part of the recording and some of the slots - cols = (layout.slot_pixel - 1) % layout.n_cols - sl = np.flatnonzero(cols >= 36) - part = read_raster_samples(layout, (100, 400), slots=sl, chunk_cycles=64, mask_unlit=True) - np.testing.assert_array_equal(part, masked[:, sl, 100:400]) - # without a curtain in the metadata, the raw values - np.testing.assert_array_equal( - read_raster_samples(plain(layout), (0, n_c), mask_unlit=True), raw - ) - assert unlit_samples(plain(layout), (0, n_c))[0].size == 0 - - -def kernel_hits( - layout: RasterLayout, unlit: np.ndarray, times: np.ndarray, reach: int, pixels: np.ndarray -) -> np.ndarray: - """``(frames, pixels)``: True where a frame's kernel holds an unlit sample. - - The kernel reaches ``reach`` lines to each side; True where it holds an - unlit sample of the pixel. - """ - p = layout.lines_per_cycle - s, c = np.nonzero(unlit) - lines = c * p + layout.slot_line[s] - j = np.searchsorted(pixels, layout.slot_pixel[s]) - hit = np.zeros((times.size, pixels.size), dtype=bool) - for f, t in enumerate(times): - near = np.abs(lines - t) <= reach - hit[f, j[near]] = True - return hit - - -def test_frames_give_unlit_samples_no_weight(curtain_recording: CurtainRecording) -> None: - """Pixels whose samples in a frame are all behind the curtain are NaN. - - Pixels with some are the mean of the lit ones, and every other value is - unchanged bit for bit. - """ - layout, online, _ = curtain_recording - n_c = layout.num_cycles - raw = read_raster_samples(layout, (0, n_c)) - masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) - times, dt = np.arange(30, layout.total_lines - 30, 97), 20 - former = FrameFormer(layout, masked, 0) - v_mask = former.frames(times, dt)[0].numpy() - v_raw = FrameFormer(layout, raw, 0).frames(times, dt)[0].numpy() - reach = max(3 * dt, layout.lines_per_cycle) # inclusive boundary - hit = kernel_hits( - layout, - unlit_by_definition(layout, online), - times, - reach, - former.pixels, - ) - assert hit.any() - np.testing.assert_array_equal(v_mask[:, ~hit], v_raw[:, ~hit]) - assert not np.isnan(v_raw).any() - assert not np.isnan(v_mask[:, ~hit]).any() - gone = np.isnan(v_mask[0]) - assert gone.any() and not gone[~hit].any() - # the strip is missing in every frame - strip = np.isin(former.pixels, STRIP[0] * layout.n_cols + STRIP[1] + 1) - assert strip.sum() == STRIP[0].size and gone[:, strip].all() - # where some samples are lit, the dark ones no longer pull values down - some = hit & ~gone - assert np.all(v_mask[:, some] >= v_raw[:, some]) - assert np.mean(v_mask[:, some] > v_raw[:, some]) > 0.5 - - -def test_extraction_frames_give_unlit_samples_no_weight( - curtain_recording: CurtainRecording, -) -> None: - """SILo's raw frames (``rawFramesAt``) leave out the same samples.""" - layout, online, _ = curtain_recording - ids = np.unique(layout.slot_pixel) - times, dt = np.arange(40, layout.total_lines - 40, 89), 8 - got = RasterPixelFrames(layout, ids, times, dt, [0, 1]).frames(times) - ref = RasterPixelFrames(plain(layout), ids, times, dt, [0, 1]).frames(times) - values = got[0][:, :-1].numpy() # (channels, pixels, frames) - before = ref[0][:, :-1].numpy() - # exclusive boundary: a kernel reaches max(3 dt, P) - 1 lines - reach = max(3 * dt, layout.lines_per_cycle) - 1 - hit = kernel_hits(layout, unlit_by_definition(layout, online), times, reach, ids).T - # equal to rounding: PixelFormer sums the weights of a band with an - # invalid sample in another order than those of a band without one - np.testing.assert_allclose(values[:, ~hit], before[:, ~hit], rtol=1e-14, atol=0) - assert not np.isnan(values[:, ~hit]).any() - strip = np.isin(ids, STRIP[0] * layout.n_cols + STRIP[1] + 1) - assert np.isnan(values[:, strip]).all() - assert not np.isnan(before).any() - - -def test_registration_window_ignores_the_curtain(curtain_recording: CurtainRecording) -> None: - """The registration window is the bounding box of the first frame's pixels. - - Those are the pixels the first frame samples, lit or not: a column behind - the curtain in that frame stays in the window. - """ - from giant_python.registration.sources import _window_pixels - - layout, online, _ = curtain_recording - x = online[0] - dt = 2 - reach = max(3 * dt, layout.lines_per_cycle) - # a frame whose kernel has x = 3 throughout: column 39 is unlit in - # every row - t = next( - t - for t in range(reach + 1, layout.total_lines - reach) - if np.all(x[t - reach - 1 : t + reach] == 3) - ) - n_c = layout.num_cycles - masked = FrameFormer(layout, read_raster_samples(layout, (0, n_c), mask_unlit=True), 0) - raw = FrameFormer(plain(layout), read_raster_samples(layout, (0, n_c)), 0) - values = masked.frames([t], dt)[0].sum(0)[0].numpy() - assert np.isnan(values[masked.cols == 39]).all() - init = np.array([t, t + 500]) - np.testing.assert_array_equal(_window_pixels(masked, init, dt), _window_pixels(raw, init, dt)) - assert _window_pixels(masked, init, dt)[masked.cols == 39].any() - - -def test_registration_leaves_out_the_strip( - curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Registration forms its frames without the unlit samples. - - The strip is missing from the registered movie, and the motion follows the - true motion (with the dark samples, which move with the offsets, it is off - by 0.2-0.5 px rms in this recording). - """ - layout, _, seen = curtain_recording - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - out = {} - for name, lay in (("curtain", layout), ("plain", plain(layout))): - monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) - res = multiroi.register_trial( - layout.files[0], - 1, - layout.total_lines - 200, - tmp_path / f"{name}.tif", - tmp_path / f"{name}.h5", - params, - ) - out[name] = (res, load_struct_h5(tmp_path / f"{name}.h5")) - res, a = out["curtain"] - dt = 1600 / 80 # the kernel that forms the frames - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - for i, est in enumerate((res.motion_r, res.motion_c)): - true = np.convolve(seen[:, i], kernel, "same")[res.ds_frames - 1] - err = est - true - assert np.sqrt(np.mean((err - np.median(err)) ** 2)) < 0.1 - # the registered movies ((frames, columns, rows) in the file): the strip - # is missing in nearly every frame; registration moves the frames by up - # to 2 px, so its neighbours are missing in part of them - trim_r = a["slap2"]["trimRows"].ravel().astype(int) - trim_c = a["slap2"]["trimCols"].ravel().astype(int) - pad = int(params.maxshift) - r = STRIP[0] + 1 - trim_r[0] + pad - c = STRIP[1] + 1 - trim_c[0] + pad - gone = {} - for name in out: - with h5py.File(tmp_path / f"{name}.tif", "r") as f: - gone[name] = np.isnan(f["data"][:, c, r]).mean(0) - assert np.all(gone["curtain"] > 0.9) - assert gone["curtain"].mean() > gone["plain"].mean() + 0.05 - - -def test_reg_stats_follow_the_alignment_file( - curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """``giant reg-stats`` forms the frames as the registration did. - - Without the samples behind the curtain where the alignment file records - ``slap2/unlitMasked``, with them in files registered before. - """ - from giant_python.pipeline.reg_stats import trial_stats - from giant_python.registration.stats.io import read_stats, stats_path - - layout = curtain_recording[0] - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - movie = tmp_path / "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - adata = tmp_path / "E1T1DMD1_ALIGNMENTDATA.h5" - last = layout.total_lines - 200 - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - multiroi.register_trial(layout.files[0], 1, last, movie, adata, params) - from giant_python.registration.outputs import unlit_masked - - assert unlit_masked(adata) - masks = [] - opened = multiroi.open_trial - - def spy(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 (forwards to open_trial unchanged) - """Record whether each open_trial call masks the unlit samples.""" - masks.append(args[5] if len(args) > 5 else kwargs["mask_unlit"]) - return opened(*args, **kwargs) - - monkeypatch.setattr(multiroi, "open_trial", spy) - cmd = tmp_path / "cmd.h5" - trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) - a, b = read_stats(stats_path(movie)), read_stats(cmd) - for k in a["gain"]: - np.testing.assert_array_equal(a["gain"][k], b["gain"][k], err_msg=k) - with h5py.File(adata, "r+") as f: # as registered before the mask - del f["slap2/unlitMasked"] - assert not unlit_masked(adata) - trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) - assert masks == [True, False] +"""Samples taken behind the DMD curtain (GIAnT-Python#66). + +The synthetic recording's online offsets move the pattern by x in 1..3 +columns; the curtain's last lit column is 41 at the raster's top row and 39 +at its bottom row (the line shear), so the raster's right columns (up to 39) +move behind it at the larger offsets, and column 39 of rows 25-27 at all of +them. +""" + +import dataclasses +import types +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.trial_data import RasterPixelFrames +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + _dmd_curtain, + lit_mirrors, + read_raster_samples, + unlit_samples, +) +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer + +from .synthetic import make_layout, online_offsets, write_recording + +# the layout, its online offsets (x, y_header, y_dmd) and the tissue's motion +# as the pattern sees it +CurtainRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] + +N_ROWS = 36 +CURTAIN = (0.05, 40.5 / 49 + 1 / 50) # last lit column 40 at zero shear +SHEAR = np.linspace(1.5, -1.5, N_ROWS) +STRIP = (np.array([25, 26, 27]), 39) # zero-based rows and column always unlit + + +@pytest.fixture(scope="module") +def curtain_recording(tmp_path_factory: pytest.TempPathFactory) -> CurtainRecording: + """Layout and online offsets of a recording with a DMD curtain. + + Returns + ------- + CurtainRecording + The layout, the online offsets and the tissue's motion as the pattern sees it. + """ + path = tmp_path_factory.mktemp("rec") / "curtain_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=900, seed=5, curtain=CURTAIN, shear=SHEAR) + online = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=online) + # the tissue's motion as the pattern sees it: the pattern follows the + # online offsets + seen = np.stack([truth[:, 0] - online[2], truth[:, 1] - online[0]], 1) + return layout, online, seen + + +def plain(layout: RasterLayout) -> RasterLayout: + """Return the same layout without a curtain. + + Returns + ------- + RasterLayout + A copy of layout with no DMD curtain and no line shear. + """ + return dataclasses.replace(layout, dmd_curtain=None, line_shear=None) + + +def unlit_by_definition( + layout: RasterLayout, online: tuple[np.ndarray, np.ndarray, np.ndarray], dmd_y: bool = True +) -> np.ndarray: + """(slots, cycles): True where the slot's mirror is behind the curtain. + + The line's offsets (header x, DMD y; the header's y with dmd_y=False) + put the slot's mirror there. + + Returns + ------- + np.ndarray + The (slots, cycles) bool array, True where the slot's mirror is behind the curtain. + """ + x, y = online[0], online[2] if dmd_y else online[1] + p = layout.lines_per_cycle + lines = np.arange(layout.num_cycles)[None, :] * p + layout.slot_line[:, None] + rows = (layout.slot_pixel - 1) // layout.n_cols + cols = (layout.slot_pixel - 1) % layout.n_cols + return ~lit_mirrors(layout, rows[:, None] + y[lines - 1], cols[:, None] + x[lines - 1]) + + +def test_curtain_from_metadata() -> None: + """The acquisition path's curtain and its DMD's line shear.""" + shear = np.arange(4.0) + meta = types.SimpleNamespace( + acquisitionPathName="Path2", + machineConfiguration=[ + { + "instanceName": "Path1", + "configuration": {"dmdCurtain": [0.0, 1.0], "hDmd": "DMD1"}, + }, + { + "instanceName": "Path2", + "configuration": { + "dmdCurtain": np.array([[0.1], [0.9]]), + # slap2_utils gives some strings as character codes + "hDmd": np.array([68, 77, 68, 50], dtype=np.uint16), + }, + }, + {"instanceName": "DMD2", "configuration": {"lineShear": shear}}, + ], + ) + curtain, got = _dmd_curtain(meta, 4) + np.testing.assert_array_equal(curtain, [0.1, 0.9]) + np.testing.assert_array_equal(got, shear) + # a shear without one value per DMD row is taken as none + np.testing.assert_array_equal(_dmd_curtain(meta, 5)[1], np.zeros(5)) + meta.acquisitionPathName = "Path3" + assert _dmd_curtain(meta, 4) == (None, None) + assert _dmd_curtain(types.SimpleNamespace(), 4) == (None, None) + + +def test_lit_mirrors_is_the_softwares_mask(curtain_recording: CurtainRecording) -> None: + """The acquisition software's curtain mask (makeDmdCurtainMask). + + Written out mirror by mirror. + """ + layout = curtain_recording[0] + n = layout.n_cols + want = np.zeros((layout.n_rows, n), dtype=bool) + for r in range(layout.n_rows): + for m in range(n): + frac = m / (n - 1) - SHEAR[r] / n + want[r, m] = CURTAIN[0] + 1 / n <= frac <= CURTAIN[1] - 1 / n + got = lit_mirrors(layout, np.arange(layout.n_rows)[:, None], np.arange(n)[None, :]) + np.testing.assert_array_equal(got, want) + last = n - 1 - np.argmax(got[:, ::-1], 1) + assert last[8] == 41 and last[27] == 39 + + +def test_unlit_samples_follow_the_offsets(curtain_recording: CurtainRecording) -> None: + """Exactly the samples behind the curtain are found. + + They hold no light, and only they are marked invalid. + """ + layout, online, _ = curtain_recording + n_c = layout.num_cycles + want = unlit_by_definition(layout, online) + assert 0 < want.mean() < 0.1 + s, c = unlit_samples(layout, (0, n_c)) + got = np.zeros_like(want) + got[s, c] = True + np.testing.assert_array_equal(got, want) + # the shear follows the y on the DMD, which switches 2-6 lines before + # the header records it + assert np.any(unlit_by_definition(layout, online, dmd_y=False) != want) + raw = read_raster_samples(layout, (0, n_c)) + assert np.all(raw[:, want] == 0) + masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) + assert np.all(masked[:, want] == INVALID_SAMPLE) + np.testing.assert_array_equal(masked[:, ~want], raw[:, ~want]) + # a part of the recording and some of the slots + cols = (layout.slot_pixel - 1) % layout.n_cols + sl = np.flatnonzero(cols >= 36) + part = read_raster_samples(layout, (100, 400), slots=sl, chunk_cycles=64, mask_unlit=True) + np.testing.assert_array_equal(part, masked[:, sl, 100:400]) + # without a curtain in the metadata, the raw values + np.testing.assert_array_equal( + read_raster_samples(plain(layout), (0, n_c), mask_unlit=True), raw + ) + assert unlit_samples(plain(layout), (0, n_c))[0].size == 0 + + +def kernel_hits( + layout: RasterLayout, unlit: np.ndarray, times: np.ndarray, reach: int, pixels: np.ndarray +) -> np.ndarray: + """(frames, pixels): True where a frame's kernel holds an unlit sample. + + The kernel reaches reach lines to each side; True where it holds an + unlit sample of the pixel. + + Returns + ------- + np.ndarray + The (frames, pixels) bool array, True where a frame's kernel holds an unlit sample. + """ + p = layout.lines_per_cycle + s, c = np.nonzero(unlit) + lines = c * p + layout.slot_line[s] + j = np.searchsorted(pixels, layout.slot_pixel[s]) + hit = np.zeros((times.size, pixels.size), dtype=bool) + for f, t in enumerate(times): + near = np.abs(lines - t) <= reach + hit[f, j[near]] = True + return hit + + +def test_frames_give_unlit_samples_no_weight(curtain_recording: CurtainRecording) -> None: + """Pixels whose samples in a frame are all behind the curtain are NaN. + + Pixels with some are the mean of the lit ones, and every other value is + unchanged bit for bit. + """ + layout, online, _ = curtain_recording + n_c = layout.num_cycles + raw = read_raster_samples(layout, (0, n_c)) + masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) + times, dt = np.arange(30, layout.total_lines - 30, 97), 20 + former = FrameFormer(layout, masked, 0) + v_mask = former.frames(times, dt)[0].numpy() + v_raw = FrameFormer(layout, raw, 0).frames(times, dt)[0].numpy() + reach = max(3 * dt, layout.lines_per_cycle) # inclusive boundary + hit = kernel_hits( + layout, + unlit_by_definition(layout, online), + times, + reach, + former.pixels, + ) + assert hit.any() + np.testing.assert_array_equal(v_mask[:, ~hit], v_raw[:, ~hit]) + assert not np.isnan(v_raw).any() + assert not np.isnan(v_mask[:, ~hit]).any() + gone = np.isnan(v_mask[0]) + assert gone.any() and not gone[~hit].any() + # the strip is missing in every frame + strip = np.isin(former.pixels, STRIP[0] * layout.n_cols + STRIP[1] + 1) + assert strip.sum() == STRIP[0].size and gone[:, strip].all() + # where some samples are lit, the dark ones no longer pull values down + some = hit & ~gone + assert np.all(v_mask[:, some] >= v_raw[:, some]) + assert np.mean(v_mask[:, some] > v_raw[:, some]) > 0.5 + + +def test_extraction_frames_give_unlit_samples_no_weight( + curtain_recording: CurtainRecording, +) -> None: + """SILo's raw frames (rawFramesAt) leave out the same samples.""" + layout, online, _ = curtain_recording + ids = np.unique(layout.slot_pixel) + times, dt = np.arange(40, layout.total_lines - 40, 89), 8 + got = RasterPixelFrames(layout, ids, times, dt, [0, 1]).frames(times) + ref = RasterPixelFrames(plain(layout), ids, times, dt, [0, 1]).frames(times) + values = got[0][:, :-1].numpy() # (channels, pixels, frames) + before = ref[0][:, :-1].numpy() + # exclusive boundary: a kernel reaches max(3 dt, P) - 1 lines + reach = max(3 * dt, layout.lines_per_cycle) - 1 + hit = kernel_hits(layout, unlit_by_definition(layout, online), times, reach, ids).T + # equal to rounding: PixelFormer sums the weights of a band with an + # invalid sample in another order than those of a band without one + np.testing.assert_allclose(values[:, ~hit], before[:, ~hit], rtol=1e-14, atol=0) + assert not np.isnan(values[:, ~hit]).any() + strip = np.isin(ids, STRIP[0] * layout.n_cols + STRIP[1] + 1) + assert np.isnan(values[:, strip]).all() + assert not np.isnan(before).any() + + +def test_registration_window_ignores_the_curtain(curtain_recording: CurtainRecording) -> None: + """The registration window is the bounding box of the first frame's pixels. + + Those are the pixels the first frame samples, lit or not: a column behind + the curtain in that frame stays in the window. + """ + from giant_python.registration.sources import _window_pixels + + layout, online, _ = curtain_recording + x = online[0] + dt = 2 + reach = max(3 * dt, layout.lines_per_cycle) + # a frame whose kernel has x = 3 throughout: column 39 is unlit in + # every row + t = next( + t + for t in range(reach + 1, layout.total_lines - reach) + if np.all(x[t - reach - 1 : t + reach] == 3) + ) + n_c = layout.num_cycles + masked = FrameFormer(layout, read_raster_samples(layout, (0, n_c), mask_unlit=True), 0) + raw = FrameFormer(plain(layout), read_raster_samples(layout, (0, n_c)), 0) + values = masked.frames([t], dt)[0].sum(0)[0].numpy() + assert np.isnan(values[masked.cols == 39]).all() + init = np.array([t, t + 500]) + np.testing.assert_array_equal(_window_pixels(masked, init, dt), _window_pixels(raw, init, dt)) + assert _window_pixels(masked, init, dt)[masked.cols == 39].any() + + +def test_registration_leaves_out_the_strip( + curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Registration forms its frames without the unlit samples. + + The strip is missing from the registered movie, and the motion follows the + true motion (with the dark samples, which move with the offsets, it is off + by 0.2-0.5 px rms in this recording). + """ + layout, _, seen = curtain_recording + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + out = {} + for name, lay in (("curtain", layout), ("plain", plain(layout))): + monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) + res = multiroi.register_trial( + layout.files[0], + 1, + layout.total_lines - 200, + tmp_path / f"{name}.tif", + tmp_path / f"{name}.h5", + params, + ) + out[name] = (res, load_struct_h5(tmp_path / f"{name}.h5")) + res, a = out["curtain"] + dt = 1600 / 80 # the kernel that forms the frames + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + for i, est in enumerate((res.motion_r, res.motion_c)): + true = np.convolve(seen[:, i], kernel, "same")[res.ds_frames - 1] + err = est - true + assert np.sqrt(np.mean((err - np.median(err)) ** 2)) < 0.1 + # the registered movies ((frames, columns, rows) in the file): the strip + # is missing in nearly every frame; registration moves the frames by up + # to 2 px, so its neighbours are missing in part of them + trim_r = a["slap2"]["trimRows"].ravel().astype(int) + trim_c = a["slap2"]["trimCols"].ravel().astype(int) + pad = int(params.maxshift) + r = STRIP[0] + 1 - trim_r[0] + pad + c = STRIP[1] + 1 - trim_c[0] + pad + gone = {} + for name in out: + with h5py.File(tmp_path / f"{name}.tif", "r") as f: + gone[name] = np.isnan(f["data"][:, c, r]).mean(0) + assert np.all(gone["curtain"] > 0.9) + assert gone["curtain"].mean() > gone["plain"].mean() + 0.05 + + +def test_reg_stats_follow_the_alignment_file( + curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """``giant reg-stats`` forms the frames as the registration did. + + Without the samples behind the curtain where the alignment file records + slap2/unlitMasked, with them in files registered before. + """ + from giant_python.pipeline.reg_stats import trial_stats + from giant_python.registration.stats.io import read_stats, stats_path + + layout = curtain_recording[0] + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + movie = tmp_path / "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + adata = tmp_path / "E1T1DMD1_ALIGNMENTDATA.h5" + last = layout.total_lines - 200 + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + multiroi.register_trial(layout.files[0], 1, last, movie, adata, params) + from giant_python.registration.outputs import unlit_masked + + assert unlit_masked(adata) + masks = [] + opened = multiroi.open_trial + + def spy(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 (forwards to open_trial unchanged) + """Record whether each open_trial call masks the unlit samples. + + Returns + ------- + Any + What open_trial returns for the same arguments. + """ + masks.append(args[5] if len(args) > 5 else kwargs["mask_unlit"]) + return opened(*args, **kwargs) + + monkeypatch.setattr(multiroi, "open_trial", spy) + cmd = tmp_path / "cmd.h5" + trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) + a, b = read_stats(stats_path(movie)), read_stats(cmd) + for k in a["gain"]: + np.testing.assert_array_equal(a["gain"][k], b["gain"][k], err_msg=k) + with h5py.File(adata, "r+") as f: # as registered before the mask + del f["slap2/unlitMasked"] + assert not unlit_masked(adata) + trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) + assert masks == [True, False] diff --git a/tests/registration/test_growth.py b/tests/registration/test_growth.py index 2bbdf4c2..3f860107 100644 --- a/tests/registration/test_growth.py +++ b/tests/registration/test_growth.py @@ -1,309 +1,321 @@ -"""The growth schedule: wide search, scheduler pieces, end to end.""" - -from pathlib import Path - -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2_raster import RasterLayout -from giant_python.registration import multiroi -from giant_python.registration.growth import ( - GROWN, - REGROWN, - _runs, - seeds_from_consensus, -) -from giant_python.registration.matching import ( - correlation_map, - peak_margin, - shift_tables, - wide_correlation, -) -from giant_python.registration.template import ( - ConsensusResult, - TemplateState, -) - -from .synthetic import make_layout, write_recording - - -def test_wide_correlation_equals_matrix_form() -> None: - """FFT correlation over the padded template equals the GEMM form.""" - rng = np.random.default_rng(0) - h, w, m = 14, 19, 4 - tmpl = rng.random((h + 2 * m, w + 2 * m)) * 10 - tmpl[rng.random(tmpl.shape) < 0.15] = np.nan - frame = tmpl[m + 1 : m + 1 + h, m - 2 : m - 2 + w] + rng.normal(0, 0.3, (h, w)) - frame[rng.random(frame.shape) < 0.3] = np.nan - fresh = np.where(np.isnan(frame), 0, rng.random((h, w)) + 0.5) - wide = wide_correlation( - torch.from_numpy(frame)[None], - torch.from_numpy(fresh)[None], - torch.from_numpy(tmpl), - )[0].numpy() - rows, cols = np.nonzero(~np.isnan(frame)) - tables = shift_tables( - torch.from_numpy(tmpl), - torch.from_numpy(rows + m), - torch.from_numpy(cols + m), - m, - torch.float64, - ) - gemm = correlation_map( - torch.from_numpy(frame[rows, cols])[None], - torch.from_numpy(fresh[rows, cols])[None], - tables, - m, - )[0].numpy() - np.testing.assert_allclose(wide, gemm, atol=1e-9) - r, c = np.unravel_index(np.nanargmax(wide), wide.shape) - assert (r - m, c - m) == (1, -2) - - -def test_peak_margin_and_runs() -> None: - """Margin excludes the peak's neighbourhood; runs of True.""" - corr = torch.zeros(1, 9, 9, dtype=torch.float64) - corr[0, 4, 4] = 1.0 - corr[0, 5, 5] = 0.9 - corr[0, 0, 8] = 0.6 - np.testing.assert_allclose(peak_margin(corr).numpy(), [0.4]) - mask = np.array([0, 1, 1, 0, 0, 1, 0, 1, 1, 1], dtype=bool) - assert _runs(mask) == [(1, 3), (5, 6), (7, 10)] - - -def test_template_update_adds_and_removes() -> None: - """Batch add then remove restores the sums.""" - total = torch.ones(3, 3, dtype=torch.float64) * 4 - count = torch.ones(3, 3, dtype=torch.float64) - state = TemplateState(total.clone(), count.clone(), None, 1) - imgs = torch.rand(5, 3, 3) * 9 - imgs[0, 1, 1] = float("nan") - state.update(imgs) - assert state.count[1, 1] == 5 and state.count[0, 0] == 6 - state.update(imgs, sign=-1) - torch.testing.assert_close(state.total, total) - torch.testing.assert_close(state.count, count) - - -def test_seeds_from_consensus() -> None: - """Seeds are the nearest DS frames, with MATLAB's motion sign.""" - init = np.array([105, 300, 501, 700]) - ds = np.arange(1, 800, 20) - mot = np.zeros((2, 4, 4)) - mot[:, 0, 2] = [1.4, -2.6] - cons = ConsensusResult(np.eye(4), mot, reference=2, members=np.array([0, 2])) - seeds, cands, indep = seeds_from_consensus(cons, init, ds, reach=30) - assert seeds == [(5, -1, 3), (25, 0, 0)] - assert cands == [15, 35] - assert not indep[5] and not indep[25] and indep[15] - - -@pytest.fixture(scope="module") -def plain_recording(tmp_path_factory: pytest.TempPathFactory) -> tuple[RasterLayout, np.ndarray]: - """Synthetic recording without online offsets.""" - path = tmp_path_factory.mktemp("rec") / "grow_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400, seed=5) - truth = write_recording(layout, seed=6) - return layout, truth - - -def test_grow_matches_sequential( - plain_recording: tuple[RasterLayout, np.ndarray], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Growth aligns every frame, like sequential, and saves its record.""" - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - out = {} - for sched in ("sequential", "grow"): - params = multiroi.MultiRoiRegistrationParams( - maxshift=6, schedule=sched, polish=sched == "grow" - ) - out[sched] = multiroi.register_trial( - layout.files[0], - 1, - 9000, - tmp_path / f"{sched}.tif", - tmp_path / f"{sched}.h5", - params, - ) - g = out["grow"].growth - assert np.all(np.isfinite(out["grow"].motion_r)) - assert g.seeds_accepted >= 1 and g.round.max() < 450 - diff = np.hypot( - out["grow"].motion_r - out["sequential"].motion_r, - out["grow"].motion_c - out["sequential"].motion_c, - ) - assert np.sqrt(np.mean(diff**2)) < 0.05 - qc = load_struct_h5(tmp_path / "grow.h5")["growthQC"] - assert qc["kind"].size == out["grow"].ds_frames.size - assert qc["seedsAccepted"].item() == g.seeds_accepted - - -def test_junction_regrows_a_wrong_island( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """An island shifted by 2 px is realigned from its neighbour.""" - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) - motion, _ = grower.run() - good = motion.copy() - bad = np.arange(200, 240) - grower._withdraw(bad) - grower._accept( - bad, - good[bad] + [2.0, 0.0], - grower.qc.peak[bad] - 0.2, - grower.qc.margin[bad], - np.full(bad.size, -1), - [GROWN] * bad.size, - [-7] * bad.size, - ) - grower.qc.anchor[240] = 241 # frame 240 was reached from the right - grower._check_junctions([240]) - assert grower.qc.junctions and grower.qc.junctions[-1][3] == "regrown" - assert np.all(grower.qc.kind[bad] == REGROWN) - err = np.hypot(*(grower.motion[bad] - good[bad]).T) - assert err.max() < 0.2 - - -def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch: pytest.MonkeyPatch) -> None: - """Seeds that align the last unaligned frame end the sub-round.""" - from giant_python.registration.growth import Grower - - class Frames: - """Stands in for a frame cache; only its length is used.""" - - def __len__(self) -> int: - """Five frames.""" - return 5 - - params = multiroi.MultiRoiRegistrationParams(schedule="grow") - grower = Grower(Frames(), None, params, [], [4]) - grower.aligned[:4] = True - grower.motion[:4] = 0.0 - grower.root[:4] = 0 - - def seed(ks: list[int]) -> None: - """Align the candidates, as an accepted wide search would.""" - grower.aligned[ks] = True - grower.motion[ks] = 0.0 - - monkeypatch.setattr(grower, "_calibrated", lambda: True) - monkeypatch.setattr(grower, "try_seeds", seed) - grower._sub_round() - assert grower.aligned.all() - - -def test_growth_handles_a_frame_without_valid_samples( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """Inside the grower, a frame whose correlation is undefined keeps its anchor's motion. - - It does not stop a realignment chain. - - (``register_grow`` leaves frames without samples out beforehand; this - covers frames whose correlation is undefined for other reasons.) - """ - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - taken = {k for k, _, _ in seeds} | set(cands) - k = next(i for i in range(200, ds.size) if i not in taken) - cache = FrameCache(source, ds) - cache.values[:, k] = float("nan") - cache.freshness[k] = 0 - grower = Grower(cache, state, params, seeds, cands, independent=indep) - motion, qc = grower.run() - assert grower.aligned.all() and np.all(np.isfinite(motion)) - assert np.isnan(qc.peak[k]) and qc.anchor[k] >= 0 - np.testing.assert_array_equal(motion[k], motion[qc.anchor[k]]) - chain, peak, _ = grower._chain([k], motion[k - 1]) - np.testing.assert_array_equal(chain[0], motion[k - 1]) - assert np.isnan(peak[0]) - - -def test_consensus_seeds_stay_within_maxshift( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """Seeds start inside the padded template even when the consensus motion exceeds ``maxshift``. - - The consensus motion goes up to ``init_search``. - """ - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=2, init_search=3, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 3000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 3000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - grower = Grower(FrameCache(source, ds), state, params, [(10, 3, -3)], []) - assert grower.seeds == [(10, 2, -2)] - grower._seed_round() - assert grower.aligned[10] and np.all(np.isfinite(grower.motion[10])) - - -def test_seed_candidates_are_listed_once() -> None: - """Initial frames nearest the same DS frame give one candidate.""" - init = np.array([2, 4, 6, 105]) - ds = np.arange(1, 200, 20) - cons = ConsensusResult(np.eye(4), np.zeros((2, 4, 4)), reference=3, members=np.array([3])) - seeds, cands, _ = seeds_from_consensus(cons, init, ds) - assert seeds == [(5, 0, 0)] and cands == [0] - - -def test_a_seed_tried_twice_is_added_once( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """A frame passed twice to the wide search adds one contribution to the template, not two.""" - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) - grower.run() - peak = np.where( - (grower.qc.kind == GROWN) & indep & ~np.isin(np.arange(ds.size), list(grower.tried)), - grower.qc.peak, - -np.inf, - ) - k = int(np.argmax(peak)) - grower._withdraw([k]) - count = grower.state.count.clone() - accepted = grower.qc.seeds_accepted - grower.try_seeds([k, k]) - assert grower.aligned[k] and grower.qc.seeds_accepted == accepted + 1 - img = grower.cache.registered_sum([k], grower.motion[[k]], grower.m)[0] - added = grower.state.count - count - assert torch.equal(added, (~torch.isnan(img)).to(added.dtype)) +"""The growth schedule: wide search, scheduler pieces, end to end.""" + +from pathlib import Path + +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.io.slap2_raster import RasterLayout +from giant_python.registration import multiroi +from giant_python.registration.growth import ( + GROWN, + REGROWN, + _runs, + seeds_from_consensus, +) +from giant_python.registration.matching import ( + correlation_map, + peak_margin, + shift_tables, + wide_correlation, +) +from giant_python.registration.template import ( + ConsensusResult, + TemplateState, +) + +from .synthetic import make_layout, write_recording + + +def test_wide_correlation_equals_matrix_form() -> None: + """FFT correlation over the padded template equals the GEMM form.""" + rng = np.random.default_rng(0) + h, w, m = 14, 19, 4 + tmpl = rng.random((h + 2 * m, w + 2 * m)) * 10 + tmpl[rng.random(tmpl.shape) < 0.15] = np.nan + frame = tmpl[m + 1 : m + 1 + h, m - 2 : m - 2 + w] + rng.normal(0, 0.3, (h, w)) + frame[rng.random(frame.shape) < 0.3] = np.nan + fresh = np.where(np.isnan(frame), 0, rng.random((h, w)) + 0.5) + wide = wide_correlation( + torch.from_numpy(frame)[None], + torch.from_numpy(fresh)[None], + torch.from_numpy(tmpl), + )[0].numpy() + rows, cols = np.nonzero(~np.isnan(frame)) + tables = shift_tables( + torch.from_numpy(tmpl), + torch.from_numpy(rows + m), + torch.from_numpy(cols + m), + m, + torch.float64, + ) + gemm = correlation_map( + torch.from_numpy(frame[rows, cols])[None], + torch.from_numpy(fresh[rows, cols])[None], + tables, + m, + )[0].numpy() + np.testing.assert_allclose(wide, gemm, atol=1e-9) + r, c = np.unravel_index(np.nanargmax(wide), wide.shape) + assert (r - m, c - m) == (1, -2) + + +def test_peak_margin_and_runs() -> None: + """Margin excludes the peak's neighbourhood; runs of True.""" + corr = torch.zeros(1, 9, 9, dtype=torch.float64) + corr[0, 4, 4] = 1.0 + corr[0, 5, 5] = 0.9 + corr[0, 0, 8] = 0.6 + np.testing.assert_allclose(peak_margin(corr).numpy(), [0.4]) + mask = np.array([0, 1, 1, 0, 0, 1, 0, 1, 1, 1], dtype=bool) + assert _runs(mask) == [(1, 3), (5, 6), (7, 10)] + + +def test_template_update_adds_and_removes() -> None: + """Batch add then remove restores the sums.""" + total = torch.ones(3, 3, dtype=torch.float64) * 4 + count = torch.ones(3, 3, dtype=torch.float64) + state = TemplateState(total.clone(), count.clone(), None, 1) + imgs = torch.rand(5, 3, 3) * 9 + imgs[0, 1, 1] = float("nan") + state.update(imgs) + assert state.count[1, 1] == 5 and state.count[0, 0] == 6 + state.update(imgs, sign=-1) + torch.testing.assert_close(state.total, total) + torch.testing.assert_close(state.count, count) + + +def test_seeds_from_consensus() -> None: + """Seeds are the nearest DS frames, with MATLAB's motion sign.""" + init = np.array([105, 300, 501, 700]) + ds = np.arange(1, 800, 20) + mot = np.zeros((2, 4, 4)) + mot[:, 0, 2] = [1.4, -2.6] + cons = ConsensusResult(np.eye(4), mot, reference=2, members=np.array([0, 2])) + seeds, cands, indep = seeds_from_consensus(cons, init, ds, reach=30) + assert seeds == [(5, -1, 3), (25, 0, 0)] + assert cands == [15, 35] + assert not indep[5] and not indep[25] and indep[15] + + +@pytest.fixture(scope="module") +def plain_recording(tmp_path_factory: pytest.TempPathFactory) -> tuple[RasterLayout, np.ndarray]: + """Synthetic recording without online offsets. + + Returns + ------- + tuple[RasterLayout, np.ndarray] + (layout, truth): the recording's layout and the truth written with it. + """ + path = tmp_path_factory.mktemp("rec") / "grow_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400, seed=5) + truth = write_recording(layout, seed=6) + return layout, truth + + +def test_grow_matches_sequential( + plain_recording: tuple[RasterLayout, np.ndarray], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Growth aligns every frame, like sequential, and saves its record.""" + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + out = {} + for sched in ("sequential", "grow"): + params = multiroi.MultiRoiRegistrationParams( + maxshift=6, schedule=sched, polish=sched == "grow" + ) + out[sched] = multiroi.register_trial( + layout.files[0], + 1, + 9000, + tmp_path / f"{sched}.tif", + tmp_path / f"{sched}.h5", + params, + ) + g = out["grow"].growth + assert np.all(np.isfinite(out["grow"].motion_r)) + assert g.seeds_accepted >= 1 and g.round.max() < 450 + diff = np.hypot( + out["grow"].motion_r - out["sequential"].motion_r, + out["grow"].motion_c - out["sequential"].motion_c, + ) + assert np.sqrt(np.mean(diff**2)) < 0.05 + qc = load_struct_h5(tmp_path / "grow.h5")["growthQC"] + assert qc["kind"].size == out["grow"].ds_frames.size + assert qc["seedsAccepted"].item() == g.seeds_accepted + + +def test_junction_regrows_a_wrong_island( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """An island shifted by 2 px is realigned from its neighbour.""" + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) + motion, _ = grower.run() + good = motion.copy() + bad = np.arange(200, 240) + grower._withdraw(bad) + grower._accept( + bad, + good[bad] + [2.0, 0.0], + grower.qc.peak[bad] - 0.2, + grower.qc.margin[bad], + np.full(bad.size, -1), + [GROWN] * bad.size, + [-7] * bad.size, + ) + grower.qc.anchor[240] = 241 # frame 240 was reached from the right + grower._check_junctions([240]) + assert grower.qc.junctions and grower.qc.junctions[-1][3] == "regrown" + assert np.all(grower.qc.kind[bad] == REGROWN) + err = np.hypot(*(grower.motion[bad] - good[bad]).T) + assert err.max() < 0.2 + + +def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch: pytest.MonkeyPatch) -> None: + """Seeds that align the last unaligned frame end the sub-round.""" + from giant_python.registration.growth import Grower + + class Frames: + """Stands in for a frame cache; only its length is used.""" + + def __len__(self) -> int: + """Five frames. + + Returns + ------- + int + The frame count, 5. + """ + return 5 + + params = multiroi.MultiRoiRegistrationParams(schedule="grow") + grower = Grower(Frames(), None, params, [], [4]) + grower.aligned[:4] = True + grower.motion[:4] = 0.0 + grower.root[:4] = 0 + + def seed(ks: list[int]) -> None: + """Align the candidates, as an accepted wide search would.""" + grower.aligned[ks] = True + grower.motion[ks] = 0.0 + + monkeypatch.setattr(grower, "_calibrated", lambda: True) + monkeypatch.setattr(grower, "try_seeds", seed) + grower._sub_round() + assert grower.aligned.all() + + +def test_growth_handles_a_frame_without_valid_samples( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """Inside the grower, a frame whose correlation is undefined keeps its anchor's motion. + + It does not stop a realignment chain. + + (register_grow leaves frames without samples out beforehand; this + covers frames whose correlation is undefined for other reasons.) + """ + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + taken = {k for k, _, _ in seeds} | set(cands) + k = next(i for i in range(200, ds.size) if i not in taken) + cache = FrameCache(source, ds) + cache.values[:, k] = float("nan") + cache.freshness[k] = 0 + grower = Grower(cache, state, params, seeds, cands, independent=indep) + motion, qc = grower.run() + assert grower.aligned.all() and np.all(np.isfinite(motion)) + assert np.isnan(qc.peak[k]) and qc.anchor[k] >= 0 + np.testing.assert_array_equal(motion[k], motion[qc.anchor[k]]) + chain, peak, _ = grower._chain([k], motion[k - 1]) + np.testing.assert_array_equal(chain[0], motion[k - 1]) + assert np.isnan(peak[0]) + + +def test_consensus_seeds_stay_within_maxshift( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """Seeds start inside the padded template even when the consensus motion exceeds maxshift. + + The consensus motion goes up to init_search. + """ + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=2, init_search=3, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 3000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 3000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + grower = Grower(FrameCache(source, ds), state, params, [(10, 3, -3)], []) + assert grower.seeds == [(10, 2, -2)] + grower._seed_round() + assert grower.aligned[10] and np.all(np.isfinite(grower.motion[10])) + + +def test_seed_candidates_are_listed_once() -> None: + """Initial frames nearest the same DS frame give one candidate.""" + init = np.array([2, 4, 6, 105]) + ds = np.arange(1, 200, 20) + cons = ConsensusResult(np.eye(4), np.zeros((2, 4, 4)), reference=3, members=np.array([3])) + seeds, cands, _ = seeds_from_consensus(cons, init, ds) + assert seeds == [(5, 0, 0)] and cands == [0] + + +def test_a_seed_tried_twice_is_added_once( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """A frame passed twice to the wide search adds one contribution to the template, not two.""" + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) + grower.run() + peak = np.where( + (grower.qc.kind == GROWN) & indep & ~np.isin(np.arange(ds.size), list(grower.tried)), + grower.qc.peak, + -np.inf, + ) + k = int(np.argmax(peak)) + grower._withdraw([k]) + count = grower.state.count.clone() + accepted = grower.qc.seeds_accepted + grower.try_seeds([k, k]) + assert grower.aligned[k] and grower.qc.seeds_accepted == accepted + 1 + img = grower.cache.registered_sum([k], grower.motion[[k]], grower.m)[0] + added = grower.state.count - count + assert torch.equal(added, (~torch.isnan(img)).to(added.dtype)) diff --git a/tests/registration/test_kernels.py b/tests/registration/test_kernels.py index 037ada43..d58e633a 100644 --- a/tests/registration/test_kernels.py +++ b/tests/registration/test_kernels.py @@ -1,257 +1,289 @@ -"""Registration kernels against direct ports of the GIAnT-MATLAB code.""" - -import warnings -from collections.abc import Callable - -import numpy as np -import pytest -import torch - -from giant_python.registration.interpolation import interp_frame -from giant_python.registration.matching import ( - RegistrationError, - correlation_map, - match, - match_maps, - shift_tables, -) -from giant_python.registration.multiroi import matlab_colon -from giant_python.registration.outputs import ( - downsample2, - matlab_round, - rec_neg_err, -) -from giant_python.registration.template import TemplateState - - -def xcorr_reference( - frame: np.ndarray, fresh: np.ndarray, template: np.ndarray, s: int -) -> np.ndarray: - """Loop port of ``xcorr2_nans_weighted`` (correlation map only).""" - h, w = template.shape - rows, cols = np.nonzero(~np.isnan(frame)) - out = np.full((2 * s + 1, 2 * s + 1), np.nan) - for i, dr in enumerate(range(-s, s + 1)): - for j, dc in enumerate(range(-s, s + 1)): - r, c = rows + dr, cols + dc - ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) - t = np.full(rows.size, np.nan) - t[ok] = template[r[ok], c[ok]] - sel = ~np.isnan(t) - f, t, wt = frame[rows, cols][sel], t[sel], fresh[rows, cols][sel] - sw = wt.sum() - df = f - (wt * f).sum() / sw - dt = t - (wt * t).sum() / sw - out[i, j] = (wt * df * dt).sum() / np.sqrt((wt * dt**2).sum() * (wt * df**2).sum()) - return out - - -def interp_reference( - m1: np.ndarray, view_c: np.ndarray, view_r: np.ndarray, fresh: np.ndarray -) -> tuple[np.ndarray, np.ndarray]: - """Gather port of ``interpFrame`` (one-based view coordinates).""" - h, w = m1.shape - - def corner( - rfun: Callable[[np.ndarray], np.ndarray], cfun: Callable[[np.ndarray], np.ndarray] - ) -> tuple[np.ndarray, np.ndarray]: - """Frame and freshness at one bilinear corner, NaN outside.""" - rr = rfun(view_r).astype(int) - cc = cfun(view_c).astype(int) - bad_r = (rr < 1) | (rr > h) - bad_c = (cc < 1) | (cc > w) - rr[bad_r], cc[bad_c] = 1, 1 - a = m1[np.ix_(rr - 1, cc - 1)].astype(np.float64) - f = fresh[np.ix_(rr - 1, cc - 1)].astype(np.float64) - for x in (a, f): - x[bad_r, :] = np.nan - x[:, bad_c] = np.nan - return a, f - - fc, fr = np.mod(view_c[0], 1), np.mod(view_r[0], 1) - coef = [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr] - funcs = [ - (np.floor, np.floor), - (np.floor, np.ceil), - (np.ceil, np.floor), - (np.ceil, np.ceil), - ] - num = den = 0 - for cf, (rf, cfun) in zip(coef, funcs): - a, f = corner(rf, cfun) - num = num + cf * f * a - den = den + cf * f - with np.errstate(divide="ignore", invalid="ignore"): - vim = 1 / den - vim[np.isinf(vim)] = np.nan - return num / den, vim - - -def random_frame( - rng: np.random.Generator, h: int = 18, w: int = 23, frac: float = 0.4 -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Smooth frame with a NaN pattern, its freshness and a template.""" - base = rng.random((h + 8, w + 8)) - img = (base[4:-4, 4:-4] + base[5:-3, 4:-4] + base[4:-4, 5:-3]) * 10 - frame = img + rng.normal(0, 0.5, img.shape) - fresh = rng.random(img.shape) + 0.2 - frame[rng.random(img.shape) < frac] = np.nan - fresh[np.isnan(frame)] = 0 - template = np.roll(img, (1, -2), (0, 1)) - template[rng.random(img.shape) < 0.2] = np.nan - return frame, fresh, template - - -@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) -def test_correlation_map_matches_matlab_loop(dtype: torch.dtype) -> None: - """Weighted NCC equals the MATLAB loop at every shift.""" - rng = np.random.default_rng(0) - frame, fresh, template = random_frame(rng) - s = 4 - rows, cols = np.nonzero(~np.isnan(frame)) - f = torch.from_numpy(frame[rows, cols])[None] - w = torch.from_numpy(fresh[rows, cols])[None] - tables = shift_tables( - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - s, - dtype, - ) - got = correlation_map(f, w, tables, s)[0].double().numpy() - want = xcorr_reference(frame, fresh, template, s) - tol = 1e-4 if dtype == torch.float32 else 1e-10 - np.testing.assert_allclose(got, want, atol=tol) - - -def test_match_recovers_shift_with_subpixel_sign() -> None: - """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" - rng = np.random.default_rng(1) - frame, fresh, template = random_frame(rng, frac=0.0) - frame = np.roll(template, (-1, 2), (0, 1)) - frame[np.isnan(frame)] = 5.0 - rows, cols = np.nonzero(~np.isnan(frame)) - mot, peak = match( - torch.from_numpy(frame[rows, cols])[None], - torch.ones(1, rows.size, dtype=torch.float64), - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - 4, - torch.float64, - ) - np.testing.assert_allclose(mot[0].numpy(), [-1, 2], atol=0.05) - assert peak[0] > 0.9 - - -def test_frame_without_valid_samples_has_nan_motion() -> None: - """An undefined correlation map gives NaN motion, not a search edge. - - The other frame of the batch is unaffected, and ``match`` raises. - """ - rng = np.random.default_rng(1) - _, _, template = random_frame(rng, frac=0.0) - good = np.roll(template, (-1, 2), (0, 1)) - good[np.isnan(good)] = 5.0 - rows, cols = np.nonzero(~np.isnan(good)) - frames = torch.from_numpy(np.stack([good[rows, cols]] * 2)) - weights = torch.ones(2, rows.size, dtype=torch.float64) - frames[1] = float("nan") # no valid samples - weights[1] = 0 - args = ( - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - 4, - torch.float64, - ) - mot, peak, corr = match_maps(frames, weights, *args) - assert torch.isnan(corr[1]).all() - assert torch.isnan(peak[1]) and torch.isnan(mot[1]).all() - want, want_peak = match(frames[:1], weights[:1], *args) - np.testing.assert_allclose(mot[0].numpy(), want[0].numpy(), rtol=1e-12) - np.testing.assert_allclose(peak[0].item(), want_peak[0].item()) - with pytest.raises(RegistrationError): - match(frames, weights, *args) - - -def test_motion_failed_needs_two_frames_with_motion() -> None: - """Missing frames are left out of the SD. - - A trial of several frames with fewer than two with motion fails (SILo - cannot interpolate it). - """ - from giant_python.registration.multiroi import motion_failed - - nan = np.nan - assert not motion_failed(np.array([0.1, 0.3, nan]), np.zeros(3)) - assert motion_failed(np.array([0.0, 5.0, nan, -5.0]), np.zeros(4)) - assert motion_failed(np.array([nan, 0.2, nan]), np.zeros(3)) - assert motion_failed(np.full(3, nan), np.full(3, nan)) - assert motion_failed(np.array([0.1, 0.2]), np.array([0.0, nan])) - with warnings.catch_warnings(): # SD of one value: NaN, as before - warnings.simplefilter("ignore", RuntimeWarning) - assert not motion_failed(np.array([0.2]), np.array([0.1])) - assert motion_failed(np.array([nan]), np.array([nan])) - - -@pytest.mark.parametrize("mr,mc", [(0.0, 0.0), (0.3, -0.7), (-1.25, 2.5), (3.0, -0.4), (30, 2)]) -def test_interp_frame_matches_matlab(mr: float, mc: float) -> None: - """Resampling equals interpFrame, including NaN and edge behaviour.""" - rng = np.random.default_rng(2) - frame, fresh, _ = random_frame(rng) - frame = frame.astype(np.float32) - fresh = fresh.astype(np.float32) - m = 3 - h, w = frame.shape - view_r = np.arange(1, h + 2 * m + 1) - m + mr - view_c = np.arange(1, w + 2 * m + 1) - m + mc - want_im, want_v = interp_reference(frame, view_c, view_r, fresh) - im, v = interp_frame(torch.from_numpy(frame), torch.from_numpy(fresh), mr, mc, m) - np.testing.assert_array_equal(np.isnan(im.numpy()), np.isnan(want_im)) - np.testing.assert_allclose(im.numpy(), want_im, rtol=1e-5, atol=1e-5) - np.testing.assert_allclose(v.numpy(), want_v, rtol=1e-5) - - -def test_matlab_helpers() -> None: - """MATLAB rounding, colon and 2 x 2 downsampling semantics.""" - np.testing.assert_array_equal(matlab_round([-2.5, -0.5, 0.5, 1.5, 2.4]), [-3, -1, 1, 2, 2]) - ds = matlab_colon(1, 133.6, 1000) - assert ds[0] == 1 and ds.size == 8 and ds[-1] <= 1000 - x = np.arange(30, dtype=np.float32).reshape(5, 6) - x[0, 0] = np.nan - y = downsample2(x) - assert y.shape == (2, 3) and np.isnan(y[0, 0]) - assert y[1, 2] == x[2, 4] + x[2, 5] + x[3, 4] + x[3, 5] - - -def test_rec_neg_err_matches_definition() -> None: - """Template excess over frames, with MATLAB's NaN handling.""" - rng = np.random.default_rng(3) - movie = rng.random((30, 6, 7)).astype(np.float32) * 20 - movie[5, 2, 3] = np.nan - movie[:, 0, 0] = np.nan - err = rec_neg_err(movie, align_hz=80) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) - tmpl = np.nanmedian(movie, 0) - tmpl[np.isnan(movie).mean(0) > 0.2] = np.nan - gam = np.sqrt(np.maximum(0, tmpl) + 10) - for k in (0, 5): - ex = (tmpl - movie[k]) / gam - num = np.nansum(np.maximum(0, ex) ** 2) / ex.size - den_v = (tmpl / gam) ** 2 + movie[k] * 0 - den = np.nanmean(den_v) - np.testing.assert_allclose(err[k], np.sqrt(num / den), rtol=1e-5) - - -def test_template_state_matches_matlab_rules() -> None: - """Sqrt of the mean, NaN below min_samples, and the T0 average.""" - total = torch.tensor([[4.0, 9.0], [0.0, 1.0]], dtype=torch.float64) - count = torch.tensor([[1.0, 1.0], [0.0, 1.0]], dtype=torch.float64) - t0 = torch.tensor([[1.0, float("nan")], [3.0, float("nan")]]) - state = TemplateState(total, count, t0.double(), min_samples=1) - np.testing.assert_allclose(state.template.numpy(), [[2, 3], [np.nan, 1]], equal_nan=True) - np.testing.assert_allclose(state.matching_template().numpy(), [[1.5, 3], [3, 1]]) - state.add(torch.tensor([[float("nan"), 7.0], [4.0, 3.0]])) - np.testing.assert_allclose(state.template.numpy(), [[2, np.sqrt(8)], [2, np.sqrt(2)]]) +"""Registration kernels against direct ports of the GIAnT-MATLAB code.""" + +import warnings +from collections.abc import Callable + +import numpy as np +import pytest +import torch + +from giant_python.registration.interpolation import interp_frame +from giant_python.registration.matching import ( + RegistrationError, + correlation_map, + match, + match_maps, + shift_tables, +) +from giant_python.registration.multiroi import matlab_colon +from giant_python.registration.outputs import ( + downsample2, + matlab_round, + rec_neg_err, +) +from giant_python.registration.template import TemplateState + + +def xcorr_reference( + frame: np.ndarray, fresh: np.ndarray, template: np.ndarray, s: int +) -> np.ndarray: + """Loop port of xcorr2_nans_weighted (correlation map only). + + Returns + ------- + np.ndarray + Weighted correlation at each shift, shape (2 * s + 1, 2 * s + 1). + """ + h, w = template.shape + rows, cols = np.nonzero(~np.isnan(frame)) + out = np.full((2 * s + 1, 2 * s + 1), np.nan) + for i, dr in enumerate(range(-s, s + 1)): + for j, dc in enumerate(range(-s, s + 1)): + r, c = rows + dr, cols + dc + ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) + t = np.full(rows.size, np.nan) + t[ok] = template[r[ok], c[ok]] + sel = ~np.isnan(t) + f, t, wt = frame[rows, cols][sel], t[sel], fresh[rows, cols][sel] + sw = wt.sum() + df = f - (wt * f).sum() / sw + dt = t - (wt * t).sum() / sw + out[i, j] = (wt * df * dt).sum() / np.sqrt((wt * dt**2).sum() * (wt * df**2).sum()) + return out + + +def interp_reference( + m1: np.ndarray, view_c: np.ndarray, view_r: np.ndarray, fresh: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + """Gather port of interpFrame (one-based view coordinates). + + Returns + ------- + frame : np.ndarray + The bilinearly interpolated frame, freshness-weighted. + vim : np.ndarray + Reciprocal of the summed bilinear freshness weights, NaN where infinite. + """ + h, w = m1.shape + + def corner( + rfun: Callable[[np.ndarray], np.ndarray], cfun: Callable[[np.ndarray], np.ndarray] + ) -> tuple[np.ndarray, np.ndarray]: + """Frame and freshness at one bilinear corner, NaN outside. + + Returns + ------- + frame : np.ndarray + The frame sampled at the corner, NaN outside the image. + fresh : np.ndarray + The freshness sampled at the corner, NaN outside the image. + """ + rr = rfun(view_r).astype(int) + cc = cfun(view_c).astype(int) + bad_r = (rr < 1) | (rr > h) + bad_c = (cc < 1) | (cc > w) + rr[bad_r], cc[bad_c] = 1, 1 + a = m1[np.ix_(rr - 1, cc - 1)].astype(np.float64) + f = fresh[np.ix_(rr - 1, cc - 1)].astype(np.float64) + for x in (a, f): + x[bad_r, :] = np.nan + x[:, bad_c] = np.nan + return a, f + + fc, fr = np.mod(view_c[0], 1), np.mod(view_r[0], 1) + coef = [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr] + funcs = [ + (np.floor, np.floor), + (np.floor, np.ceil), + (np.ceil, np.floor), + (np.ceil, np.ceil), + ] + num = den = 0 + for cf, (rf, cfun) in zip(coef, funcs): + a, f = corner(rf, cfun) + num = num + cf * f * a + den = den + cf * f + with np.errstate(divide="ignore", invalid="ignore"): + vim = 1 / den + vim[np.isinf(vim)] = np.nan + return num / den, vim + + +def random_frame( + rng: np.random.Generator, h: int = 18, w: int = 23, frac: float = 0.4 +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Smooth frame with a NaN pattern, its freshness and a template. + + Returns + ------- + frame : np.ndarray + Noisy smooth frame with NaN at random pixels. + fresh : np.ndarray + Freshness weights, 0 where the frame is NaN. + template : np.ndarray + Shifted copy of the underlying image with some NaN pixels. + """ + base = rng.random((h + 8, w + 8)) + img = (base[4:-4, 4:-4] + base[5:-3, 4:-4] + base[4:-4, 5:-3]) * 10 + frame = img + rng.normal(0, 0.5, img.shape) + fresh = rng.random(img.shape) + 0.2 + frame[rng.random(img.shape) < frac] = np.nan + fresh[np.isnan(frame)] = 0 + template = np.roll(img, (1, -2), (0, 1)) + template[rng.random(img.shape) < 0.2] = np.nan + return frame, fresh, template + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) +def test_correlation_map_matches_matlab_loop(dtype: torch.dtype) -> None: + """Weighted NCC equals the MATLAB loop at every shift.""" + rng = np.random.default_rng(0) + frame, fresh, template = random_frame(rng) + s = 4 + rows, cols = np.nonzero(~np.isnan(frame)) + f = torch.from_numpy(frame[rows, cols])[None] + w = torch.from_numpy(fresh[rows, cols])[None] + tables = shift_tables( + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + s, + dtype, + ) + got = correlation_map(f, w, tables, s)[0].double().numpy() + want = xcorr_reference(frame, fresh, template, s) + tol = 1e-4 if dtype == torch.float32 else 1e-10 + np.testing.assert_allclose(got, want, atol=tol) + + +def test_match_recovers_shift_with_subpixel_sign() -> None: + """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" + rng = np.random.default_rng(1) + frame, fresh, template = random_frame(rng, frac=0.0) + frame = np.roll(template, (-1, 2), (0, 1)) + frame[np.isnan(frame)] = 5.0 + rows, cols = np.nonzero(~np.isnan(frame)) + mot, peak = match( + torch.from_numpy(frame[rows, cols])[None], + torch.ones(1, rows.size, dtype=torch.float64), + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + 4, + torch.float64, + ) + np.testing.assert_allclose(mot[0].numpy(), [-1, 2], atol=0.05) + assert peak[0] > 0.9 + + +def test_frame_without_valid_samples_has_nan_motion() -> None: + """An undefined correlation map gives NaN motion, not a search edge. + + The other frame of the batch is unaffected, and match raises. + """ + rng = np.random.default_rng(1) + _, _, template = random_frame(rng, frac=0.0) + good = np.roll(template, (-1, 2), (0, 1)) + good[np.isnan(good)] = 5.0 + rows, cols = np.nonzero(~np.isnan(good)) + frames = torch.from_numpy(np.stack([good[rows, cols]] * 2)) + weights = torch.ones(2, rows.size, dtype=torch.float64) + frames[1] = float("nan") # no valid samples + weights[1] = 0 + args = ( + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + 4, + torch.float64, + ) + mot, peak, corr = match_maps(frames, weights, *args) + assert torch.isnan(corr[1]).all() + assert torch.isnan(peak[1]) and torch.isnan(mot[1]).all() + want, want_peak = match(frames[:1], weights[:1], *args) + np.testing.assert_allclose(mot[0].numpy(), want[0].numpy(), rtol=1e-12) + np.testing.assert_allclose(peak[0].item(), want_peak[0].item()) + with pytest.raises(RegistrationError): + match(frames, weights, *args) + + +def test_motion_failed_needs_two_frames_with_motion() -> None: + """Missing frames are left out of the SD. + + A trial of several frames with fewer than two with motion fails (SILo + cannot interpolate it). + """ + from giant_python.registration.multiroi import motion_failed + + nan = np.nan + assert not motion_failed(np.array([0.1, 0.3, nan]), np.zeros(3)) + assert motion_failed(np.array([0.0, 5.0, nan, -5.0]), np.zeros(4)) + assert motion_failed(np.array([nan, 0.2, nan]), np.zeros(3)) + assert motion_failed(np.full(3, nan), np.full(3, nan)) + assert motion_failed(np.array([0.1, 0.2]), np.array([0.0, nan])) + with warnings.catch_warnings(): # SD of one value: NaN, as before + warnings.simplefilter("ignore", RuntimeWarning) + assert not motion_failed(np.array([0.2]), np.array([0.1])) + assert motion_failed(np.array([nan]), np.array([nan])) + + +@pytest.mark.parametrize("mr,mc", [(0.0, 0.0), (0.3, -0.7), (-1.25, 2.5), (3.0, -0.4), (30, 2)]) +def test_interp_frame_matches_matlab(mr: float, mc: float) -> None: + """Resampling equals interpFrame, including NaN and edge behaviour.""" + rng = np.random.default_rng(2) + frame, fresh, _ = random_frame(rng) + frame = frame.astype(np.float32) + fresh = fresh.astype(np.float32) + m = 3 + h, w = frame.shape + view_r = np.arange(1, h + 2 * m + 1) - m + mr + view_c = np.arange(1, w + 2 * m + 1) - m + mc + want_im, want_v = interp_reference(frame, view_c, view_r, fresh) + im, v = interp_frame(torch.from_numpy(frame), torch.from_numpy(fresh), mr, mc, m) + np.testing.assert_array_equal(np.isnan(im.numpy()), np.isnan(want_im)) + np.testing.assert_allclose(im.numpy(), want_im, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(v.numpy(), want_v, rtol=1e-5) + + +def test_matlab_helpers() -> None: + """MATLAB rounding, colon and 2 x 2 downsampling semantics.""" + np.testing.assert_array_equal(matlab_round([-2.5, -0.5, 0.5, 1.5, 2.4]), [-3, -1, 1, 2, 2]) + ds = matlab_colon(1, 133.6, 1000) + assert ds[0] == 1 and ds.size == 8 and ds[-1] <= 1000 + x = np.arange(30, dtype=np.float32).reshape(5, 6) + x[0, 0] = np.nan + y = downsample2(x) + assert y.shape == (2, 3) and np.isnan(y[0, 0]) + assert y[1, 2] == x[2, 4] + x[2, 5] + x[3, 4] + x[3, 5] + + +def test_rec_neg_err_matches_definition() -> None: + """Template excess over frames, with MATLAB's NaN handling.""" + rng = np.random.default_rng(3) + movie = rng.random((30, 6, 7)).astype(np.float32) * 20 + movie[5, 2, 3] = np.nan + movie[:, 0, 0] = np.nan + err = rec_neg_err(movie, align_hz=80) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + tmpl = np.nanmedian(movie, 0) + tmpl[np.isnan(movie).mean(0) > 0.2] = np.nan + gam = np.sqrt(np.maximum(0, tmpl) + 10) + for k in (0, 5): + ex = (tmpl - movie[k]) / gam + num = np.nansum(np.maximum(0, ex) ** 2) / ex.size + den_v = (tmpl / gam) ** 2 + movie[k] * 0 + den = np.nanmean(den_v) + np.testing.assert_allclose(err[k], np.sqrt(num / den), rtol=1e-5) + + +def test_template_state_matches_matlab_rules() -> None: + """Sqrt of the mean, NaN below min_samples, and the T0 average.""" + total = torch.tensor([[4.0, 9.0], [0.0, 1.0]], dtype=torch.float64) + count = torch.tensor([[1.0, 1.0], [0.0, 1.0]], dtype=torch.float64) + t0 = torch.tensor([[1.0, float("nan")], [3.0, float("nan")]]) + state = TemplateState(total, count, t0.double(), min_samples=1) + np.testing.assert_allclose(state.template.numpy(), [[2, 3], [np.nan, 1]], equal_nan=True) + np.testing.assert_allclose(state.matching_template().numpy(), [[1.5, 3], [3, 1]]) + state.add(torch.tensor([[float("nan"), 7.0], [4.0, 3.0]])) + np.testing.assert_allclose(state.template.numpy(), [[2, np.sqrt(8)], [2, np.sqrt(2)]]) diff --git a/tests/registration/test_reg_stats.py b/tests/registration/test_reg_stats.py index 1caacee8..e0ec137a 100644 --- a/tests/registration/test_reg_stats.py +++ b/tests/registration/test_reg_stats.py @@ -1,889 +1,983 @@ -"""Registration summary statistics (``registration.stats``).""" - -from collections.abc import Iterator -from pathlib import Path -from typing import Any, NoReturn - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import RasterLayout, read_raster_samples -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer -from giant_python.registration.interpolation import interp_frame -from giant_python.registration.multiroi import frame_times -from giant_python.registration.sources import CompensatedFrames, PlainFrames, make_source -from giant_python.registration.stats import ( - STATS_VERSION, - measure_gain_curves, - new_accumulator, - read_stats, - stats_path, -) -from giant_python.registration.stats.gain import ( - curve_from_sums, - next_slots, - pair_curve, - pair_sums, - slot_sums, -) -from giant_python.registration.stats.geometry import ( - FrameGeometry, - bilinear_corners, -) -from giant_python.registration.stats.session import combine_trials - -from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout, write_recording - -MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" -ADATA = "E1T1DMD1_ALIGNMENTDATA.h5" - - -@pytest.fixture(scope="module") -def recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: - """Layout and data file of a 6-second recording (moving scene).""" - path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400) - write_recording(layout, invalid=0.0) - return layout - - -@pytest.fixture -def patched(recording: RasterLayout, monkeypatch: pytest.MonkeyPatch) -> RasterLayout: - """Patch registration to read the recording's layout.""" - monkeypatch.setattr(multiroi, "raster_layout", lambda path: recording) - return recording - - -def _source( - layout: RasterLayout, samples: np.ndarray, first: float = 1.0, last: float = 3000.0 -) -> tuple[PlainFrames | CompensatedFrames, np.ndarray]: - """Frame source of samples over the layout (as registration's).""" - former = FrameFormer(layout, samples, 0) - dt = (1 / layout.line_period_s) / 80 - dtk = int(np.ceil(dt)) - init, ds = frame_times(first, last, dt, 40) - return make_source(layout, former, first, last, init, ds, dtk, False), ds - - -def _motion(n: int, seed: int = 0, jump: int | None = None) -> np.ndarray: - """Sub-pixel motion (rows, cols) with jitter.""" - rng = np.random.default_rng(seed) - t = np.arange(n) - m = np.stack( - [ - 0.7 * np.sin(t / 7.0) + rng.normal(0, 0.15, n), - 0.9 * np.cos(t / 11.0) + rng.normal(0, 0.15, n), - ], - 1, - ) - if jump is not None: - m[jump] += [1.3, -1.1] - return m - - -def _registered( - source: PlainFrames | CompensatedFrames, ds: np.ndarray, motion: np.ndarray, margin: int -) -> Iterator[tuple[list[torch.Tensor], torch.Tensor]]: - """Yield registered frames and variance factors (``interp_frame``).""" - vals, fresh = source.frames(ds) - win = source.window - for k in range(ds.size): - fimg = win.image(fresh[k], 0.0) - regs = [ - interp_frame(win.image(vals[ch, k], float("nan")), fimg, *motion[k], margin) - for ch in range(vals.shape[0]) - ] - yield [r for r, _ in regs], regs[0][1] - - -# --------------------------------------------------------------- geometry - - -def _coefficients( - layout: RasterLayout, - source: PlainFrames | CompensatedFrames, - ds: np.ndarray, - motion: np.ndarray, - margin: int, - t: int, - p: int, -) -> dict[tuple[int, int], float]: - """Sample coefficients of registered frame ``t`` at output pixel ``p`` by the definition. - - This uses slow loops. - """ - win = source.window - w_out = win.shape[1] + 2 * margin - ids = source.former.pixels[source.pixels.numpy()] - where = { - (int(r), int(c)): i for i, (r, c) in enumerate(zip(win.rows.numpy(), win.cols.numpy())) - } - dt = int(source.dt) - reach = max(3 * dt, layout.lines_per_cycle) - r, c = divmod(int(p), w_out) - off_r, off_c, coef, _ = bilinear_corners(*motion[t], margin) - parts, den = [], 0.0 - for k, (a, b) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))): - i = where.get((r + off_r + a, c + off_c + b)) - if i is None: - continue - slots = np.flatnonzero(layout.slot_pixel == ids[i]) - for s in slots: - for cyc in range(layout.num_cycles): - line = cyc * layout.lines_per_cycle + layout.slot_line[s] - if abs(ds[t] - line) <= reach: - wgt = coef[k] * np.exp(-abs(ds[t] - line) / dt) - parts.append(((s, cyc), wgt)) - den += wgt - out = {} - for key, v in parts: - out[key] = out.get(key, 0.0) + v / den - return out - - -def test_geometry_matches_definition(recording: RasterLayout) -> None: - """Photon-noise sums equal sums over the samples' coefficients.""" - layout = recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - source, ds = _source(layout, samples) - m = 6 - motion = _motion(ds.size, jump=12) - geo = FrameGeometry(source, ds, m) - assert geo.n_lags == 6 - vfs = torch.stack([vf.reshape(-1) for _, vf in - _registered(source, ds, motion, m)]) # fmt: skip - ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() - pix = ok[:: max(1, ok.numel() // 6)][:6] - f0, f1 = 8, 16 - e = f1 + geo.n_lags - res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) - for j, p in enumerate(pix.tolist()): - for t in range(f0, f1): - at = _coefficients(layout, source, ds, motion, m, t, p) - g0 = sum(v * v for v in at.values()) - r0 = sum(v**3 for v in at.values()) - assert res["G"][0, t - f0, j] == pytest.approx(g0, rel=1e-5) - assert res["R0"][t - f0, j] == pytest.approx(r0, rel=1e-5) - for lag in (1, 3, 6): - au = _coefficients(layout, source, ds, motion, m, t + lag, p) - g = sum(v * au.get(k, 0) for k, v in at.items()) - rr = sum(v * v * au.get(k, 0) for k, v in at.items()) - got = res["G"][lag, t - f0, j] - assert abs(got - g) <= 1e-5 * g0 - assert abs(res["R"][lag - 1, t - f0, j] - rr) <= 1e-5 * r0 - - -# ------------------------------------------------------------------- gains - - -def _compound_poisson( - rate: np.ndarray, rng: np.random.Generator, k: float = 5.0, theta: float = 22.0 -) -> np.ndarray: - """Draw samples: sums of Poisson(rate) integer gamma pulses (int16).""" - n = rng.poisson(rate) - out = np.zeros(rate.shape) - for j in range(int(n.max())): - use = n > j - out[use] += np.round(rng.gamma(k, theta, int(use.sum()))) - return out.astype(np.int16) - - -def scan_layout(path: Path, n_cycles: int) -> RasterLayout: - """Build a raster scanned row by row. - - Line ``r + 2`` samples row ``8 + r``, columns 10-39 from left to right - (so consecutive samples on a line are horizontal neighbours); line 1 has - no samples. - """ - n_rows, n_cols, n_ch, rows = 36, 50, 2, 20 - p = rows + 1 - slot_line, slot_pos, slot_pixel = [], [], [] - for r in range(rows): - for j, c in enumerate(range(10, 40)): - slot_line.append(r + 2) - slot_pos.append(j) - slot_pixel.append((8 + r) * n_cols + c + 1) - n_per = np.array([0] + [30] * rows) - header_words = LINE_HEADER_BYTES // 2 - line_words = header_words + n_ch * n_per - line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) - return RasterLayout( - files=(str(path),), - file_cycles=np.array([n_cycles]), - file_offset_words=np.array([HEADER_WORDS]), - words_per_cycle=int(line_words.sum()), - lines_per_cycle=p, - n_rows=n_rows, - n_cols=n_cols, - num_channels=n_ch, - line_period_s=1 / 1600.0, - line_header_bytes=LINE_HEADER_BYTES, - line_header_words=line_header, - row_base=line_header + header_words, - n_per_channel=n_per, - line_fast_z=np.ones(p, dtype=np.int64), - fast_zs=np.array([-20.0]), - slot_line=np.array(slot_line), - slot_pos=np.array(slot_pos), - slot_pixel=np.array(slot_pixel), - ) - - -def _shared_pulses( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - p_split: float = 0.35, - k: float = 5.0, - theta: float = 22.0, -) -> np.ndarray: - """Draw compound-Poisson samples whose pulses are sometimes shared with the next sample. - - With probability ``p_split`` a fraction ``U(0, 0.5)`` of a pulse goes to - the next sample on the line. - """ - n = rng.poisson(rate) - out = np.zeros(rate.shape) - has = nxt >= 0 - for j in range(int(n.max())): - use = n > j - a = np.zeros(rate.shape) - a[use] = np.round(rng.gamma(k, theta, int(use.sum()))) - split = (rng.random(rate.shape) < p_split) & has[..., :, None] - moved = np.round(a * rng.random(rate.shape) * 0.5) * split - out += a - moved - out[..., nxt[has], :] += moved[..., has, :] - return out.astype(np.int16) - - -def test_gain_groups_without_zeros_keep_their_gains() -> None: - """Bright groups that have no zero sample keep their gains. - - The non-zero rate comes from the groups that have zeros. - """ - rng = np.random.default_rng(4) - rate = np.repeat(np.geomspace(0.05, 60, 320)[:, None], 2000, 1) - x = (100 * rng.poisson(rate)).astype(np.int16) - curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) - assert curve.mu.size == 16 - assert np.isnan(curve.nu_per_mu[-1]) # no zeros at ~50 photons - np.testing.assert_allclose(curve.g2, 100, rtol=0.05) # >= 2000 photons - assert np.isfinite(curve.g3).all() - np.testing.assert_allclose(curve.g3[:8], 1e4, rtol=0.1) # dim: precise - at = curve.at(curve.mu) - assert np.isfinite(at["nu"]).all() - ok = np.isfinite(curve.nu_per_mu) - np.testing.assert_allclose(at["nu"][ok], (curve.mu * curve.nu_per_mu)[ok]) - one = curve.at(100.0) # a scalar mean too - assert one["g2"].shape == () and np.isfinite(one["g2"]) - assert np.isnan(curve.at(np.nan)["g2"]) - - -def test_gain_sums_do_not_overflow() -> None: - """Cubes of extreme second differences over a long trial would overflow int64. - - Those sums are float64 then (and exact int64 for ordinary trials). - """ - x = np.zeros((2, 150_000), dtype=np.int16) - x[:, ::3] = 32767 # d = 65534, -32767, -32767: cubes sum to > 2^63 - got = slot_sums(torch.from_numpy(x[None]), 0) - d = 2 * x[:, 1:-1].astype(object) - x[:, :-2] - x[:, 2:] - want = [sum(int(v) ** 3 for v in row) for row in d] - np.testing.assert_allclose(got[:, 6], np.array(want, float), rtol=1e-12) - assert abs(want[0]) > 2**63 # int64 would have overflowed - short = slot_sums(torch.from_numpy(x[None, :, :100]), 0) - assert short.dtype == np.int64 - # nor do a group's sums of large per-slot sums - rows = np.tile([100, 1000, 10, 98, 980, 6000, 3 * 10**18], (32, 1)) - curve = curve_from_sums(rows.astype(np.int64), n_bins=2) - np.testing.assert_allclose(curve.g3, 3e18 / (6 * 980), rtol=1e-12) - - -def test_components_of_tall_and_wide_inputs() -> None: - """The top components equal numpy's SVD whichever Gram matrix is smaller. - - That is, with more time bins than spatial bins, or fewer. - """ - from giant_python.registration.stats.svd import _components - - rng = np.random.default_rng(9) - for shape in ((40, 300), (300, 40)): - y = rng.normal(size=shape) + np.outer( - np.sin(np.arange(shape[0]) / 5), rng.normal(size=shape[1]) - ) - u, s, total = _components(y, 3) - uu, ss, _ = np.linalg.svd(y, full_matrices=False) - np.testing.assert_allclose(s, ss[:3], rtol=1e-9) - np.testing.assert_allclose(np.abs(u.T @ uu[:, :3]), np.eye(3), atol=1e-8) - assert (np.sum(y.T @ u, 0) >= 0).all() - assert total == pytest.approx(np.sum(y**2)) - # rank 1 (tall and wide): one component, finite, and weights for it - for shape in ((300, 40), (40, 300)): - a, b = rng.normal(size=shape[0]), rng.normal(size=shape[1]) - y = np.outer(a, b) - u, s, _ = _components(y, 3) - assert u.shape == (shape[0], 1) and np.isfinite(u).all() - np.testing.assert_allclose(s, [np.linalg.norm(a) * np.linalg.norm(b)]) - - -def test_regression_weights_of_undetermined_pixels() -> None: - """A pixel whose valid bins leave a time course flat gets NaN weights (not an error). - - The others are fitted. - """ - from giant_python.registration.stats.svd import regression_weights - - rng = np.random.default_rng(8) - nb = 280 - u = np.zeros((nb, 2)) - u[:100, 0] = rng.normal(size=100) # active in the first 100 bins only - u[:, 1] = rng.normal(size=nb) - u /= np.linalg.norm(u, axis=0) - y = 5 + u @ np.array([[3.0, 2.0, 1.0], [1.0, -1.0, 4.0]]) - y[:100, 1] = np.nan # pixel 1 misses the first course's activity - w = regression_weights(y, u) - np.testing.assert_allclose(w[[0, 2]], [[3.0, 1.0], [1.0, 4.0]]) - assert np.isnan(w[1]).all() - - -def test_gain_curve_of_compound_poisson() -> None: - """Gains equal E[A^2]/E[A] and E[A^3]/E[A] of the pulse heights.""" - rng = np.random.default_rng(3) - rate = np.repeat(np.geomspace(0.03, 3, 1600)[:, None], 3000, 1) - x = _compound_poisson(rate, rng) - pulses = np.round(rng.gamma(5.0, 22.0, 2_000_000)) - g2 = (pulses**2).mean() / pulses.mean() - g3 = (pulses**3).mean() / pulses.mean() - curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) - assert np.allclose(curve.g2, g2, rtol=0.03) # >= 9000 photons each - assert np.allclose(curve.g3, g3, rtol=0.08) - nu = curve.at(curve.mu)["nu"] - zero = (x == 0).mean(1) - mean = x.mean(1) - want = np.interp(curve.mu, mean, -np.log(zero)) - assert np.allclose(nu, want, rtol=0.05) - - -# --------------------------------------------------------------- the maps - - -def _stats( - layout: RasterLayout, samples: np.ndarray, motion_seed: int = 0, last: float = 9000.0 -) -> dict: - """Statistics of samples through registration's frame formation.""" - source, ds = _source(layout, samples, last=last) - acc = new_accumulator(source, ds, 6, layout.num_channels) - motion = _motion(ds.size, motion_seed) - for k, (regs, vf) in enumerate(_registered(source, ds, motion, 6)): - acc.add(k, regs, vf, tuple(motion[k])) - return acc.finish() - - -def _interior(maps: dict[str, np.ndarray]) -> np.ndarray: - """Pixels whose maps are defined in every channel.""" - return np.isfinite(maps["slow_rel"]).all(0) & np.isfinite(maps["fast_rel"]).all(0) - - -@pytest.fixture(scope="module") -def uniform( - tmp_path_factory: pytest.TempPathFactory, -) -> tuple[RasterLayout, np.ndarray, np.ndarray]: - """Simulate a uniform scene of compound-Poisson samples. - - 0.05 and 2 photons per sample in the two channels; no file needed. - """ - path = tmp_path_factory.mktemp("uni") / "uniform_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1600) - rng = np.random.default_rng(5) - shape = (layout.slot_line.size, layout.num_cycles) - rate = np.stack([np.full(shape, 0.05), np.full(shape, 2.0)]) - return layout, _compound_poisson(rate, rng), rate - - -def test_photon_noise_maps_read_zero(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: - """Under photon noise alone the normalised maps are 0 at any brightness. - - Means over pixels: a variance from few blocks is unbiased but its median - is low, as for chi-square. - """ - layout, samples, _ = uniform - res = _stats(layout, samples, last=11000.0) - maps = res["maps"] - use = _interior(maps) - assert use.sum() > 300 - for ch in range(2): - for name, tol in ( - ("var_rel", 0.02), - ("fast_rel", 0.02), - ("slow_rel", 0.1), - ("fast_skew_rel", 0.06), - ("zero_excess", 0.003), - ): - mean = np.mean(maps[name][ch][use]) - assert abs(mean) < tol, (ch, name, mean) - gains = measure_gain_curves(torch.from_numpy(samples)) - assert np.allclose(gains[1].g2, 132.0, rtol=0.03) - assert res["svd"]["var_share"].shape == (2, 3) - - -def test_events_raise_fast_skewness(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: - """Positive transients raise the fast maps where they are.""" - layout, _, rate = uniform - rate = rate.copy() - rows = (layout.slot_pixel - 1) // layout.n_cols - cols = (layout.slot_pixel - 1) % layout.n_cols - src = (np.abs(rows - 17) <= 1) & (np.abs(cols - 24) <= 1) - p = layout.lines_per_cycle - t = (np.arange(layout.num_cycles) * p) * layout.line_period_s - kern = np.zeros(t.size) - for onset in np.arange(0.3, t[-1], 0.9): - kern += np.where(t >= onset, np.exp(-(t - onset) / 0.025), 0.0) - rate[1, src] += 4.0 * kern - samples = _compound_poisson(rate, np.random.default_rng(6)) - maps = _stats(layout, samples, last=11000.0)["maps"] - m = 6 - sk = maps["fast_skew_rel"][1] - fr = maps["fast_rel"][1] - at = sk[17 - 8 + m, 24 - 10 + m] - away = np.nanmedian(sk[m : m + 5]) # DMD rows 8-12 - assert at > 1.0 and abs(away) < 0.2 - assert fr[17 - 8 + m, 24 - 10 + m] > 1.0 - - -# ------------------------------------------------- registration and command - - -@pytest.mark.parametrize( - "device", - [ - "cpu", - pytest.param( - "cuda", - marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="no CUDA device"), - ), - ], -) -def test_registration_and_command_agree(patched: RasterLayout, tmp_path: Path, device: str) -> None: - """``giant reg-stats`` on registration's outputs gives the same maps. - - On a GPU registration's run on a thread and stream of their own, the - command's in line. The mean equals ``meanIM``; statistics do not change - the movie. - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - out = {} - for stats in (True, False): - d = tmp_path / str(stats) - d.mkdir() - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - multiroi.register_trial( - layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params, - device=device, stats=stats, - ) # fmt: skip - with h5py.File(d / MOVIE) as f: - out[stats] = f["data"][()] - np.testing.assert_array_equal(out[True], out[False]) - assert not stats_path(tmp_path / "False" / MOVIE).exists() - d = tmp_path / "True" - a = read_stats(stats_path(d / MOVIE)) - assert a["attrs"]["stats_version"] == STATS_VERSION - with h5py.File(d / ADATA) as f: - mean_im = np.swapaxes(np.moveaxis(f["meanIM"][()], -1, 0), 1, 2) - np.testing.assert_array_equal(a["maps"]["mean"], mean_im) - cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name - trial_stats(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, cmd, device, - {"maxshift": 6}) # fmt: skip - b = read_stats(cmd) - for grp in ("maps", "svd", "gain"): - assert a[grp].keys() == b[grp].keys() - for k in a[grp]: - np.testing.assert_array_equal(a[grp][k], b[grp][k], err_msg=k) - - -@pytest.mark.parametrize("last", [2.0, 60.0]) -def test_short_trials_get_statistics(patched: RasterLayout, tmp_path: Path, last: float) -> None: - """A one-frame (or three-frame) trial gets a statistics file equal to the command's. - - Its maps are NaN where there are too few frames. - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, last, tmp_path / MOVIE, tmp_path / ADATA) - res = multiroi.register_trial(*args, params) - assert res.ds_frames.size <= 3 - a = read_stats(stats_path(tmp_path / MOVIE)) - assert np.isnan(a["maps"]["fast_rel"]).all() - assert np.nanmax(a["maps"]["n_valid"]) == res.ds_frames.size - b = trial_stats(*args, tmp_path / "cmd.h5", "cpu", {"maxshift": 6}) - for k in a["maps"]: - np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) - - -def test_command_treats_empty_frames_as_missing(patched: RasterLayout, tmp_path: Path) -> None: - """A frame without data counts as missing in the command. - - This holds even where the alignment file gives it a motion (as - GIAnT-MATLAB's may). - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) - multiroi.register_trial(*args, params) - with h5py.File(tmp_path / MOVIE, "r+") as f: - n_ch = layout.num_channels - f["data"][10 * n_ch : 11 * n_ch] = np.nan # frame 10 without data - finite = trial_stats(*args, tmp_path / "a.h5", "cpu", {"maxshift": 6}) - with h5py.File(tmp_path / ADATA, "r+") as f: - for key in ("motionDSr", "motionDSc"): - m = f[key][()] - m.reshape(-1)[10] = np.nan - f[key][...] = m - missing = trial_stats(*args, tmp_path / "b.h5", "cpu", {"maxshift": 6}) - for k in finite["maps"]: - np.testing.assert_array_equal(finite["maps"][k], missing["maps"][k], err_msg=k) - for k in ("spatial_factor", "pair_bin_factor"): # frame 10 left out - assert finite["attrs"][k] == missing["attrs"][k] - - -def test_rerun_without_stats_removes_old_file(patched: RasterLayout, tmp_path: Path) -> None: - """A registration without statistics leaves none from an earlier one.""" - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) - multiroi.register_trial(*args, params) - assert stats_path(tmp_path / MOVIE).exists() - multiroi.register_trial(*args, params, stats=False) - assert not stats_path(tmp_path / MOVIE).exists() - - -@pytest.mark.parametrize("step", ["start", "setup", "add", "finish", "write"]) -def test_failed_statistics_leave_registration( - patched: RasterLayout, - tmp_path: Path, - step: str, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, -) -> None: - """A statistics step that fails is logged. - - The step fails on the worker thread, or writing the file, with its - cleanup failing too. Registration publishes the same movie and alignment - file, without statistics (and removes an earlier statistics file). - """ - import pathlib - - from giant_python.registration.stats import accumulate, io - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - ref = tmp_path / "ref" - ref.mkdir() - multiroi.register_trial(layout.files[0], 1, 3000, ref / MOVIE, ref / ADATA, params, stats=False) - - def fail(*args: object, **kwargs: object) -> NoReturn: - """Fail as a broken step.""" - raise RuntimeError("broken statistics") - - if step == "start": - monkeypatch.setattr(multiroi, "StatsWorker", fail) - elif step == "setup": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "__init__", fail) - elif step == "add": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_block", fail) - elif step == "finish": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_maps", fail) - else: - monkeypatch.setattr(io, "write_stats", fail) - unlink = pathlib.Path.unlink - - def locked(path: Path, *args: Any, **kwargs: Any) -> None: # noqa: ANN401 - forwarded to unlink - """Path.unlink, refusing the partial statistics file.""" - if "REGSTATS" in path.name and path.name != STATS_NAME: - raise PermissionError("locked") - return unlink(path, *args, **kwargs) - - STATS_NAME = stats_path(tmp_path / MOVIE).name - monkeypatch.setattr(pathlib.Path, "unlink", locked) - d = tmp_path / "run" - d.mkdir() - stats_path(d / MOVIE).write_bytes(b"from an earlier registration") - multiroi.register_trial(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params) - assert "summary statistics" in caplog.text - assert not stats_path(d / MOVIE).exists() - assert sorted(p.name for p in d.iterdir()) == [ADATA, MOVIE] - with h5py.File(d / MOVIE) as f, h5py.File(ref / MOVIE) as g: - np.testing.assert_array_equal(f["data"][()], g["data"][()]) - with h5py.File(d / ADATA) as f, h5py.File(ref / ADATA) as g: - for k in ("motionDSr", "motionDSc", "meanIM"): - np.testing.assert_array_equal(f[k][()], g[k][()]) - - -def test_command_checks_online_compensation( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """For an online-compensated trial the command rebuilds the compensation registration saved. - - It gets the same maps and refuses a trial whose saved record differs. - """ - from giant_python.pipeline.reg_stats import trial_stats - - from .synthetic import online_offsets - - layout = make_layout(tmp_path / "online_DMD1-TRIAL000001.dat", n_cycles=1400, seed=5) - write_recording(layout, seed=6, online=online_offsets(layout.total_lines)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=True) - d = tmp_path / "reg" - d.mkdir() - args = (layout.files[0], 1, 6000, d / MOVIE, d / ADATA) - multiroi.register_trial(*args, params) - a = read_stats(stats_path(d / MOVIE)) - cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name - trial_stats(*args, cmd, "cpu", {"maxshift": 6}) - b = read_stats(cmd) - for k in a["maps"]: - np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) - with h5py.File(d / ADATA, "r+") as f: - lead = f["slap2/onlineCompensation/yLead"] - lead[...] = lead[()] + 1 - with pytest.raises(ValueError, match="yLead"): - trial_stats(*args, tmp_path / "other.h5", "cpu", {"maxshift": 6}) - - -def test_statistics_file_that_cannot_be_moved( - patched: RasterLayout, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, -) -> None: - """If the statistics file cannot be moved into place, the other outputs are published. - - The movie and the alignment file are published all the same, without - statistics (an earlier statistics file is removed). - """ - import os - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - stale = stats_path(tmp_path / MOVIE) - stale.write_bytes(b"from an earlier registration") - replace = os.replace - - def refuse_stats(src: str | Path, dst: str | Path) -> None: - """os.replace, refusing the statistics file.""" - if Path(dst) == stale: - raise PermissionError("locked") - return replace(src, dst) - - monkeypatch.setattr(os, "replace", refuse_stats) - multiroi.register_trial(layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA, params) - assert "not published" in caplog.text - assert sorted(p.name for p in tmp_path.iterdir()) == [ADATA, MOVIE] - - -def test_reg_stats_command(patched: RasterLayout, tmp_path: Path) -> None: - """The CLI writes the statistics of a table's trials once.""" - from giant_python.cli import main - from giant_python.pipeline.reg_stats import reg_stats - from giant_python.pipeline.register import register_multiroi - - layout = patched - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[1.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - }, - ) - register_multiroi( - table, - {"maxshift": 5}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - out = tmp_path / "stats" - assert main(["reg-stats", str(table), "--out", str(out), - "--device", "cpu"]) == 0 # fmt: skip - written = out / "E1T1DMD1_REGSTATS-80Hz.h5" - assert written.exists() - assert reg_stats(table, out, device="cpu") == [] # up to date - with h5py.File(written, "r+") as f: # as if the movie were rewritten - f.attrs["movie_size"] = int(f.attrs["movie_size"]) + 1 - assert len(reg_stats(table, out, device="cpu")) == 1 - assert read_stats(written)["attrs"]["validity_differs"] == [0, 0] - movie = tmp_path / "motion_correction" / MOVIE - movie.rename(movie.with_suffix(".moved")) # a requested trial is missing - assert main(["reg-stats", str(table), "--out", str(out), - "--device", "cpu"]) == 1 # fmt: skip - - -def test_validity_mismatch_counts_channels() -> None: - """Samples whose validity differs from the first channel's are counted per channel.""" - from giant_python.io.slap2_raster import INVALID_SAMPLE - from giant_python.registration.stats.gain import validity_mismatch - - x = np.ones((3, 300, 50), dtype=np.int16) - x[:, 0, :5] = INVALID_SAMPLE # all channels: no mismatch - x[1, 10, :7] = INVALID_SAMPLE - x[2, 200, :3] = INVALID_SAMPLE - x[0, 250, :2] = INVALID_SAMPLE # first channel only: both others - assert validity_mismatch(torch.from_numpy(x)) == [0, 9, 5] - - -def test_stats_path_names() -> None: - """Statistics files sit next to the movie, named after it.""" - assert stats_path(Path("d") / MOVIE).name == "E1T1DMD1_REGSTATS-80Hz.h5" - tif = Path("E2T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif") - assert stats_path(tif).name == "E2T3DMD2_REGSTATS-80Hz.h5" - assert stats_path(Path("m.h5")).name == "m_REGSTATS.h5" - - -# ----------------------------------------------------------------- session - - -def test_combine_trials_weights_by_frames() -> None: - """Session maps: shifted, frame-weighted means. - - Normalised maps are formed from the averages. - """ - shape = (1, 20, 30) - trials = [] - for t, (n, var) in enumerate(((100.0, 2.0), (300.0, 4.0))): - maps = {} - for k in ("n_valid", "n_blocks", "n_fast"): - maps[k] = np.full(shape, n) - for k in ("mean", "var", "var_q", "zero_share", "zero_ph", - "gain_g2", "gain_g3", "sigma8_ph", "slow_var", "slow_q", - "fast_var", "fast_q", "fast_m3", "fast_q3", - "fast_m3_ph"): # fmt: skip - maps[k] = np.full(shape, 1.0) - maps["var"] = np.full(shape, var) - for k in ("var_ph", "slow_var_ph", "fast_var_ph"): - maps[k] = np.full(shape, 2.0) - maps["mean"][0, :, 0] = np.nan - trials.append({"maps": maps}) - out = combine_trials(trials, shifts=np.array([[0.0, 0.0], [0.0, 1.0]])) - assert out["n_valid"][0, 5, 5] == pytest.approx(400.0) - assert out["var"][0, 5, 5] == pytest.approx((100 * 2 + 300 * 4) / 400) - assert out["var_rel"][0, 5, 5] == pytest.approx(3.5 / 2 - 1) - assert out["n_trials"][0, 5, 5] == 2 - # trial 2's first column is missing; shifted by one column it lands - # left of the frame, and its last column has no data - assert out["n_trials"][0, 5, -1] == 1 - - -def test_combine_trials_of_different_sizes() -> None: - """Trials of different registered sizes share the largest canvas (top left, as SILo's).""" - trials = [] - for shape in ((1, 20, 30), (1, 18, 32)): - maps = {k: np.full(shape, 50.0) for k in ("n_valid", "n_blocks", - "n_fast")} # fmt: skip - for k in ("mean", "var", "var_ph", "zero_share", "zero_ph"): - maps[k] = np.full(shape, 1.0) - trials.append({"maps": maps}) - out = combine_trials(trials, shifts=np.zeros((2, 2))) - assert out["n_valid"].shape == (1, 20, 32) - assert out["n_trials"][0, 5, 5] == 2 - assert out["n_trials"][0, 19, 5] == 1 # rows 18-19: the first only - assert out["n_trials"][0, 5, 31] == 1 # cols 30-31: the second only - assert out["n_trials"][0, 19, 31] == 0 - assert np.isnan(out["var"][0, 19, 31]) - two = {"maps": {k: np.concatenate([v, v]) for k, v in trials[1]["maps"].items()}} - with pytest.raises(ValueError, match="channels"): - combine_trials([trials[0], two], shifts=np.zeros((2, 2))) - # fractional shifts: interior pixels count every trial despite rounding - out = combine_trials([trials[0], trials[0]], shifts=np.array([[0.3, 0.7], [0.1, 0.9]])) - assert (out["n_trials"][0, 2:-2, 2:-2] == 2).all() - - -def test_pair_sums_match_definition(tmp_path: Path) -> None: - """Sums over pairs of consecutive samples equal their definition.""" - layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 600) - samples = np.ones((2, layout.slot_line.size, 600), dtype=np.int16) - source, ds = _source(layout, samples) - m = 6 - motion = _motion(ds.size, seed=3) - geo = FrameGeometry(source, ds, m) - assert (0, 1) in geo.directions - vfs = torch.stack([vf.reshape(-1) for _, vf in - _registered(source, ds, motion, m)]) # fmt: skip - ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() - pix = ok[:: max(1, ok.numel() // 6)][:6] - f0, f1 = 8, 14 - e = f1 + geo.n_lags - res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) - nxt = next_slots(layout.slot_line, layout.slot_pos) - for j, p in enumerate(pix.tolist()): - for t in range(f0, f1): - at = _coefficients(layout, source, ds, motion, m, t, p) - pairs = [ - (v, at[(nxt[s], c)]) - for (s, c), v in at.items() - if nxt[s] >= 0 and (nxt[s], c) in at - ] - g0 = sum(v * v for v in at.values()) - want = ( - sum(a * b for a, b in pairs), - sum(a * a * b for a, b in pairs), - sum(a * b * b for a, b in pairs), - ) - for name, ref in zip(("QA2", "QA3a", "QA3b"), want): - assert abs(res[name][t - f0, j] - ref) <= 1e-5 * g0 - - -def test_shared_pulses_read_zero(tmp_path: Path) -> None: - """Pulses shared by consecutive samples correlate neighbouring pixels. - - With the pair terms, photon noise still reads 0 after registration's - bilinear resampling mixes them. - """ - layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 1600) - nxt = next_slots(layout.slot_line, layout.slot_pos) - rng = np.random.default_rng(7) - shape = (layout.slot_line.size, layout.num_cycles) - rate = np.stack([np.full(shape, 0.1), np.full(shape, 2.0)]) - samples = _shared_pulses(rate, nxt, rng) - curve = pair_curve(pair_sums(torch.from_numpy(samples), 1, nxt)) - rho = np.median(curve["c2"]) / 132.0 - assert 0.05 < rho < 0.2 - res = _stats(layout, samples, last=11000.0) - maps = res["maps"] - use = _interior(maps) - assert use.sum() > 300 - for ch in range(2): - assert np.mean(maps["var_qa"][ch][use]) > 0 - # at this size the dim channel's skewness varies by about 0.08 - # between seeds (the pixels share the measured gains) - for name, tol in ( - ("var_rel", 0.03), - ("fast_rel", 0.03), - ("slow_rel", 0.1), - ("fast_skew_rel", 0.15 if ch == 0 else 0.06), - ("zero_excess", 0.005), - ): - mean = np.mean(maps[name][ch][use]) - assert abs(mean) < tol, (ch, name, mean) - # the shared modes' input is in photon-noise units: unit variance per - # 2 x 2 bin and 8-frame bin (centred over time), pairs inside included - svd = res["svd"] - unit = svd["total_var"] / (svd["n_space"] * (svd["n_bins"] - 1)) - np.testing.assert_allclose(unit, 1.0, atol=0.05) # 1.08-1.11 without +"""Registration summary statistics (registration.stats).""" + +from collections.abc import Iterator +from pathlib import Path +from typing import Any, NoReturn + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import RasterLayout, read_raster_samples +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer +from giant_python.registration.interpolation import interp_frame +from giant_python.registration.multiroi import frame_times +from giant_python.registration.sources import CompensatedFrames, PlainFrames, make_source +from giant_python.registration.stats import ( + STATS_VERSION, + measure_gain_curves, + new_accumulator, + read_stats, + stats_path, +) +from giant_python.registration.stats.gain import ( + curve_from_sums, + next_slots, + pair_curve, + pair_sums, + slot_sums, +) +from giant_python.registration.stats.geometry import ( + FrameGeometry, + bilinear_corners, +) +from giant_python.registration.stats.session import combine_trials + +from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout, write_recording + +MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" +ADATA = "E1T1DMD1_ALIGNMENTDATA.h5" + + +@pytest.fixture(scope="module") +def recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: + """Layout and data file of a 6-second recording (moving scene). + + Returns + ------- + RasterLayout + The layout of the written recording. + """ + path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400) + write_recording(layout, invalid=0.0) + return layout + + +@pytest.fixture +def patched(recording: RasterLayout, monkeypatch: pytest.MonkeyPatch) -> RasterLayout: + """Patch registration to read the recording's layout. + + Returns + ------- + RasterLayout + The recording's layout. + """ + monkeypatch.setattr(multiroi, "raster_layout", lambda path: recording) + return recording + + +def _source( + layout: RasterLayout, samples: np.ndarray, first: float = 1.0, last: float = 3000.0 +) -> tuple[PlainFrames | CompensatedFrames, np.ndarray]: + """Frame source of samples over the layout (as registration's). + + Returns + ------- + source : PlainFrames or CompensatedFrames + The frame source of samples. + ds : np.ndarray + The frame times the source is read at. + """ + former = FrameFormer(layout, samples, 0) + dt = (1 / layout.line_period_s) / 80 + dtk = int(np.ceil(dt)) + init, ds = frame_times(first, last, dt, 40) + return make_source(layout, former, first, last, init, ds, dtk, False), ds + + +def _motion(n: int, seed: int = 0, jump: int | None = None) -> np.ndarray: + """Sub-pixel motion (rows, cols) with jitter. + + Returns + ------- + np.ndarray + (n, 2) row and column motion per frame, with a step at jump when given. + """ + rng = np.random.default_rng(seed) + t = np.arange(n) + m = np.stack( + [ + 0.7 * np.sin(t / 7.0) + rng.normal(0, 0.15, n), + 0.9 * np.cos(t / 11.0) + rng.normal(0, 0.15, n), + ], + 1, + ) + if jump is not None: + m[jump] += [1.3, -1.1] + return m + + +def _registered( + source: PlainFrames | CompensatedFrames, ds: np.ndarray, motion: np.ndarray, margin: int +) -> Iterator[tuple[list[torch.Tensor], torch.Tensor]]: + """Yield registered frames and variance factors (interp_frame). + + Yields + ------ + list of torch.Tensor + The registered frame of each channel. + torch.Tensor + The frame's variance factor. + """ + vals, fresh = source.frames(ds) + win = source.window + for k in range(ds.size): + fimg = win.image(fresh[k], 0.0) + regs = [ + interp_frame(win.image(vals[ch, k], float("nan")), fimg, *motion[k], margin) + for ch in range(vals.shape[0]) + ] + yield [r for r, _ in regs], regs[0][1] + + +# --------------------------------------------------------------- geometry + + +def _coefficients( + layout: RasterLayout, + source: PlainFrames | CompensatedFrames, + ds: np.ndarray, + motion: np.ndarray, + margin: int, + t: int, + p: int, +) -> dict[tuple[int, int], float]: + """Sample coefficients of registered frame t at output pixel p by the definition. + + This uses slow loops. + + Returns + ------- + dict + The coefficient of each (slot, cycle) sample, normalised to sum to 1. + """ + win = source.window + w_out = win.shape[1] + 2 * margin + ids = source.former.pixels[source.pixels.numpy()] + where = { + (int(r), int(c)): i for i, (r, c) in enumerate(zip(win.rows.numpy(), win.cols.numpy())) + } + dt = int(source.dt) + reach = max(3 * dt, layout.lines_per_cycle) + r, c = divmod(int(p), w_out) + off_r, off_c, coef, _ = bilinear_corners(*motion[t], margin) + parts, den = [], 0.0 + for k, (a, b) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))): + i = where.get((r + off_r + a, c + off_c + b)) + if i is None: + continue + slots = np.flatnonzero(layout.slot_pixel == ids[i]) + for s in slots: + for cyc in range(layout.num_cycles): + line = cyc * layout.lines_per_cycle + layout.slot_line[s] + if abs(ds[t] - line) <= reach: + wgt = coef[k] * np.exp(-abs(ds[t] - line) / dt) + parts.append(((s, cyc), wgt)) + den += wgt + out = {} + for key, v in parts: + out[key] = out.get(key, 0.0) + v / den + return out + + +def test_geometry_matches_definition(recording: RasterLayout) -> None: + """Photon-noise sums equal sums over the samples' coefficients.""" + layout = recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + source, ds = _source(layout, samples) + m = 6 + motion = _motion(ds.size, jump=12) + geo = FrameGeometry(source, ds, m) + assert geo.n_lags == 6 + vfs = torch.stack([vf.reshape(-1) for _, vf in + _registered(source, ds, motion, m)]) # fmt: skip + ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() + pix = ok[:: max(1, ok.numel() // 6)][:6] + f0, f1 = 8, 16 + e = f1 + geo.n_lags + res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) + for j, p in enumerate(pix.tolist()): + for t in range(f0, f1): + at = _coefficients(layout, source, ds, motion, m, t, p) + g0 = sum(v * v for v in at.values()) + r0 = sum(v**3 for v in at.values()) + assert res["G"][0, t - f0, j] == pytest.approx(g0, rel=1e-5) + assert res["R0"][t - f0, j] == pytest.approx(r0, rel=1e-5) + for lag in (1, 3, 6): + au = _coefficients(layout, source, ds, motion, m, t + lag, p) + g = sum(v * au.get(k, 0) for k, v in at.items()) + rr = sum(v * v * au.get(k, 0) for k, v in at.items()) + got = res["G"][lag, t - f0, j] + assert abs(got - g) <= 1e-5 * g0 + assert abs(res["R"][lag - 1, t - f0, j] - rr) <= 1e-5 * r0 + + +# ------------------------------------------------------------------- gains + + +def _compound_poisson( + rate: np.ndarray, rng: np.random.Generator, k: float = 5.0, theta: float = 22.0 +) -> np.ndarray: + """Draw samples: sums of Poisson(rate) integer gamma pulses (int16). + + Returns + ------- + np.ndarray + The samples, with the shape of rate, as int16. + """ + n = rng.poisson(rate) + out = np.zeros(rate.shape) + for j in range(int(n.max())): + use = n > j + out[use] += np.round(rng.gamma(k, theta, int(use.sum()))) + return out.astype(np.int16) + + +def scan_layout(path: Path, n_cycles: int) -> RasterLayout: + """Build a raster scanned row by row. + + Line r + 2 samples row 8 + r, columns 10-39 from left to right + (so consecutive samples on a line are horizontal neighbours); line 1 has + no samples. + + Returns + ------- + RasterLayout + The layout of the scanned raster (not written to a file). + """ + n_rows, n_cols, n_ch, rows = 36, 50, 2, 20 + p = rows + 1 + slot_line, slot_pos, slot_pixel = [], [], [] + for r in range(rows): + for j, c in enumerate(range(10, 40)): + slot_line.append(r + 2) + slot_pos.append(j) + slot_pixel.append((8 + r) * n_cols + c + 1) + n_per = np.array([0] + [30] * rows) + header_words = LINE_HEADER_BYTES // 2 + line_words = header_words + n_ch * n_per + line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) + return RasterLayout( + files=(str(path),), + file_cycles=np.array([n_cycles]), + file_offset_words=np.array([HEADER_WORDS]), + words_per_cycle=int(line_words.sum()), + lines_per_cycle=p, + n_rows=n_rows, + n_cols=n_cols, + num_channels=n_ch, + line_period_s=1 / 1600.0, + line_header_bytes=LINE_HEADER_BYTES, + line_header_words=line_header, + row_base=line_header + header_words, + n_per_channel=n_per, + line_fast_z=np.ones(p, dtype=np.int64), + fast_zs=np.array([-20.0]), + slot_line=np.array(slot_line), + slot_pos=np.array(slot_pos), + slot_pixel=np.array(slot_pixel), + ) + + +def _shared_pulses( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + p_split: float = 0.35, + k: float = 5.0, + theta: float = 22.0, +) -> np.ndarray: + """Draw compound-Poisson samples whose pulses are sometimes shared with the next sample. + + With probability p_split a fraction U(0, 0.5) of a pulse goes to + the next sample on the line. + + Returns + ------- + np.ndarray + The samples, with the shape of rate, as int16. + """ + n = rng.poisson(rate) + out = np.zeros(rate.shape) + has = nxt >= 0 + for j in range(int(n.max())): + use = n > j + a = np.zeros(rate.shape) + a[use] = np.round(rng.gamma(k, theta, int(use.sum()))) + split = (rng.random(rate.shape) < p_split) & has[..., :, None] + moved = np.round(a * rng.random(rate.shape) * 0.5) * split + out += a - moved + out[..., nxt[has], :] += moved[..., has, :] + return out.astype(np.int16) + + +def test_gain_groups_without_zeros_keep_their_gains() -> None: + """Bright groups that have no zero sample keep their gains. + + The non-zero rate comes from the groups that have zeros. + """ + rng = np.random.default_rng(4) + rate = np.repeat(np.geomspace(0.05, 60, 320)[:, None], 2000, 1) + x = (100 * rng.poisson(rate)).astype(np.int16) + curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) + assert curve.mu.size == 16 + assert np.isnan(curve.nu_per_mu[-1]) # no zeros at ~50 photons + np.testing.assert_allclose(curve.g2, 100, rtol=0.05) # >= 2000 photons + assert np.isfinite(curve.g3).all() + np.testing.assert_allclose(curve.g3[:8], 1e4, rtol=0.1) # dim: precise + at = curve.at(curve.mu) + assert np.isfinite(at["nu"]).all() + ok = np.isfinite(curve.nu_per_mu) + np.testing.assert_allclose(at["nu"][ok], (curve.mu * curve.nu_per_mu)[ok]) + one = curve.at(100.0) # a scalar mean too + assert one["g2"].shape == () and np.isfinite(one["g2"]) + assert np.isnan(curve.at(np.nan)["g2"]) + + +def test_gain_sums_do_not_overflow() -> None: + """Cubes of extreme second differences over a long trial would overflow int64. + + Those sums are float64 then (and exact int64 for ordinary trials). + """ + x = np.zeros((2, 150_000), dtype=np.int16) + x[:, ::3] = 32767 # d = 65534, -32767, -32767: cubes sum to > 2^63 + got = slot_sums(torch.from_numpy(x[None]), 0) + d = 2 * x[:, 1:-1].astype(object) - x[:, :-2] - x[:, 2:] + want = [sum(int(v) ** 3 for v in row) for row in d] + np.testing.assert_allclose(got[:, 6], np.array(want, float), rtol=1e-12) + assert abs(want[0]) > 2**63 # int64 would have overflowed + short = slot_sums(torch.from_numpy(x[None, :, :100]), 0) + assert short.dtype == np.int64 + # nor do a group's sums of large per-slot sums + rows = np.tile([100, 1000, 10, 98, 980, 6000, 3 * 10**18], (32, 1)) + curve = curve_from_sums(rows.astype(np.int64), n_bins=2) + np.testing.assert_allclose(curve.g3, 3e18 / (6 * 980), rtol=1e-12) + + +def test_components_of_tall_and_wide_inputs() -> None: + """The top components equal numpy's SVD whichever Gram matrix is smaller. + + That is, with more time bins than spatial bins, or fewer. + """ + from giant_python.registration.stats.svd import _components + + rng = np.random.default_rng(9) + for shape in ((40, 300), (300, 40)): + y = rng.normal(size=shape) + np.outer( + np.sin(np.arange(shape[0]) / 5), rng.normal(size=shape[1]) + ) + u, s, total = _components(y, 3) + uu, ss, _ = np.linalg.svd(y, full_matrices=False) + np.testing.assert_allclose(s, ss[:3], rtol=1e-9) + np.testing.assert_allclose(np.abs(u.T @ uu[:, :3]), np.eye(3), atol=1e-8) + assert (np.sum(y.T @ u, 0) >= 0).all() + assert total == pytest.approx(np.sum(y**2)) + # rank 1 (tall and wide): one component, finite, and weights for it + for shape in ((300, 40), (40, 300)): + a, b = rng.normal(size=shape[0]), rng.normal(size=shape[1]) + y = np.outer(a, b) + u, s, _ = _components(y, 3) + assert u.shape == (shape[0], 1) and np.isfinite(u).all() + np.testing.assert_allclose(s, [np.linalg.norm(a) * np.linalg.norm(b)]) + + +def test_regression_weights_of_undetermined_pixels() -> None: + """A pixel whose valid bins leave a time course flat gets NaN weights (not an error). + + The others are fitted. + """ + from giant_python.registration.stats.svd import regression_weights + + rng = np.random.default_rng(8) + nb = 280 + u = np.zeros((nb, 2)) + u[:100, 0] = rng.normal(size=100) # active in the first 100 bins only + u[:, 1] = rng.normal(size=nb) + u /= np.linalg.norm(u, axis=0) + y = 5 + u @ np.array([[3.0, 2.0, 1.0], [1.0, -1.0, 4.0]]) + y[:100, 1] = np.nan # pixel 1 misses the first course's activity + w = regression_weights(y, u) + np.testing.assert_allclose(w[[0, 2]], [[3.0, 1.0], [1.0, 4.0]]) + assert np.isnan(w[1]).all() + + +def test_gain_curve_of_compound_poisson() -> None: + """Gains equal E[A^2]/E[A] and E[A^3]/E[A] of the pulse heights.""" + rng = np.random.default_rng(3) + rate = np.repeat(np.geomspace(0.03, 3, 1600)[:, None], 3000, 1) + x = _compound_poisson(rate, rng) + pulses = np.round(rng.gamma(5.0, 22.0, 2_000_000)) + g2 = (pulses**2).mean() / pulses.mean() + g3 = (pulses**3).mean() / pulses.mean() + curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) + assert np.allclose(curve.g2, g2, rtol=0.03) # >= 9000 photons each + assert np.allclose(curve.g3, g3, rtol=0.08) + nu = curve.at(curve.mu)["nu"] + zero = (x == 0).mean(1) + mean = x.mean(1) + want = np.interp(curve.mu, mean, -np.log(zero)) + assert np.allclose(nu, want, rtol=0.05) + + +# --------------------------------------------------------------- the maps + + +def _stats( + layout: RasterLayout, samples: np.ndarray, motion_seed: int = 0, last: float = 9000.0 +) -> dict: + """Statistics of samples through registration's frame formation. + + Returns + ------- + dict + The finished accumulator's statistics (maps and curves). + """ + source, ds = _source(layout, samples, last=last) + acc = new_accumulator(source, ds, 6, layout.num_channels) + motion = _motion(ds.size, motion_seed) + for k, (regs, vf) in enumerate(_registered(source, ds, motion, 6)): + acc.add(k, regs, vf, tuple(motion[k])) + return acc.finish() + + +def _interior(maps: dict[str, np.ndarray]) -> np.ndarray: + """Pixels whose maps are defined in every channel. + + Returns + ------- + np.ndarray + Boolean mask of the pixels where the slow and fast maps are finite in all channels. + """ + return np.isfinite(maps["slow_rel"]).all(0) & np.isfinite(maps["fast_rel"]).all(0) + + +@pytest.fixture(scope="module") +def uniform( + tmp_path_factory: pytest.TempPathFactory, +) -> tuple[RasterLayout, np.ndarray, np.ndarray]: + """Simulate a uniform scene of compound-Poisson samples. + + 0.05 and 2 photons per sample in the two channels; no file needed. + + Returns + ------- + layout : RasterLayout + The layout of the simulated recording. + samples : np.ndarray + The compound-Poisson samples of both channels. + rate : np.ndarray + The photon rate per sample (channels, slots, cycles). + """ + path = tmp_path_factory.mktemp("uni") / "uniform_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1600) + rng = np.random.default_rng(5) + shape = (layout.slot_line.size, layout.num_cycles) + rate = np.stack([np.full(shape, 0.05), np.full(shape, 2.0)]) + return layout, _compound_poisson(rate, rng), rate + + +def test_photon_noise_maps_read_zero(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: + """Under photon noise alone the normalised maps are 0 at any brightness. + + Means over pixels: a variance from few blocks is unbiased but its median + is low, as for chi-square. + """ + layout, samples, _ = uniform + res = _stats(layout, samples, last=11000.0) + maps = res["maps"] + use = _interior(maps) + assert use.sum() > 300 + for ch in range(2): + for name, tol in ( + ("var_rel", 0.02), + ("fast_rel", 0.02), + ("slow_rel", 0.1), + ("fast_skew_rel", 0.06), + ("zero_excess", 0.003), + ): + mean = np.mean(maps[name][ch][use]) + assert abs(mean) < tol, (ch, name, mean) + gains = measure_gain_curves(torch.from_numpy(samples)) + assert np.allclose(gains[1].g2, 132.0, rtol=0.03) + assert res["svd"]["var_share"].shape == (2, 3) + + +def test_events_raise_fast_skewness(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: + """Positive transients raise the fast maps where they are.""" + layout, _, rate = uniform + rate = rate.copy() + rows = (layout.slot_pixel - 1) // layout.n_cols + cols = (layout.slot_pixel - 1) % layout.n_cols + src = (np.abs(rows - 17) <= 1) & (np.abs(cols - 24) <= 1) + p = layout.lines_per_cycle + t = (np.arange(layout.num_cycles) * p) * layout.line_period_s + kern = np.zeros(t.size) + for onset in np.arange(0.3, t[-1], 0.9): + kern += np.where(t >= onset, np.exp(-(t - onset) / 0.025), 0.0) + rate[1, src] += 4.0 * kern + samples = _compound_poisson(rate, np.random.default_rng(6)) + maps = _stats(layout, samples, last=11000.0)["maps"] + m = 6 + sk = maps["fast_skew_rel"][1] + fr = maps["fast_rel"][1] + at = sk[17 - 8 + m, 24 - 10 + m] + away = np.nanmedian(sk[m : m + 5]) # DMD rows 8-12 + assert at > 1.0 and abs(away) < 0.2 + assert fr[17 - 8 + m, 24 - 10 + m] > 1.0 + + +# ------------------------------------------------- registration and command + + +@pytest.mark.parametrize( + "device", + [ + "cpu", + pytest.param( + "cuda", + marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="no CUDA device"), + ), + ], +) +def test_registration_and_command_agree(patched: RasterLayout, tmp_path: Path, device: str) -> None: + """``giant reg-stats`` on registration's outputs gives the same maps. + + On a GPU registration's run on a thread and stream of their own, the + command's in line. The mean equals meanIM; statistics do not change + the movie. + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + out = {} + for stats in (True, False): + d = tmp_path / str(stats) + d.mkdir() + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + multiroi.register_trial( + layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params, + device=device, stats=stats, + ) # fmt: skip + with h5py.File(d / MOVIE) as f: + out[stats] = f["data"][()] + np.testing.assert_array_equal(out[True], out[False]) + assert not stats_path(tmp_path / "False" / MOVIE).exists() + d = tmp_path / "True" + a = read_stats(stats_path(d / MOVIE)) + assert a["attrs"]["stats_version"] == STATS_VERSION + with h5py.File(d / ADATA) as f: + mean_im = np.swapaxes(np.moveaxis(f["meanIM"][()], -1, 0), 1, 2) + np.testing.assert_array_equal(a["maps"]["mean"], mean_im) + cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name + trial_stats(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, cmd, device, + {"maxshift": 6}) # fmt: skip + b = read_stats(cmd) + for grp in ("maps", "svd", "gain"): + assert a[grp].keys() == b[grp].keys() + for k in a[grp]: + np.testing.assert_array_equal(a[grp][k], b[grp][k], err_msg=k) + + +@pytest.mark.parametrize("last", [2.0, 60.0]) +def test_short_trials_get_statistics(patched: RasterLayout, tmp_path: Path, last: float) -> None: + """A one-frame (or three-frame) trial gets a statistics file equal to the command's. + + Its maps are NaN where there are too few frames. + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, last, tmp_path / MOVIE, tmp_path / ADATA) + res = multiroi.register_trial(*args, params) + assert res.ds_frames.size <= 3 + a = read_stats(stats_path(tmp_path / MOVIE)) + assert np.isnan(a["maps"]["fast_rel"]).all() + assert np.nanmax(a["maps"]["n_valid"]) == res.ds_frames.size + b = trial_stats(*args, tmp_path / "cmd.h5", "cpu", {"maxshift": 6}) + for k in a["maps"]: + np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) + + +def test_command_treats_empty_frames_as_missing(patched: RasterLayout, tmp_path: Path) -> None: + """A frame without data counts as missing in the command. + + This holds even where the alignment file gives it a motion (as + GIAnT-MATLAB's may). + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) + multiroi.register_trial(*args, params) + with h5py.File(tmp_path / MOVIE, "r+") as f: + n_ch = layout.num_channels + f["data"][10 * n_ch : 11 * n_ch] = np.nan # frame 10 without data + finite = trial_stats(*args, tmp_path / "a.h5", "cpu", {"maxshift": 6}) + with h5py.File(tmp_path / ADATA, "r+") as f: + for key in ("motionDSr", "motionDSc"): + m = f[key][()] + m.reshape(-1)[10] = np.nan + f[key][...] = m + missing = trial_stats(*args, tmp_path / "b.h5", "cpu", {"maxshift": 6}) + for k in finite["maps"]: + np.testing.assert_array_equal(finite["maps"][k], missing["maps"][k], err_msg=k) + for k in ("spatial_factor", "pair_bin_factor"): # frame 10 left out + assert finite["attrs"][k] == missing["attrs"][k] + + +def test_rerun_without_stats_removes_old_file(patched: RasterLayout, tmp_path: Path) -> None: + """A registration without statistics leaves none from an earlier one.""" + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) + multiroi.register_trial(*args, params) + assert stats_path(tmp_path / MOVIE).exists() + multiroi.register_trial(*args, params, stats=False) + assert not stats_path(tmp_path / MOVIE).exists() + + +@pytest.mark.parametrize("step", ["start", "setup", "add", "finish", "write"]) +def test_failed_statistics_leave_registration( + patched: RasterLayout, + tmp_path: Path, + step: str, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A statistics step that fails is logged. + + The step fails on the worker thread, or writing the file, with its + cleanup failing too. Registration publishes the same movie and alignment + file, without statistics (and removes an earlier statistics file). + """ + import pathlib + + from giant_python.registration.stats import accumulate, io + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + ref = tmp_path / "ref" + ref.mkdir() + multiroi.register_trial(layout.files[0], 1, 3000, ref / MOVIE, ref / ADATA, params, stats=False) + + def fail(*args: object, **kwargs: object) -> NoReturn: + """Fail as a broken step. + + Raises + ------ + RuntimeError + Always. + """ + raise RuntimeError("broken statistics") + + if step == "start": + monkeypatch.setattr(multiroi, "StatsWorker", fail) + elif step == "setup": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "__init__", fail) + elif step == "add": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_block", fail) + elif step == "finish": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_maps", fail) + else: + monkeypatch.setattr(io, "write_stats", fail) + unlink = pathlib.Path.unlink + + def locked(path: Path, *args: Any, **kwargs: Any) -> None: # noqa: ANN401 - forwarded to unlink + """Path.unlink, refusing the partial statistics file. + + Raises + ------ + PermissionError + If the path is a partial statistics file, not the final one. + """ + if "REGSTATS" in path.name and path.name != STATS_NAME: + raise PermissionError("locked") + return unlink(path, *args, **kwargs) + + STATS_NAME = stats_path(tmp_path / MOVIE).name + monkeypatch.setattr(pathlib.Path, "unlink", locked) + d = tmp_path / "run" + d.mkdir() + stats_path(d / MOVIE).write_bytes(b"from an earlier registration") + multiroi.register_trial(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params) + assert "summary statistics" in caplog.text + assert not stats_path(d / MOVIE).exists() + assert sorted(p.name for p in d.iterdir()) == [ADATA, MOVIE] + with h5py.File(d / MOVIE) as f, h5py.File(ref / MOVIE) as g: + np.testing.assert_array_equal(f["data"][()], g["data"][()]) + with h5py.File(d / ADATA) as f, h5py.File(ref / ADATA) as g: + for k in ("motionDSr", "motionDSc", "meanIM"): + np.testing.assert_array_equal(f[k][()], g[k][()]) + + +def test_command_checks_online_compensation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """For an online-compensated trial the command rebuilds the compensation registration saved. + + It gets the same maps and refuses a trial whose saved record differs. + """ + from giant_python.pipeline.reg_stats import trial_stats + + from .synthetic import online_offsets + + layout = make_layout(tmp_path / "online_DMD1-TRIAL000001.dat", n_cycles=1400, seed=5) + write_recording(layout, seed=6, online=online_offsets(layout.total_lines)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=True) + d = tmp_path / "reg" + d.mkdir() + args = (layout.files[0], 1, 6000, d / MOVIE, d / ADATA) + multiroi.register_trial(*args, params) + a = read_stats(stats_path(d / MOVIE)) + cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name + trial_stats(*args, cmd, "cpu", {"maxshift": 6}) + b = read_stats(cmd) + for k in a["maps"]: + np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) + with h5py.File(d / ADATA, "r+") as f: + lead = f["slap2/onlineCompensation/yLead"] + lead[...] = lead[()] + 1 + with pytest.raises(ValueError, match="yLead"): + trial_stats(*args, tmp_path / "other.h5", "cpu", {"maxshift": 6}) + + +def test_statistics_file_that_cannot_be_moved( + patched: RasterLayout, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """If the statistics file cannot be moved into place, the other outputs are published. + + The movie and the alignment file are published all the same, without + statistics (an earlier statistics file is removed). + """ + import os + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + stale = stats_path(tmp_path / MOVIE) + stale.write_bytes(b"from an earlier registration") + replace = os.replace + + def refuse_stats(src: str | Path, dst: str | Path) -> None: + """os.replace, refusing the statistics file. + + Raises + ------ + PermissionError + If the destination is the statistics file. + """ + if Path(dst) == stale: + raise PermissionError("locked") + return replace(src, dst) + + monkeypatch.setattr(os, "replace", refuse_stats) + multiroi.register_trial(layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA, params) + assert "not published" in caplog.text + assert sorted(p.name for p in tmp_path.iterdir()) == [ADATA, MOVIE] + + +def test_reg_stats_command(patched: RasterLayout, tmp_path: Path) -> None: + """The CLI writes the statistics of a table's trials once.""" + from giant_python.cli import main + from giant_python.pipeline.reg_stats import reg_stats + from giant_python.pipeline.register import register_multiroi + + layout = patched + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[1.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + }, + ) + register_multiroi( + table, + {"maxshift": 5}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + out = tmp_path / "stats" + assert main(["reg-stats", str(table), "--out", str(out), + "--device", "cpu"]) == 0 # fmt: skip + written = out / "E1T1DMD1_REGSTATS-80Hz.h5" + assert written.exists() + assert reg_stats(table, out, device="cpu") == [] # up to date + with h5py.File(written, "r+") as f: # as if the movie were rewritten + f.attrs["movie_size"] = int(f.attrs["movie_size"]) + 1 + assert len(reg_stats(table, out, device="cpu")) == 1 + assert read_stats(written)["attrs"]["validity_differs"] == [0, 0] + movie = tmp_path / "motion_correction" / MOVIE + movie.rename(movie.with_suffix(".moved")) # a requested trial is missing + assert main(["reg-stats", str(table), "--out", str(out), + "--device", "cpu"]) == 1 # fmt: skip + + +def test_validity_mismatch_counts_channels() -> None: + """Samples whose validity differs from the first channel's are counted per channel.""" + from giant_python.io.slap2_raster import INVALID_SAMPLE + from giant_python.registration.stats.gain import validity_mismatch + + x = np.ones((3, 300, 50), dtype=np.int16) + x[:, 0, :5] = INVALID_SAMPLE # all channels: no mismatch + x[1, 10, :7] = INVALID_SAMPLE + x[2, 200, :3] = INVALID_SAMPLE + x[0, 250, :2] = INVALID_SAMPLE # first channel only: both others + assert validity_mismatch(torch.from_numpy(x)) == [0, 9, 5] + + +def test_stats_path_names() -> None: + """Statistics files sit next to the movie, named after it.""" + assert stats_path(Path("d") / MOVIE).name == "E1T1DMD1_REGSTATS-80Hz.h5" + tif = Path("E2T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif") + assert stats_path(tif).name == "E2T3DMD2_REGSTATS-80Hz.h5" + assert stats_path(Path("m.h5")).name == "m_REGSTATS.h5" + + +# ----------------------------------------------------------------- session + + +def test_combine_trials_weights_by_frames() -> None: + """Session maps: shifted, frame-weighted means. + + Normalised maps are formed from the averages. + """ + shape = (1, 20, 30) + trials = [] + for t, (n, var) in enumerate(((100.0, 2.0), (300.0, 4.0))): + maps = {} + for k in ("n_valid", "n_blocks", "n_fast"): + maps[k] = np.full(shape, n) + for k in ("mean", "var", "var_q", "zero_share", "zero_ph", + "gain_g2", "gain_g3", "sigma8_ph", "slow_var", "slow_q", + "fast_var", "fast_q", "fast_m3", "fast_q3", + "fast_m3_ph"): # fmt: skip + maps[k] = np.full(shape, 1.0) + maps["var"] = np.full(shape, var) + for k in ("var_ph", "slow_var_ph", "fast_var_ph"): + maps[k] = np.full(shape, 2.0) + maps["mean"][0, :, 0] = np.nan + trials.append({"maps": maps}) + out = combine_trials(trials, shifts=np.array([[0.0, 0.0], [0.0, 1.0]])) + assert out["n_valid"][0, 5, 5] == pytest.approx(400.0) + assert out["var"][0, 5, 5] == pytest.approx((100 * 2 + 300 * 4) / 400) + assert out["var_rel"][0, 5, 5] == pytest.approx(3.5 / 2 - 1) + assert out["n_trials"][0, 5, 5] == 2 + # trial 2's first column is missing; shifted by one column it lands + # left of the frame, and its last column has no data + assert out["n_trials"][0, 5, -1] == 1 + + +def test_combine_trials_of_different_sizes() -> None: + """Trials of different registered sizes share the largest canvas (top left, as SILo's).""" + trials = [] + for shape in ((1, 20, 30), (1, 18, 32)): + maps = {k: np.full(shape, 50.0) for k in ("n_valid", "n_blocks", + "n_fast")} # fmt: skip + for k in ("mean", "var", "var_ph", "zero_share", "zero_ph"): + maps[k] = np.full(shape, 1.0) + trials.append({"maps": maps}) + out = combine_trials(trials, shifts=np.zeros((2, 2))) + assert out["n_valid"].shape == (1, 20, 32) + assert out["n_trials"][0, 5, 5] == 2 + assert out["n_trials"][0, 19, 5] == 1 # rows 18-19: the first only + assert out["n_trials"][0, 5, 31] == 1 # cols 30-31: the second only + assert out["n_trials"][0, 19, 31] == 0 + assert np.isnan(out["var"][0, 19, 31]) + two = {"maps": {k: np.concatenate([v, v]) for k, v in trials[1]["maps"].items()}} + with pytest.raises(ValueError, match="channels"): + combine_trials([trials[0], two], shifts=np.zeros((2, 2))) + # fractional shifts: interior pixels count every trial despite rounding + out = combine_trials([trials[0], trials[0]], shifts=np.array([[0.3, 0.7], [0.1, 0.9]])) + assert (out["n_trials"][0, 2:-2, 2:-2] == 2).all() + + +def test_pair_sums_match_definition(tmp_path: Path) -> None: + """Sums over pairs of consecutive samples equal their definition.""" + layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 600) + samples = np.ones((2, layout.slot_line.size, 600), dtype=np.int16) + source, ds = _source(layout, samples) + m = 6 + motion = _motion(ds.size, seed=3) + geo = FrameGeometry(source, ds, m) + assert (0, 1) in geo.directions + vfs = torch.stack([vf.reshape(-1) for _, vf in + _registered(source, ds, motion, m)]) # fmt: skip + ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() + pix = ok[:: max(1, ok.numel() // 6)][:6] + f0, f1 = 8, 14 + e = f1 + geo.n_lags + res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) + nxt = next_slots(layout.slot_line, layout.slot_pos) + for j, p in enumerate(pix.tolist()): + for t in range(f0, f1): + at = _coefficients(layout, source, ds, motion, m, t, p) + pairs = [ + (v, at[(nxt[s], c)]) + for (s, c), v in at.items() + if nxt[s] >= 0 and (nxt[s], c) in at + ] + g0 = sum(v * v for v in at.values()) + want = ( + sum(a * b for a, b in pairs), + sum(a * a * b for a, b in pairs), + sum(a * b * b for a, b in pairs), + ) + for name, ref in zip(("QA2", "QA3a", "QA3b"), want): + assert abs(res[name][t - f0, j] - ref) <= 1e-5 * g0 + + +def test_shared_pulses_read_zero(tmp_path: Path) -> None: + """Pulses shared by consecutive samples correlate neighbouring pixels. + + With the pair terms, photon noise still reads 0 after registration's + bilinear resampling mixes them. + """ + layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 1600) + nxt = next_slots(layout.slot_line, layout.slot_pos) + rng = np.random.default_rng(7) + shape = (layout.slot_line.size, layout.num_cycles) + rate = np.stack([np.full(shape, 0.1), np.full(shape, 2.0)]) + samples = _shared_pulses(rate, nxt, rng) + curve = pair_curve(pair_sums(torch.from_numpy(samples), 1, nxt)) + rho = np.median(curve["c2"]) / 132.0 + assert 0.05 < rho < 0.2 + res = _stats(layout, samples, last=11000.0) + maps = res["maps"] + use = _interior(maps) + assert use.sum() > 300 + for ch in range(2): + assert np.mean(maps["var_qa"][ch][use]) > 0 + # at this size the dim channel's skewness varies by about 0.08 + # between seeds (the pixels share the measured gains) + for name, tol in ( + ("var_rel", 0.03), + ("fast_rel", 0.03), + ("slow_rel", 0.1), + ("fast_skew_rel", 0.15 if ch == 0 else 0.06), + ("zero_excess", 0.005), + ): + mean = np.mean(maps[name][ch][use]) + assert abs(mean) < tol, (ch, name, mean) + # the shared modes' input is in photon-noise units: unit variance per + # 2 x 2 bin and 8-frame bin (centred over time), pairs inside included + svd = res["svd"] + unit = svd["total_var"] / (svd["n_space"] * (svd["n_bins"] - 1)) + np.testing.assert_allclose(unit, 1.0, atol=0.05) # 1.08-1.11 without diff --git a/tests/registration/test_synthetic.py b/tests/registration/test_synthetic.py index acf51686..fd2954ae 100644 --- a/tests/registration/test_synthetic.py +++ b/tests/registration/test_synthetic.py @@ -1,883 +1,965 @@ -"""Reader, frame formation and registration on a synthetic recording.""" - -import dataclasses -import hashlib -import json -import os -from collections.abc import Callable, Sequence -from pathlib import Path -from typing import NoReturn - -import h5py -import numpy as np -import pytest -import torch -from numpy.typing import ArrayLike - -from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 -from giant_python.io.slap2 import is_cycle_split -from giant_python.io.slap2_raster import RasterLayout, read_line_offsets, read_raster_samples -from giant_python.io.trial_table import read_trial_table -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer - -from .synthetic import HEADER_WORDS, make_layout, write_recording - -Recording = tuple[RasterLayout, np.ndarray] -"""A synthetic recording's layout and its true motion.""" - - -@pytest.fixture(scope="module") -def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: - """Layout, data file and true motion of a 6-second recording.""" - path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400) - truth = write_recording(layout, invalid=0.002) - return layout, truth - - -def frames_reference( - layout: RasterLayout, samples: np.ndarray, times: np.ndarray, dt: float -) -> tuple[np.ndarray, np.ndarray]: - """Per-pixel weighted means by the definition (slow loops).""" - p, total = layout.lines_per_cycle, layout.total_lines - pix = np.unique(layout.slot_pixel) - dt_read = max(3 * dt, p) - num = np.zeros((layout.num_channels, len(times), pix.size)) - den = np.zeros_like(num) - for s in range(layout.slot_line.size): - j = np.searchsorted(pix, layout.slot_pixel[s]) - for f, t in enumerate(times): - lines = np.arange(max(1, t - dt_read), min(total, t + dt_read) + 1) - lines = lines[(lines - 1) % p + 1 == layout.slot_line[s]] - for ln in lines: - w = np.exp(-abs(t - ln) / dt) - for ch in range(layout.num_channels): - x = samples[ch, s, (ln - 1) // p] - if x != -32768: - num[ch, f, j] += w * x - den[ch, f, j] += w - return num, den - - -def test_reader_and_line_headers(recording: Recording) -> None: - """Samples land at their slots; header offsets decode.""" - layout, _ = recording - s = read_raster_samples(layout, (10, 20), chunk_cycles=3) - whole = read_raster_samples(layout, (0, layout.num_cycles)) - np.testing.assert_array_equal(s, whole[:, :, 10:20]) - p = layout.lines_per_cycle - lines = np.array([1, p, p + 3, 5 * p + 2]) - x, y, z = read_line_offsets(layout, lines) - cyc = (lines - 1) // p - np.testing.assert_array_equal(x, cyc % 3) - np.testing.assert_array_equal(y, -(cyc % 2)) - np.testing.assert_allclose(z, 0.25 * cyc) - - -def test_frame_former_matches_definition(recording: Recording) -> None: - """Exp-kernel sums equal the definition, invalid samples masked.""" - layout, _ = recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - times = np.array([1, 50, 333, 4000]) - former = FrameFormer(layout, samples, 0) - num, den = former.sums(times, 20) - want_num, want_den = frames_reference(layout, samples, times, 20) - np.testing.assert_allclose(num.numpy(), want_num, rtol=1e-12) - np.testing.assert_allclose(den.numpy(), want_den, rtol=1e-12) - part = FrameFormer(layout, samples[:, :, 40:200], 40) - np.testing.assert_allclose(part.sums([700], 20)[0].numpy(), former.sums([700], 20)[0].numpy()) - with pytest.raises(ValueError): - part.sums([20], 20) - - -def test_register_trial_recovers_motion( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Recovered motion follows the known motion (up to a constant).""" - layout, truth = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - n_lines = 9000 - res = multiroi.register_trial( - layout.files[0], - 1, - n_lines, - tmp_path / "m.tif", - tmp_path / "a.h5", - params, - ) - dt = 1600 / 80 - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - true = np.stack([np.convolve(truth[:, i], kernel, "same")[res.ds_frames - 1] for i in (0, 1)]) - est = np.stack([res.motion_r, res.motion_c]) - err = est - true - err -= np.median(err, axis=1, keepdims=True) - assert np.sqrt(np.mean(err**2)) < 0.1 - a = load_struct_h5(tmp_path / "a.h5") - assert a["slap2"]["varFacDS"].shape == ( - a["meanIM"].shape[1], - a["meanIM"].shape[2], - res.ds_frames.size, - ) - np.testing.assert_array_equal(a["DSframes"].ravel(), res.ds_frames) - assert not (tmp_path / "a.h5.partial").exists() - - -def digests(*paths: str | Path) -> list[str]: - """SHA-256 of each file.""" - return [hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths] - - -@pytest.mark.parametrize("save_tif", [True, False]) -def test_failed_rerun_keeps_the_previous_outputs( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, save_tif: bool -) -> None: - """A run that fails while writing leaves an existing pair as it was.""" - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=save_tif) - movie = tmp_path / ("m.tif" if save_tif else "m.h5") - adata = tmp_path / "a.h5" - args = (layout.files[0], 1, 3000, movie, adata, params) - multiroi.register_trial(*args) - stats = movie.with_name(movie.stem + "_REGSTATS.h5") - before = digests(movie, adata, stats) - add = multiroi.OutputSink.add - - def fail_midway( - self: multiroi.OutputSink, - k: int, - regs: list[torch.Tensor], - var_factor: torch.Tensor, - *rest: object, - ) -> torch.Tensor: - """Write 50 frames, then fail.""" - if k == 50: - raise OSError("disk full") - return add(self, k, regs, var_factor, *rest) - - def fail_at_the_end(*args: object, **kwargs: object) -> NoReturn: - """Fail after the movie is complete.""" - raise OSError("disk full") - - for target, name, fail in ( - (multiroi.OutputSink, "add", fail_midway), - (multiroi, "alignment_fields", fail_at_the_end), - ): - with monkeypatch.context() as m: - m.setattr(target, name, fail) - with pytest.raises(OSError): - multiroi.register_trial(*args) - assert digests(movie, adata, stats) == before - assert sorted(tmp_path.iterdir()) == sorted([movie, adata, stats]) - - -def test_interrupted_publish_leaves_no_alignment_file( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A pair that cannot be moved into place leaves no alignment file. - - The movie may then be new, but without an alignment file the trial is - not taken for registered. - """ - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) - movie, adata = tmp_path / "m.h5", tmp_path / "a.h5" - args = (layout.files[0], 1, 3000, movie, adata, params) - multiroi.register_trial(*args) - replace = os.replace - - def refuse_alignment_file(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: - """Fail to move the alignment file into place.""" - if Path(dst) == adata: - raise PermissionError("in use") - replace(src, dst) - - monkeypatch.setattr(os, "replace", refuse_alignment_file) - with pytest.raises(PermissionError): - multiroi.register_trial(*args) - # the new movie and its statistics are in place, the alignment file not - stats = movie.with_name(movie.stem + "_REGSTATS.h5") - assert sorted(tmp_path.iterdir()) == sorted([movie, stats]) - - -def blank_frames( - monkeypatch: pytest.MonkeyPatch, - blank: Callable[[np.ndarray], np.ndarray], - half: Callable[[np.ndarray], np.ndarray] | None = None, -) -> None: - """Frames formed at times where ``blank(times)`` holds have no samples. - - Where ``half(times)`` holds, the lower half of the raster has none. - """ - from giant_python.registration.frames import FrameFormer - - frames = FrameFormer.frames - - def blanked( - self: FrameFormer, times: ArrayLike, dt: int, channels: Sequence[int] | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """Form the frames, with the selected ones emptied.""" - vals, fresh = frames(self, times, dt, channels) - t = np.asarray(times).ravel() - lower = self.rows > np.median(self.rows) - for i in np.flatnonzero(half(t) if half else []): - vals[:, i, lower] = float("nan") - fresh[i, lower] = 0 - hit = torch.as_tensor(blank(t), device=vals.device) - vals[:, hit] = float("nan") - fresh[hit] = 0 - return vals, fresh - - monkeypatch.setattr(FrameFormer, "frames", blanked) - - -@pytest.mark.parametrize("schedule", ["sequential", "grow"]) -def test_frame_without_samples_is_missing( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str -) -> None: - """A frame without valid samples in mid-trial gets NaN motion and an all-NaN movie frame. - - The other frames are registered exactly as in a run without that frame, - and the trial does not fail. - """ - from giant_python.registration.growth import MISSING - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) - dt = (1 / layout.line_period_s) / params.align_hz - init, ds = multiroi.frame_times(1, 3000, dt, params.init_frames) - k = 70 - assert ds[k] not in init - times = multiroi.frame_times - out = {} - for name in ("blank", "without"): - with monkeypatch.context() as m: - if name == "blank": - blank_frames(m, lambda t: t == ds[k]) - else: - m.setattr( - multiroi, - "frame_times", - lambda *a: (times(*a)[0], np.delete(times(*a)[1], k)), - ) - out[name] = multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"{name}.h5", - tmp_path / f"{name}_a.h5", - params, - ) - res, ref = out["blank"], out["without"] - assert not res.registration_failed - assert np.isnan([res.motion_r[k], res.motion_c[k], res.peak[k]]).all() - others = np.arange(ds.size) != k - for f in ("motion_r", "motion_c", "peak"): - np.testing.assert_array_equal(getattr(res, f)[others], getattr(ref, f)) - n_ch = layout.num_channels - with ( - h5py.File(tmp_path / "blank.h5") as a, - h5py.File(tmp_path / "without.h5") as b, - ): - pages = a["data"][()] - mine = np.s_[k * n_ch : (k + 1) * n_ch] - assert np.isnan(pages[mine]).all() - np.testing.assert_array_equal(np.delete(pages, mine, axis=0), b["data"][()]) - adata = load_struct_h5(tmp_path / "blank_a.h5") - want = load_struct_h5(tmp_path / "without_a.h5") - assert adata["registrationFailed"].item() == 0 - assert np.isnan(adata["motionDSr"].ravel()[k]) - assert np.isnan(adata["slap2"]["varFacDS"][..., k]).all() - np.testing.assert_array_equal(adata["meanIM"], want["meanIM"]) - if schedule == "grow": - assert adata["growthQC"]["kind"].ravel()[k] == MISSING - - -@pytest.mark.parametrize("schedule", ["sequential", "grow"]) -def test_trial_without_samples_at_its_start_or_at_all( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str -) -> None: - """A recording that starts late is registered from its first frames with samples. - - It is registered in the usual window even if the first of them covers only - part of the raster; a trial without any samples completes and is flagged. - """ - from giant_python.registration.sources import make_source - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) - args = (layout.files[0], 1, 3000) - lay, former, init, ds, dt = multiroi.open_trial(*args, params, torch.device("cpu")) - window = make_source(lay, former, 1, 3000, init, ds, dt, False).window - with monkeypatch.context() as m: - # the first initial frames have no samples, the next one only half - assert np.sum((init >= 1200) & (init < 1300)) == 1 - blank_frames(m, lambda t: t < 1200, lambda t: t < 1300) - late = multiroi.register_trial(*args, tmp_path / "late.h5", tmp_path / "late_a.h5", params) - early = late.ds_frames < 1200 - assert np.isnan(late.motion_r[early]).all() - assert np.isfinite(late.motion_r[late.ds_frames >= 1200]).all() - assert not late.registration_failed - trim = load_struct_h5(tmp_path / "late_a.h5")["slap2"] - np.testing.assert_array_equal(trim["trimRows"].ravel(), window.trim_rows) - np.testing.assert_array_equal(trim["trimCols"].ravel(), window.trim_cols) - with monkeypatch.context() as m: - blank_frames(m, lambda t: np.ones(t.shape, dtype=bool)) - empty = multiroi.register_trial( - *args, tmp_path / "empty.h5", tmp_path / "empty_a.h5", params - ) - assert np.isnan(empty.motion_r).all() and empty.registration_failed - with h5py.File(tmp_path / "empty.h5") as f: - assert np.isnan(f["data"][()]).all() - - -def test_register_trial_keeps_fractional_lines( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Fractional trial edges set the frame times, as in MATLAB. - - Trial tables of continuous recordings cut trials at ``linspace`` edges; - MultiRoiRegistration uses them unrounded: ``ceil(first:dt:last)``. - """ - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - first, last = 1000.4, 4000.7 - res = multiroi.register_trial( - layout.files[0], - first, - last, - tmp_path / "m.tif", - tmp_path / "a.h5", - params, - ) - dt = 1600 / 80 - n = int(np.floor((last - first) / dt)) + 1 - np.testing.assert_array_equal(res.ds_frames, np.ceil(first + dt * np.arange(n))) - assert res.ds_frames[0] == 1001 - - -def test_register_multiroi_updates_trial_table( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The pipeline writes MATLAB-named outputs and motion_correction.""" - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - name = dat.name - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - "motion_correction": {"keep_me": 7.0}, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert fields["fn_adata"][0, 0] == "E3T1DMD1_ALIGNMENTDATA.h5" - movie = tmp_path / "motion_correction" / fields["fn_reg_ds"][0, 0] - assert movie.name == "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - with h5py.File(movie) as f: - assert f["data"].shape[0] == 2 * 150 - tt = read_trial_table(table) - mc = tt.motion_correction - assert mc["keep_me"].item() == 7.0 - assert mc["fn_adata"] == "E3T1DMD1_ALIGNMENTDATA.h5" - assert mc["align_params"]["alignHz"].item() == 80.0 - assert mc["registration_failed"].dtype == np.int8 - - -def one_trial_table(layout: RasterLayout, tmp_path: Path) -> Path: - """Write a MATLAB-style trial table with one 3000-line trial.""" - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - }, - ) - return table - - -def test_rerun_keeps_the_saved_failure_flag( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Reused outputs report the registrationFailed they were saved with.""" - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - run = dict( - params={"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - fields = register_multiroi(table, **run) - assert not fields["registration_failed"][0, 0] - adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] - with h5py.File(adata, "r+") as f: # as if the motion had been too large - f["registrationFailed"][...] = 1 - before = digests(adata) - fields = register_multiroi(table, **run) - assert digests(adata) == before # reused, not registered again - assert fields["registration_failed"][0, 0] - assert read_trial_table(table).motion_correction["registration_failed"] - - -def test_rerun_with_other_settings_registers_again( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Outputs are reused only if made with the requested settings.""" - from giant_python.pipeline.register import register_multiroi - from giant_python.registration.outputs import SETTINGS_ATTR - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - execution = {"device": "cpu", "max_workers": 1} - sequential = {"maxshift": 5, "save_tif": False} - grow = dict(sequential, schedule="grow") - fields = register_multiroi(table, sequential, execution=execution) - adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] - first = digests(adata) - assert "growthQC" not in load_struct_h5(adata) - - fields = register_multiroi(table, grow, execution=execution) - assert digests(adata) != first # registered again - assert "growthQC" in load_struct_h5(adata) - mc = read_trial_table(table).motion_correction - assert mc["align_params"]["schedule"] == "grow" - with h5py.File(adata) as f: - saved = json.loads(f.attrs[SETTINGS_ATTR]) - assert saved["schedule"] == "grow" and saved["maxshift"] == 5 - assert "overwriteExisting" not in saved - - grown = digests(adata) - register_multiroi(table, grow, execution=execution) - assert digests(adata) == grown # same settings: reused - - with h5py.File(adata, "r+") as f: # outputs that do not record them - del f.attrs[SETTINGS_ATTR] - register_multiroi(table, grow, execution=execution) - with h5py.File(adata) as f: - assert SETTINGS_ATTR in f.attrs - - -def test_failed_rerun_does_not_name_the_old_outputs( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A re-registration that raises leaves the old files on disk but clears their names. - - So the table never pairs them with new settings. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - execution = {"device": "cpu", "max_workers": 1} - sequential = {"maxshift": 5, "save_tif": False} - fields = register_multiroi(table, sequential, execution=execution) - moco = tmp_path / "motion_correction" - files = [moco / fields["fn_reg_ds"][0, 0], moco / fields["fn_adata"][0, 0]] - before = digests(*files) - - def fail(*args: object, **kwargs: object) -> NoReturn: - """Fail before anything is published.""" - raise OSError("disk full") - - monkeypatch.setattr(multiroi, "register_trial", fail) - fields = register_multiroi(table, dict(sequential, schedule="grow"), execution=execution) - assert fields["fn_reg_ds"][0, 0] == fields["fn_adata"][0, 0] == "" - assert fields["registration_failed"][0, 0] - assert digests(*files) == before - mc = read_trial_table(table).motion_correction - assert mc["fn_reg_ds"] == mc["fn_adata"] == "" - assert mc["registration_failed"] - assert mc["align_params"]["schedule"] == "grow" - - -@pytest.mark.parametrize("case", ["row_major", "channels", "device"]) -def test_rejected_request_writes_nothing( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str -) -> None: - """A request that fails validation leaves outputs and table untouched. - - Such requests are a row-major table, an unsupported recording, an - unavailable device. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - lay = layout - if case == "channels": - lay = dataclasses.replace(layout, num_channels=3) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: lay) - table = one_trial_table(layout, tmp_path) - if case == "row_major": - with h5py.File(table, "r+") as f: - f["row_major"][...] = 1 - moco = tmp_path / "motion_correction" - moco.mkdir() - old = [ - moco / "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5", - moco / "E3T1DMD1_ALIGNMENTDATA.h5", - ] - for p in old: - p.write_bytes(b"from an earlier run") - before = digests(table, *old) - with pytest.raises(ValueError): - register_multiroi( - table, - {"maxshift": 5, "save_tif": False, "overwrite_existing": True}, - execution={ - "device": "cuda:99" if case == "device" else "cpu", - "max_workers": 1, - }, - ) - assert digests(table, *old) == before - assert sorted(moco.iterdir()) == sorted(old) - - -def test_ragged_table_skips_empty_cells( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A cell without a recording (one path has fewer trials) is skipped and flagged. - - It gets empty output names; the other cells register. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name, dat.name], [dat.name, ""]], dtype=object), - "epoch": np.array([[3.0, 3.0], [3.0, np.nan]]), - "true_trial_ix": np.array([[1.0, 2.0]]), - "slap2_info": { - "first_line": np.array([[1.0, 3001.0], [1.0, np.nan]]), - "last_line": np.array([[3000.0, 6000.0], [3000.0, np.nan]]), - }, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert fields["fn_reg_ds"][1, 1] == fields["fn_adata"][1, 1] == "" - np.testing.assert_array_equal(fields["registration_failed"], [[False, False], [False, True]]) - names = [ - fields[k][d, t] for k in ("fn_reg_ds", "fn_adata") for d, t in ((0, 0), (0, 1), (1, 0)) - ] - assert all(names) - moco = tmp_path / "motion_correction" - stats = [ - n.replace("_REGISTERED_DOWNSAMPLED-", "_REGSTATS-") for n in names if "_REGISTERED_" in n - ] - assert sorted(p.name for p in moco.iterdir()) == sorted(names + stats) - mc = read_trial_table(table).motion_correction - assert mc["fn_reg_ds"][1, 1] == mc["fn_adata"][1, 1] == "" - assert mc["registration_failed"][1, 1] == 1 - - -def test_trial_table_update_keeps_other_entries( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Only the registration fields are replaced, once all are written. - - Other entries of the group and their attributes are left untouched. - """ - from giant_python.pipeline import register - - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": "d", - "motion_correction": { - "keep_me": 7.0, - "fn_adata": "old.h5", - "align_params": {"old_only": 1.0}, - }, - }, - ) - with h5py.File(table, "r+") as f: - mc = f["motion_correction"] - mc.attrs["note"] = "kept" - mc["keep_me"].attrs["unit"] = "px" - mc.create_dataset("empty", shape=(0, 0), dtype=np.float64) - nested = mc.create_group("nested") - nested.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) - fields = { - "fn_adata": np.array([["new.h5"]], dtype=object), - "registration_failed": np.array([[True]]), - "align_params": {"alignHz": 80.0}, - } - write = register.write_matlab_value - - def fail_on_align_params(grp: h5py.Group, key: str, value: dict | ArrayLike) -> None: - """Fail while writing the last field.""" - if key.startswith("align_params"): - raise OSError("disk full") - write(grp, key, value) - - def entries() -> set[str]: - """Every entry under motion_correction.""" - names = [] - with h5py.File(table) as f: - f["motion_correction"].visit(names.append) - return set(names) - - kept = {"keep_me", "empty", "nested", "nested/row_major"} - with monkeypatch.context() as m: - m.setattr(register, "write_matlab_value", fail_on_align_params) - with pytest.raises(OSError): - register._update_trial_table(table, fields) - old = {"fn_adata", "align_params", "align_params/old_only"} - assert entries() == kept | old - assert load_struct_h5(table)["motion_correction"]["fn_adata"] == "old.h5" - register._update_trial_table(table, fields) - assert entries() == kept | { - "fn_adata", - "registration_failed", - "align_params", - "align_params/alignHz", - } - with h5py.File(table) as f: - mc = f["motion_correction"] - assert mc.attrs["note"] == "kept" - assert mc["keep_me"].attrs["unit"] == "px" - assert mc["empty"].shape == (0, 0) - mc = load_struct_h5(table)["motion_correction"] - assert mc["fn_adata"] == "new.h5" - assert mc["registration_failed"].item() == 1 - assert mc["align_params"]["alignHz"].item() == 80.0 - - -def test_register_multiroi_keeps_fractional_lines( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The pipeline passes the table's fractional trial edges on unrounded.""" - from giant_python.io.hdf5 import load_struct_h5 - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - first, last = 1000.4, 4000.7 - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[first]]), - "last_line": np.array([[last]]), - }, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - adata = load_struct_h5(tmp_path / "motion_correction" / fields["fn_adata"][0, 0]) - adata = adata.get("aData", adata) - dt = 1600 / 80 - n = int(np.floor((last - first) / dt)) + 1 - np.testing.assert_array_equal(np.ravel(adata["DSframes"]), np.ceil(first + dt * np.arange(n))) - - -def test_unsupported_options_raise() -> None: - """MATLAB options that are not ported are rejected.""" - with pytest.raises(NotImplementedError): - multiroi.MultiRoiRegistrationParams(ref_stack_template=True) - with pytest.raises(TypeError): - from giant_python.models.params import resolve_registration_options - - resolve_registration_options({"compensateOnline": True}) - - -def test_save_struct_h5_is_column_major(tmp_path: Path) -> None: - """Values come back in MATLAB orientation and MATLAB classes.""" - path = tmp_path / "s.h5" - save_struct_h5( - path, - { - "a": np.arange(6.0).reshape(2, 3), - "v": np.arange(4.0), - "flag": True, - "n": 3, - "s": "text", - "cells": np.array([["x"], ["yy"]], dtype=object), - "g": {"single": np.float32(2.5)}, - }, - ) - with h5py.File(path) as f: - assert f["a"].shape == (3, 2) and f["v"].shape == (4, 1) - assert f["flag"].dtype == np.int8 and f["n"].dtype == np.float64 - assert f["row_major"][()] == 0 - back = load_struct_h5(path) - np.testing.assert_array_equal(back["a"], np.arange(6.0).reshape(2, 3)) - assert back["v"].shape == (1, 4) - assert back["s"] == "text" - assert list(back["cells"].ravel()) == ["x", "yy"] - assert back["g"]["single"].dtype == np.float32 - - -def test_registration_runs_on_cuda_like_cpu( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """CUDA and CPU give the same motion (skipped without a GPU).""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - out = [ - multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"{d}.tif", - tmp_path / f"{d}.h5", - params, - device=d, - ) - for d in ("cpu", "cuda") - ] - diff = np.hypot(out[0].motion_r - out[1].motion_r, out[0].motion_c - out[1].motion_c) - # float32 sums differ in order; a near-tie peak may resolve differently - assert np.median(diff) < 1e-3 and diff.max() < 0.1 - - -def test_var_factor_deflate_keeps_values( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Deflated varFacDS (default) holds the same values as uncompressed.""" - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - for level in (0, 1): - params = multiroi.MultiRoiRegistrationParams( - maxshift=5, var_factor_deflate=level, save_tif=False - ) - multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"m{level}.h5", - tmp_path / f"a{level}.h5", - params, - ) - with ( - h5py.File(tmp_path / "a0.h5") as a, - h5py.File(tmp_path / "a1.h5") as b, - ): - assert a["slap2/varFacDS"].compression is None - assert b["slap2/varFacDS"].compression == "gzip" - np.testing.assert_array_equal(a["slap2/varFacDS"][()], b["slap2/varFacDS"][()]) - with h5py.File(tmp_path / "m1.h5") as m: - assert m["data"].compression == "gzip" - assert m["data"].compression_opts == 1 - - -def test_cycle_split_names() -> None: - """Files of CYCLE-split recordings are recognised by name only.""" - assert is_cycle_split("acq_DMD1-TRIAL000001-CYCLE-000000.dat") - assert is_cycle_split("d/acq_DMD2-CYCLE-318000.dat") - assert is_cycle_split("acq_DMD1-CYCLE000000.dat") - assert not is_cycle_split("acq_DMD1-TRIAL000001.dat") - assert not is_cycle_split("CYCLE-1/acq_DMD1-TRIAL000001.dat") - - -def split_recording(layout: RasterLayout, k: int, tmp_path: Path) -> RasterLayout: - """Write the recording as two files, split before cycle ``k``.""" - raw = np.fromfile(layout.files[0], dtype=np.int16) - head = raw[:HEADER_WORDS] - body = raw[HEADER_WORDS:].reshape(layout.num_cycles, -1) - files = [] - for name, part in (("a", body[:k]), ("b", body[k:])): - path = tmp_path / f"split_{name}.dat" - with open(path, "wb") as f: - f.write(head.tobytes()) - f.write(part.tobytes()) - files.append(str(path)) - return dataclasses.replace( - layout, - files=tuple(files), - file_cycles=np.array([k, layout.num_cycles - k]), - file_offset_words=np.array([HEADER_WORDS, HEADER_WORDS]), - ) - - -def test_split_recording_reads_and_registers_alike( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Reads and registration across two files equal those of one file.""" - layout, _ = recording - k = 500 - split = split_recording(layout, k, tmp_path) - for cycles in ((k - 7, k + 9), (0, layout.num_cycles), (k + 3, k + 40)): - np.testing.assert_array_equal( - read_raster_samples(split, cycles, chunk_cycles=5), - read_raster_samples(layout, cycles), - ) - p = layout.lines_per_cycle - lines = np.arange((k - 3) * p + 1, (k + 3) * p + 1) - for a, b in zip(read_line_offsets(split, lines), read_line_offsets(layout, lines)): - np.testing.assert_array_equal(a, b) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) - first, last = (k - 150) * p + 1, (k + 150) * p - out = {} - for name, lay in (("one", layout), ("two", split)): - monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) - out[name] = multiroi.register_trial( - lay.files[0], - first, - last, - tmp_path / f"m_{name}.h5", - tmp_path / f"a_{name}.h5", - params, - ) - for f in ("ds_frames", "motion_r", "motion_c", "peak"): - np.testing.assert_array_equal(getattr(out["one"], f), getattr(out["two"], f)) +"""Reader, frame formation and registration on a synthetic recording.""" + +import dataclasses +import hashlib +import json +import os +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import NoReturn + +import h5py +import numpy as np +import pytest +import torch +from numpy.typing import ArrayLike + +from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 +from giant_python.io.slap2 import is_cycle_split +from giant_python.io.slap2_raster import RasterLayout, read_line_offsets, read_raster_samples +from giant_python.io.trial_table import read_trial_table +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer + +from .synthetic import HEADER_WORDS, make_layout, write_recording + +Recording = tuple[RasterLayout, np.ndarray] +"""A synthetic recording's layout and its true motion.""" + + +@pytest.fixture(scope="module") +def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: + """Layout, data file and true motion of a 6-second recording. + + Returns + ------- + Recording + The recording's layout and its true motion. + """ + path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400) + truth = write_recording(layout, invalid=0.002) + return layout, truth + + +def frames_reference( + layout: RasterLayout, samples: np.ndarray, times: np.ndarray, dt: float +) -> tuple[np.ndarray, np.ndarray]: + """Per-pixel weighted means by the definition (slow loops). + + Returns + ------- + num : np.ndarray + Weighted sums of the valid samples, (channels, frames, pixels). + den : np.ndarray + The corresponding sums of the weights, same shape. + """ + p, total = layout.lines_per_cycle, layout.total_lines + pix = np.unique(layout.slot_pixel) + dt_read = max(3 * dt, p) + num = np.zeros((layout.num_channels, len(times), pix.size)) + den = np.zeros_like(num) + for s in range(layout.slot_line.size): + j = np.searchsorted(pix, layout.slot_pixel[s]) + for f, t in enumerate(times): + lines = np.arange(max(1, t - dt_read), min(total, t + dt_read) + 1) + lines = lines[(lines - 1) % p + 1 == layout.slot_line[s]] + for ln in lines: + w = np.exp(-abs(t - ln) / dt) + for ch in range(layout.num_channels): + x = samples[ch, s, (ln - 1) // p] + if x != -32768: + num[ch, f, j] += w * x + den[ch, f, j] += w + return num, den + + +def test_reader_and_line_headers(recording: Recording) -> None: + """Samples land at their slots; header offsets decode.""" + layout, _ = recording + s = read_raster_samples(layout, (10, 20), chunk_cycles=3) + whole = read_raster_samples(layout, (0, layout.num_cycles)) + np.testing.assert_array_equal(s, whole[:, :, 10:20]) + p = layout.lines_per_cycle + lines = np.array([1, p, p + 3, 5 * p + 2]) + x, y, z = read_line_offsets(layout, lines) + cyc = (lines - 1) // p + np.testing.assert_array_equal(x, cyc % 3) + np.testing.assert_array_equal(y, -(cyc % 2)) + np.testing.assert_allclose(z, 0.25 * cyc) + + +def test_frame_former_matches_definition(recording: Recording) -> None: + """Exp-kernel sums equal the definition, invalid samples masked.""" + layout, _ = recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + times = np.array([1, 50, 333, 4000]) + former = FrameFormer(layout, samples, 0) + num, den = former.sums(times, 20) + want_num, want_den = frames_reference(layout, samples, times, 20) + np.testing.assert_allclose(num.numpy(), want_num, rtol=1e-12) + np.testing.assert_allclose(den.numpy(), want_den, rtol=1e-12) + part = FrameFormer(layout, samples[:, :, 40:200], 40) + np.testing.assert_allclose(part.sums([700], 20)[0].numpy(), former.sums([700], 20)[0].numpy()) + with pytest.raises(ValueError): + part.sums([20], 20) + + +def test_register_trial_recovers_motion( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Recovered motion follows the known motion (up to a constant).""" + layout, truth = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + n_lines = 9000 + res = multiroi.register_trial( + layout.files[0], + 1, + n_lines, + tmp_path / "m.tif", + tmp_path / "a.h5", + params, + ) + dt = 1600 / 80 + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + true = np.stack([np.convolve(truth[:, i], kernel, "same")[res.ds_frames - 1] for i in (0, 1)]) + est = np.stack([res.motion_r, res.motion_c]) + err = est - true + err -= np.median(err, axis=1, keepdims=True) + assert np.sqrt(np.mean(err**2)) < 0.1 + a = load_struct_h5(tmp_path / "a.h5") + assert a["slap2"]["varFacDS"].shape == ( + a["meanIM"].shape[1], + a["meanIM"].shape[2], + res.ds_frames.size, + ) + np.testing.assert_array_equal(a["DSframes"].ravel(), res.ds_frames) + assert not (tmp_path / "a.h5.partial").exists() + + +def digests(*paths: str | Path) -> list[str]: + """SHA-256 of each file. + + Returns + ------- + list[str] + The hex digest of each of `paths`, in order. + """ + return [hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths] + + +@pytest.mark.parametrize("save_tif", [True, False]) +def test_failed_rerun_keeps_the_previous_outputs( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, save_tif: bool +) -> None: + """A run that fails while writing leaves an existing pair as it was.""" + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=save_tif) + movie = tmp_path / ("m.tif" if save_tif else "m.h5") + adata = tmp_path / "a.h5" + args = (layout.files[0], 1, 3000, movie, adata, params) + multiroi.register_trial(*args) + stats = movie.with_name(movie.stem + "_REGSTATS.h5") + before = digests(movie, adata, stats) + add = multiroi.OutputSink.add + + def fail_midway( + self: multiroi.OutputSink, + k: int, + regs: list[torch.Tensor], + var_factor: torch.Tensor, + *rest: object, + ) -> torch.Tensor: + """Write 50 frames, then fail. + + Returns + ------- + torch.Tensor + The sum of the frame's registered channels, from the original add. + + Raises + ------ + OSError + At frame 50. + """ + if k == 50: + raise OSError("disk full") + return add(self, k, regs, var_factor, *rest) + + def fail_at_the_end(*args: object, **kwargs: object) -> NoReturn: + """Fail after the movie is complete. + + Raises + ------ + OSError + Always. + """ + raise OSError("disk full") + + for target, name, fail in ( + (multiroi.OutputSink, "add", fail_midway), + (multiroi, "alignment_fields", fail_at_the_end), + ): + with monkeypatch.context() as m: + m.setattr(target, name, fail) + with pytest.raises(OSError): + multiroi.register_trial(*args) + assert digests(movie, adata, stats) == before + assert sorted(tmp_path.iterdir()) == sorted([movie, adata, stats]) + + +def test_interrupted_publish_leaves_no_alignment_file( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A pair that cannot be moved into place leaves no alignment file. + + The movie may then be new, but without an alignment file the trial is + not taken for registered. + """ + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) + movie, adata = tmp_path / "m.h5", tmp_path / "a.h5" + args = (layout.files[0], 1, 3000, movie, adata, params) + multiroi.register_trial(*args) + replace = os.replace + + def refuse_alignment_file(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: + """Fail to move the alignment file into place. + + Raises + ------ + PermissionError + If the destination is the alignment file. + """ + if Path(dst) == adata: + raise PermissionError("in use") + replace(src, dst) + + monkeypatch.setattr(os, "replace", refuse_alignment_file) + with pytest.raises(PermissionError): + multiroi.register_trial(*args) + # the new movie and its statistics are in place, the alignment file not + stats = movie.with_name(movie.stem + "_REGSTATS.h5") + assert sorted(tmp_path.iterdir()) == sorted([movie, stats]) + + +def blank_frames( + monkeypatch: pytest.MonkeyPatch, + blank: Callable[[np.ndarray], np.ndarray], + half: Callable[[np.ndarray], np.ndarray] | None = None, +) -> None: + """Frames formed at times where blank(times) holds have no samples. + + Where half(times) holds, the lower half of the raster has none. + """ + from giant_python.registration.frames import FrameFormer + + frames = FrameFormer.frames + + def blanked( + self: FrameFormer, times: ArrayLike, dt: int, channels: Sequence[int] | None = None + ) -> tuple[torch.Tensor, torch.Tensor]: + """Form the frames, with the selected ones emptied. + + Returns + ------- + vals : torch.Tensor + The frame values, NaN in the emptied frames (and in the lower half where + half(times) holds). + fresh : torch.Tensor + The per-pixel freshness, zero where emptied. + """ + vals, fresh = frames(self, times, dt, channels) + t = np.asarray(times).ravel() + lower = self.rows > np.median(self.rows) + for i in np.flatnonzero(half(t) if half else []): + vals[:, i, lower] = float("nan") + fresh[i, lower] = 0 + hit = torch.as_tensor(blank(t), device=vals.device) + vals[:, hit] = float("nan") + fresh[hit] = 0 + return vals, fresh + + monkeypatch.setattr(FrameFormer, "frames", blanked) + + +@pytest.mark.parametrize("schedule", ["sequential", "grow"]) +def test_frame_without_samples_is_missing( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str +) -> None: + """A frame without valid samples in mid-trial gets NaN motion and an all-NaN movie frame. + + The other frames are registered exactly as in a run without that frame, + and the trial does not fail. + """ + from giant_python.registration.growth import MISSING + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) + dt = (1 / layout.line_period_s) / params.align_hz + init, ds = multiroi.frame_times(1, 3000, dt, params.init_frames) + k = 70 + assert ds[k] not in init + times = multiroi.frame_times + out = {} + for name in ("blank", "without"): + with monkeypatch.context() as m: + if name == "blank": + blank_frames(m, lambda t: t == ds[k]) + else: + m.setattr( + multiroi, + "frame_times", + lambda *a: (times(*a)[0], np.delete(times(*a)[1], k)), + ) + out[name] = multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"{name}.h5", + tmp_path / f"{name}_a.h5", + params, + ) + res, ref = out["blank"], out["without"] + assert not res.registration_failed + assert np.isnan([res.motion_r[k], res.motion_c[k], res.peak[k]]).all() + others = np.arange(ds.size) != k + for f in ("motion_r", "motion_c", "peak"): + np.testing.assert_array_equal(getattr(res, f)[others], getattr(ref, f)) + n_ch = layout.num_channels + with ( + h5py.File(tmp_path / "blank.h5") as a, + h5py.File(tmp_path / "without.h5") as b, + ): + pages = a["data"][()] + mine = np.s_[k * n_ch : (k + 1) * n_ch] + assert np.isnan(pages[mine]).all() + np.testing.assert_array_equal(np.delete(pages, mine, axis=0), b["data"][()]) + adata = load_struct_h5(tmp_path / "blank_a.h5") + want = load_struct_h5(tmp_path / "without_a.h5") + assert adata["registrationFailed"].item() == 0 + assert np.isnan(adata["motionDSr"].ravel()[k]) + assert np.isnan(adata["slap2"]["varFacDS"][..., k]).all() + np.testing.assert_array_equal(adata["meanIM"], want["meanIM"]) + if schedule == "grow": + assert adata["growthQC"]["kind"].ravel()[k] == MISSING + + +@pytest.mark.parametrize("schedule", ["sequential", "grow"]) +def test_trial_without_samples_at_its_start_or_at_all( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str +) -> None: + """A recording that starts late is registered from its first frames with samples. + + It is registered in the usual window even if the first of them covers only + part of the raster; a trial without any samples completes and is flagged. + """ + from giant_python.registration.sources import make_source + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) + args = (layout.files[0], 1, 3000) + lay, former, init, ds, dt = multiroi.open_trial(*args, params, torch.device("cpu")) + window = make_source(lay, former, 1, 3000, init, ds, dt, False).window + with monkeypatch.context() as m: + # the first initial frames have no samples, the next one only half + assert np.sum((init >= 1200) & (init < 1300)) == 1 + blank_frames(m, lambda t: t < 1200, lambda t: t < 1300) + late = multiroi.register_trial(*args, tmp_path / "late.h5", tmp_path / "late_a.h5", params) + early = late.ds_frames < 1200 + assert np.isnan(late.motion_r[early]).all() + assert np.isfinite(late.motion_r[late.ds_frames >= 1200]).all() + assert not late.registration_failed + trim = load_struct_h5(tmp_path / "late_a.h5")["slap2"] + np.testing.assert_array_equal(trim["trimRows"].ravel(), window.trim_rows) + np.testing.assert_array_equal(trim["trimCols"].ravel(), window.trim_cols) + with monkeypatch.context() as m: + blank_frames(m, lambda t: np.ones(t.shape, dtype=bool)) + empty = multiroi.register_trial( + *args, tmp_path / "empty.h5", tmp_path / "empty_a.h5", params + ) + assert np.isnan(empty.motion_r).all() and empty.registration_failed + with h5py.File(tmp_path / "empty.h5") as f: + assert np.isnan(f["data"][()]).all() + + +def test_register_trial_keeps_fractional_lines( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fractional trial edges set the frame times, as in MATLAB. + + Trial tables of continuous recordings cut trials at linspace edges; + MultiRoiRegistration uses them unrounded: ceil(first:dt:last). + """ + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + first, last = 1000.4, 4000.7 + res = multiroi.register_trial( + layout.files[0], + first, + last, + tmp_path / "m.tif", + tmp_path / "a.h5", + params, + ) + dt = 1600 / 80 + n = int(np.floor((last - first) / dt)) + 1 + np.testing.assert_array_equal(res.ds_frames, np.ceil(first + dt * np.arange(n))) + assert res.ds_frames[0] == 1001 + + +def test_register_multiroi_updates_trial_table( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pipeline writes MATLAB-named outputs and motion_correction.""" + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + name = dat.name + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + "motion_correction": {"keep_me": 7.0}, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert fields["fn_adata"][0, 0] == "E3T1DMD1_ALIGNMENTDATA.h5" + movie = tmp_path / "motion_correction" / fields["fn_reg_ds"][0, 0] + assert movie.name == "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + with h5py.File(movie) as f: + assert f["data"].shape[0] == 2 * 150 + tt = read_trial_table(table) + mc = tt.motion_correction + assert mc["keep_me"].item() == 7.0 + assert mc["fn_adata"] == "E3T1DMD1_ALIGNMENTDATA.h5" + assert mc["align_params"]["alignHz"].item() == 80.0 + assert mc["registration_failed"].dtype == np.int8 + + +def one_trial_table(layout: RasterLayout, tmp_path: Path) -> Path: + """Write a MATLAB-style trial table with one 3000-line trial. + + Returns + ------- + Path + The trial table file. + """ + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + }, + ) + return table + + +def test_rerun_keeps_the_saved_failure_flag( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Reused outputs report the registrationFailed they were saved with.""" + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + run = dict( + params={"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + fields = register_multiroi(table, **run) + assert not fields["registration_failed"][0, 0] + adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] + with h5py.File(adata, "r+") as f: # as if the motion had been too large + f["registrationFailed"][...] = 1 + before = digests(adata) + fields = register_multiroi(table, **run) + assert digests(adata) == before # reused, not registered again + assert fields["registration_failed"][0, 0] + assert read_trial_table(table).motion_correction["registration_failed"] + + +def test_rerun_with_other_settings_registers_again( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Outputs are reused only if made with the requested settings.""" + from giant_python.pipeline.register import register_multiroi + from giant_python.registration.outputs import SETTINGS_ATTR + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + execution = {"device": "cpu", "max_workers": 1} + sequential = {"maxshift": 5, "save_tif": False} + grow = dict(sequential, schedule="grow") + fields = register_multiroi(table, sequential, execution=execution) + adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] + first = digests(adata) + assert "growthQC" not in load_struct_h5(adata) + + fields = register_multiroi(table, grow, execution=execution) + assert digests(adata) != first # registered again + assert "growthQC" in load_struct_h5(adata) + mc = read_trial_table(table).motion_correction + assert mc["align_params"]["schedule"] == "grow" + with h5py.File(adata) as f: + saved = json.loads(f.attrs[SETTINGS_ATTR]) + assert saved["schedule"] == "grow" and saved["maxshift"] == 5 + assert "overwriteExisting" not in saved + + grown = digests(adata) + register_multiroi(table, grow, execution=execution) + assert digests(adata) == grown # same settings: reused + + with h5py.File(adata, "r+") as f: # outputs that do not record them + del f.attrs[SETTINGS_ATTR] + register_multiroi(table, grow, execution=execution) + with h5py.File(adata) as f: + assert SETTINGS_ATTR in f.attrs + + +def test_failed_rerun_does_not_name_the_old_outputs( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A re-registration that raises leaves the old files on disk but clears their names. + + So the table never pairs them with new settings. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + execution = {"device": "cpu", "max_workers": 1} + sequential = {"maxshift": 5, "save_tif": False} + fields = register_multiroi(table, sequential, execution=execution) + moco = tmp_path / "motion_correction" + files = [moco / fields["fn_reg_ds"][0, 0], moco / fields["fn_adata"][0, 0]] + before = digests(*files) + + def fail(*args: object, **kwargs: object) -> NoReturn: + """Fail before anything is published. + + Raises + ------ + OSError + Always. + """ + raise OSError("disk full") + + monkeypatch.setattr(multiroi, "register_trial", fail) + fields = register_multiroi(table, dict(sequential, schedule="grow"), execution=execution) + assert fields["fn_reg_ds"][0, 0] == fields["fn_adata"][0, 0] == "" + assert fields["registration_failed"][0, 0] + assert digests(*files) == before + mc = read_trial_table(table).motion_correction + assert mc["fn_reg_ds"] == mc["fn_adata"] == "" + assert mc["registration_failed"] + assert mc["align_params"]["schedule"] == "grow" + + +@pytest.mark.parametrize("case", ["row_major", "channels", "device"]) +def test_rejected_request_writes_nothing( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + """A request that fails validation leaves outputs and table untouched. + + Such requests are a row-major table, an unsupported recording, an + unavailable device. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + lay = layout + if case == "channels": + lay = dataclasses.replace(layout, num_channels=3) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: lay) + table = one_trial_table(layout, tmp_path) + if case == "row_major": + with h5py.File(table, "r+") as f: + f["row_major"][...] = 1 + moco = tmp_path / "motion_correction" + moco.mkdir() + old = [ + moco / "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5", + moco / "E3T1DMD1_ALIGNMENTDATA.h5", + ] + for p in old: + p.write_bytes(b"from an earlier run") + before = digests(table, *old) + with pytest.raises(ValueError): + register_multiroi( + table, + {"maxshift": 5, "save_tif": False, "overwrite_existing": True}, + execution={ + "device": "cuda:99" if case == "device" else "cpu", + "max_workers": 1, + }, + ) + assert digests(table, *old) == before + assert sorted(moco.iterdir()) == sorted(old) + + +def test_ragged_table_skips_empty_cells( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A cell without a recording (one path has fewer trials) is skipped and flagged. + + It gets empty output names; the other cells register. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name, dat.name], [dat.name, ""]], dtype=object), + "epoch": np.array([[3.0, 3.0], [3.0, np.nan]]), + "true_trial_ix": np.array([[1.0, 2.0]]), + "slap2_info": { + "first_line": np.array([[1.0, 3001.0], [1.0, np.nan]]), + "last_line": np.array([[3000.0, 6000.0], [3000.0, np.nan]]), + }, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert fields["fn_reg_ds"][1, 1] == fields["fn_adata"][1, 1] == "" + np.testing.assert_array_equal(fields["registration_failed"], [[False, False], [False, True]]) + names = [ + fields[k][d, t] for k in ("fn_reg_ds", "fn_adata") for d, t in ((0, 0), (0, 1), (1, 0)) + ] + assert all(names) + moco = tmp_path / "motion_correction" + stats = [ + n.replace("_REGISTERED_DOWNSAMPLED-", "_REGSTATS-") for n in names if "_REGISTERED_" in n + ] + assert sorted(p.name for p in moco.iterdir()) == sorted(names + stats) + mc = read_trial_table(table).motion_correction + assert mc["fn_reg_ds"][1, 1] == mc["fn_adata"][1, 1] == "" + assert mc["registration_failed"][1, 1] == 1 + + +def test_trial_table_update_keeps_other_entries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only the registration fields are replaced, once all are written. + + Other entries of the group and their attributes are left untouched. + """ + from giant_python.pipeline import register + + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": "d", + "motion_correction": { + "keep_me": 7.0, + "fn_adata": "old.h5", + "align_params": {"old_only": 1.0}, + }, + }, + ) + with h5py.File(table, "r+") as f: + mc = f["motion_correction"] + mc.attrs["note"] = "kept" + mc["keep_me"].attrs["unit"] = "px" + mc.create_dataset("empty", shape=(0, 0), dtype=np.float64) + nested = mc.create_group("nested") + nested.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) + fields = { + "fn_adata": np.array([["new.h5"]], dtype=object), + "registration_failed": np.array([[True]]), + "align_params": {"alignHz": 80.0}, + } + write = register.write_matlab_value + + def fail_on_align_params(grp: h5py.Group, key: str, value: dict | ArrayLike) -> None: + """Fail while writing the last field. + + Raises + ------ + OSError + If key starts with align_params. + """ + if key.startswith("align_params"): + raise OSError("disk full") + write(grp, key, value) + + def entries() -> set[str]: + """Every entry under motion_correction. + + Returns + ------- + set[str] + The names of all groups and datasets under motion_correction in the table. + """ + names = [] + with h5py.File(table) as f: + f["motion_correction"].visit(names.append) + return set(names) + + kept = {"keep_me", "empty", "nested", "nested/row_major"} + with monkeypatch.context() as m: + m.setattr(register, "write_matlab_value", fail_on_align_params) + with pytest.raises(OSError): + register._update_trial_table(table, fields) + old = {"fn_adata", "align_params", "align_params/old_only"} + assert entries() == kept | old + assert load_struct_h5(table)["motion_correction"]["fn_adata"] == "old.h5" + register._update_trial_table(table, fields) + assert entries() == kept | { + "fn_adata", + "registration_failed", + "align_params", + "align_params/alignHz", + } + with h5py.File(table) as f: + mc = f["motion_correction"] + assert mc.attrs["note"] == "kept" + assert mc["keep_me"].attrs["unit"] == "px" + assert mc["empty"].shape == (0, 0) + mc = load_struct_h5(table)["motion_correction"] + assert mc["fn_adata"] == "new.h5" + assert mc["registration_failed"].item() == 1 + assert mc["align_params"]["alignHz"].item() == 80.0 + + +def test_register_multiroi_keeps_fractional_lines( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pipeline passes the table's fractional trial edges on unrounded.""" + from giant_python.io.hdf5 import load_struct_h5 + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + first, last = 1000.4, 4000.7 + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[first]]), + "last_line": np.array([[last]]), + }, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + adata = load_struct_h5(tmp_path / "motion_correction" / fields["fn_adata"][0, 0]) + adata = adata.get("aData", adata) + dt = 1600 / 80 + n = int(np.floor((last - first) / dt)) + 1 + np.testing.assert_array_equal(np.ravel(adata["DSframes"]), np.ceil(first + dt * np.arange(n))) + + +def test_unsupported_options_raise() -> None: + """MATLAB options that are not ported are rejected.""" + with pytest.raises(NotImplementedError): + multiroi.MultiRoiRegistrationParams(ref_stack_template=True) + with pytest.raises(TypeError): + from giant_python.models.params import resolve_registration_options + + resolve_registration_options({"compensateOnline": True}) + + +def test_save_struct_h5_is_column_major(tmp_path: Path) -> None: + """Values come back in MATLAB orientation and MATLAB classes.""" + path = tmp_path / "s.h5" + save_struct_h5( + path, + { + "a": np.arange(6.0).reshape(2, 3), + "v": np.arange(4.0), + "flag": True, + "n": 3, + "s": "text", + "cells": np.array([["x"], ["yy"]], dtype=object), + "g": {"single": np.float32(2.5)}, + }, + ) + with h5py.File(path) as f: + assert f["a"].shape == (3, 2) and f["v"].shape == (4, 1) + assert f["flag"].dtype == np.int8 and f["n"].dtype == np.float64 + assert f["row_major"][()] == 0 + back = load_struct_h5(path) + np.testing.assert_array_equal(back["a"], np.arange(6.0).reshape(2, 3)) + assert back["v"].shape == (1, 4) + assert back["s"] == "text" + assert list(back["cells"].ravel()) == ["x", "yy"] + assert back["g"]["single"].dtype == np.float32 + + +def test_registration_runs_on_cuda_like_cpu( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """CUDA and CPU give the same motion (skipped without a GPU).""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + out = [ + multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"{d}.tif", + tmp_path / f"{d}.h5", + params, + device=d, + ) + for d in ("cpu", "cuda") + ] + diff = np.hypot(out[0].motion_r - out[1].motion_r, out[0].motion_c - out[1].motion_c) + # float32 sums differ in order; a near-tie peak may resolve differently + assert np.median(diff) < 1e-3 and diff.max() < 0.1 + + +def test_var_factor_deflate_keeps_values( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Deflated varFacDS (default) holds the same values as uncompressed.""" + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + for level in (0, 1): + params = multiroi.MultiRoiRegistrationParams( + maxshift=5, var_factor_deflate=level, save_tif=False + ) + multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"m{level}.h5", + tmp_path / f"a{level}.h5", + params, + ) + with ( + h5py.File(tmp_path / "a0.h5") as a, + h5py.File(tmp_path / "a1.h5") as b, + ): + assert a["slap2/varFacDS"].compression is None + assert b["slap2/varFacDS"].compression == "gzip" + np.testing.assert_array_equal(a["slap2/varFacDS"][()], b["slap2/varFacDS"][()]) + with h5py.File(tmp_path / "m1.h5") as m: + assert m["data"].compression == "gzip" + assert m["data"].compression_opts == 1 + + +def test_cycle_split_names() -> None: + """Files of CYCLE-split recordings are recognised by name only.""" + assert is_cycle_split("acq_DMD1-TRIAL000001-CYCLE-000000.dat") + assert is_cycle_split("d/acq_DMD2-CYCLE-318000.dat") + assert is_cycle_split("acq_DMD1-CYCLE000000.dat") + assert not is_cycle_split("acq_DMD1-TRIAL000001.dat") + assert not is_cycle_split("CYCLE-1/acq_DMD1-TRIAL000001.dat") + + +def split_recording(layout: RasterLayout, k: int, tmp_path: Path) -> RasterLayout: + """Write the recording as two files, split before cycle k. + + Returns + ------- + RasterLayout + `layout` with its files replaced by the two split files. + """ + raw = np.fromfile(layout.files[0], dtype=np.int16) + head = raw[:HEADER_WORDS] + body = raw[HEADER_WORDS:].reshape(layout.num_cycles, -1) + files = [] + for name, part in (("a", body[:k]), ("b", body[k:])): + path = tmp_path / f"split_{name}.dat" + with open(path, "wb") as f: + f.write(head.tobytes()) + f.write(part.tobytes()) + files.append(str(path)) + return dataclasses.replace( + layout, + files=tuple(files), + file_cycles=np.array([k, layout.num_cycles - k]), + file_offset_words=np.array([HEADER_WORDS, HEADER_WORDS]), + ) + + +def test_split_recording_reads_and_registers_alike( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Reads and registration across two files equal those of one file.""" + layout, _ = recording + k = 500 + split = split_recording(layout, k, tmp_path) + for cycles in ((k - 7, k + 9), (0, layout.num_cycles), (k + 3, k + 40)): + np.testing.assert_array_equal( + read_raster_samples(split, cycles, chunk_cycles=5), + read_raster_samples(layout, cycles), + ) + p = layout.lines_per_cycle + lines = np.arange((k - 3) * p + 1, (k + 3) * p + 1) + for a, b in zip(read_line_offsets(split, lines), read_line_offsets(layout, lines)): + np.testing.assert_array_equal(a, b) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) + first, last = (k - 150) * p + 1, (k + 150) * p + out = {} + for name, lay in (("one", layout), ("two", split)): + monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) + out[name] = multiroi.register_trial( + lay.files[0], + first, + last, + tmp_path / f"m_{name}.h5", + tmp_path / f"a_{name}.h5", + params, + ) + for f in ("ds_frames", "motion_r", "motion_c", "peak"): + np.testing.assert_array_equal(getattr(out["one"], f), getattr(out["two"], f)) diff --git a/tests/simulation/__init__.py b/tests/simulation/__init__.py index 16662977..e6392c55 100644 --- a/tests/simulation/__init__.py +++ b/tests/simulation/__init__.py @@ -1 +1 @@ -"""Tests of synthetic ground truth (event injection).""" +"""Tests of synthetic ground truth (event injection).""" diff --git a/tests/simulation/test_injection.py b/tests/simulation/test_injection.py index 813ffd20..dbda863e 100644 --- a/tests/simulation/test_injection.py +++ b/tests/simulation/test_injection.py @@ -1,1448 +1,1513 @@ -"""Event injection into raw SLAP2 samples, on small synthetic recordings.""" - -import hashlib -import json -from collections.abc import Sequence -from dataclasses import replace -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples -from giant_python.pipeline.register import register_multiroi -from giant_python.registration import multiroi -from giant_python.simulation import injection as inj -from giant_python.simulation.render import iter_registered_frames - -from ..registration.synthetic import ( - HEADER_WORDS, - make_layout, - online_offsets, - write_recording, -) - -N_CYCLES = 1400 - -# online offsets (x, y_header, y_dmd) per line, as online_offsets returns them -Offsets = tuple[np.ndarray, np.ndarray, np.ndarray] -# the layout, its online offsets and the true motion of the synthetic recording -OnlineRecording = tuple[RasterLayout, Offsets, np.ndarray] -# the injected copy's folder, its summary and the settings it was made with -Injected = tuple[Path, dict, inj.InjectionSettings] - - -def sha(path: str | Path) -> str: - """SHA-256 of a file.""" - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - - -# --------------------------------------------------------- pure functions - - -def test_time_course_peaks_at_one() -> None: - """Instant rise: exp decay from 1; short rise: peak 1 at its delay.""" - t = np.array([-0.01, 0.0, 0.024, 0.048]) - np.testing.assert_allclose(inj.time_course(t, 0.024), [0, 1, np.exp(-1), np.exp(-2)]) - tp = inj.peak_delay_s(0.024, 0.003) - assert 0 < tp < 0.024 - grid = np.linspace(0, 0.1, 100001) - k = inj.time_course(grid, 0.024, 0.003) - assert k.max() == pytest.approx(1.0, abs=1e-8) - assert grid[np.argmax(k)] == pytest.approx(tp, abs=2e-6) - assert inj.time_course(-1e-9, 0.024, 0.003) == 0 - - -def test_event_traces_sum_events() -> None: - """Traces are sums of size x time course at the line times.""" - s = inj.InjectionSettings(tau_s=0.01) - ev = inj.Events( - np.array([0, 0, 1]), - np.array([1, 1, 1]), - np.array([10.5, 30.0, 12.0]), - np.array([0, 1, 2]), - np.array([2.0, 3.0, 1.0]), - ) - tr = inj.event_traces(ev, 2, (5, 60), 0.001, s) - lines = np.arange(5, 61) - want0 = 2 * inj.time_course((lines - 10.5) * 1e-3, 0.01) + 3 * ( - inj.time_course((lines - 30.0) * 1e-3, 0.01) - ) - np.testing.assert_allclose(tr[0], want0, atol=1e-12) - assert tr[1, 12 - 5] == pytest.approx(1.0) - assert np.all(tr[1, : 12 - 5] == 0) - - -def test_draw_events_respect_edges_dead_time_and_classes() -> None: - """Onsets stay inside the edges, apart by the dead time; classes mix.""" - s = inj.InjectionSettings(rate_hz=4.0, min_interval_s=0.1, edge_s=0.5) - period = 1e-4 - ev = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) - assert np.all(ev.trial == 3) - assert ev.onset_line.min() >= 1 + 0.5 / period - assert ev.onset_line.max() <= 100001 - 0.5 / period - for j in range(200): - t = ev.onset_line[ev.source == j] - assert np.all(np.diff(t) >= 0.1 / period - 1e-6) - dur = 10.0 - 1.0 - rate = len(ev) / 200 / dur - assert rate == pytest.approx(1 / (0.1 + 1 / 4.0), rel=0.05) - counts = np.bincount(ev.size_class, minlength=6) - assert counts.min() > 0.8 * counts.mean() - np.testing.assert_array_equal(ev.size, np.asarray(s.size_classes)[ev.size_class]) - again = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) - np.testing.assert_array_equal(again.onset_line, ev.onset_line) - none = inj.draw_events(5, 1.0, 100001.0, period, replace(s, rate_hz=0.0), None) - assert len(none) == 0 - - -def _draw_events_before_sync( - n_sources: int, - first: float, - last: float, - period: float, - s: inj.InjectionSettings, - rng: np.random.Generator, -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Draw the events as they were drawn before ``sync_share`` existed. - - This is the loop of ``draw_events`` at GIAnT-Python a673714, kept here as - the reference: source, onset line and size class of every event. - """ - edge = s.edge_s / period - lo, hi = float(first) + edge, float(last) - edge - mean_gap = 1.0 / s.rate_hz / period - dead = s.min_interval_s / period - n_draw = int((hi - lo) / (mean_gap + dead) * 1.5) + 20 - src, onset, classes = [], [], [] - for j in range(n_sources): - while True: - gaps = rng.exponential(mean_gap, n_draw) + dead - gaps[0] -= dead - t = lo + np.cumsum(gaps) - if t[-1] > hi: - break - n_draw *= 2 - t = t[t <= hi] - cls = rng.choice(len(s.size_classes), t.size, p=s.weights) - src.append(np.full(t.size, j)) - onset.append(t) - classes.append(cls) - return np.concatenate(src), np.concatenate(onset), np.concatenate(classes) - - -def test_draw_events_with_common_onsets() -> None: - """``sync_share`` gives every source the onsets of one common train beside its own. - - The common ones are in every source, the dead time holds, the rate is - about kept, and a share of 0 changes no draw. - """ - period = 1e-4 - s = inj.InjectionSettings(rate_hz=2.0, min_interval_s=0.1, edge_s=0.5) - args = (60, 1.0, 600001.0, period) # a minute - plain = inj.draw_events(*args, s, np.random.default_rng(3)) - # a share of 0 draws what the tool drew before the option existed: - # the same generator calls in the same order (the default setting, a - # high rate without dead time, weighted size classes) - for setting, n_src, seed in ( - (s, 60, 3), - (replace(s, rate_hz=40.0, min_interval_s=0.0), 7, 11), - (replace(s, class_weights=(1, 1, 1, 1, 1, 5)), 12, 5), - ): - got = inj.draw_events(n_src, *args[1:], setting, np.random.default_rng(seed)) - src, onset, cls = _draw_events_before_sync( - n_src, *args[1:], setting, np.random.default_rng(seed) - ) - np.testing.assert_array_equal(got.source, src) - np.testing.assert_array_equal(got.onset_line, onset) - np.testing.assert_array_equal(got.size_class, cls) - assert len(got) > 100 - rate0 = len(plain) / 60 / 59.0 - - def common_onsets(ev: inj.Events, n: int) -> np.ndarray: - """Onsets that every one of the n sources has.""" - t, counts = np.unique(ev.onset_line, return_counts=True) - return t[counts == n] - - assert common_onsets(plain, 60).size == 0 - for share in (0.5, 1.0): - ev = inj.draw_events(*args, replace(s, sync_share=share), np.random.default_rng(3)) - both = common_onsets(ev, 60) - assert both.size > 20 - for j in range(60): - t = ev.onset_line[ev.source == j] - assert np.all(np.diff(t) >= 0.1 / period - 1e-6) - in_common = np.isin(t, both).mean() - if share == 1.0: - assert in_common == 1.0 - else: - assert 0.35 < in_common < 0.7 - rate = len(ev) / 60 / 59.0 - assert rate == pytest.approx(rate0, rel=0.12) - if share == 1.0: # one train, sixty times, with sizes of their own - assert len(ev) == 60 * both.size - first = ev.size_class[ev.source == 0] - second = ev.size_class[ev.source == 1] - assert np.any(first != second) - # an own onset never falls within the dead time of a common one - ev = inj.draw_events(*args, replace(s, sync_share=0.5), np.random.default_rng(3)) - both = common_onsets(ev, 60) - own = ev.onset_line[~np.isin(ev.onset_line, both)] - k = np.searchsorted(both, own) - gap = np.minimum( - np.abs(both[np.minimum(k, both.size - 1)] - own), - np.abs(own - both[np.maximum(k - 1, 0)]), - ) - assert gap.min() >= 0.1 / period - 1e-6 - - -def test_settings_reject_bad_values() -> None: - """Invalid settings raise.""" - with pytest.raises(ValueError): - inj.InjectionSettings(rise_s=0.03) - with pytest.raises(ValueError): - inj.InjectionSettings(sync_share=1.5) - with pytest.raises(ValueError): - inj.InjectionSettings(class_weights=(1.0, 2.0)) - with pytest.raises(ValueError): - inj.InjectionSettings(rate_hz=-1) - - -def test_footprints() -> None: - """Gaussian peak 1 and cut at its radius; image footprints interpolate.""" - g = inj.GaussianFootprint(1.33, 4.0) - assert g(0.0, 0.0) == 1.0 - assert g(1.33, 0.0) == pytest.approx(np.exp(-0.5)) - assert g(5.4, 0.0) == 0.0 and g.radius == pytest.approx(5.32) - img = np.zeros((5, 5)) - img[2, 2], img[2, 3] = 4.0, 2.0 - f = inj.ImageFootprint(img) - assert f(0.0, 0.0) == 1.0 - assert f(0.0, 0.5) == pytest.approx(0.75) - assert f(0.0, 9.0) == 0.0 - patch, origin = inj.footprint_patch(g, (10.0, 20.4), 3) - assert origin == [7, 17] and patch.shape == (7, 7) - assert patch[3, 3] == pytest.approx(np.exp(-0.5 * (0.4 / 1.33) ** 2)) - - -def test_place_sources_follow_the_rules() -> None: - """Sources sit on labeled pixels, away from edges, others and each other.""" - rng = np.random.default_rng(0) - img = np.full((60, 80), 1.0) - img[20:24, 5:75] = 10.0 # a horizontal "dendrite" - img[30:50, 40:44] = 10.0 # a vertical one - img[:, :3] = np.nan - exclude = np.array([[22.0, 40.0]]) - s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) - pos, n_cand = inj.place_sources(img, 100, rng, s, exclude_rc=exclude) - assert 0 < pos.shape[0] < 100 and n_cand > pos.shape[0] - lab = inj.labeled_pixels(img) - r, c = pos.T.astype(int) - assert lab[r, c].all() - assert c.min() >= 3 + 5 - 1 # distance from the NaN columns - d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) - assert d[np.triu_indices(len(pos), 1)].min() >= 6 - assert np.hypot(*(pos - exclude).T).min() >= 8 - - -def test_place_sources_keep_apart_from_placed_ones() -> None: - """Candidates near sources placed already are dropped before any is chosen. - - Candidates within the minimum distance of sources placed already are - dropped first: one that is too near cannot stand in the way of a free - one behind it. - """ - img = np.full((40, 60), 1.0) - img[19:22, 20:41] = 10.0 # a short "dendrite" - s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) - placed = np.array([[20.0, 24.0]]) - for seed in range(8): - pos, n_cand = inj.place_sources( - img, 10, np.random.default_rng(seed), s, keep_apart_rc=placed - ) - _, n_free = inj.place_sources(img, 10, np.random.default_rng(seed), s) - # fewer candidates, and none of the chosen within 6 px of the - # placed source or of each other - assert 0 < n_cand < n_free and pos.shape[0] >= 1 - assert np.hypot(*(pos - placed).T).min() >= 6 - d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) - assert len(pos) < 2 or d[np.triu_indices(len(pos), 1)].min() >= 6 - # with one place wanted and only the pixels 4 and 8 px from the placed - # source as candidates, the far one is found whatever the order - two = np.full((40, 60), np.nan) - two[10:31, 10:51] = 1.0 - two[19:22, 27:30] = 10.0 - two[19:22, 31:34] = 10.0 - for seed in range(8): - pos, _ = inj.place_sources( - two, - 1, - np.random.default_rng(seed), - replace(s, edge_px=0), - keep_apart_rc=placed, - ) - assert pos.shape[0] == 1 - assert np.hypot(*(pos[0] - placed[0])) >= 6 - - -def test_align_images_recovers_subpixel_shift() -> None: - """A smooth random image moved by a known shift is found again.""" - from scipy.ndimage import gaussian_filter - - rng = np.random.default_rng(3) - ref = gaussian_filter(rng.random((90, 120)), 2.0) * 100 - ref[:, :10] = np.nan - s = np.array([1.3, -2.6]) - moved = inj.shift_image(ref, -s) # moved(p + s) = ref(p) - est = inj.align_images(ref, moved) - np.testing.assert_allclose(est, s, atol=0.08) - - -# ------------------------------------------------------ synthetic recordings - - -def write_static(layout: RasterLayout, gain: float, rate: float, seed: int = 0) -> None: - """Write samples ``gain * Poisson(rate * brightness)`` of a static scene.""" - rng = np.random.default_rng(seed) - words = np.zeros((layout.num_cycles, layout.words_per_cycle), np.int16) - bright = 1 + 9 * ((layout.slot_pixel * 7919) % 97) / 97.0 - for ch in range(layout.num_channels): - li = layout.slot_line - 1 - w = layout.row_base[li] + ch * layout.n_per_channel[li] - w = w + layout.slot_pos - lam = rate * bright - words[:, w] = (gain * rng.poisson(lam, (layout.num_cycles, lam.size))).astype(np.int16) - with open(layout.files[0], "wb") as f: - f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) - f.write(words.tobytes()) - - -def test_measure_raw_per_photon(tmp_path: Path) -> None: - """The variance-to-mean ratio of scaled Poisson samples is the gain.""" - layout = make_layout(tmp_path / "g_DMD1-TRIAL000001.dat", 400, seed=2) - write_static(layout, gain=110.0, rate=0.05) - g = inj.measure_raw_per_photon(layout, channel=0) - assert g.raw_per_photon == pytest.approx(110.0, rel=0.05) - assert g.mean_pulse == pytest.approx(110.0, rel=0.01) - assert g.cycles == (0, 400) and g.n_slots > 0 - - -@pytest.fixture(scope="module") -def online(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: - """Synthetic recording with known motion and online offsets.""" - path = tmp_path_factory.mktemp("rec") / "inj_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=N_CYCLES, seed=5) - offs = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=offs) - path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) - return layout, offs, truth - - -def truth_geometry( - layout: RasterLayout, offs: Offsets, truth: np.ndarray, lines: tuple[int, int] -) -> inj.TrialGeometry: - """Geometry in the scene frame. - - The sample of DMD (r, c) on line l shows the scene at - (r + y_dmd - m_r, c + x - m_c). - """ - x, _, y_dmd = offs - ln = np.arange(lines[0], lines[1] + 1) - shift = np.stack([y_dmd[ln - 1] - truth[ln - 1, 0], x[ln - 1] - truth[ln - 1, 1]], 1) - return inj.TrialGeometry(lines[0], shift.astype(np.float64), True) - - -def test_sample_model_follows_the_tissue(online: OnlineRecording) -> None: - """Expected counts follow the tissue, for every chunk of cycles. - - They are photon_scale x footprint at the sample's tissue position x the - trace at its line. - """ - layout, offs, truth = online - lines = (8, layout.total_lines - 3) - geo = truth_geometry(layout, offs, truth, lines) - pos = np.array([[17.3, 22.0], [12.0, 30.6]]) - fps = [inj.GaussianFootprint(1.33), inj.GaussianFootprint(2.0)] - n_l = lines[1] - lines[0] + 1 - rng = np.random.default_rng(0) - traces = rng.random((2, n_l)) - model = inj.SampleModel(layout, geo, pos, fps, traces, 25.0) - cycles = np.arange(0, 30) - got = model.expected(cycles) - pix = layout.slot_pixel[model.slots] - 1 - r0, c0 = pix // layout.n_cols, pix % layout.n_cols - ln = cycles[:, None] * layout.lines_per_cycle + layout.slot_line[model.slots] - inside = (ln >= lines[0]) & (ln <= lines[1]) - li = np.clip(ln - lines[0], 0, n_l - 1) - want = np.zeros(got.shape) - for j in range(2): - f = fps[j]( - r0 + geo.shift[li, 0] - pos[j, 0], - c0 + geo.shift[li, 1] - pos[j, 1], - ) - want += 25.0 * f * traces[j, li] - want[~inside] = 0 - np.testing.assert_allclose(got, want, rtol=1e-12, atol=1e-12) - # every slot whose footprint value can be non-zero is reachable - every = np.arange(layout.slot_line.size) - allpix = layout.slot_pixel[every] - 1 - near = np.zeros(every.size, bool) - for j in range(2): - for s in geo.shift[:: layout.lines_per_cycle]: - d = np.hypot( - allpix // layout.n_cols + s[0] - pos[j, 0], - allpix % layout.n_cols + s[1] - pos[j, 1], - ) - near |= d <= fps[j].radius - assert np.all(np.isin(every[near], model.slots)) - - -def registered_table( - layout: RasterLayout, tmp_path: Path, compensate: bool, trials: Sequence[tuple[int, int]] -) -> Path: - """Register line ranges of a recording through a trial table.""" - dat = Path(layout.files[0]) - n = len(trials) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name] * n], dtype=object), - "epoch": np.ones((1, n)), - "true_trial_ix": np.arange(1.0, n + 1)[None, :], - "slap2_info": { - "first_line": np.array([[float(a) for a, _ in trials]]), - "last_line": np.array([[float(b) for _, b in trials]]), - }, - }, - ) - register_multiroi( - table, - {"maxshift": 6, "compensate_online": compensate}, - execution={"device": "cpu", "max_workers": 1}, - ) - return table - - -@pytest.fixture(scope="module") -def registered( - online: OnlineRecording, tmp_path_factory: pytest.TempPathFactory -) -> dict[bool, Path]: - """Register the online recording as two trials, both ways.""" - layout, _, _ = online - out = {} - with pytest.MonkeyPatch.context() as mp: - mp.setattr(multiroi, "raster_layout", lambda path: layout) - for comp in (True, False): - d = tmp_path_factory.mktemp(f"reg{int(comp)}") - out[comp] = registered_table(layout, d, comp, [(1, 4800), (4801, 9700)]) - return out - - -@pytest.mark.parametrize("compensate", [True, False]) -def test_geometry_from_registration_tracks_true_motion( - online: OnlineRecording, registered: dict[bool, Path], compensate: bool -) -> None: - """The registered position of each line's samples follows the tissue. - - shift(l) equals the true scene shift up to a constant. - """ - layout, offs, truth = online - table = Path(registered[compensate]) - al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - assert (al.compensation is not None) == compensate - lines = (1, 4800) - geo = inj.trial_geometry(layout, al, lines) - want = truth_geometry(layout, offs, truth, lines).shift - if not compensate: - # uncompensated frames blur the offsets' steps (every 23-50 ms - # here) over their kernel: the motion can only follow that blur - k = np.exp(-np.abs(np.arange(-60, 61)) / 20.0) - want = np.stack( - [np.convolve(np.pad(w, 60, "edge"), k / k.sum(), "valid") for w in want.T], - 1, - ) - err = geo.shift - want - err -= np.median(err, axis=0) - # within the registration's own error (as its tests require) - assert np.sqrt(np.mean(err**2)) < 0.12 - - -def run_injection( - online: OnlineRecording, - table: Path, - out: Path, - monkeypatch: pytest.MonkeyPatch, - **kw: Any, # noqa: ANN401 (forwarded to inject_session's keyword-only arguments) -) -> dict: - """inject_session on the synthetic recording.""" - layout, _, _ = online - monkeypatch.setattr(inj, "raster_layout", lambda path: layout) - return inj.inject_session(table, out, paths=(1,), **kw) - - -def test_no_events_leave_the_copy_identical( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Without events the copy equals the original byte for byte. - - The .meta file is copied. - """ - layout, _, _ = online - s = inj.InjectionSettings(rate_hz=0.0, raw_per_photon=1.0) - summary = run_injection(online, registered[True], tmp_path / "out", monkeypatch, settings=s) - src = Path(layout.files[0]) - dst = tmp_path / "out" / "raw" / src.name - assert sha(dst) == sha(src) - meta = src.with_name("inj_DMD1.meta") - assert sha(dst.with_name(meta.name)) == sha(meta) - assert summary["paths"][1]["n_events"] == 0 - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) - assert truth["paths"][1]["events"]["source"].size == 0 - - -BRIGHT = inj.InjectionSettings( - size_classes=(4.0, 8.0), - rate_hz=3.0, - min_interval_s=0.06, - edge_s=0.1, - tau_s=0.012, - raw_per_photon=2.0, - seed=11, - device="cpu", -) -BRIGHT_AT = {1: np.array([[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]])} - - -@pytest.fixture(scope="module") -def injected( - online: OnlineRecording, registered: dict[bool, Path], tmp_path_factory: pytest.TempPathFactory -) -> Injected: - """Bright events injected into both trials (compensated registration).""" - out = tmp_path_factory.mktemp("inj") - with pytest.MonkeyPatch.context() as mp: - summary = run_injection( - online, - registered[True], - out, - mp, - settings=BRIGHT, - positions=BRIGHT_AT, - ) - return out, summary, BRIGHT - - -def test_placed_sources_without_data_are_moved( - online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path -) -> None: - """A source the tool put on a pixel without data where its peaks are calibrated is moved. - - A source that the tool itself puts on a pixel without data in the - stretch its frame peaks are calibrated on is placed anew: at the - minimum distance from the sources that stay and from every place tried - before; the others stay. A position that was given is not moved (an - error, as before), and so is a move with no place left. - """ - first = np.array([[16.0, 20.0], [16.0, 200.0], [12.0, 27.0]]) - asked = [] - # the free candidates of the move, in the order they are drawn: the - # first is 4 px from a source that stays, the second is the place that - # had no data, the third is free - pools = [np.array([[16.0, 24.0], [16.0, 200.0], [18.0, 30.0]])] - - def place( - mean_im: np.ndarray, - n: int, - rng: np.random.Generator, - settings: inj.PlacementSettings | None = None, - valid: np.ndarray | None = None, - exclude_rc: np.ndarray | None = None, - keep_apart_rc: np.ndarray | None = None, - ) -> tuple[np.ndarray, int]: - """Stand-in for place_sources. - - A first placement with a source where no data is, then the - candidates of a move. - """ - asked.append((n, exclude_rc, keep_apart_rc)) - if len(asked) == 1: # the path's placement: one where no data is - return first.copy(), 3 - # a move: the candidates on offer, less those within 6 px of the - # places to keep apart from (place_sources' rule, tested above) - pool = pools[min(len(asked) - 2, len(pools) - 1)] - far = [np.hypot(*(keep_apart_rc - q).T).min() >= 6 for q in pool] - return pool[np.array(far, dtype=bool)][:n], 1 - - out = tmp_path / "moved" - with pytest.MonkeyPatch.context() as mp: - mp.setattr(inj, "place_sources", place) - run_injection(online, registered[True], out, mp, settings=BRIGHT, n_sources=3) - # one move of one source; no external sources to keep away from; apart - # from the sources that stay and from the place that had no data - assert len(asked) == 2 and asked[1][0] == 1 and asked[1][1] is None - assert {tuple(q) for q in asked[1][2]} == {tuple(q) for q in first} - p = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(p["positions_rc"], [[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]]) - assert np.all(p["frame_peak"] > 0) and p["frame_peak"].size == 3 - assert set(p["events"]["source"]) == {0, 1, 2} - # the sources that stayed are calibrated as if the third had been - # where it ended up from the start - with pytest.MonkeyPatch.context() as mp: - run_injection( - online, - registered[True], - tmp_path / "given", - mp, - settings=BRIGHT, - positions={1: np.array(p["positions_rc"])}, - ) - given = inj.read_truth(tmp_path / "given" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_allclose(given["frame_peak"][[0, 2]], p["frame_peak"][[0, 2]], rtol=0.05) - # a position that was given and has no data is an error - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match=r"sources \[1\] have no data"), - ): - run_injection( - online, - registered[True], - tmp_path / "fixed", - mp, - settings=BRIGHT, - positions={1: np.array([[16.0, 20.0], [16.0, 200.0]])}, - ) - # no place left for the move: the only candidates are too near a - # source that stays, or the place that was tried - asked.clear() - pools[:] = [np.array([[16.0, 24.0], [16.0, 200.0], [13.0, 31.0]])] - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match="only 0 free places"), - ): - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "full", - mp, - settings=BRIGHT, - n_sources=3, - ) - # a place tried in an earlier round is not taken again: the first move - # lands without data, and the second is offered the path's first place - # (no longer any source's) before a free one - asked.clear() - pools[:] = [ - np.array([[16.0, 210.0]]), - np.array([[16.0, 200.0], [18.0, 30.0]]), - ] - with pytest.MonkeyPatch.context() as mp: - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "twice", - mp, - settings=BRIGHT, - n_sources=3, - ) - twice = inj.read_truth(tmp_path / "twice" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(twice["positions_rc"][1], [18.0, 30.0]) - assert len(asked) == 3 - # the second move keeps apart from the first place too, though no - # source is there any more - assert (16.0, 200.0) in {tuple(q) for q in asked[2][2]} - assert (16.0, 210.0) in {tuple(q) for q in asked[2][2]} - # moves that land without data every time: after REPLACE_ROUNDS the - # injection gives up - asked.clear() - pools[:] = [ - np.array([[16.0, 210.0 + 10 * k], [16.0, 200.0 + 10 * k]]) - for k in range(inj.REPLACE_ROUNDS) - ] - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match="after 5 placements"), - ): - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "again", - mp, - settings=BRIGHT, - n_sources=3, - ) - assert len(asked) == 1 + inj.REPLACE_ROUNDS - - -def test_injection_changes_only_injected_samples( - online: OnlineRecording, injected: Injected -) -> None: - """Only channel-0 raster samples change, never invalid ones. - - The added counts are the recorded ones. - """ - layout, _, _ = online - out, summary, s = injected - src = Path(layout.files[0]) - a = np.fromfile(src, np.int16) - b = np.fromfile(out / "raw" / src.name, np.int16) - changed = np.flatnonzero(a != b) - assert changed.size > 0 - words = changed - HEADER_WORDS - w = words % layout.words_per_cycle - li = layout.slot_line - 1 - ch0 = layout.row_base[li] + layout.slot_pos - assert np.all(np.isin(w, ch0)) - assert np.all(b[changed] > a[changed]) - total = sum(t["added_raw"] for t in summary["paths"][1]["trials"]) - assert int((b.astype(np.int64) - a).sum()) == total - stats = summary["paths"][1]["trials"] - drawn = sum(t["drawn_photons"] for t in stats) - lam = sum(t["expected_photons"] for t in stats) - assert abs(drawn - lam) < 5 * np.sqrt(lam) - assert total == pytest.approx(drawn * s.raw_per_photon, rel=1e-3) - - -def test_truth_file_describes_the_injection(online: OnlineRecording, injected: Injected) -> None: - """The truth has positions per trial, events and traces at frame lines.""" - layout, _, _ = online - out, summary, s = injected - truth = inj.read_truth(out / inj.TRUTH_NAME) - assert truth["seed"] == 11 - assert truth["settings"]["size_classes"] == [4.0, 8.0] - p = truth["paths"][1] - assert p["raw_per_photon"] == 2.0 - np.testing.assert_array_equal(p["trials"], [1, 2]) - np.testing.assert_allclose(p["trial_shift_rc"][0], 0.0) - ev = p["events"] - assert ev["source"].size == summary["paths"][1]["n_events"] > 0 - for t, (lo, hi) in ((1, (1, 4800)), (2, (4801, 9700))): - on = ev["onset_line"][ev["trial"] == t] - assert on.min() >= lo + 0.1 * 1600 and on.max() <= hi - 0.1 * 1600 - d = p["trials_detail"][t] - np.testing.assert_allclose( - d["positions_rc"], p["positions_rc"] + p["trial_shift_rc"][t - 1] - ) - fl = d["frame_lines"] - assert fl[0] == lo and np.all(np.diff(fl) == 8) - # the trace peaks at each event's size within one frame of onset - k = np.searchsorted(fl, on[0]) - j = ev["source"][ev["trial"] == t][0] - size = ev["size"][ev["trial"] == t][0] - assert d["trace"][j, k] <= size * 1.0001 + d["trace"][j].max() - assert d["trace"].shape == (3, fl.size) - assert p["footprint"]["patch"].shape[0] == 3 - with h5py.File(out / "trial_table.h5") as f: - assert "motion_correction" not in f - tt = inj.load_struct_h5(out / "trial_table.h5") - assert Path(tt["datadr"]) == out / "raw" - assert np.asarray(tt["slap2_info"]["last_line"]).ravel().tolist() == [ - 4800.0, - 9700.0, - ] - - -def test_injected_signal_is_still_and_as_expected( - online: OnlineRecording, registered: dict[bool, Path], injected: Injected -) -> None: - """In frames registered with the original's motion, the copy matches the expected counts. - - In registered frames made with the original's motion, the copy minus the - original matches the expected counts within Poisson noise, and a static - source's centroid stays put (drift < 0.1 px) across the online offsets' - switches. - """ - layout, _, _ = online - out, _, s = injected - table = Path(registered[True]) - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - orig = read_raster_samples(layout, (0, layout.num_cycles))[0] - new = read_raster_samples(copy, (0, layout.num_cycles))[0] - diff = np.where(orig == INVALID_SAMPLE, INVALID_SAMPLE, new - orig) - lines = (1, 4800) - geo = inj.trial_geometry(layout, al, lines) - pos = truth["trials_detail"][1]["positions_rc"] - fp = [inj.GaussianFootprint(1.33)] * 3 - ev = truth["events"] - sel = ev["trial"] == 1 - events = inj.Events( - ev["source"][sel], - ev["trial"][sel], - ev["onset_line"][sel], - ev["size_class"][sel], - ev["size"][sel] / truth["frame_peak"][ev["source"][sel]], - ) - tr = inj.event_traces(events, 3, lines, layout.line_period_s, s) - expect = inj.SampleModel(layout, geo, pos, fp, tr, 25.0) - static = inj.SampleModel(layout, geo, pos, fp, np.ones_like(tr), 25.0) - n_c = layout.num_cycles # the frame kernels reach past the trial - samples = np.zeros((3, layout.slot_line.size, n_c), np.float32) - samples[0] = diff[:, :n_c] - samples[1][expect.slots] = expect.expected(np.arange(n_c)).T - samples[2][static.slots] = static.expected(np.arange(n_c)).T - samples[:, orig[:, :n_c] == INVALID_SAMPLE] = INVALID_SAMPLE - times = al.ds_frames.astype(np.int64) - # frames whose kernel (60 lines) stays inside the trial - times = times[(times > lines[0] + 60) & (times < lines[1] - 60)] - acc_d = acc_e = 0.0 - drift = {j: [] for j in range(3)} - for idx, frames, _ in iter_registered_frames(layout, samples, 0, al, times, 20, chunk=50): - f = frames.numpy() - for j, (r, c) in enumerate(pos): - ri, ci = int(round(r)), int(round(c)) - win = f[:, :, ri - 3 : ri + 4, ci - 3 : ci + 4] - acc_d = acc_d + np.nansum(win[0]) - acc_e = acc_e + np.nansum(win[1]) - whole = ~np.isnan(win[2]).any((1, 2)) # not cut by an edge - st = win[2][whole] - rr, cc = np.mgrid[-3:4, -3:4] - m = st.sum((1, 2)) - cr = (st * rr).sum((1, 2)) / m + ri - r - cc_ = (st * cc).sum((1, 2)) / m + ci - c - drift[j].append(np.stack([cr, cc_], 1)) - for j in range(3): - d = np.concatenate(drift[j]) - assert d.shape[0] > 0.9 * times.size - assert np.abs(d - np.median(d, axis=0)).max() < 0.1 - assert np.abs(np.median(d, axis=0)).max() < 0.1 - # the summed signal at the sources: Poisson error of photons x g - se = np.sqrt(acc_e * s.raw_per_photon) * 3 - assert abs(acc_d - acc_e) < 5 * se - - -def test_registered_copy_keeps_the_motion( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Registering the injected copy gives the original's motion up to the grid's anchoring. - - The truth then records both. - """ - layout, _, _ = online - out = tmp_path / "inj" - run_injection( - online, - registered[True], - out, - monkeypatch, - settings=replace(BRIGHT, size_classes=(1.0, 2.0)), - positions=BRIGHT_AT, - ) - copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: copy) - register_multiroi( - out / "trial_table.h5", - {"maxshift": 6, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert inj.main(["compare", str(out)]) == 0 - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - for t in (1, 2): - d = truth["trials_detail"][t] - assert d["copy_motion_rms_px"] < 0.05 - np.testing.assert_allclose(d["positions_copy_rc"], d["positions_rc"] + d["copy_shift_rc"]) - a = inj.read_alignment(d["alignment"]) - b = inj.read_alignment(d["copy_alignment"]) - off = inj.registration_offset(a, b) - np.testing.assert_allclose(off["shift_rc"], d["copy_shift_rc"]) - - -def test_saturation_invalid_samples_and_chunking(online: OnlineRecording, tmp_path: Path) -> None: - """Huge events saturate at 32767; invalid samples stay. - - Results do not depend on the chunk size. - """ - layout, offs, truth = online - src = Path(layout.files[0]) - data = np.fromfile(src, np.int16) - rng = np.random.default_rng(2) - li = layout.slot_line - 1 - ch0 = layout.row_base[li] + layout.slot_pos - rows = HEADER_WORDS + np.arange(N_CYCLES)[:, None] * layout.words_per_cycle - w = (rows + ch0[None, :]).ravel() - bad = w[rng.random(w.size) < 0.05] - data[bad] = INVALID_SAMPLE - outs = [] - lines = (1, layout.total_lines) - geo = truth_geometry(layout, offs, truth, lines) - tr = np.full((1, lines[1]), 2000.0) - for chunk in (7, 64): - dst = tmp_path / f"c{chunk}.dat" - data.tofile(dst) - lay = replace(layout, files=(str(dst),)) - model = inj.SampleModel(lay, geo, np.array([[18.0, 25.0]]), [inj.GaussianFootprint()], tr) - st = inj.inject_samples(lay, model, 3.0, 0, (5, 1, 1), chunk) - outs.append(np.fromfile(dst, np.int16)) - assert st.saturated > 0 and st.lost_raw > 0 - assert st.expected_photons_invalid > 0 - np.testing.assert_array_equal(outs[0], outs[1]) - assert np.all(outs[0][bad] == INVALID_SAMPLE) - assert outs[0].max() == inj.SAMPLE_MAX - - -def test_command_line( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """``python -m giant_python.simulation.injection`` runs a session.""" - layout, _, _ = online - monkeypatch.setattr(inj, "raster_layout", lambda path: layout) - pos = tmp_path / "pos.h5" - with h5py.File(pos, "w") as f: - f["path1"] = np.array([[16.0, 20.0]]) - code = inj.main([ - "inject", - str(registered[False]), - str(tmp_path / "cli"), - "--paths", - "1", - "--trials", - "2", - "--positions", - str(pos), - "--raw-per-photon", - "4", - "--sizes", - "8", - "--seed", - "3", - "--size-reference", - "tissue", - "--no-frame-traces", - ]) - assert code == 0 - summary = json.loads(capsys.readouterr().out) - assert summary["paths"]["1"]["n_sources"] == 1 - truth = inj.read_truth(tmp_path / "cli" / inj.TRUTH_NAME) - np.testing.assert_array_equal(truth["paths"][1]["trials"], [2]) - p = truth["paths"][1] - assert not p["trials_detail"][2]["compensated"] - np.testing.assert_array_equal(p["frame_peak"], [1.0]) - assert "trace_frames" not in p["trials_detail"][2] - - -def test_cuda_render_matches_cpu(online: OnlineRecording, registered: dict[bool, Path]) -> None: - """Rendering on CUDA equals the CPU.""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - layout, _, _ = online - table = Path(registered[True]) - al = inj.read_alignment(table.parent / "motion_correction" / "E1T2DMD1_ALIGNMENTDATA.h5") - s = read_raster_samples(layout, (0, layout.num_cycles))[:1] - times = al.ds_frames[:40].astype(np.int64) - cpu = next(iter_registered_frames(layout, s, 0, al, times, 20))[1] - gpu = next(iter_registered_frames(layout, s, 0, al, times, 20, "cuda"))[1] - np.testing.assert_allclose(gpu.cpu().numpy(), cpu.numpy(), rtol=1e-5, atol=1e-4, equal_nan=True) - - -def test_ragged_table_keeps_copy_columns( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A trial without a recording is skipped. - - The others keep their column of the copy's trial table. - """ - from giant_python.io.hdf5 import load_struct_h5 - - table = load_struct_h5(registered[False]) - table["filename"] = np.array([["", table["filename"][0, 1]]], object) - ragged = tmp_path / "trial_table.h5" - save_struct_h5(ragged, table) - s = inj.InjectionSettings(raw_per_photon=4.0, seed=1) - run_injection( - online, - ragged, - tmp_path / "out", - monkeypatch, - settings=s, - positions={1: np.array([[16.0, 20.0]])}, - moco_dir=Path(registered[False]).parent / "motion_correction", - ) - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME)["paths"][1] - assert list(truth["trials_detail"]) == [2] - assert truth["trials_detail"][2]["copy_trial"] == 2 - np.testing.assert_array_equal(np.unique(truth["events"]["trial"]), [2]) - - -def test_sizes_are_peaks_in_frames(online: OnlineRecording, injected: Injected) -> None: - """With sizes in frame units, an isolated event's noiseless peak is its size. - - The peak is taken in the 200 Hz frames at its source's peak pixel, and - equals the size on average. - """ - out, _, s = injected - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - fp = truth["frame_peak"] - assert np.all((fp > 0.2) & (fp < 1.0)) - ev = truth["events"] - reach = 24 # max(3 * 8, P) lines at 1600 Hz and 200 Hz frames - tail = 6 * s.tau_s * 1600 - ratios = [] - for t in (1, 2): - d = truth["trials_detail"][t] - fl, tf = d["frame_lines"], d["trace_frames"] - assert tf.shape == d["trace"].shape - # the ideal trace is sampled at frame lines: within a frame of each - # largest peak (overlapping events may add up) - top = np.array([ - ev["size"][(ev["trial"] == t) & (ev["source"] == j)].max() for j in range(3) - ]) - assert np.all(d["trace"].max(1) >= top * np.exp(-0.005 / s.tau_s)) - for j in range(3): - on = ev["onset_line"][(ev["trial"] == t) & (ev["source"] == j)] - size = ev["size"][(ev["trial"] == t) & (ev["source"] == j)] - for k, (t0, a) in enumerate(zip(on, size)): - alone = (k == 0 or t0 - on[k - 1] > 2 * tail) and ( - k == on.size - 1 or on[k + 1] - t0 > tail + reach - ) - sel = (fl >= t0 - reach) & (fl <= t0 + tail) - if alone and sel.any(): - ratios.append(np.nanmax(tf[j, sel]) / a) - assert len(ratios) > 20 - assert np.mean(ratios) == pytest.approx(1.0, abs=0.06) - - -def test_refuses_to_write_into_the_original( - online: OnlineRecording, registered: dict[bool, Path], monkeypatch: pytest.MonkeyPatch -) -> None: - """The copy's folder cannot be the original's data folder.""" - layout, _, _ = online - src = Path(layout.files[0]) - out = src.parent.parent / "same" - with pytest.raises(ValueError, match="original's data folder"): - run_injection( - online, - registered[True], - out, - monkeypatch, - data_dir=out / "raw", - ) - - -def test_registration_offset_includes_the_grid(registered: dict[bool, Path]) -> None: - """Different padding, window and reference offset move the copy's positions. - - Mixed compensation is refused. - """ - from dataclasses import replace as dc_replace - - moco = Path(registered[True]).parent / "motion_correction" - a = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - comp = dict(a.compensation, refOffset=a.compensation["refOffset"] + 1) - b = dc_replace( - a, - margin=a.margin + 3, - trim_r0=a.trim_r0 + 1, - motion_r=a.motion_r + 0.25, - compensation=comp, - ) - off = inj.registration_offset(a, b) - # continuous motion unchanged in columns; rows: +0.25 recorded, -1 from - # the reference (mapping swaps x and y) - np.testing.assert_allclose(off["motion_offset_rc"], [0.25 - 1, -1.0]) - np.testing.assert_allclose(off["shift_rc"], [3 - 1 - 1 - (0.25 - 1), 3 - 1 + 1]) - assert off["rms_px"] < 1e-9 - plain = inj.read_alignment( - Path(registered[False]).parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5" - ) - with pytest.raises(ValueError, match="online motion correction"): - inj.registration_offset(a, plain) - - -def test_frame_motion_uses_each_frames_own_reference(registered: dict[bool, Path]) -> None: - """A frame with another reference offset is moved by its own reference. - - The frame is at a registered frame's time but with another reference - offset, and is moved by its own reference, not the recorded motion. - """ - from giant_python.simulation.render import frame_motion - - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - t = al.ds_frames.astype(np.int64) - c = al.compensation - refs = np.stack([c["frameRefX"], c["frameRefY"]], 1) - ok = np.isfinite(al.motion_r) - same = frame_motion(al, t, refs) - np.testing.assert_allclose(same[ok, 0], al.motion_r[ok], atol=1e-9) - np.testing.assert_allclose(same[ok, 1], al.motion_c[ok], atol=1e-9) - other = frame_motion(al, t, refs + np.array([1, 0])) # x one more - np.testing.assert_allclose(other[ok, 1], al.motion_c[ok] - 1, atol=1e-9) - np.testing.assert_allclose(other[ok, 0], al.motion_r[ok], atol=1e-9) - - -def test_calibration_keeps_overlapping_sources_apart( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """Overlapping sources are calibrated in turns. - - A close neighbour does not change a source's frame peak. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = inj.GaussianFootprint(1.33) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.5) - pair = np.array([[16.0, 20.0], [16.0, 22.0], [10.0, 33.0]]) - np.testing.assert_array_equal(inj.overlap_classes(pair, [fp] * 3), [0, 1, 0]) - both = inj.calibrate_frame_peaks( - layout, - al, - geo, - pair, - (0.0, 0.0), - [fp] * 3, - s, - np.random.default_rng(0), - ) - alone = inj.calibrate_frame_peaks( - layout, - al, - geo, - pair[:1], - (0.0, 0.0), - [fp], - s, - np.random.default_rng(0), - ) - assert both[0] == pytest.approx(alone[0], rel=0.05) - - -def test_inputs_that_would_corrupt_a_dataset_are_refused( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Repeated trials or paths and an existing dataset are refused before writing. - - Repeated trials or paths, and an output folder that already holds a - dataset, are refused before anything is written. - """ - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - pos = {1: np.array([[16.0, 20.0]])} - with pytest.raises(ValueError, match="must not repeat"): - run_injection( - online, - registered[False], - tmp_path / "a", - monkeypatch, - settings=s, - positions=pos, - trials=[1, 1], - ) - with pytest.raises(ValueError, match="must not repeat"): - inj.inject_session( - registered[False], - tmp_path / "b", - paths=(1, 1), - settings=s, - positions=pos, - ) - assert not (tmp_path / "a").exists() and not (tmp_path / "b").exists() - out = tmp_path / "c" - (out / "motion_correction").mkdir(parents=True) - with pytest.raises(ValueError, match="already holds motion_correction"): - run_injection( - online, - registered[False], - out, - monkeypatch, - settings=s, - positions=pos, - ) - - -def test_copy_table_paths_and_absolute_folders( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The copy's table has absolute folders and no files for paths not copied.""" - from giant_python.io.hdf5 import load_struct_h5 - - table = { - "datadr": "x", - "savedr": "y", - "filename": np.array([["a1", "b1"], ["a2", "b2"]], dtype=object), - "epoch": np.ones((2, 2)), - "slap2_info": {"first_line": np.ones((2, 2))}, - "motion_correction": {"fn_adata": "z"}, - } - monkeypatch.chdir(tmp_path) - Path("rel").mkdir() - p = inj.write_copy_table(table, np.array([1]), Path("rel/raw"), Path("rel"), paths=[1]) - t = load_struct_h5(p) - assert Path(t["datadr"]).is_absolute() and Path(t["savedr"]).is_absolute() - assert Path(t["savedr"]) == tmp_path / "rel" - np.testing.assert_array_equal(np.asarray(t["filename"], dtype=object).ravel(), ["b1", ""]) - assert "motion_correction" not in t - - -def test_image_footprint_peak_and_calibration( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """An off-centre image footprint is calibrated at its maximum.""" - layout, _, _ = online - img = np.zeros((5, 5)) - img[2, 4] = 1.0 - fp = inj.ImageFootprint(img) - assert fp.peak_offset == (0.0, 2.0) - pos = np.array([[16.0, 20.0]]) - np.testing.assert_array_equal(inj.peak_pixels(pos, [fp]), [[16, 22]]) - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) - peak = inj.calibrate_frame_peaks( - layout, al, geo, pos, (0.0, 0.0), [fp], s, np.random.default_rng(0) - ) - assert 0.05 < peak[0] < 1.0 - - -def test_expected_frames_follow_the_trial_grid( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """A path-frame pixel outside the trial grid's size is still rendered. - - It is rendered where its trial position has data; channel 1 renders - with channel 0's freshness. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = [inj.GaussianFootprint(1.33)] - model = inj.SampleModel(layout, geo, np.array([[16.3, 20.4]]), fp, np.ones((1, 4800))) - fl = np.arange(200, 1200, 8) - here = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0) - far = inj.expected_frames(layout, al, model, fl, [[16 - 40, 20 + 60]], (40.3, -59.6), 200.0) - assert al.shape[1] < 80 and np.isfinite(far).all() - np.testing.assert_allclose(far, here, rtol=1e-6) - ch1 = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0, channel=1) - np.testing.assert_allclose(ch1, here, rtol=1e-6) # no invalid samples - - -def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected: Injected) -> None: - """Two trials of one file: frames reading the other trial's injections are NaN. - - Frames whose kernel reads the other trial's injected samples are NaN in - the truth's frame traces. - """ - out, _, _ = injected - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - reach = 24 - t1, t2 = truth["trials_detail"][1], truth["trials_detail"][2] - near1 = t1["frame_lines"] + reach >= 4801 - near2 = t2["frame_lines"] - reach <= 4800 - assert near1.any() and near2.any() - assert np.isnan(t1["trace_frames"][:, near1]).all() - assert np.isnan(t2["trace_frames"][:, near2]).all() - assert np.isfinite(t1["trace_frames"][:, ~near1]).mean() > 0.9 - - -def test_relative_registration_folder_is_stored_absolute( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A relative registration folder is recorded as an absolute path.""" - import os - - reg = Path(registered[False]).parent - monkeypatch.chdir(reg) - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - run_injection( - online, - registered[False], - tmp_path / "out", - monkeypatch, - settings=s, - positions={1: np.array([[16.0, 20.0]])}, - trials=[1], - moco_dir="motion_correction", - ) - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) - al = Path(str(truth["paths"][1]["trials_detail"][1]["alignment"])) - assert al.is_absolute() and al.exists() - assert os.path.isabs(truth["origin"]["moco_dir"]) - - -def test_more_inputs_are_checked( - online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path -) -> None: - """Non-finite gains are refused; sources without data cannot be calibrated. - - Copies' filenames are their basenames; larger trial grids keep their - data when shifted into the path frame. - """ - from giant_python.io.hdf5 import load_struct_h5 - - for bad in (float("inf"), float("nan")): - with pytest.raises(ValueError, match="finite"): - inj.InjectionSettings(raw_per_photon=bad) - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = inj.GaussianFootprint(1.33) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) - with pytest.raises(ValueError, match=r"sources \[1\] have no data"): - inj.calibrate_frame_peaks( - layout, - al, - geo, - np.array([[16.0, 20.0], [16.0, 200.0]]), - (0.0, 0.0), - [fp, fp], - s, - np.random.default_rng(0), - ) - table = { - "filename": np.array([["sub/a_DMD1.dat"], [""]], dtype=object), - "slap2_info": {"first_line": np.ones((2, 1))}, - } - p = inj.write_copy_table(table, np.array([0]), tmp_path, tmp_path) - names = np.asarray(load_struct_h5(p)["filename"], dtype=object).ravel() - np.testing.assert_array_equal(names, ["a_DMD1.dat", ""]) - big = np.arange(10 * 112, dtype=float).reshape(10, 112) - out = inj.shift_image(big, (0.0, 8.0), (10, 100)) - np.testing.assert_allclose(out, big[:, 8:108]) - - -def test_bad_chunks_and_name_collisions_are_refused( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A nonpositive chunk size and copies sharing a name are refused before writing. - - A nonpositive chunk size, and two recordings that would be copied under - one name, are refused before anything is written. - """ - import shutil - - from giant_python.io.hdf5 import load_struct_h5 - - layout, _, _ = online - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - with pytest.raises(ValueError, match="chunk_cycles"): - run_injection( - online, - registered[False], - tmp_path / "c", - monkeypatch, - settings=s, - chunk_cycles=0, - ) - assert not (tmp_path / "c").exists() - data = tmp_path / "data" - src = Path(layout.files[0]) - for sub in ("a", "b"): - (data / sub).mkdir(parents=True) - shutil.copyfile(src, data / sub / src.name) - table = load_struct_h5(registered[False]) - table["filename"] = np.array([[f"a/{src.name}", f"b/{src.name}"]], dtype=object) - twins = tmp_path / "twins.h5" - save_struct_h5(twins, table) - monkeypatch.setattr(inj, "raster_layout", lambda path: replace(layout, files=(str(path),))) - with pytest.raises(ValueError, match="would both be copied"): - inj.inject_session(twins, tmp_path / "t", paths=(1,), settings=s, data_dir=data) - assert not (tmp_path / "t").exists() - - -def test_neighbours_share_recording_files() -> None: - """Trials are neighbours when their recordings share a file. - - This holds whatever file each trial names. - """ - ctx = { - "names": ["c0.dat", "c1.dat", "other.dat"], - "files": { - 0: ("c0.dat", "c1.dat"), - 1: ("c0.dat", "c1.dat"), - 2: ("other.dat",), - }, - "first": [1.0, 101.0, 1.0], - "last": [100.0, 200.0, 50.0], - } - near = inj._neighbours(ctx, [0, 1, 2]) - assert near(0) == [(101.0, 200.0)] - assert near(1) == [(1.0, 100.0)] - assert near(2) == [] - - -def test_no_events_need_no_calibration( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Without events nothing is calibrated, and the copy stays identical. - - This holds even in a trial too short to calibrate. - """ - layout, _, _ = online - s = inj.InjectionSettings(rate_hz=0.0, edge_s=1.6, raw_per_photon=1.0) - run_injection(online, registered[True], tmp_path / "o", monkeypatch, settings=s) - src = Path(layout.files[0]) - assert sha(tmp_path / "o" / "raw" / src.name) == sha(src) - truth = inj.read_truth(tmp_path / "o" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(truth["frame_peak"], 1.0) - - -def test_silo_frames_leave_out_the_kernels_edge( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """Frame traces and calibration use SILo's extraction frames. - - These leave out the samples exactly at the kernel's reach. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - model = inj.SampleModel( - layout, - geo, - np.array([[16.0, 20.0]]), - [inj.GaussianFootprint()], - np.ones((1, 4800)), - ) - fl = np.arange(300, 900, 8) - got = inj.expected_frames(layout, al, model, fl, [[16, 21]], (0, 0), 200) - n_c = layout.num_cycles - smp = np.zeros((1, layout.slot_line.size, n_c), np.float32) - smp[0][model.slots] = model.expected(np.arange(n_c)).T - want = {} - for exclusive in (True, False): - out = [] - for _, f, _ in iter_registered_frames( - layout, smp, 0, al, fl, 8, chunk=200, exclusive=exclusive - ): - out.append(f[0][:, 16, 21].numpy()) - want[exclusive] = np.concatenate(out) - np.testing.assert_allclose(got[0], want[True], rtol=1e-6) - assert np.max(np.abs(want[True] - want[False])) > 1e-6 +"""Event injection into raw SLAP2 samples, on small synthetic recordings.""" + +import hashlib +import json +from collections.abc import Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples +from giant_python.pipeline.register import register_multiroi +from giant_python.registration import multiroi +from giant_python.simulation import injection as inj +from giant_python.simulation.render import iter_registered_frames + +from ..registration.synthetic import ( + HEADER_WORDS, + make_layout, + online_offsets, + write_recording, +) + +N_CYCLES = 1400 + +# online offsets (x, y_header, y_dmd) per line, as online_offsets returns them +Offsets = tuple[np.ndarray, np.ndarray, np.ndarray] +# the layout, its online offsets and the true motion of the synthetic recording +OnlineRecording = tuple[RasterLayout, Offsets, np.ndarray] +# the injected copy's folder, its summary and the settings it was made with +Injected = tuple[Path, dict, inj.InjectionSettings] + + +def sha(path: str | Path) -> str: + """SHA-256 of a file. + + Returns + ------- + str + The hexadecimal SHA-256 digest of the file's bytes. + """ + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +# --------------------------------------------------------- pure functions + + +def test_time_course_peaks_at_one() -> None: + """Instant rise: exp decay from 1; short rise: peak 1 at its delay.""" + t = np.array([-0.01, 0.0, 0.024, 0.048]) + np.testing.assert_allclose(inj.time_course(t, 0.024), [0, 1, np.exp(-1), np.exp(-2)]) + tp = inj.peak_delay_s(0.024, 0.003) + assert 0 < tp < 0.024 + grid = np.linspace(0, 0.1, 100001) + k = inj.time_course(grid, 0.024, 0.003) + assert k.max() == pytest.approx(1.0, abs=1e-8) + assert grid[np.argmax(k)] == pytest.approx(tp, abs=2e-6) + assert inj.time_course(-1e-9, 0.024, 0.003) == 0 + + +def test_event_traces_sum_events() -> None: + """Traces are sums of size x time course at the line times.""" + s = inj.InjectionSettings(tau_s=0.01) + ev = inj.Events( + np.array([0, 0, 1]), + np.array([1, 1, 1]), + np.array([10.5, 30.0, 12.0]), + np.array([0, 1, 2]), + np.array([2.0, 3.0, 1.0]), + ) + tr = inj.event_traces(ev, 2, (5, 60), 0.001, s) + lines = np.arange(5, 61) + want0 = 2 * inj.time_course((lines - 10.5) * 1e-3, 0.01) + 3 * ( + inj.time_course((lines - 30.0) * 1e-3, 0.01) + ) + np.testing.assert_allclose(tr[0], want0, atol=1e-12) + assert tr[1, 12 - 5] == pytest.approx(1.0) + assert np.all(tr[1, : 12 - 5] == 0) + + +def test_draw_events_respect_edges_dead_time_and_classes() -> None: + """Onsets stay inside the edges, apart by the dead time; classes mix.""" + s = inj.InjectionSettings(rate_hz=4.0, min_interval_s=0.1, edge_s=0.5) + period = 1e-4 + ev = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) + assert np.all(ev.trial == 3) + assert ev.onset_line.min() >= 1 + 0.5 / period + assert ev.onset_line.max() <= 100001 - 0.5 / period + for j in range(200): + t = ev.onset_line[ev.source == j] + assert np.all(np.diff(t) >= 0.1 / period - 1e-6) + dur = 10.0 - 1.0 + rate = len(ev) / 200 / dur + assert rate == pytest.approx(1 / (0.1 + 1 / 4.0), rel=0.05) + counts = np.bincount(ev.size_class, minlength=6) + assert counts.min() > 0.8 * counts.mean() + np.testing.assert_array_equal(ev.size, np.asarray(s.size_classes)[ev.size_class]) + again = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) + np.testing.assert_array_equal(again.onset_line, ev.onset_line) + none = inj.draw_events(5, 1.0, 100001.0, period, replace(s, rate_hz=0.0), None) + assert len(none) == 0 + + +def _draw_events_before_sync( + n_sources: int, + first: float, + last: float, + period: float, + s: inj.InjectionSettings, + rng: np.random.Generator, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Draw the events as they were drawn before sync_share existed. + + This is the loop of draw_events at GIAnT-Python a673714, kept here as + the reference: source, onset line and size class of every event. + + Returns + ------- + source : np.ndarray + Source index of every event. + onset_line : np.ndarray + Onset line of every event. + size_class : np.ndarray + Size class of every event. + """ + edge = s.edge_s / period + lo, hi = float(first) + edge, float(last) - edge + mean_gap = 1.0 / s.rate_hz / period + dead = s.min_interval_s / period + n_draw = int((hi - lo) / (mean_gap + dead) * 1.5) + 20 + src, onset, classes = [], [], [] + for j in range(n_sources): + while True: + gaps = rng.exponential(mean_gap, n_draw) + dead + gaps[0] -= dead + t = lo + np.cumsum(gaps) + if t[-1] > hi: + break + n_draw *= 2 + t = t[t <= hi] + cls = rng.choice(len(s.size_classes), t.size, p=s.weights) + src.append(np.full(t.size, j)) + onset.append(t) + classes.append(cls) + return np.concatenate(src), np.concatenate(onset), np.concatenate(classes) + + +def test_draw_events_with_common_onsets() -> None: + """sync_share gives every source the onsets of one common train beside its own. + + The common ones are in every source, the dead time holds, the rate is + about kept, and a share of 0 changes no draw. + """ + period = 1e-4 + s = inj.InjectionSettings(rate_hz=2.0, min_interval_s=0.1, edge_s=0.5) + args = (60, 1.0, 600001.0, period) # a minute + plain = inj.draw_events(*args, s, np.random.default_rng(3)) + # a share of 0 draws what the tool drew before the option existed: + # the same generator calls in the same order (the default setting, a + # high rate without dead time, weighted size classes) + for setting, n_src, seed in ( + (s, 60, 3), + (replace(s, rate_hz=40.0, min_interval_s=0.0), 7, 11), + (replace(s, class_weights=(1, 1, 1, 1, 1, 5)), 12, 5), + ): + got = inj.draw_events(n_src, *args[1:], setting, np.random.default_rng(seed)) + src, onset, cls = _draw_events_before_sync( + n_src, *args[1:], setting, np.random.default_rng(seed) + ) + np.testing.assert_array_equal(got.source, src) + np.testing.assert_array_equal(got.onset_line, onset) + np.testing.assert_array_equal(got.size_class, cls) + assert len(got) > 100 + rate0 = len(plain) / 60 / 59.0 + + def common_onsets(ev: inj.Events, n: int) -> np.ndarray: + """Onsets that every one of the n sources has. + + Returns + ------- + np.ndarray + The onset lines present in all n sources. + """ + t, counts = np.unique(ev.onset_line, return_counts=True) + return t[counts == n] + + assert common_onsets(plain, 60).size == 0 + for share in (0.5, 1.0): + ev = inj.draw_events(*args, replace(s, sync_share=share), np.random.default_rng(3)) + both = common_onsets(ev, 60) + assert both.size > 20 + for j in range(60): + t = ev.onset_line[ev.source == j] + assert np.all(np.diff(t) >= 0.1 / period - 1e-6) + in_common = np.isin(t, both).mean() + if share == 1.0: + assert in_common == 1.0 + else: + assert 0.35 < in_common < 0.7 + rate = len(ev) / 60 / 59.0 + assert rate == pytest.approx(rate0, rel=0.12) + if share == 1.0: # one train, sixty times, with sizes of their own + assert len(ev) == 60 * both.size + first = ev.size_class[ev.source == 0] + second = ev.size_class[ev.source == 1] + assert np.any(first != second) + # an own onset never falls within the dead time of a common one + ev = inj.draw_events(*args, replace(s, sync_share=0.5), np.random.default_rng(3)) + both = common_onsets(ev, 60) + own = ev.onset_line[~np.isin(ev.onset_line, both)] + k = np.searchsorted(both, own) + gap = np.minimum( + np.abs(both[np.minimum(k, both.size - 1)] - own), + np.abs(own - both[np.maximum(k - 1, 0)]), + ) + assert gap.min() >= 0.1 / period - 1e-6 + + +def test_settings_reject_bad_values() -> None: + """Invalid settings raise.""" + with pytest.raises(ValueError): + inj.InjectionSettings(rise_s=0.03) + with pytest.raises(ValueError): + inj.InjectionSettings(sync_share=1.5) + with pytest.raises(ValueError): + inj.InjectionSettings(class_weights=(1.0, 2.0)) + with pytest.raises(ValueError): + inj.InjectionSettings(rate_hz=-1) + + +def test_footprints() -> None: + """Gaussian peak 1 and cut at its radius; image footprints interpolate.""" + g = inj.GaussianFootprint(1.33, 4.0) + assert g(0.0, 0.0) == 1.0 + assert g(1.33, 0.0) == pytest.approx(np.exp(-0.5)) + assert g(5.4, 0.0) == 0.0 and g.radius == pytest.approx(5.32) + img = np.zeros((5, 5)) + img[2, 2], img[2, 3] = 4.0, 2.0 + f = inj.ImageFootprint(img) + assert f(0.0, 0.0) == 1.0 + assert f(0.0, 0.5) == pytest.approx(0.75) + assert f(0.0, 9.0) == 0.0 + patch, origin = inj.footprint_patch(g, (10.0, 20.4), 3) + assert origin == [7, 17] and patch.shape == (7, 7) + assert patch[3, 3] == pytest.approx(np.exp(-0.5 * (0.4 / 1.33) ** 2)) + + +def test_place_sources_follow_the_rules() -> None: + """Sources sit on labeled pixels, away from edges, others and each other.""" + rng = np.random.default_rng(0) + img = np.full((60, 80), 1.0) + img[20:24, 5:75] = 10.0 # a horizontal "dendrite" + img[30:50, 40:44] = 10.0 # a vertical one + img[:, :3] = np.nan + exclude = np.array([[22.0, 40.0]]) + s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) + pos, n_cand = inj.place_sources(img, 100, rng, s, exclude_rc=exclude) + assert 0 < pos.shape[0] < 100 and n_cand > pos.shape[0] + lab = inj.labeled_pixels(img) + r, c = pos.T.astype(int) + assert lab[r, c].all() + assert c.min() >= 3 + 5 - 1 # distance from the NaN columns + d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) + assert d[np.triu_indices(len(pos), 1)].min() >= 6 + assert np.hypot(*(pos - exclude).T).min() >= 8 + + +def test_place_sources_keep_apart_from_placed_ones() -> None: + """Candidates near sources placed already are dropped before any is chosen. + + Candidates within the minimum distance of sources placed already are + dropped first: one that is too near cannot stand in the way of a free + one behind it. + """ + img = np.full((40, 60), 1.0) + img[19:22, 20:41] = 10.0 # a short "dendrite" + s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) + placed = np.array([[20.0, 24.0]]) + for seed in range(8): + pos, n_cand = inj.place_sources( + img, 10, np.random.default_rng(seed), s, keep_apart_rc=placed + ) + _, n_free = inj.place_sources(img, 10, np.random.default_rng(seed), s) + # fewer candidates, and none of the chosen within 6 px of the + # placed source or of each other + assert 0 < n_cand < n_free and pos.shape[0] >= 1 + assert np.hypot(*(pos - placed).T).min() >= 6 + d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) + assert len(pos) < 2 or d[np.triu_indices(len(pos), 1)].min() >= 6 + # with one place wanted and only the pixels 4 and 8 px from the placed + # source as candidates, the far one is found whatever the order + two = np.full((40, 60), np.nan) + two[10:31, 10:51] = 1.0 + two[19:22, 27:30] = 10.0 + two[19:22, 31:34] = 10.0 + for seed in range(8): + pos, _ = inj.place_sources( + two, + 1, + np.random.default_rng(seed), + replace(s, edge_px=0), + keep_apart_rc=placed, + ) + assert pos.shape[0] == 1 + assert np.hypot(*(pos[0] - placed[0])) >= 6 + + +def test_align_images_recovers_subpixel_shift() -> None: + """A smooth random image moved by a known shift is found again.""" + from scipy.ndimage import gaussian_filter + + rng = np.random.default_rng(3) + ref = gaussian_filter(rng.random((90, 120)), 2.0) * 100 + ref[:, :10] = np.nan + s = np.array([1.3, -2.6]) + moved = inj.shift_image(ref, -s) # moved(p + s) = ref(p) + est = inj.align_images(ref, moved) + np.testing.assert_allclose(est, s, atol=0.08) + + +# ------------------------------------------------------ synthetic recordings + + +def write_static(layout: RasterLayout, gain: float, rate: float, seed: int = 0) -> None: + """Write samples gain * Poisson(rate * brightness) of a static scene.""" + rng = np.random.default_rng(seed) + words = np.zeros((layout.num_cycles, layout.words_per_cycle), np.int16) + bright = 1 + 9 * ((layout.slot_pixel * 7919) % 97) / 97.0 + for ch in range(layout.num_channels): + li = layout.slot_line - 1 + w = layout.row_base[li] + ch * layout.n_per_channel[li] + w = w + layout.slot_pos + lam = rate * bright + words[:, w] = (gain * rng.poisson(lam, (layout.num_cycles, lam.size))).astype(np.int16) + with open(layout.files[0], "wb") as f: + f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) + f.write(words.tobytes()) + + +def test_measure_raw_per_photon(tmp_path: Path) -> None: + """The variance-to-mean ratio of scaled Poisson samples is the gain.""" + layout = make_layout(tmp_path / "g_DMD1-TRIAL000001.dat", 400, seed=2) + write_static(layout, gain=110.0, rate=0.05) + g = inj.measure_raw_per_photon(layout, channel=0) + assert g.raw_per_photon == pytest.approx(110.0, rel=0.05) + assert g.mean_pulse == pytest.approx(110.0, rel=0.01) + assert g.cycles == (0, 400) and g.n_slots > 0 + + +@pytest.fixture(scope="module") +def online(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: + """Synthetic recording with known motion and online offsets. + + Returns + ------- + OnlineRecording + The layout, its online offsets and the true motion, as (layout, offs, truth). + """ + path = tmp_path_factory.mktemp("rec") / "inj_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=N_CYCLES, seed=5) + offs = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=offs) + path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) + return layout, offs, truth + + +def truth_geometry( + layout: RasterLayout, offs: Offsets, truth: np.ndarray, lines: tuple[int, int] +) -> inj.TrialGeometry: + """Geometry in the scene frame. + + The sample of DMD (r, c) on line l shows the scene at + (r + y_dmd - m_r, c + x - m_c). + + Returns + ------- + inj.TrialGeometry + The per-line shifts for lines lines[0] to lines[1], with the geometry in the + scene frame. + """ + x, _, y_dmd = offs + ln = np.arange(lines[0], lines[1] + 1) + shift = np.stack([y_dmd[ln - 1] - truth[ln - 1, 0], x[ln - 1] - truth[ln - 1, 1]], 1) + return inj.TrialGeometry(lines[0], shift.astype(np.float64), True) + + +def test_sample_model_follows_the_tissue(online: OnlineRecording) -> None: + """Expected counts follow the tissue, for every chunk of cycles. + + They are photon_scale x footprint at the sample's tissue position x the + trace at its line. + """ + layout, offs, truth = online + lines = (8, layout.total_lines - 3) + geo = truth_geometry(layout, offs, truth, lines) + pos = np.array([[17.3, 22.0], [12.0, 30.6]]) + fps = [inj.GaussianFootprint(1.33), inj.GaussianFootprint(2.0)] + n_l = lines[1] - lines[0] + 1 + rng = np.random.default_rng(0) + traces = rng.random((2, n_l)) + model = inj.SampleModel(layout, geo, pos, fps, traces, 25.0) + cycles = np.arange(0, 30) + got = model.expected(cycles) + pix = layout.slot_pixel[model.slots] - 1 + r0, c0 = pix // layout.n_cols, pix % layout.n_cols + ln = cycles[:, None] * layout.lines_per_cycle + layout.slot_line[model.slots] + inside = (ln >= lines[0]) & (ln <= lines[1]) + li = np.clip(ln - lines[0], 0, n_l - 1) + want = np.zeros(got.shape) + for j in range(2): + f = fps[j]( + r0 + geo.shift[li, 0] - pos[j, 0], + c0 + geo.shift[li, 1] - pos[j, 1], + ) + want += 25.0 * f * traces[j, li] + want[~inside] = 0 + np.testing.assert_allclose(got, want, rtol=1e-12, atol=1e-12) + # every slot whose footprint value can be non-zero is reachable + every = np.arange(layout.slot_line.size) + allpix = layout.slot_pixel[every] - 1 + near = np.zeros(every.size, bool) + for j in range(2): + for s in geo.shift[:: layout.lines_per_cycle]: + d = np.hypot( + allpix // layout.n_cols + s[0] - pos[j, 0], + allpix % layout.n_cols + s[1] - pos[j, 1], + ) + near |= d <= fps[j].radius + assert np.all(np.isin(every[near], model.slots)) + + +def registered_table( + layout: RasterLayout, tmp_path: Path, compensate: bool, trials: Sequence[tuple[int, int]] +) -> Path: + """Register line ranges of a recording through a trial table. + + Returns + ------- + Path + The path of the trial table that was registered. + """ + dat = Path(layout.files[0]) + n = len(trials) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name] * n], dtype=object), + "epoch": np.ones((1, n)), + "true_trial_ix": np.arange(1.0, n + 1)[None, :], + "slap2_info": { + "first_line": np.array([[float(a) for a, _ in trials]]), + "last_line": np.array([[float(b) for _, b in trials]]), + }, + }, + ) + register_multiroi( + table, + {"maxshift": 6, "compensate_online": compensate}, + execution={"device": "cpu", "max_workers": 1}, + ) + return table + + +@pytest.fixture(scope="module") +def registered( + online: OnlineRecording, tmp_path_factory: pytest.TempPathFactory +) -> dict[bool, Path]: + """Register the online recording as two trials, both ways. + + Returns + ------- + dict[bool, Path] + The trial table registered with (True) and without (False) online compensation. + """ + layout, _, _ = online + out = {} + with pytest.MonkeyPatch.context() as mp: + mp.setattr(multiroi, "raster_layout", lambda path: layout) + for comp in (True, False): + d = tmp_path_factory.mktemp(f"reg{int(comp)}") + out[comp] = registered_table(layout, d, comp, [(1, 4800), (4801, 9700)]) + return out + + +@pytest.mark.parametrize("compensate", [True, False]) +def test_geometry_from_registration_tracks_true_motion( + online: OnlineRecording, registered: dict[bool, Path], compensate: bool +) -> None: + """The registered position of each line's samples follows the tissue. + + shift(l) equals the true scene shift up to a constant. + """ + layout, offs, truth = online + table = Path(registered[compensate]) + al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + assert (al.compensation is not None) == compensate + lines = (1, 4800) + geo = inj.trial_geometry(layout, al, lines) + want = truth_geometry(layout, offs, truth, lines).shift + if not compensate: + # uncompensated frames blur the offsets' steps (every 23-50 ms + # here) over their kernel: the motion can only follow that blur + k = np.exp(-np.abs(np.arange(-60, 61)) / 20.0) + want = np.stack( + [np.convolve(np.pad(w, 60, "edge"), k / k.sum(), "valid") for w in want.T], + 1, + ) + err = geo.shift - want + err -= np.median(err, axis=0) + # within the registration's own error (as its tests require) + assert np.sqrt(np.mean(err**2)) < 0.12 + + +def run_injection( + online: OnlineRecording, + table: Path, + out: Path, + monkeypatch: pytest.MonkeyPatch, + **kw: Any, # noqa: ANN401 (forwarded to inject_session's keyword-only arguments) +) -> dict: + """inject_session on the synthetic recording. + + Returns + ------- + dict + The summary returned by inject_session. + """ + layout, _, _ = online + monkeypatch.setattr(inj, "raster_layout", lambda path: layout) + return inj.inject_session(table, out, paths=(1,), **kw) + + +def test_no_events_leave_the_copy_identical( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Without events the copy equals the original byte for byte. + + The .meta file is copied. + """ + layout, _, _ = online + s = inj.InjectionSettings(rate_hz=0.0, raw_per_photon=1.0) + summary = run_injection(online, registered[True], tmp_path / "out", monkeypatch, settings=s) + src = Path(layout.files[0]) + dst = tmp_path / "out" / "raw" / src.name + assert sha(dst) == sha(src) + meta = src.with_name("inj_DMD1.meta") + assert sha(dst.with_name(meta.name)) == sha(meta) + assert summary["paths"][1]["n_events"] == 0 + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) + assert truth["paths"][1]["events"]["source"].size == 0 + + +BRIGHT = inj.InjectionSettings( + size_classes=(4.0, 8.0), + rate_hz=3.0, + min_interval_s=0.06, + edge_s=0.1, + tau_s=0.012, + raw_per_photon=2.0, + seed=11, + device="cpu", +) +BRIGHT_AT = {1: np.array([[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]])} + + +@pytest.fixture(scope="module") +def injected( + online: OnlineRecording, registered: dict[bool, Path], tmp_path_factory: pytest.TempPathFactory +) -> Injected: + """Bright events injected into both trials (compensated registration). + + Returns + ------- + Injected + The injected copy's folder, its summary and the settings it was made with. + """ + out = tmp_path_factory.mktemp("inj") + with pytest.MonkeyPatch.context() as mp: + summary = run_injection( + online, + registered[True], + out, + mp, + settings=BRIGHT, + positions=BRIGHT_AT, + ) + return out, summary, BRIGHT + + +def test_placed_sources_without_data_are_moved( + online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path +) -> None: + """A source the tool put on a pixel without data where its peaks are calibrated is moved. + + A source that the tool itself puts on a pixel without data in the + stretch its frame peaks are calibrated on is placed anew: at the + minimum distance from the sources that stay and from every place tried + before; the others stay. A position that was given is not moved (an + error, as before), and so is a move with no place left. + """ + first = np.array([[16.0, 20.0], [16.0, 200.0], [12.0, 27.0]]) + asked = [] + # the free candidates of the move, in the order they are drawn: the + # first is 4 px from a source that stays, the second is the place that + # had no data, the third is free + pools = [np.array([[16.0, 24.0], [16.0, 200.0], [18.0, 30.0]])] + + def place( + mean_im: np.ndarray, + n: int, + rng: np.random.Generator, + settings: inj.PlacementSettings | None = None, + valid: np.ndarray | None = None, + exclude_rc: np.ndarray | None = None, + keep_apart_rc: np.ndarray | None = None, + ) -> tuple[np.ndarray, int]: + """Stand-in for place_sources. + + A first placement with a source where no data is, then the + candidates of a move. + + Returns + ------- + positions : np.ndarray + (k, 2) source positions: first on the first call, the free candidates + of the move afterwards. + n_candidates : int + 3 for the first placement, 1 for a move. + """ + asked.append((n, exclude_rc, keep_apart_rc)) + if len(asked) == 1: # the path's placement: one where no data is + return first.copy(), 3 + # a move: the candidates on offer, less those within 6 px of the + # places to keep apart from (place_sources' rule, tested above) + pool = pools[min(len(asked) - 2, len(pools) - 1)] + far = [np.hypot(*(keep_apart_rc - q).T).min() >= 6 for q in pool] + return pool[np.array(far, dtype=bool)][:n], 1 + + out = tmp_path / "moved" + with pytest.MonkeyPatch.context() as mp: + mp.setattr(inj, "place_sources", place) + run_injection(online, registered[True], out, mp, settings=BRIGHT, n_sources=3) + # one move of one source; no external sources to keep away from; apart + # from the sources that stay and from the place that had no data + assert len(asked) == 2 and asked[1][0] == 1 and asked[1][1] is None + assert {tuple(q) for q in asked[1][2]} == {tuple(q) for q in first} + p = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(p["positions_rc"], [[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]]) + assert np.all(p["frame_peak"] > 0) and p["frame_peak"].size == 3 + assert set(p["events"]["source"]) == {0, 1, 2} + # the sources that stayed are calibrated as if the third had been + # where it ended up from the start + with pytest.MonkeyPatch.context() as mp: + run_injection( + online, + registered[True], + tmp_path / "given", + mp, + settings=BRIGHT, + positions={1: np.array(p["positions_rc"])}, + ) + given = inj.read_truth(tmp_path / "given" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_allclose(given["frame_peak"][[0, 2]], p["frame_peak"][[0, 2]], rtol=0.05) + # a position that was given and has no data is an error + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match=r"sources \[1\] have no data"), + ): + run_injection( + online, + registered[True], + tmp_path / "fixed", + mp, + settings=BRIGHT, + positions={1: np.array([[16.0, 20.0], [16.0, 200.0]])}, + ) + # no place left for the move: the only candidates are too near a + # source that stays, or the place that was tried + asked.clear() + pools[:] = [np.array([[16.0, 24.0], [16.0, 200.0], [13.0, 31.0]])] + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match="only 0 free places"), + ): + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "full", + mp, + settings=BRIGHT, + n_sources=3, + ) + # a place tried in an earlier round is not taken again: the first move + # lands without data, and the second is offered the path's first place + # (no longer any source's) before a free one + asked.clear() + pools[:] = [ + np.array([[16.0, 210.0]]), + np.array([[16.0, 200.0], [18.0, 30.0]]), + ] + with pytest.MonkeyPatch.context() as mp: + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "twice", + mp, + settings=BRIGHT, + n_sources=3, + ) + twice = inj.read_truth(tmp_path / "twice" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(twice["positions_rc"][1], [18.0, 30.0]) + assert len(asked) == 3 + # the second move keeps apart from the first place too, though no + # source is there any more + assert (16.0, 200.0) in {tuple(q) for q in asked[2][2]} + assert (16.0, 210.0) in {tuple(q) for q in asked[2][2]} + # moves that land without data every time: after REPLACE_ROUNDS the + # injection gives up + asked.clear() + pools[:] = [ + np.array([[16.0, 210.0 + 10 * k], [16.0, 200.0 + 10 * k]]) + for k in range(inj.REPLACE_ROUNDS) + ] + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match="after 5 placements"), + ): + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "again", + mp, + settings=BRIGHT, + n_sources=3, + ) + assert len(asked) == 1 + inj.REPLACE_ROUNDS + + +def test_injection_changes_only_injected_samples( + online: OnlineRecording, injected: Injected +) -> None: + """Only channel-0 raster samples change, never invalid ones. + + The added counts are the recorded ones. + """ + layout, _, _ = online + out, summary, s = injected + src = Path(layout.files[0]) + a = np.fromfile(src, np.int16) + b = np.fromfile(out / "raw" / src.name, np.int16) + changed = np.flatnonzero(a != b) + assert changed.size > 0 + words = changed - HEADER_WORDS + w = words % layout.words_per_cycle + li = layout.slot_line - 1 + ch0 = layout.row_base[li] + layout.slot_pos + assert np.all(np.isin(w, ch0)) + assert np.all(b[changed] > a[changed]) + total = sum(t["added_raw"] for t in summary["paths"][1]["trials"]) + assert int((b.astype(np.int64) - a).sum()) == total + stats = summary["paths"][1]["trials"] + drawn = sum(t["drawn_photons"] for t in stats) + lam = sum(t["expected_photons"] for t in stats) + assert abs(drawn - lam) < 5 * np.sqrt(lam) + assert total == pytest.approx(drawn * s.raw_per_photon, rel=1e-3) + + +def test_truth_file_describes_the_injection(online: OnlineRecording, injected: Injected) -> None: + """The truth has positions per trial, events and traces at frame lines.""" + layout, _, _ = online + out, summary, s = injected + truth = inj.read_truth(out / inj.TRUTH_NAME) + assert truth["seed"] == 11 + assert truth["settings"]["size_classes"] == [4.0, 8.0] + p = truth["paths"][1] + assert p["raw_per_photon"] == 2.0 + np.testing.assert_array_equal(p["trials"], [1, 2]) + np.testing.assert_allclose(p["trial_shift_rc"][0], 0.0) + ev = p["events"] + assert ev["source"].size == summary["paths"][1]["n_events"] > 0 + for t, (lo, hi) in ((1, (1, 4800)), (2, (4801, 9700))): + on = ev["onset_line"][ev["trial"] == t] + assert on.min() >= lo + 0.1 * 1600 and on.max() <= hi - 0.1 * 1600 + d = p["trials_detail"][t] + np.testing.assert_allclose( + d["positions_rc"], p["positions_rc"] + p["trial_shift_rc"][t - 1] + ) + fl = d["frame_lines"] + assert fl[0] == lo and np.all(np.diff(fl) == 8) + # the trace peaks at each event's size within one frame of onset + k = np.searchsorted(fl, on[0]) + j = ev["source"][ev["trial"] == t][0] + size = ev["size"][ev["trial"] == t][0] + assert d["trace"][j, k] <= size * 1.0001 + d["trace"][j].max() + assert d["trace"].shape == (3, fl.size) + assert p["footprint"]["patch"].shape[0] == 3 + with h5py.File(out / "trial_table.h5") as f: + assert "motion_correction" not in f + tt = inj.load_struct_h5(out / "trial_table.h5") + assert Path(tt["datadr"]) == out / "raw" + assert np.asarray(tt["slap2_info"]["last_line"]).ravel().tolist() == [ + 4800.0, + 9700.0, + ] + + +def test_injected_signal_is_still_and_as_expected( + online: OnlineRecording, registered: dict[bool, Path], injected: Injected +) -> None: + """In frames registered with the original's motion, the copy matches the expected counts. + + In registered frames made with the original's motion, the copy minus the + original matches the expected counts within Poisson noise, and a static + source's centroid stays put (drift < 0.1 px) across the online offsets' + switches. + """ + layout, _, _ = online + out, _, s = injected + table = Path(registered[True]) + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + orig = read_raster_samples(layout, (0, layout.num_cycles))[0] + new = read_raster_samples(copy, (0, layout.num_cycles))[0] + diff = np.where(orig == INVALID_SAMPLE, INVALID_SAMPLE, new - orig) + lines = (1, 4800) + geo = inj.trial_geometry(layout, al, lines) + pos = truth["trials_detail"][1]["positions_rc"] + fp = [inj.GaussianFootprint(1.33)] * 3 + ev = truth["events"] + sel = ev["trial"] == 1 + events = inj.Events( + ev["source"][sel], + ev["trial"][sel], + ev["onset_line"][sel], + ev["size_class"][sel], + ev["size"][sel] / truth["frame_peak"][ev["source"][sel]], + ) + tr = inj.event_traces(events, 3, lines, layout.line_period_s, s) + expect = inj.SampleModel(layout, geo, pos, fp, tr, 25.0) + static = inj.SampleModel(layout, geo, pos, fp, np.ones_like(tr), 25.0) + n_c = layout.num_cycles # the frame kernels reach past the trial + samples = np.zeros((3, layout.slot_line.size, n_c), np.float32) + samples[0] = diff[:, :n_c] + samples[1][expect.slots] = expect.expected(np.arange(n_c)).T + samples[2][static.slots] = static.expected(np.arange(n_c)).T + samples[:, orig[:, :n_c] == INVALID_SAMPLE] = INVALID_SAMPLE + times = al.ds_frames.astype(np.int64) + # frames whose kernel (60 lines) stays inside the trial + times = times[(times > lines[0] + 60) & (times < lines[1] - 60)] + acc_d = acc_e = 0.0 + drift = {j: [] for j in range(3)} + for idx, frames, _ in iter_registered_frames(layout, samples, 0, al, times, 20, chunk=50): + f = frames.numpy() + for j, (r, c) in enumerate(pos): + ri, ci = int(round(r)), int(round(c)) + win = f[:, :, ri - 3 : ri + 4, ci - 3 : ci + 4] + acc_d = acc_d + np.nansum(win[0]) + acc_e = acc_e + np.nansum(win[1]) + whole = ~np.isnan(win[2]).any((1, 2)) # not cut by an edge + st = win[2][whole] + rr, cc = np.mgrid[-3:4, -3:4] + m = st.sum((1, 2)) + cr = (st * rr).sum((1, 2)) / m + ri - r + cc_ = (st * cc).sum((1, 2)) / m + ci - c + drift[j].append(np.stack([cr, cc_], 1)) + for j in range(3): + d = np.concatenate(drift[j]) + assert d.shape[0] > 0.9 * times.size + assert np.abs(d - np.median(d, axis=0)).max() < 0.1 + assert np.abs(np.median(d, axis=0)).max() < 0.1 + # the summed signal at the sources: Poisson error of photons x g + se = np.sqrt(acc_e * s.raw_per_photon) * 3 + assert abs(acc_d - acc_e) < 5 * se + + +def test_registered_copy_keeps_the_motion( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Registering the injected copy gives the original's motion up to the grid's anchoring. + + The truth then records both. + """ + layout, _, _ = online + out = tmp_path / "inj" + run_injection( + online, + registered[True], + out, + monkeypatch, + settings=replace(BRIGHT, size_classes=(1.0, 2.0)), + positions=BRIGHT_AT, + ) + copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: copy) + register_multiroi( + out / "trial_table.h5", + {"maxshift": 6, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert inj.main(["compare", str(out)]) == 0 + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + for t in (1, 2): + d = truth["trials_detail"][t] + assert d["copy_motion_rms_px"] < 0.05 + np.testing.assert_allclose(d["positions_copy_rc"], d["positions_rc"] + d["copy_shift_rc"]) + a = inj.read_alignment(d["alignment"]) + b = inj.read_alignment(d["copy_alignment"]) + off = inj.registration_offset(a, b) + np.testing.assert_allclose(off["shift_rc"], d["copy_shift_rc"]) + + +def test_saturation_invalid_samples_and_chunking(online: OnlineRecording, tmp_path: Path) -> None: + """Huge events saturate at 32767; invalid samples stay. + + Results do not depend on the chunk size. + """ + layout, offs, truth = online + src = Path(layout.files[0]) + data = np.fromfile(src, np.int16) + rng = np.random.default_rng(2) + li = layout.slot_line - 1 + ch0 = layout.row_base[li] + layout.slot_pos + rows = HEADER_WORDS + np.arange(N_CYCLES)[:, None] * layout.words_per_cycle + w = (rows + ch0[None, :]).ravel() + bad = w[rng.random(w.size) < 0.05] + data[bad] = INVALID_SAMPLE + outs = [] + lines = (1, layout.total_lines) + geo = truth_geometry(layout, offs, truth, lines) + tr = np.full((1, lines[1]), 2000.0) + for chunk in (7, 64): + dst = tmp_path / f"c{chunk}.dat" + data.tofile(dst) + lay = replace(layout, files=(str(dst),)) + model = inj.SampleModel(lay, geo, np.array([[18.0, 25.0]]), [inj.GaussianFootprint()], tr) + st = inj.inject_samples(lay, model, 3.0, 0, (5, 1, 1), chunk) + outs.append(np.fromfile(dst, np.int16)) + assert st.saturated > 0 and st.lost_raw > 0 + assert st.expected_photons_invalid > 0 + np.testing.assert_array_equal(outs[0], outs[1]) + assert np.all(outs[0][bad] == INVALID_SAMPLE) + assert outs[0].max() == inj.SAMPLE_MAX + + +def test_command_line( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """``python -m giant_python.simulation.injection`` runs a session.""" + layout, _, _ = online + monkeypatch.setattr(inj, "raster_layout", lambda path: layout) + pos = tmp_path / "pos.h5" + with h5py.File(pos, "w") as f: + f["path1"] = np.array([[16.0, 20.0]]) + code = inj.main([ + "inject", + str(registered[False]), + str(tmp_path / "cli"), + "--paths", + "1", + "--trials", + "2", + "--positions", + str(pos), + "--raw-per-photon", + "4", + "--sizes", + "8", + "--seed", + "3", + "--size-reference", + "tissue", + "--no-frame-traces", + ]) + assert code == 0 + summary = json.loads(capsys.readouterr().out) + assert summary["paths"]["1"]["n_sources"] == 1 + truth = inj.read_truth(tmp_path / "cli" / inj.TRUTH_NAME) + np.testing.assert_array_equal(truth["paths"][1]["trials"], [2]) + p = truth["paths"][1] + assert not p["trials_detail"][2]["compensated"] + np.testing.assert_array_equal(p["frame_peak"], [1.0]) + assert "trace_frames" not in p["trials_detail"][2] + + +def test_cuda_render_matches_cpu(online: OnlineRecording, registered: dict[bool, Path]) -> None: + """Rendering on CUDA equals the CPU.""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + layout, _, _ = online + table = Path(registered[True]) + al = inj.read_alignment(table.parent / "motion_correction" / "E1T2DMD1_ALIGNMENTDATA.h5") + s = read_raster_samples(layout, (0, layout.num_cycles))[:1] + times = al.ds_frames[:40].astype(np.int64) + cpu = next(iter_registered_frames(layout, s, 0, al, times, 20))[1] + gpu = next(iter_registered_frames(layout, s, 0, al, times, 20, "cuda"))[1] + np.testing.assert_allclose(gpu.cpu().numpy(), cpu.numpy(), rtol=1e-5, atol=1e-4, equal_nan=True) + + +def test_ragged_table_keeps_copy_columns( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A trial without a recording is skipped. + + The others keep their column of the copy's trial table. + """ + from giant_python.io.hdf5 import load_struct_h5 + + table = load_struct_h5(registered[False]) + table["filename"] = np.array([["", table["filename"][0, 1]]], object) + ragged = tmp_path / "trial_table.h5" + save_struct_h5(ragged, table) + s = inj.InjectionSettings(raw_per_photon=4.0, seed=1) + run_injection( + online, + ragged, + tmp_path / "out", + monkeypatch, + settings=s, + positions={1: np.array([[16.0, 20.0]])}, + moco_dir=Path(registered[False]).parent / "motion_correction", + ) + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME)["paths"][1] + assert list(truth["trials_detail"]) == [2] + assert truth["trials_detail"][2]["copy_trial"] == 2 + np.testing.assert_array_equal(np.unique(truth["events"]["trial"]), [2]) + + +def test_sizes_are_peaks_in_frames(online: OnlineRecording, injected: Injected) -> None: + """With sizes in frame units, an isolated event's noiseless peak is its size. + + The peak is taken in the 200 Hz frames at its source's peak pixel, and + equals the size on average. + """ + out, _, s = injected + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + fp = truth["frame_peak"] + assert np.all((fp > 0.2) & (fp < 1.0)) + ev = truth["events"] + reach = 24 # max(3 * 8, P) lines at 1600 Hz and 200 Hz frames + tail = 6 * s.tau_s * 1600 + ratios = [] + for t in (1, 2): + d = truth["trials_detail"][t] + fl, tf = d["frame_lines"], d["trace_frames"] + assert tf.shape == d["trace"].shape + # the ideal trace is sampled at frame lines: within a frame of each + # largest peak (overlapping events may add up) + top = np.array([ + ev["size"][(ev["trial"] == t) & (ev["source"] == j)].max() for j in range(3) + ]) + assert np.all(d["trace"].max(1) >= top * np.exp(-0.005 / s.tau_s)) + for j in range(3): + on = ev["onset_line"][(ev["trial"] == t) & (ev["source"] == j)] + size = ev["size"][(ev["trial"] == t) & (ev["source"] == j)] + for k, (t0, a) in enumerate(zip(on, size)): + alone = (k == 0 or t0 - on[k - 1] > 2 * tail) and ( + k == on.size - 1 or on[k + 1] - t0 > tail + reach + ) + sel = (fl >= t0 - reach) & (fl <= t0 + tail) + if alone and sel.any(): + ratios.append(np.nanmax(tf[j, sel]) / a) + assert len(ratios) > 20 + assert np.mean(ratios) == pytest.approx(1.0, abs=0.06) + + +def test_refuses_to_write_into_the_original( + online: OnlineRecording, registered: dict[bool, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + """The copy's folder cannot be the original's data folder.""" + layout, _, _ = online + src = Path(layout.files[0]) + out = src.parent.parent / "same" + with pytest.raises(ValueError, match="original's data folder"): + run_injection( + online, + registered[True], + out, + monkeypatch, + data_dir=out / "raw", + ) + + +def test_registration_offset_includes_the_grid(registered: dict[bool, Path]) -> None: + """Different padding, window and reference offset move the copy's positions. + + Mixed compensation is refused. + """ + from dataclasses import replace as dc_replace + + moco = Path(registered[True]).parent / "motion_correction" + a = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + comp = dict(a.compensation, refOffset=a.compensation["refOffset"] + 1) + b = dc_replace( + a, + margin=a.margin + 3, + trim_r0=a.trim_r0 + 1, + motion_r=a.motion_r + 0.25, + compensation=comp, + ) + off = inj.registration_offset(a, b) + # continuous motion unchanged in columns; rows: +0.25 recorded, -1 from + # the reference (mapping swaps x and y) + np.testing.assert_allclose(off["motion_offset_rc"], [0.25 - 1, -1.0]) + np.testing.assert_allclose(off["shift_rc"], [3 - 1 - 1 - (0.25 - 1), 3 - 1 + 1]) + assert off["rms_px"] < 1e-9 + plain = inj.read_alignment( + Path(registered[False]).parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5" + ) + with pytest.raises(ValueError, match="online motion correction"): + inj.registration_offset(a, plain) + + +def test_frame_motion_uses_each_frames_own_reference(registered: dict[bool, Path]) -> None: + """A frame with another reference offset is moved by its own reference. + + The frame is at a registered frame's time but with another reference + offset, and is moved by its own reference, not the recorded motion. + """ + from giant_python.simulation.render import frame_motion + + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + t = al.ds_frames.astype(np.int64) + c = al.compensation + refs = np.stack([c["frameRefX"], c["frameRefY"]], 1) + ok = np.isfinite(al.motion_r) + same = frame_motion(al, t, refs) + np.testing.assert_allclose(same[ok, 0], al.motion_r[ok], atol=1e-9) + np.testing.assert_allclose(same[ok, 1], al.motion_c[ok], atol=1e-9) + other = frame_motion(al, t, refs + np.array([1, 0])) # x one more + np.testing.assert_allclose(other[ok, 1], al.motion_c[ok] - 1, atol=1e-9) + np.testing.assert_allclose(other[ok, 0], al.motion_r[ok], atol=1e-9) + + +def test_calibration_keeps_overlapping_sources_apart( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """Overlapping sources are calibrated in turns. + + A close neighbour does not change a source's frame peak. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = inj.GaussianFootprint(1.33) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.5) + pair = np.array([[16.0, 20.0], [16.0, 22.0], [10.0, 33.0]]) + np.testing.assert_array_equal(inj.overlap_classes(pair, [fp] * 3), [0, 1, 0]) + both = inj.calibrate_frame_peaks( + layout, + al, + geo, + pair, + (0.0, 0.0), + [fp] * 3, + s, + np.random.default_rng(0), + ) + alone = inj.calibrate_frame_peaks( + layout, + al, + geo, + pair[:1], + (0.0, 0.0), + [fp], + s, + np.random.default_rng(0), + ) + assert both[0] == pytest.approx(alone[0], rel=0.05) + + +def test_inputs_that_would_corrupt_a_dataset_are_refused( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Repeated trials or paths and an existing dataset are refused before writing. + + Repeated trials or paths, and an output folder that already holds a + dataset, are refused before anything is written. + """ + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + pos = {1: np.array([[16.0, 20.0]])} + with pytest.raises(ValueError, match="must not repeat"): + run_injection( + online, + registered[False], + tmp_path / "a", + monkeypatch, + settings=s, + positions=pos, + trials=[1, 1], + ) + with pytest.raises(ValueError, match="must not repeat"): + inj.inject_session( + registered[False], + tmp_path / "b", + paths=(1, 1), + settings=s, + positions=pos, + ) + assert not (tmp_path / "a").exists() and not (tmp_path / "b").exists() + out = tmp_path / "c" + (out / "motion_correction").mkdir(parents=True) + with pytest.raises(ValueError, match="already holds motion_correction"): + run_injection( + online, + registered[False], + out, + monkeypatch, + settings=s, + positions=pos, + ) + + +def test_copy_table_paths_and_absolute_folders( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The copy's table has absolute folders and no files for paths not copied.""" + from giant_python.io.hdf5 import load_struct_h5 + + table = { + "datadr": "x", + "savedr": "y", + "filename": np.array([["a1", "b1"], ["a2", "b2"]], dtype=object), + "epoch": np.ones((2, 2)), + "slap2_info": {"first_line": np.ones((2, 2))}, + "motion_correction": {"fn_adata": "z"}, + } + monkeypatch.chdir(tmp_path) + Path("rel").mkdir() + p = inj.write_copy_table(table, np.array([1]), Path("rel/raw"), Path("rel"), paths=[1]) + t = load_struct_h5(p) + assert Path(t["datadr"]).is_absolute() and Path(t["savedr"]).is_absolute() + assert Path(t["savedr"]) == tmp_path / "rel" + np.testing.assert_array_equal(np.asarray(t["filename"], dtype=object).ravel(), ["b1", ""]) + assert "motion_correction" not in t + + +def test_image_footprint_peak_and_calibration( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """An off-centre image footprint is calibrated at its maximum.""" + layout, _, _ = online + img = np.zeros((5, 5)) + img[2, 4] = 1.0 + fp = inj.ImageFootprint(img) + assert fp.peak_offset == (0.0, 2.0) + pos = np.array([[16.0, 20.0]]) + np.testing.assert_array_equal(inj.peak_pixels(pos, [fp]), [[16, 22]]) + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) + peak = inj.calibrate_frame_peaks( + layout, al, geo, pos, (0.0, 0.0), [fp], s, np.random.default_rng(0) + ) + assert 0.05 < peak[0] < 1.0 + + +def test_expected_frames_follow_the_trial_grid( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """A path-frame pixel outside the trial grid's size is still rendered. + + It is rendered where its trial position has data; channel 1 renders + with channel 0's freshness. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = [inj.GaussianFootprint(1.33)] + model = inj.SampleModel(layout, geo, np.array([[16.3, 20.4]]), fp, np.ones((1, 4800))) + fl = np.arange(200, 1200, 8) + here = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0) + far = inj.expected_frames(layout, al, model, fl, [[16 - 40, 20 + 60]], (40.3, -59.6), 200.0) + assert al.shape[1] < 80 and np.isfinite(far).all() + np.testing.assert_allclose(far, here, rtol=1e-6) + ch1 = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0, channel=1) + np.testing.assert_allclose(ch1, here, rtol=1e-6) # no invalid samples + + +def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected: Injected) -> None: + """Two trials of one file: frames reading the other trial's injections are NaN. + + Frames whose kernel reads the other trial's injected samples are NaN in + the truth's frame traces. + """ + out, _, _ = injected + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + reach = 24 + t1, t2 = truth["trials_detail"][1], truth["trials_detail"][2] + near1 = t1["frame_lines"] + reach >= 4801 + near2 = t2["frame_lines"] - reach <= 4800 + assert near1.any() and near2.any() + assert np.isnan(t1["trace_frames"][:, near1]).all() + assert np.isnan(t2["trace_frames"][:, near2]).all() + assert np.isfinite(t1["trace_frames"][:, ~near1]).mean() > 0.9 + + +def test_relative_registration_folder_is_stored_absolute( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A relative registration folder is recorded as an absolute path.""" + import os + + reg = Path(registered[False]).parent + monkeypatch.chdir(reg) + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + run_injection( + online, + registered[False], + tmp_path / "out", + monkeypatch, + settings=s, + positions={1: np.array([[16.0, 20.0]])}, + trials=[1], + moco_dir="motion_correction", + ) + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) + al = Path(str(truth["paths"][1]["trials_detail"][1]["alignment"])) + assert al.is_absolute() and al.exists() + assert os.path.isabs(truth["origin"]["moco_dir"]) + + +def test_more_inputs_are_checked( + online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path +) -> None: + """Non-finite gains are refused; sources without data cannot be calibrated. + + Copies' filenames are their basenames; larger trial grids keep their + data when shifted into the path frame. + """ + from giant_python.io.hdf5 import load_struct_h5 + + for bad in (float("inf"), float("nan")): + with pytest.raises(ValueError, match="finite"): + inj.InjectionSettings(raw_per_photon=bad) + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = inj.GaussianFootprint(1.33) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) + with pytest.raises(ValueError, match=r"sources \[1\] have no data"): + inj.calibrate_frame_peaks( + layout, + al, + geo, + np.array([[16.0, 20.0], [16.0, 200.0]]), + (0.0, 0.0), + [fp, fp], + s, + np.random.default_rng(0), + ) + table = { + "filename": np.array([["sub/a_DMD1.dat"], [""]], dtype=object), + "slap2_info": {"first_line": np.ones((2, 1))}, + } + p = inj.write_copy_table(table, np.array([0]), tmp_path, tmp_path) + names = np.asarray(load_struct_h5(p)["filename"], dtype=object).ravel() + np.testing.assert_array_equal(names, ["a_DMD1.dat", ""]) + big = np.arange(10 * 112, dtype=float).reshape(10, 112) + out = inj.shift_image(big, (0.0, 8.0), (10, 100)) + np.testing.assert_allclose(out, big[:, 8:108]) + + +def test_bad_chunks_and_name_collisions_are_refused( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A nonpositive chunk size and copies sharing a name are refused before writing. + + A nonpositive chunk size, and two recordings that would be copied under + one name, are refused before anything is written. + """ + import shutil + + from giant_python.io.hdf5 import load_struct_h5 + + layout, _, _ = online + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + with pytest.raises(ValueError, match="chunk_cycles"): + run_injection( + online, + registered[False], + tmp_path / "c", + monkeypatch, + settings=s, + chunk_cycles=0, + ) + assert not (tmp_path / "c").exists() + data = tmp_path / "data" + src = Path(layout.files[0]) + for sub in ("a", "b"): + (data / sub).mkdir(parents=True) + shutil.copyfile(src, data / sub / src.name) + table = load_struct_h5(registered[False]) + table["filename"] = np.array([[f"a/{src.name}", f"b/{src.name}"]], dtype=object) + twins = tmp_path / "twins.h5" + save_struct_h5(twins, table) + monkeypatch.setattr(inj, "raster_layout", lambda path: replace(layout, files=(str(path),))) + with pytest.raises(ValueError, match="would both be copied"): + inj.inject_session(twins, tmp_path / "t", paths=(1,), settings=s, data_dir=data) + assert not (tmp_path / "t").exists() + + +def test_neighbours_share_recording_files() -> None: + """Trials are neighbours when their recordings share a file. + + This holds whatever file each trial names. + """ + ctx = { + "names": ["c0.dat", "c1.dat", "other.dat"], + "files": { + 0: ("c0.dat", "c1.dat"), + 1: ("c0.dat", "c1.dat"), + 2: ("other.dat",), + }, + "first": [1.0, 101.0, 1.0], + "last": [100.0, 200.0, 50.0], + } + near = inj._neighbours(ctx, [0, 1, 2]) + assert near(0) == [(101.0, 200.0)] + assert near(1) == [(1.0, 100.0)] + assert near(2) == [] + + +def test_no_events_need_no_calibration( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Without events nothing is calibrated, and the copy stays identical. + + This holds even in a trial too short to calibrate. + """ + layout, _, _ = online + s = inj.InjectionSettings(rate_hz=0.0, edge_s=1.6, raw_per_photon=1.0) + run_injection(online, registered[True], tmp_path / "o", monkeypatch, settings=s) + src = Path(layout.files[0]) + assert sha(tmp_path / "o" / "raw" / src.name) == sha(src) + truth = inj.read_truth(tmp_path / "o" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(truth["frame_peak"], 1.0) + + +def test_silo_frames_leave_out_the_kernels_edge( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """Frame traces and calibration use SILo's extraction frames. + + These leave out the samples exactly at the kernel's reach. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + model = inj.SampleModel( + layout, + geo, + np.array([[16.0, 20.0]]), + [inj.GaussianFootprint()], + np.ones((1, 4800)), + ) + fl = np.arange(300, 900, 8) + got = inj.expected_frames(layout, al, model, fl, [[16, 21]], (0, 0), 200) + n_c = layout.num_cycles + smp = np.zeros((1, layout.slot_line.size, n_c), np.float32) + smp[0][model.slots] = model.expected(np.arange(n_c)).T + want = {} + for exclusive in (True, False): + out = [] + for _, f, _ in iter_registered_frames( + layout, smp, 0, al, fl, 8, chunk=200, exclusive=exclusive + ): + out.append(f[0][:, 16, 21].numpy()) + want[exclusive] = np.concatenate(out) + np.testing.assert_allclose(got[0], want[True], rtol=1e-6) + assert np.max(np.abs(want[True] - want[False])) > 1e-6 diff --git a/tests/spine/__init__.py b/tests/spine/__init__.py index 291c0378..d84fd25f 100644 --- a/tests/spine/__init__.py +++ b/tests/spine/__init__.py @@ -1 +1 @@ -"""Tests of the spine-size readout (:mod:`giant_python.spine`).""" +"""Tests of the spine-size readout (:mod:`giant_python.spine`).""" diff --git a/tests/spine/synthetic.py b/tests/spine/synthetic.py index 5eea7a90..4e15614f 100644 --- a/tests/spine/synthetic.py +++ b/tests/spine/synthetic.py @@ -1,320 +1,375 @@ -"""A small synthetic session for the spine-size tests. - -One run folder with ``experiment_summary.h5`` and ``per_trial_summary.h5`` -in GIAnT-MATLAB's schema, a ``trial_table.h5``, a motion-correction folder -with ``_ALIGNMENTDATA.h5`` files (``recNegErr``) and a baseline folder -with ``_BASELINE-80Hz.h5`` files, for two imaging paths. - -Each trial's registered image is the consensus scene shifted by a whole -number of pixels (trial pixel = consensus pixel + shift), so a trial's -image resampled into the consensus frame equals the scene exactly where it -is covered. -""" - -from __future__ import annotations - -import json -from collections.abc import Callable -from pathlib import Path - -import h5py -import numpy as np - -from giant_python.io.hdf5 import save_struct_h5 - -H, W = 24, 30 -N_TRIALS = 4 -N_FRAMES = 160 -ALIGN_HZ = 80.0 -SHIFTS = [(0, 0), (1, 0), (0, -2), (2, 1)] -"""Each trial's shift (rows, cols): trial pixel = consensus pixel + shift.""" - -SOURCES = [(8.0, 9.0), (15.0, 20.0), (12.0, 14.0)] -"""Centres (row, col) of the sources' footprints.""" - - -def scene(path: int) -> np.ndarray: - """Build the consensus F0 scene of a path: smooth and positive.""" - rr, cc = np.mgrid[0:H, 0:W].astype(float) - return 50 + 10 * path + 2 * rr + 0.5 * cc - - -def trial_scale(t: int) -> float: - """Each trial's brightness factor (e.g. bleaching).""" - return 1.0 - 0.05 * t - - -def footprints() -> np.ndarray: - """Build the sources' footprints ``(sources, rows, cols)``.""" - rr, cc = np.mgrid[0:H, 0:W].astype(float) - out = np.zeros((len(SOURCES), H, W)) - for k, (r0, c0) in enumerate(SOURCES): - f = np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) - f[f < 0.01 * f.max()] = 0 - out[k] = f / f.sum() - return out - - -def trial_image(path: int, t: int) -> np.ndarray: - """Build a trial's registered F0 image (NaN where the shift leaves no data).""" - s = scene(path) * trial_scale(t) - dr, dc = SHIFTS[t] - out = np.full((H, W), np.nan) - # trial pixel (r + dr, c + dc) shows consensus pixel (r, c) - rs = slice(max(0, dr), H + min(0, dr)) - cs = slice(max(0, dc), W + min(0, dc)) - rs0 = slice(max(0, -dr), H - max(0, dr)) - cs0 = slice(max(0, -dc), W - max(0, dc)) - out[rs, cs] = s[rs0, cs0] - return out - - -def consensus_trial(path: int, t: int) -> np.ndarray: - """Show what a trial's image looks like in the consensus frame.""" - out = scene(path) * trial_scale(t) - dr, dc = SHIFTS[t] - rr, cc = np.mgrid[0:H, 0:W] - ok = (rr + dr >= 0) & (rr + dr < H) & (cc + dc >= 0) & (cc + dc < W) - return np.where(ok, out, np.nan) - - -def _trial_maps(affine: np.ndarray | None, displacement: bool) -> dict: - """Build the ``frame_info`` trial maps. - - ``affine`` (default: the shifts ``SHIFTS``), or with ``displacement`` the - shifts as a displacement field beside identity affine maps. - """ - if displacement: - disp = np.broadcast_to( - np.asarray(SHIFTS, float)[:, :, None, None], (N_TRIALS, 2, H, W) - ).copy() - eye = np.zeros((N_TRIALS, 2, 3)) - eye[:, :, :2] = np.eye(2) - return { - "trial_alignment_affine": eye, - "trial_alignment_displacement": disp, - } - if affine is None: - affine = np.zeros((N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - affine[:, :, 2] = np.asarray(SHIFTS, float) - return {"trial_alignment_affine": affine} - - -def _in_box(images: np.ndarray, box: tuple[slice, slice] | None) -> np.ndarray: - """``images`` (``(..., H, W)``) with NaN outside ``box``. - - ``box`` is rows, cols slices; None keeps every pixel. - """ - if box is None: - return images - keep = np.zeros((H, W), bool) - keep[box] = True - return np.where(keep, images, np.nan) - - -def make_session( - root: Path, - with_f0_silo: bool = True, - activity_channel: int = 1, - missing_trial: int | None = None, - discard_initial_s: float | None = None, - affine: np.ndarray | None = None, - displacement: bool = False, - f0_silo_box: tuple | None = None, -) -> dict: - """Write the synthetic session under ``root``; return its folders. - - ``dF_ls`` counts up through the frames in file channel 1 and from 1000 - in file channel 2; ``activity_channel`` is the run's - ``params/activityChannel``. ``missing_trial`` (zero-based) gets NaN - traces, as a trial without extracted sources. ``discard_initial_s`` - is recorded as the run's ``params/discardInitial_s`` (not recorded if - None). ``affine`` replaces the trial maps (``(trials, 2, 3)``, written - as given; default: the shifts ``SHIFTS``). With ``displacement`` the - shifts are written as a displacement field - (``trial_alignment_displacement``, as patchwise alignment saves it) and - the affine maps are the identity, so only the field puts the trials in - place. ``f0_silo_box`` (rows, cols slices) limits the run's own F0 - images to a box, as they have values only at the pixels SILo fitted. - """ - root = Path(root) - run = root / "run" - moco = root / "motion_correction" - base = root / "baselines" - for d in (run, moco, base): - d.mkdir(parents=True, exist_ok=True) - maps = _trial_maps(affine, displacement) - fp = footprints() - exp: dict = { - "params": { - "activityChannel": float(activity_channel), - "numChannels": 2.0, - } - } - if discard_initial_s is not None: - exp["params"]["discardInitial_s"] = float(discard_initial_s) - per: dict = {} - dF = np.tile(np.arange(N_TRIALS * 10, dtype=float), (len(SOURCES), 2, 1)) - dF[:, 1] += 1000 - ev = np.zeros((len(SOURCES), 2, N_TRIALS * 10)) - ev[:, 1] = 1.0 # events only in file channel 2 - if missing_trial is not None: - dF[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan - ev[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan - rng = np.random.default_rng(0) - for p in (1, 2): - imgs = np.stack([consensus_trial(p, t) for t in range(N_TRIALS)]) - mean_t = np.stack([imgs * 1.2, imgs * 0.1], axis=1) # T x C x H x W - exp[f"Path{p}"] = { - "visualizations": { - "mean_im": np.nanmean(mean_t, axis=0)[:, None], - "act_im": rng.random((1, H, W)), - }, - "sources": { - "spatial": {"profiles": fp[:, None]}, - "temporal": {"dF_ls": dF, "events": ev}, - }, - "frame_info": { - "trial_num_frames": np.full((1, N_TRIALS), 10.0), - **maps, - }, - "user_rois": { - "labels": np.array([["roi A", "roi B"]], dtype=object), - "mask": np.stack([ - np.pad(np.ones((4, 4)), ((2, H - 6), (2, W - 6))), - np.pad(np.ones((3, 5)), ((10, H - 13), (20, W - 25))), - ])[:, None] - > 0, - }, - } - per[f"Path{p}"] = {"visualizations": {"per_trial_mean_im": mean_t[:, :, None]}} - if with_f0_silo: - f0 = np.stack([imgs, imgs * 0.1], axis=1)[:, :, None] - per[f"Path{p}"]["visualizations"]["per_trial_F0_im"] = _in_box(f0, f0_silo_box) - for t in range(N_TRIALS): - stem = f"E1T{t + 1}DMD{p}" - img = trial_image(p, t) - frames = np.repeat(img.T[None], N_FRAMES, axis=0) # frame, col, row - frames[:5] = 1e4 # the trimmed start: must not enter - with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: - f.create_dataset("baseline", data=frames.astype(np.float16)) - f.attrs["checkpoint"] = "synthetic.pt" - f.attrs["step"] = 1 - with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["recNegErr"] = np.zeros((N_FRAMES, 1)) - save_struct_h5(run / "experiment_summary.h5", exp) - save_struct_h5(run / "per_trial_summary.h5", per) - fn = np.array( - [ - [f"E1T{t + 1}DMD{p}_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in range(N_TRIALS)] - for p in (1, 2) - ], - dtype=object, - ) - raw = np.array( - [[f"activity_x_DMD{p}-TRIAL{t + 2:06d}.dat" for t in range(N_TRIALS)] for p in (1, 2)], - dtype=object, - ) - table = root / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(root / "raw"), - "savedr": str(root / "guard"), - "filename": raw, - "motion_correction": {"fn_reg_ds": fn}, - }, - ) - return {"run": run, "moco": moco, "baselines": base, "table": table} - - -PLAN_HASH = "plan-a" -"""The synthetic plans' settings hash.""" - -RESULT_ATTRS = {"plan_hash": PLAN_HASH, "solve_science": "science-a"} -"""Attributes of the synthetic results files (with a container hash).""" - - -def write_results(path: Path, subproblems: dict, **attrs: str | int) -> None: - """Write a results file with ``subproblems`` (index -> (pixels, info)).""" - with h5py.File(path, "w") as f: - for k, v in {**RESULT_ATTRS, "container_hash": "c", **attrs}.items(): - f.attrs[k] = v - f["subproblems/index"] = np.array(sorted(subproblems)) - for k, (pix, info) in subproblems.items(): - g = f.create_group(f"subproblems/{k}") - g["pixels"] = np.asarray(pix) - g.attrs["info"] = json.dumps(info) - - -def baseline_record(path: Path) -> str: - """Build the ``network_baseline`` attribute SILo's results record for a baseline file. - - The attribute holds the file's identity and network. - """ - st = Path(path).stat() - return json.dumps( - { - "file": { - "name": Path(path).name, - "size": st.st_size, - "mtime_ns": st.st_mtime_ns, - }, - "network": {"checkpoint": "synthetic.pt", "step": 1}, - }, - sort_keys=True, - ) - - -def make_gain_work( - root: Path, - gain_of_trial: Callable[[int], float], - baselines: str | Path | None = None, -) -> Path: - """Write a minimal 'gain'-mode work folder. - - A plan per path with the selected pixels, and per trial-path one results - file with two overlapping subproblems whose gains are ``gain_of_trial(t)`` - and twice that. - - With ``baselines`` (the session's folder) the results record its files - as the baselines the gains were fitted against. - - Returns the work folder. - """ - work = Path(root) / "work" - (work / "plan").mkdir(parents=True, exist_ok=True) - (work / "results").mkdir(parents=True, exist_ok=True) - sel = np.zeros((H, W), bool) - sel[4:14, 5:15] = True - n_sel = int(sel.sum()) - for p in (1, 2): - with h5py.File(work / "plan" / f"path{p}.h5", "w") as f: - f["sources/sel"] = sel.astype(np.uint8) - f.attrs["settings_hash"] = PLAN_HASH - halves = ( - np.arange(0, n_sel // 2 + 1), - np.arange(n_sel // 2, n_sel), - ) - for t in range(N_TRIALS): - g0 = float(gain_of_trial(t)) - extra = {} - if baselines is not None: - extra["network_baseline"] = baseline_record( - Path(baselines) / f"E1T{t + 1}DMD{p}_BASELINE-80Hz.h5" - ) - write_results( - work / "results" / f"path{p}_trial{t + 1:04d}.h5", - { - k: ( - pix, - {"baseline_step": {"gain": [g0 * (k + 1)] * pix.size}}, - ) - for k, pix in enumerate(halves) - }, - container_hash=f"c{p}-{t}", - n_subproblems=2, - **extra, - ) - return work +"""A small synthetic session for the spine-size tests. + +One run folder with experiment_summary.h5 and per_trial_summary.h5 +in GIAnT-MATLAB's schema, a trial_table.h5, a motion-correction folder +with _ALIGNMENTDATA.h5 files (recNegErr) and a baseline folder +with _BASELINE-80Hz.h5 files, for two imaging paths. + +Each trial's registered image is the consensus scene shifted by a whole +number of pixels (trial pixel = consensus pixel + shift), so a trial's +image resampled into the consensus frame equals the scene exactly where it +is covered. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from pathlib import Path + +import h5py +import numpy as np + +from giant_python.io.hdf5 import save_struct_h5 + +H, W = 24, 30 +N_TRIALS = 4 +N_FRAMES = 160 +ALIGN_HZ = 80.0 +SHIFTS = [(0, 0), (1, 0), (0, -2), (2, 1)] +"""Each trial's shift (rows, cols): trial pixel = consensus pixel + shift.""" + +SOURCES = [(8.0, 9.0), (15.0, 20.0), (12.0, 14.0)] +"""Centres (row, col) of the sources' footprints.""" + + +def scene(path: int) -> np.ndarray: + """Build the consensus F0 scene of a path: smooth and positive. + + Returns + ------- + np.ndarray + The scene, (H, W). + """ + rr, cc = np.mgrid[0:H, 0:W].astype(float) + return 50 + 10 * path + 2 * rr + 0.5 * cc + + +def trial_scale(t: int) -> float: + """Each trial's brightness factor (e.g. bleaching). + + Returns + ------- + float + The factor of trial `t`, falling by 0.05 per trial from 1. + """ + return 1.0 - 0.05 * t + + +def footprints() -> np.ndarray: + """Build the sources' footprints (sources, rows, cols). + + Returns + ------- + np.ndarray + Gaussian footprints centred on SOURCES, each normalized to sum to 1. + """ + rr, cc = np.mgrid[0:H, 0:W].astype(float) + out = np.zeros((len(SOURCES), H, W)) + for k, (r0, c0) in enumerate(SOURCES): + f = np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) + f[f < 0.01 * f.max()] = 0 + out[k] = f / f.sum() + return out + + +def trial_image(path: int, t: int) -> np.ndarray: + """Build a trial's registered F0 image (NaN where the shift leaves no data). + + Returns + ------- + np.ndarray + The trial's image, (H, W): the scaled scene shifted by the trial's shift. + """ + s = scene(path) * trial_scale(t) + dr, dc = SHIFTS[t] + out = np.full((H, W), np.nan) + # trial pixel (r + dr, c + dc) shows consensus pixel (r, c) + rs = slice(max(0, dr), H + min(0, dr)) + cs = slice(max(0, dc), W + min(0, dc)) + rs0 = slice(max(0, -dr), H - max(0, dr)) + cs0 = slice(max(0, -dc), W - max(0, dc)) + out[rs, cs] = s[rs0, cs0] + return out + + +def consensus_trial(path: int, t: int) -> np.ndarray: + """Show what a trial's image looks like in the consensus frame. + + Returns + ------- + np.ndarray + The trial's scaled scene, (H, W), NaN where the trial does not cover the + consensus pixel. + """ + out = scene(path) * trial_scale(t) + dr, dc = SHIFTS[t] + rr, cc = np.mgrid[0:H, 0:W] + ok = (rr + dr >= 0) & (rr + dr < H) & (cc + dc >= 0) & (cc + dc < W) + return np.where(ok, out, np.nan) + + +def _trial_maps(affine: np.ndarray | None, displacement: bool) -> dict: + """Build the frame_info trial maps. + + affine (default: the shifts SHIFTS), or with displacement the + shifts as a displacement field beside identity affine maps. + + Returns + ------- + dict + trial_alignment_affine and, with displacement, trial_alignment_displacement. + """ + if displacement: + disp = np.broadcast_to( + np.asarray(SHIFTS, float)[:, :, None, None], (N_TRIALS, 2, H, W) + ).copy() + eye = np.zeros((N_TRIALS, 2, 3)) + eye[:, :, :2] = np.eye(2) + return { + "trial_alignment_affine": eye, + "trial_alignment_displacement": disp, + } + if affine is None: + affine = np.zeros((N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + affine[:, :, 2] = np.asarray(SHIFTS, float) + return {"trial_alignment_affine": affine} + + +def _in_box(images: np.ndarray, box: tuple[slice, slice] | None) -> np.ndarray: + """``images`` ((..., H, W)) with NaN outside box. + + box is rows, cols slices; None keeps every pixel. + + Returns + ------- + np.ndarray + `images` unchanged if `box` is None, else a copy with NaN outside `box`. + """ + if box is None: + return images + keep = np.zeros((H, W), bool) + keep[box] = True + return np.where(keep, images, np.nan) + + +def make_session( + root: Path, + with_f0_silo: bool = True, + activity_channel: int = 1, + missing_trial: int | None = None, + discard_initial_s: float | None = None, + affine: np.ndarray | None = None, + displacement: bool = False, + f0_silo_box: tuple | None = None, +) -> dict: + """Write the synthetic session under root; return its folders. + + dF_ls counts up through the frames in file channel 1 and from 1000 + in file channel 2; activity_channel is the run's + params/activityChannel. missing_trial (zero-based) gets NaN + traces, as a trial without extracted sources. discard_initial_s + is recorded as the run's params/discardInitial_s (not recorded if + None). affine replaces the trial maps ((trials, 2, 3), written + as given; default: the shifts SHIFTS). With displacement the + shifts are written as a displacement field + (trial_alignment_displacement, as patchwise alignment saves it) and + the affine maps are the identity, so only the field puts the trials in + place. f0_silo_box (rows, cols slices) limits the run's own F0 + images to a box, as they have values only at the pixels SILo fitted. + + Returns + ------- + dict + The session's folders: run, moco, baselines and the table file. + """ + root = Path(root) + run = root / "run" + moco = root / "motion_correction" + base = root / "baselines" + for d in (run, moco, base): + d.mkdir(parents=True, exist_ok=True) + maps = _trial_maps(affine, displacement) + fp = footprints() + exp: dict = { + "params": { + "activityChannel": float(activity_channel), + "numChannels": 2.0, + } + } + if discard_initial_s is not None: + exp["params"]["discardInitial_s"] = float(discard_initial_s) + per: dict = {} + dF = np.tile(np.arange(N_TRIALS * 10, dtype=float), (len(SOURCES), 2, 1)) + dF[:, 1] += 1000 + ev = np.zeros((len(SOURCES), 2, N_TRIALS * 10)) + ev[:, 1] = 1.0 # events only in file channel 2 + if missing_trial is not None: + dF[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan + ev[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan + rng = np.random.default_rng(0) + for p in (1, 2): + imgs = np.stack([consensus_trial(p, t) for t in range(N_TRIALS)]) + mean_t = np.stack([imgs * 1.2, imgs * 0.1], axis=1) # T x C x H x W + exp[f"Path{p}"] = { + "visualizations": { + "mean_im": np.nanmean(mean_t, axis=0)[:, None], + "act_im": rng.random((1, H, W)), + }, + "sources": { + "spatial": {"profiles": fp[:, None]}, + "temporal": {"dF_ls": dF, "events": ev}, + }, + "frame_info": { + "trial_num_frames": np.full((1, N_TRIALS), 10.0), + **maps, + }, + "user_rois": { + "labels": np.array([["roi A", "roi B"]], dtype=object), + "mask": np.stack([ + np.pad(np.ones((4, 4)), ((2, H - 6), (2, W - 6))), + np.pad(np.ones((3, 5)), ((10, H - 13), (20, W - 25))), + ])[:, None] + > 0, + }, + } + per[f"Path{p}"] = {"visualizations": {"per_trial_mean_im": mean_t[:, :, None]}} + if with_f0_silo: + f0 = np.stack([imgs, imgs * 0.1], axis=1)[:, :, None] + per[f"Path{p}"]["visualizations"]["per_trial_F0_im"] = _in_box(f0, f0_silo_box) + for t in range(N_TRIALS): + stem = f"E1T{t + 1}DMD{p}" + img = trial_image(p, t) + frames = np.repeat(img.T[None], N_FRAMES, axis=0) # frame, col, row + frames[:5] = 1e4 # the trimmed start: must not enter + with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: + f.create_dataset("baseline", data=frames.astype(np.float16)) + f.attrs["checkpoint"] = "synthetic.pt" + f.attrs["step"] = 1 + with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["recNegErr"] = np.zeros((N_FRAMES, 1)) + save_struct_h5(run / "experiment_summary.h5", exp) + save_struct_h5(run / "per_trial_summary.h5", per) + fn = np.array( + [ + [f"E1T{t + 1}DMD{p}_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in range(N_TRIALS)] + for p in (1, 2) + ], + dtype=object, + ) + raw = np.array( + [[f"activity_x_DMD{p}-TRIAL{t + 2:06d}.dat" for t in range(N_TRIALS)] for p in (1, 2)], + dtype=object, + ) + table = root / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(root / "raw"), + "savedr": str(root / "guard"), + "filename": raw, + "motion_correction": {"fn_reg_ds": fn}, + }, + ) + return {"run": run, "moco": moco, "baselines": base, "table": table} + + +PLAN_HASH = "plan-a" +"""The synthetic plans' settings hash.""" + +RESULT_ATTRS = {"plan_hash": PLAN_HASH, "solve_science": "science-a"} +"""Attributes of the synthetic results files (with a container hash).""" + + +def write_results(path: Path, subproblems: dict, **attrs: str | int) -> None: + """Write a results file with subproblems (index -> (pixels, info)).""" + with h5py.File(path, "w") as f: + for k, v in {**RESULT_ATTRS, "container_hash": "c", **attrs}.items(): + f.attrs[k] = v + f["subproblems/index"] = np.array(sorted(subproblems)) + for k, (pix, info) in subproblems.items(): + g = f.create_group(f"subproblems/{k}") + g["pixels"] = np.asarray(pix) + g.attrs["info"] = json.dumps(info) + + +def baseline_record(path: Path) -> str: + """Build the network_baseline attribute SILo's results record for a baseline file. + + The attribute holds the file's identity and network. + + Returns + ------- + str + The attribute as a JSON string with the file's name, size and mtime_ns and + the synthetic network. + """ + st = Path(path).stat() + return json.dumps( + { + "file": { + "name": Path(path).name, + "size": st.st_size, + "mtime_ns": st.st_mtime_ns, + }, + "network": {"checkpoint": "synthetic.pt", "step": 1}, + }, + sort_keys=True, + ) + + +def make_gain_work( + root: Path, + gain_of_trial: Callable[[int], float], + baselines: str | Path | None = None, +) -> Path: + """Write a minimal 'gain'-mode work folder. + + A plan per path with the selected pixels, and per trial-path one results + file with two overlapping subproblems whose gains are gain_of_trial(t) + and twice that. + + With baselines (the session's folder) the results record its files + as the baselines the gains were fitted against. + + Returns + ------- + Path + The work folder. + """ + work = Path(root) / "work" + (work / "plan").mkdir(parents=True, exist_ok=True) + (work / "results").mkdir(parents=True, exist_ok=True) + sel = np.zeros((H, W), bool) + sel[4:14, 5:15] = True + n_sel = int(sel.sum()) + for p in (1, 2): + with h5py.File(work / "plan" / f"path{p}.h5", "w") as f: + f["sources/sel"] = sel.astype(np.uint8) + f.attrs["settings_hash"] = PLAN_HASH + halves = ( + np.arange(0, n_sel // 2 + 1), + np.arange(n_sel // 2, n_sel), + ) + for t in range(N_TRIALS): + g0 = float(gain_of_trial(t)) + extra = {} + if baselines is not None: + extra["network_baseline"] = baseline_record( + Path(baselines) / f"E1T{t + 1}DMD{p}_BASELINE-80Hz.h5" + ) + write_results( + work / "results" / f"path{p}_trial{t + 1:04d}.h5", + { + k: ( + pix, + {"baseline_step": {"gain": [g0 * (k + 1)] * pix.size}}, + ) + for k, pix in enumerate(halves) + }, + container_hash=f"c{p}-{t}", + n_subproblems=2, + **extra, + ) + return work diff --git a/tests/spine/test_spine_coverage.py b/tests/spine/test_spine_coverage.py index 89355cbf..3c293b0c 100644 --- a/tests/spine/test_spine_coverage.py +++ b/tests/spine/test_spine_coverage.py @@ -1,279 +1,295 @@ -"""Tests of the pixels a trial did not image and of their place in ``giant spine readout``. - -See :mod:`giant_python.spine.coverage`. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.spine.coverage import unimaged_pixels, window_weight_kept -from giant_python.spine.pipeline import make_spine_summary -from giant_python.spine.product import read_product -from giant_python.spine.rois import masks_roiset -from giant_python.spine.summary_io import RunSummary - -from . import synthetic as syn - - -def _stack(T: int = 6, H: int = 12, W: int = 16, level: float = 10.0) -> np.ndarray: - """Mean images with a NaN margin on the right (outside the scan).""" - a = np.full((T, H, W), level) - a[:, :, 14:] = np.nan - return a - - -def test_band_at_the_scan_edge_is_found() -> None: - """A near-zero band touching the missing pixels is not imaged. - - The band is in the later trials and in every channel; one pixel around it - is not imaged too. - """ - ch1, ch2 = _stack(), _stack(level=1.0) - for c, lvl in ((ch1, 0.2), (ch2, 0.02)): - c[3:, :, 11:14] = lvl - un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) - assert not un[:3].any() - assert un[3:, :, 11:14].all() - assert un[3:, :, 10].all() and not un[3:, :, :10].any() # dilation - assert not un[:, :, 14:].any() # missing pixels are not marked - assert not unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0)[3:, :, 10].any() - - -def test_dimming_inside_the_field_or_in_one_channel_is_kept() -> None: - """Dark pixels away from the scan's edge, or dark in one channel only, are imaged.""" - ch1, ch2 = _stack(), _stack(level=1.0) - ch1[3:, 5:7, 5:7] = 0.1 # interior, both channels - ch2[3:, 5:7, 5:7] = 0.01 - ch1[3:, :, 12:14] = 0.1 # edge band in channel 1 only - un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) - assert not un.any() - assert not unimaged_pixels([ch1, ch2], frac=0.0).any() - - -def test_the_frame_border_counts_as_the_edge() -> None: - """A band at the frame's border is found without missing pixels.""" - ch = np.full((4, 8, 8), 5.0) - ch[2:, :, 6:] = 0.0 - un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) - assert un[2:, :, 6:].all() and un.sum() == 2 * 8 * 2 - - -def test_unimaged_pixels_checks_its_input() -> None: - """Channels must share a shape, and there must be one.""" - with pytest.raises(ValueError, match="shape"): - unimaged_pixels([np.ones((2, 3, 3)), np.ones((2, 3, 4))]) - with pytest.raises(ValueError, match="at least one"): - unimaged_pixels([]) - - -def test_window_weight_kept() -> None: - """The share of each window's weight on the valid pixels.""" - masks = np.zeros((2, 4, 4), bool) - masks[0, :, :2] = True - masks[1, :, 2:] = True - rs = masks_roiset(masks, ["a", "b"]) - valid = np.ones((4, 4), bool) - valid[:, 3] = False - np.testing.assert_allclose(window_weight_kept(rs, valid), [1.0, 0.5]) - - -@pytest.fixture -def banded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: - """Build the synthetic session with a near-zero band at the right edge of trials 3 and 4. - - The band is as left by a step of online motion correction, in every - per-trial image. - """ - s = syn.make_session(tmp_path) - real = RunSummary.per_trial_images - - def with_band( - self: RunSummary, path: int, name: str, channel: int | None - ) -> np.ndarray: - """Return the run's per-trial images with the band.""" - a = np.array(real(self, path, name, channel), dtype=np.float32) - band = a[2:, :, 17:] - a[2:, :, 17:] = np.where(np.isfinite(band), 0.02, band) - return a - - monkeypatch.setattr(RunSummary, "per_trial_images", with_band) - return s - - -def test_readout_leaves_out_the_band(banded: dict[str, Path], tmp_path: Path) -> None: - """The band is left out of every image. - - A source mostly in it gets NaN sizes, and a source partly in it keeps the - same window in every trial (no dip). - """ - notes = [] - rep = make_spine_summary( - banded["run"], - banded["table"], - tmp_path / "o", - n_perm=0, - unimaged_max_share=0.5, - progress=notes.append, - ) - p = read_product(rep["output"])["paths"][1] - un = p["unimaged"] - assert un[2:, :, 17:].any() and not un[:2].any() - assert rep["paths"][1]["unimaged"]["3"] > 0 - assert any("were not imaged" in m for m in notes) - for name in ("mean_ch1", "f0_silo_ch1"): - assert np.isnan(p["images"][name][un]).all() - assert not p["valid"][:, 16:].any() # the band and its dilation - kept = p["readout"]["sources"]["weight_kept"] - assert kept[1] < 0.5 <= kept[2] < 1 and kept[0] == pytest.approx(1) - assert rep["paths"][1]["small_windows"] == [2] - assert np.isnan(p["readout"]["sources"]["mean_ch1"][:, 1]).all() - norm = p["normalized"]["sources"] - assert not norm["ok"][1] and norm["ok"][2] - # the scene scales alike everywhere: no dip once the band is out - np.testing.assert_allclose(norm["mean_ch1"][:, 2], 0, atol=1e-6) - r = p["readout"]["sources"]["mean_ch1"][:, 2] - scale = np.array([syn.trial_scale(t) for t in range(syn.N_TRIALS)]) - np.testing.assert_allclose(r / r[0], scale / scale[0], rtol=1e-5) - assert p["image_attrs"]["mean_ch1"]["covers"] == "field" - - -def test_without_the_mask_the_band_makes_a_dip(banded: dict[str, Path], tmp_path: Path) -> None: - """With the mask off, the partly covered source dips in the banded trials. - - This is what the mask removes. - """ - rep = make_spine_summary( - banded["run"], - banded["table"], - tmp_path / "o", - n_perm=0, - unimaged_frac=0.0, - min_window=0.0, - ) - p = read_product(rep["output"])["paths"][1] - assert "unimaged" not in p - r = p["readout"]["sources"]["mean_ch1"][:, 2] - scale = np.array([syn.trial_scale(t) for t in range(syn.N_TRIALS)]) - rel = (r / r[0]) / (scale / scale[0]) - np.testing.assert_allclose(rel[:2], 1, rtol=1e-5) - assert rel[2:].max() < 0.99 # the footprint's edge reaches the band - r1 = p["readout"]["sources"]["mean_ch1"][:, 1] - assert (r1[2:] / r1[0]).max() < 0.2 # mostly in the band - - -@pytest.mark.parametrize( - "kw, match", - [ - (dict(unimaged_frac=1.0), "unimaged_frac"), - (dict(unimaged_frac=-0.1), "unimaged_frac"), - (dict(unimaged_dilate=-1), "unimaged_dilate"), - (dict(min_window=1.5), "min_window"), - ], -) -def test_coverage_settings_are_checked(tmp_path: Path, kw: dict[str, float], match: str) -> None: - """Settings that cannot work are refused before anything is read.""" - with pytest.raises(ValueError, match=match): - make_spine_summary(tmp_path, tmp_path / "t.h5", tmp_path / "o", **kw) - - -def test_a_dimmer_trial_is_not_a_band() -> None: - """A trial whose whole field is dimmer (bleaching, laser power) is not taken for a band. - - A band in such a trial still is. - """ - ch1, ch2 = _stack(), _stack(level=1.0) - ch1[4:] *= 0.2 - ch2[4:] *= 0.2 - assert not unimaged_pixels([ch1, ch2], frac=0.5).any() - ch1[5, :, 12:14] = 0.0 - ch2[5, :, 12:14] = 0.0 - un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0) - assert un[5, :, 12:14].all() and un.sum() == 12 * 2 - - -def test_missing_pixels_of_any_channel_set_the_edge() -> None: - """The scan's edge is where any channel lacks a value, whatever the channels' order. - - No missing pixel is marked. - """ - ch1, ch2 = _stack(), _stack(level=1.0) - ch1[:, :, 13] = np.nan # channel 1 misses one more column - ch1[3:, :, 11:13] = 0.1 - ch2[3:, :, 11:13] = 0.01 - a = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) - b = unimaged_pixels([ch2, ch1], frac=0.5, dilate=1, max_share=1.0) - np.testing.assert_array_equal(a, b) - assert a[3:, :, 11:13].all() and not a[:, :, 13:].any() - - -def test_no_source_left_is_not_a_reference() -> None: - """When every source's sizes are NaN, none is in the normalization's reference set. - - Every source's sizes are NaN when all windows are rejected. - """ - from giant_python.spine.pipeline import _normalize - - nan = np.full((4, 3), np.nan) - images = {"mean_ch1": (None, {"covers": "field"})} - norm = _normalize({"mean_ch1": nan}, images, ["mean_ch1"], np.arange(4)) - assert not norm["ok"].any() - assert np.isnan(norm["mean_ch1"]).all() - - -def test_a_trial_without_values_does_not_stop_the_search() -> None: - """A trial with no value at all (not extracted) does not stop the search. - - It neither empties the pixels every trial has nor gets marked. - """ - ch1, ch2 = _stack(), _stack(level=1.0) - ch1[1] = np.nan - ch2[1] = np.nan - ch1[3:, :, 11:14] = 0.2 - ch2[3:, :, 11:14] = 0.02 - un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0) - assert un[3:, :, 11:14].all() and not un[1].any() - assert un.sum() == 3 * 12 * 3 - - -def test_a_wide_band_does_not_set_the_brightness_scale() -> None: - """Without the share limit, a band covering most of the field in two trials is found. - - The rest of the field is not marked in the other trials; with the limit - (default), such trials are skipped. - """ - ch = np.full((6, 10, 10), 10.0) - ch[4:, :, 4:] = 0.2 # 60% of the pixels - un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) - assert un[4:, :, 4:].all() and un.sum() == 2 * 10 * 6 - - -def test_a_band_too_large_to_tell_from_the_scene_is_not_marked() -> None: - """A brightness change with a band over most of the field cannot be told from a scene change. - - A brightness change together with a band over most of the field cannot be - told from a change of the scene: such trials get nothing marked and are - reported, rather than losing their windows. - """ - ch = np.full((6, 10, 10), 2.0) - ch[4:] = 10.0 - ch[4:, :, 4:] = 0.2 - un, skipped = unimaged_pixels([ch], frac=0.5, dilate=0, with_skipped=True) - assert not un.any() - assert skipped.size > 0 - # a narrow band in the same situation is still found - ch = np.full((6, 10, 10), 2.0) - ch[4:] = 10.0 - ch[4:, :, 9:] = 0.2 - un, skipped = unimaged_pixels([ch], frac=0.5, dilate=0, with_skipped=True) - assert un[4:, :, 9:].all() and un.sum() == 2 * 10 and skipped.size == 0 - - -def test_wide_band_skipped_by_default() -> None: - """With the default share limit, a band over 60% of the field is reported, not marked.""" - ch = np.full((6, 10, 10), 10.0) - ch[4:, :, 4:] = 0.2 - un, skipped = unimaged_pixels([ch], frac=0.5, with_skipped=True) - assert not un.any() - np.testing.assert_array_equal(skipped, [4, 5]) +"""Tests of the pixels a trial did not image and of their place in giant spine readout. + +See :mod:`giant_python.spine.coverage`. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.spine.coverage import unimaged_pixels, window_weight_kept +from giant_python.spine.pipeline import make_spine_summary +from giant_python.spine.product import read_product +from giant_python.spine.rois import masks_roiset +from giant_python.spine.summary_io import RunSummary + +from . import synthetic as syn + + +def _stack(T: int = 6, H: int = 12, W: int = 16, level: float = 10.0) -> np.ndarray: + """Mean images with a NaN margin on the right (outside the scan). + + Returns + ------- + np.ndarray + Array (T, H, W) filled with `level`, NaN from column 14 on. + """ + a = np.full((T, H, W), level) + a[:, :, 14:] = np.nan + return a + + +def test_band_at_the_scan_edge_is_found() -> None: + """A near-zero band touching the missing pixels is not imaged. + + The band is in the later trials and in every channel; one pixel around it + is not imaged too. + """ + ch1, ch2 = _stack(), _stack(level=1.0) + for c, lvl in ((ch1, 0.2), (ch2, 0.02)): + c[3:, :, 11:14] = lvl + un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) + assert not un[:3].any() + assert un[3:, :, 11:14].all() + assert un[3:, :, 10].all() and not un[3:, :, :10].any() # dilation + assert not un[:, :, 14:].any() # missing pixels are not marked + assert not unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0)[3:, :, 10].any() + + +def test_dimming_inside_the_field_or_in_one_channel_is_kept() -> None: + """Dark pixels away from the scan's edge, or dark in one channel only, are imaged.""" + ch1, ch2 = _stack(), _stack(level=1.0) + ch1[3:, 5:7, 5:7] = 0.1 # interior, both channels + ch2[3:, 5:7, 5:7] = 0.01 + ch1[3:, :, 12:14] = 0.1 # edge band in channel 1 only + un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) + assert not un.any() + assert not unimaged_pixels([ch1, ch2], frac=0.0).any() + + +def test_the_frame_border_counts_as_the_edge() -> None: + """A band at the frame's border is found without missing pixels.""" + ch = np.full((4, 8, 8), 5.0) + ch[2:, :, 6:] = 0.0 + un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) + assert un[2:, :, 6:].all() and un.sum() == 2 * 8 * 2 + + +def test_unimaged_pixels_checks_its_input() -> None: + """Channels must share a shape, and there must be one.""" + with pytest.raises(ValueError, match="shape"): + unimaged_pixels([np.ones((2, 3, 3)), np.ones((2, 3, 4))]) + with pytest.raises(ValueError, match="at least one"): + unimaged_pixels([]) + + +def test_window_weight_kept() -> None: + """The share of each window's weight on the valid pixels.""" + masks = np.zeros((2, 4, 4), bool) + masks[0, :, :2] = True + masks[1, :, 2:] = True + rs = masks_roiset(masks, ["a", "b"]) + valid = np.ones((4, 4), bool) + valid[:, 3] = False + np.testing.assert_allclose(window_weight_kept(rs, valid), [1.0, 0.5]) + + +@pytest.fixture +def banded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: + """Build the synthetic session with a near-zero band at the right edge of trials 3 and 4. + + The band is as left by a step of online motion correction, in every + per-trial image. + + Returns + ------- + dict[str, Path] + The synthetic session's folders and table, as from syn.make_session. + """ + s = syn.make_session(tmp_path) + real = RunSummary.per_trial_images + + def with_band(self: RunSummary, path: int, name: str, channel: int | None) -> np.ndarray: + """Return the run's per-trial images with the band. + + Returns + ------- + np.ndarray + The per-trial images as float32, with the finite pixels of trials 3 onward at + columns 17 and beyond set to 0.02. + """ + a = np.array(real(self, path, name, channel), dtype=np.float32) + band = a[2:, :, 17:] + a[2:, :, 17:] = np.where(np.isfinite(band), 0.02, band) + return a + + monkeypatch.setattr(RunSummary, "per_trial_images", with_band) + return s + + +def test_readout_leaves_out_the_band(banded: dict[str, Path], tmp_path: Path) -> None: + """The band is left out of every image. + + A source mostly in it gets NaN sizes, and a source partly in it keeps the + same window in every trial (no dip). + """ + notes = [] + rep = make_spine_summary( + banded["run"], + banded["table"], + tmp_path / "o", + n_perm=0, + unimaged_max_share=0.5, + progress=notes.append, + ) + p = read_product(rep["output"])["paths"][1] + un = p["unimaged"] + assert un[2:, :, 17:].any() and not un[:2].any() + assert rep["paths"][1]["unimaged"]["3"] > 0 + assert any("were not imaged" in m for m in notes) + for name in ("mean_ch1", "f0_silo_ch1"): + assert np.isnan(p["images"][name][un]).all() + assert not p["valid"][:, 16:].any() # the band and its dilation + kept = p["readout"]["sources"]["weight_kept"] + assert kept[1] < 0.5 <= kept[2] < 1 and kept[0] == pytest.approx(1) + assert rep["paths"][1]["small_windows"] == [2] + assert np.isnan(p["readout"]["sources"]["mean_ch1"][:, 1]).all() + norm = p["normalized"]["sources"] + assert not norm["ok"][1] and norm["ok"][2] + # the scene scales alike everywhere: no dip once the band is out + np.testing.assert_allclose(norm["mean_ch1"][:, 2], 0, atol=1e-6) + r = p["readout"]["sources"]["mean_ch1"][:, 2] + scale = np.array([syn.trial_scale(t) for t in range(syn.N_TRIALS)]) + np.testing.assert_allclose(r / r[0], scale / scale[0], rtol=1e-5) + assert p["image_attrs"]["mean_ch1"]["covers"] == "field" + + +def test_without_the_mask_the_band_makes_a_dip(banded: dict[str, Path], tmp_path: Path) -> None: + """With the mask off, the partly covered source dips in the banded trials. + + This is what the mask removes. + """ + rep = make_spine_summary( + banded["run"], + banded["table"], + tmp_path / "o", + n_perm=0, + unimaged_frac=0.0, + min_window=0.0, + ) + p = read_product(rep["output"])["paths"][1] + assert "unimaged" not in p + r = p["readout"]["sources"]["mean_ch1"][:, 2] + scale = np.array([syn.trial_scale(t) for t in range(syn.N_TRIALS)]) + rel = (r / r[0]) / (scale / scale[0]) + np.testing.assert_allclose(rel[:2], 1, rtol=1e-5) + assert rel[2:].max() < 0.99 # the footprint's edge reaches the band + r1 = p["readout"]["sources"]["mean_ch1"][:, 1] + assert (r1[2:] / r1[0]).max() < 0.2 # mostly in the band + + +@pytest.mark.parametrize( + "kw, match", + [ + (dict(unimaged_frac=1.0), "unimaged_frac"), + (dict(unimaged_frac=-0.1), "unimaged_frac"), + (dict(unimaged_dilate=-1), "unimaged_dilate"), + (dict(min_window=1.5), "min_window"), + ], +) +def test_coverage_settings_are_checked(tmp_path: Path, kw: dict[str, float], match: str) -> None: + """Settings that cannot work are refused before anything is read.""" + with pytest.raises(ValueError, match=match): + make_spine_summary(tmp_path, tmp_path / "t.h5", tmp_path / "o", **kw) + + +def test_a_dimmer_trial_is_not_a_band() -> None: + """A trial whose whole field is dimmer (bleaching, laser power) is not taken for a band. + + A band in such a trial still is. + """ + ch1, ch2 = _stack(), _stack(level=1.0) + ch1[4:] *= 0.2 + ch2[4:] *= 0.2 + assert not unimaged_pixels([ch1, ch2], frac=0.5).any() + ch1[5, :, 12:14] = 0.0 + ch2[5, :, 12:14] = 0.0 + un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0) + assert un[5, :, 12:14].all() and un.sum() == 12 * 2 + + +def test_missing_pixels_of_any_channel_set_the_edge() -> None: + """The scan's edge is where any channel lacks a value, whatever the channels' order. + + No missing pixel is marked. + """ + ch1, ch2 = _stack(), _stack(level=1.0) + ch1[:, :, 13] = np.nan # channel 1 misses one more column + ch1[3:, :, 11:13] = 0.1 + ch2[3:, :, 11:13] = 0.01 + a = unimaged_pixels([ch1, ch2], frac=0.5, dilate=1, max_share=1.0) + b = unimaged_pixels([ch2, ch1], frac=0.5, dilate=1, max_share=1.0) + np.testing.assert_array_equal(a, b) + assert a[3:, :, 11:13].all() and not a[:, :, 13:].any() + + +def test_no_source_left_is_not_a_reference() -> None: + """When every source's sizes are NaN, none is in the normalization's reference set. + + Every source's sizes are NaN when all windows are rejected. + """ + from giant_python.spine.pipeline import _normalize + + nan = np.full((4, 3), np.nan) + images = {"mean_ch1": (None, {"covers": "field"})} + norm = _normalize({"mean_ch1": nan}, images, ["mean_ch1"], np.arange(4)) + assert not norm["ok"].any() + assert np.isnan(norm["mean_ch1"]).all() + + +def test_a_trial_without_values_does_not_stop_the_search() -> None: + """A trial with no value at all (not extracted) does not stop the search. + + It neither empties the pixels every trial has nor gets marked. + """ + ch1, ch2 = _stack(), _stack(level=1.0) + ch1[1] = np.nan + ch2[1] = np.nan + ch1[3:, :, 11:14] = 0.2 + ch2[3:, :, 11:14] = 0.02 + un = unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0) + assert un[3:, :, 11:14].all() and not un[1].any() + assert un.sum() == 3 * 12 * 3 + + +def test_a_wide_band_does_not_set_the_brightness_scale() -> None: + """Without the share limit, a band covering most of the field in two trials is found. + + The rest of the field is not marked in the other trials; with the limit + (default), such trials are skipped. + """ + ch = np.full((6, 10, 10), 10.0) + ch[4:, :, 4:] = 0.2 # 60% of the pixels + un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) + assert un[4:, :, 4:].all() and un.sum() == 2 * 10 * 6 + + +def test_a_band_too_large_to_tell_from_the_scene_is_not_marked() -> None: + """A brightness change with a band over most of the field cannot be told from a scene change. + + A brightness change together with a band over most of the field cannot be + told from a change of the scene: such trials get nothing marked and are + reported, rather than losing their windows. + """ + ch = np.full((6, 10, 10), 2.0) + ch[4:] = 10.0 + ch[4:, :, 4:] = 0.2 + un, skipped = unimaged_pixels([ch], frac=0.5, dilate=0, with_skipped=True) + assert not un.any() + assert skipped.size > 0 + # a narrow band in the same situation is still found + ch = np.full((6, 10, 10), 2.0) + ch[4:] = 10.0 + ch[4:, :, 9:] = 0.2 + un, skipped = unimaged_pixels([ch], frac=0.5, dilate=0, with_skipped=True) + assert un[4:, :, 9:].all() and un.sum() == 2 * 10 and skipped.size == 0 + + +def test_wide_band_skipped_by_default() -> None: + """With the default share limit, a band over 60% of the field is reported, not marked.""" + ch = np.full((6, 10, 10), 10.0) + ch[4:, :, 4:] = 0.2 + un, skipped = unimaged_pixels([ch], frac=0.5, with_skipped=True) + assert not un.any() + np.testing.assert_array_equal(skipped, [4, 5]) diff --git a/tests/spine/test_spine_gains.py b/tests/spine/test_spine_gains.py index 2dce9126..9811fab0 100644 --- a/tests/spine/test_spine_gains.py +++ b/tests/spine/test_spine_gains.py @@ -1,246 +1,246 @@ -"""Tests of the gain-rescaled F0 (:mod:`giant_python.spine.gains`).""" - -import json -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.spine.gains import ( - gain_maps, - results_files, - selected_pixels, - trial_gains, -) -from giant_python.spine.pipeline import make_spine_summary -from giant_python.spine.product import read_product -from giant_python.spine.readout import project - -from . import synthetic as syn - - -def test_gain_maps_average_overlapping_subproblems(tmp_path: Path) -> None: - """A pixel in two subproblems gets the mean of its gains. - - Their spread is reported. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0 + 0.1 * t) - rows, cols, shape = selected_pixels(work / "plan" / "path1.h5") - gain, spread, n_files = gain_maps(work, 1, syn.N_TRIALS) - assert gain.shape == (syn.N_TRIALS,) + shape - assert (n_files == 1).all() - n = rows.size - overlap = n // 2 - g1 = 1.1 # trial 2 - np.testing.assert_allclose(gain[1, rows[0], cols[0]], g1) - np.testing.assert_allclose(gain[1, rows[-1], cols[-1]], 2 * g1) - np.testing.assert_allclose(gain[1, rows[overlap], cols[overlap]], 1.5 * g1, rtol=1e-6) - np.testing.assert_allclose(spread[1, rows[overlap], cols[overlap]], g1, rtol=1e-6) - assert spread[1, rows[0], cols[0]] == 0 - assert np.isnan(gain[1, 0, 0]) - - -def test_trial_gains_needs_a_gain_record(tmp_path: Path) -> None: - """Results of a mode without gains are refused.""" - path = tmp_path / "r.h5" - with h5py.File(path, "w") as f: - f["subproblems/index"] = np.array([0]) - g = f.create_group("subproblems/0") - g["pixels"] = np.arange(3) - g.attrs["info"] = json.dumps({"iterations": 3}) - with pytest.raises(ValueError, match="no gain record"): - trial_gains([path]) - - -def test_readout_adds_the_gain_image(tmp_path: Path) -> None: - """``f0_gain`` is the gain times the network's image, at the selected pixels.""" - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - rep = make_spine_summary( - s["run"], - s["table"], - tmp_path / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) - p = read_product(rep["output"])["paths"][1] - gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) - ok = np.isfinite(p["images"]["f0_gain"]) - assert ok.any() - np.testing.assert_allclose( - p["images"]["f0_gain"][ok], - (gain * p["images"]["f0_net"])[ok], - rtol=1e-6, - ) - assert not np.isfinite(p["images"]["f0_gain"][:, 0, 0]).any() - assert rep["paths"][1]["gain"]["median"] > 1.0 - # every image is read in the same windows: the source inside the - # selected pixels reads gain x f0_net in the field images' window - src = p["readout"]["sources"] - expect, _ = project(gain * p["images"]["f0_net"], p["rois"]["sources"], p["valid"]) - np.testing.assert_allclose(src["f0_gain"][:, 0], expect[:, 0], rtol=1e-5) - # the gains (selected pixels only) do not shrink the other images' - # windows: the sources and user ROIs outside them keep their readouts, - # and the report counts the windows f0_gain leaves out - assert np.isfinite(src["f0_net"]).all() - assert np.isnan(src["f0_gain"][:, 1]).all() - assert np.isfinite(p["readout"]["user"]["f0_net"]).all() - gaps = rep["paths"][1]["not_covered"] - assert gaps == {"sources": {"f0_gain": 2}, "user": {"f0_gain": 2}} - assert rep["paths"][1]["window_images"] == [ - "mean_ch1", - "mean_ch2", - "f0_net", - ] - # its normalization uses the sources it covers; the others' is unchanged - norm = p["normalized"]["sources"] - assert norm["ok"].all() - np.testing.assert_allclose(norm["f0_gain"][:, 0], 0, atol=1e-6) - assert np.isnan(norm["f0_gain"][:, 1:]).all() - with pytest.raises(ValueError, match="needs --baseline-dir"): - make_spine_summary(s["run"], s["table"], tmp_path, gain_work_dir=work) - - -def test_results_files_select_the_plan_and_the_exact_trial(tmp_path: Path) -> None: - """Results of another plan are left out. - - A longer trial number with the same prefix is not this trial, and two - solves of the plan are refused. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0) - res = work / "results" - info = {"baseline_step": {"gain": [9.0]}} - syn.write_results(res / "path1_trial0001_s9.h5", {0: ([0], info)}, plan_hash="old-plan") - assert [f.name for f in results_files(work, 1, 0)] == ["path1_trial0001.h5"] - syn.write_results(res / "path1_trial1000.h5", {0: ([0], info)}) - syn.write_results(res / "path1_trial10000.h5", {0: ([0], info)}) - assert [f.name for f in results_files(work, 1, 999)] == ["path1_trial1000.h5"] - syn.write_results( - res / "path1_trial0002_s1.h5", - {0: ([0], info)}, - solve_science="science-b", - container_hash="c1-1", - ) - with pytest.raises(ValueError, match="more than one solve"): - results_files(work, 1, 1) - # other numerical settings (solve_settings) of the same science - syn.write_results( - res / "path1_trial0003_s1.h5", - {0: ([0], info)}, - container_hash="c1-2", - solve_settings="other-iterations", - ) - with pytest.raises(ValueError, match="more than one solve"): - results_files(work, 1, 2) - - -def test_trial_gains_counts_a_copied_subproblem_once(tmp_path: Path) -> None: - """A subproblem in two files (identical copies) is one subproblem. - - Two different copies are refused. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0) - rows, cols, _ = selected_pixels(work / "plan" / "path1.h5") - n = rows.size - first = np.arange(0, n // 2 + 1) - copy = {0: (first, {"baseline_step": {"gain": [1.0] * first.size}})} - syn.write_results(work / "results" / "path1_trial0001_s1.h5", copy, container_hash="c1-0") - gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) - k = n // 2 # the pixel in both subproblems: gains 1 and 2 - np.testing.assert_allclose(gain[0, rows[k], cols[k]], 1.5, rtol=1e-6) - other = {0: (first, {"baseline_step": {"gain": [3.0] * first.size}})} - syn.write_results( - work / "results" / "path1_trial0001_s1.h5", - other, - container_hash="c1-0", - ) - with pytest.raises(ValueError, match="two different results"): - gain_maps(work, 1, syn.N_TRIALS) - - -def test_trial_gains_refuses_a_shared_time_course(tmp_path: Path) -> None: - """'gain_shared' subproblems are read only while their shared time course is 1. - - Then the baseline is still gain x network baseline. - """ - path = tmp_path / "r.h5" - step = {"gain": [2.0, 2.0], "shared": [1.0, 1.0, 1.0]} - syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) - pix, g = trial_gains([path]) - assert pix.tolist() == [0, 1] and g.tolist() == [2.0, 2.0] - step["shared"] = [1.0, 1.1, 0.9] - syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) - with pytest.raises(ValueError, match="shared baseline time course"): - trial_gains([path]) - - -def test_summary_key_follows_the_gain_plan(tmp_path: Path) -> None: - """A changed plan gives a new summary, not the old one reused.""" - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = dict( - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - with h5py.File(work / "plan" / "path1.h5", "a") as f: - f.attrs["note"] = "replanned" - rep2 = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - assert rep2["key"] != rep["key"] and not rep2["reused"] - - -def test_gains_need_the_images_baseline_files(tmp_path: Path) -> None: - """Gains are used only with the baseline files they were fitted against. - - A baseline predicted again after the solve, or results that record no - network baseline, are refused. - """ - import os - - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = dict( - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - b = s["baselines"] / "E1T2DMD1_BASELINE-80Hz.h5" - st = b.stat() - os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - with pytest.raises(ValueError, match="Path1 trial 2: the gains were"): - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns)) - plain = syn.make_gain_work(tmp_path / "plain", lambda t: 1.0) - kw["gain_work_dir"] = plain - with pytest.raises(ValueError, match="record no network baseline"): - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - - -def test_trial_gains_needs_every_subproblem(tmp_path: Path) -> None: - """As in the collect stage, a trial's results must hold all of its subproblems. - - A missing shard, or files that disagree on the number of subproblems, - are refused; a trial too short to extract is not. - """ - info = {"baseline_step": {"gain": [1.0, 1.0]}} - a, b = tmp_path / "a.h5", tmp_path / "b.h5" - syn.write_results(a, {0: ([0, 1], info)}, n_subproblems=2) - with pytest.raises(ValueError, match="1 of 2 subproblems"): - trial_gains([a]) - syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=2) - pix, _ = trial_gains([a, b]) - assert sorted(pix.tolist()) == [0, 1, 2, 3] - syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=3) - with pytest.raises(ValueError, match="3 subproblems here but 2"): - trial_gains([a, b]) - short = tmp_path / "short.h5" - syn.write_results(short, {}, n_subproblems=4, extracted=0) - pix, _ = trial_gains([short]) - assert pix.size == 0 +"""Tests of the gain-rescaled F0 (:mod:`giant_python.spine.gains`).""" + +import json +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.spine.gains import ( + gain_maps, + results_files, + selected_pixels, + trial_gains, +) +from giant_python.spine.pipeline import make_spine_summary +from giant_python.spine.product import read_product +from giant_python.spine.readout import project + +from . import synthetic as syn + + +def test_gain_maps_average_overlapping_subproblems(tmp_path: Path) -> None: + """A pixel in two subproblems gets the mean of its gains. + + Their spread is reported. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0 + 0.1 * t) + rows, cols, shape = selected_pixels(work / "plan" / "path1.h5") + gain, spread, n_files = gain_maps(work, 1, syn.N_TRIALS) + assert gain.shape == (syn.N_TRIALS,) + shape + assert (n_files == 1).all() + n = rows.size + overlap = n // 2 + g1 = 1.1 # trial 2 + np.testing.assert_allclose(gain[1, rows[0], cols[0]], g1) + np.testing.assert_allclose(gain[1, rows[-1], cols[-1]], 2 * g1) + np.testing.assert_allclose(gain[1, rows[overlap], cols[overlap]], 1.5 * g1, rtol=1e-6) + np.testing.assert_allclose(spread[1, rows[overlap], cols[overlap]], g1, rtol=1e-6) + assert spread[1, rows[0], cols[0]] == 0 + assert np.isnan(gain[1, 0, 0]) + + +def test_trial_gains_needs_a_gain_record(tmp_path: Path) -> None: + """Results of a mode without gains are refused.""" + path = tmp_path / "r.h5" + with h5py.File(path, "w") as f: + f["subproblems/index"] = np.array([0]) + g = f.create_group("subproblems/0") + g["pixels"] = np.arange(3) + g.attrs["info"] = json.dumps({"iterations": 3}) + with pytest.raises(ValueError, match="no gain record"): + trial_gains([path]) + + +def test_readout_adds_the_gain_image(tmp_path: Path) -> None: + """f0_gain is the gain times the network's image, at the selected pixels.""" + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + rep = make_spine_summary( + s["run"], + s["table"], + tmp_path / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + gain_work_dir=work, + ) + p = read_product(rep["output"])["paths"][1] + gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) + ok = np.isfinite(p["images"]["f0_gain"]) + assert ok.any() + np.testing.assert_allclose( + p["images"]["f0_gain"][ok], + (gain * p["images"]["f0_net"])[ok], + rtol=1e-6, + ) + assert not np.isfinite(p["images"]["f0_gain"][:, 0, 0]).any() + assert rep["paths"][1]["gain"]["median"] > 1.0 + # every image is read in the same windows: the source inside the + # selected pixels reads gain x f0_net in the field images' window + src = p["readout"]["sources"] + expect, _ = project(gain * p["images"]["f0_net"], p["rois"]["sources"], p["valid"]) + np.testing.assert_allclose(src["f0_gain"][:, 0], expect[:, 0], rtol=1e-5) + # the gains (selected pixels only) do not shrink the other images' + # windows: the sources and user ROIs outside them keep their readouts, + # and the report counts the windows f0_gain leaves out + assert np.isfinite(src["f0_net"]).all() + assert np.isnan(src["f0_gain"][:, 1]).all() + assert np.isfinite(p["readout"]["user"]["f0_net"]).all() + gaps = rep["paths"][1]["not_covered"] + assert gaps == {"sources": {"f0_gain": 2}, "user": {"f0_gain": 2}} + assert rep["paths"][1]["window_images"] == [ + "mean_ch1", + "mean_ch2", + "f0_net", + ] + # its normalization uses the sources it covers; the others' is unchanged + norm = p["normalized"]["sources"] + assert norm["ok"].all() + np.testing.assert_allclose(norm["f0_gain"][:, 0], 0, atol=1e-6) + assert np.isnan(norm["f0_gain"][:, 1:]).all() + with pytest.raises(ValueError, match="needs --baseline-dir"): + make_spine_summary(s["run"], s["table"], tmp_path, gain_work_dir=work) + + +def test_results_files_select_the_plan_and_the_exact_trial(tmp_path: Path) -> None: + """Results of another plan are left out. + + A longer trial number with the same prefix is not this trial, and two + solves of the plan are refused. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0) + res = work / "results" + info = {"baseline_step": {"gain": [9.0]}} + syn.write_results(res / "path1_trial0001_s9.h5", {0: ([0], info)}, plan_hash="old-plan") + assert [f.name for f in results_files(work, 1, 0)] == ["path1_trial0001.h5"] + syn.write_results(res / "path1_trial1000.h5", {0: ([0], info)}) + syn.write_results(res / "path1_trial10000.h5", {0: ([0], info)}) + assert [f.name for f in results_files(work, 1, 999)] == ["path1_trial1000.h5"] + syn.write_results( + res / "path1_trial0002_s1.h5", + {0: ([0], info)}, + solve_science="science-b", + container_hash="c1-1", + ) + with pytest.raises(ValueError, match="more than one solve"): + results_files(work, 1, 1) + # other numerical settings (solve_settings) of the same science + syn.write_results( + res / "path1_trial0003_s1.h5", + {0: ([0], info)}, + container_hash="c1-2", + solve_settings="other-iterations", + ) + with pytest.raises(ValueError, match="more than one solve"): + results_files(work, 1, 2) + + +def test_trial_gains_counts_a_copied_subproblem_once(tmp_path: Path) -> None: + """A subproblem in two files (identical copies) is one subproblem. + + Two different copies are refused. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0) + rows, cols, _ = selected_pixels(work / "plan" / "path1.h5") + n = rows.size + first = np.arange(0, n // 2 + 1) + copy = {0: (first, {"baseline_step": {"gain": [1.0] * first.size}})} + syn.write_results(work / "results" / "path1_trial0001_s1.h5", copy, container_hash="c1-0") + gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) + k = n // 2 # the pixel in both subproblems: gains 1 and 2 + np.testing.assert_allclose(gain[0, rows[k], cols[k]], 1.5, rtol=1e-6) + other = {0: (first, {"baseline_step": {"gain": [3.0] * first.size}})} + syn.write_results( + work / "results" / "path1_trial0001_s1.h5", + other, + container_hash="c1-0", + ) + with pytest.raises(ValueError, match="two different results"): + gain_maps(work, 1, syn.N_TRIALS) + + +def test_trial_gains_refuses_a_shared_time_course(tmp_path: Path) -> None: + """'gain_shared' subproblems are read only while their shared time course is 1. + + Then the baseline is still gain x network baseline. + """ + path = tmp_path / "r.h5" + step = {"gain": [2.0, 2.0], "shared": [1.0, 1.0, 1.0]} + syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) + pix, g = trial_gains([path]) + assert pix.tolist() == [0, 1] and g.tolist() == [2.0, 2.0] + step["shared"] = [1.0, 1.1, 0.9] + syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) + with pytest.raises(ValueError, match="shared baseline time course"): + trial_gains([path]) + + +def test_summary_key_follows_the_gain_plan(tmp_path: Path) -> None: + """A changed plan gives a new summary, not the old one reused.""" + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + kw = dict( + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + gain_work_dir=work, + ) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + with h5py.File(work / "plan" / "path1.h5", "a") as f: + f.attrs["note"] = "replanned" + rep2 = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + assert rep2["key"] != rep["key"] and not rep2["reused"] + + +def test_gains_need_the_images_baseline_files(tmp_path: Path) -> None: + """Gains are used only with the baseline files they were fitted against. + + A baseline predicted again after the solve, or results that record no + network baseline, are refused. + """ + import os + + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + kw = dict( + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + gain_work_dir=work, + ) + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + b = s["baselines"] / "E1T2DMD1_BASELINE-80Hz.h5" + st = b.stat() + os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + with pytest.raises(ValueError, match="Path1 trial 2: the gains were"): + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns)) + plain = syn.make_gain_work(tmp_path / "plain", lambda t: 1.0) + kw["gain_work_dir"] = plain + with pytest.raises(ValueError, match="record no network baseline"): + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + + +def test_trial_gains_needs_every_subproblem(tmp_path: Path) -> None: + """As in the collect stage, a trial's results must hold all of its subproblems. + + A missing shard, or files that disagree on the number of subproblems, + are refused; a trial too short to extract is not. + """ + info = {"baseline_step": {"gain": [1.0, 1.0]}} + a, b = tmp_path / "a.h5", tmp_path / "b.h5" + syn.write_results(a, {0: ([0, 1], info)}, n_subproblems=2) + with pytest.raises(ValueError, match="1 of 2 subproblems"): + trial_gains([a]) + syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=2) + pix, _ = trial_gains([a, b]) + assert sorted(pix.tolist()) == [0, 1, 2, 3] + syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=3) + with pytest.raises(ValueError, match="3 subproblems here but 2"): + trial_gains([a, b]) + short = tmp_path / "short.h5" + syn.write_results(short, {}, n_subproblems=4, extracted=0) + pix, _ = trial_gains([short]) + assert pix.size == 0 diff --git a/tests/spine/test_spine_images.py b/tests/spine/test_spine_images.py index 84d17a0b..85799e98 100644 --- a/tests/spine/test_spine_images.py +++ b/tests/spine/test_spine_images.py @@ -1,193 +1,193 @@ -"""Tests of the per-trial F0 images (:mod:`giant_python.spine.images`).""" - -import warnings -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.spine.images import ( - baseline_trial_mean, - file_identity, - kept_frames, - network_f0_stack, - stack_key, - to_consensus, -) -from giant_python.spine.summary_io import TrialMap - -from . import synthetic as syn - - -def test_kept_frames_trims_both_ends() -> None: - """The first and last round(trim_s * align_hz) frames are left out.""" - keep = kept_frames(np.zeros(100), align_hz=10.0, trim_s=0.5) - assert not keep[:5].any() and not keep[-5:].any() - assert keep[5:95].all() - - -def test_kept_frames_falls_back_when_too_short() -> None: - """A trial too short to trim keeps its frames that are not discarded.""" - keep = kept_frames(np.zeros(10), align_hz=10.0, trim_s=1.0) - assert keep.all() - - -def test_kept_frames_drops_motion_discards() -> None: - """Frames SiLo discards for motion do not enter.""" - rne = np.zeros(400) - rne[200:204] = 1.0 # a sharp rise of the registration error - keep = kept_frames(rne, align_hz=80.0, trim_s=0.0) - assert not keep[200:204].any() - assert keep[:150].all() - - -def _baseline_file(path: Path, frames: np.ndarray) -> None: - """Write ``frames`` ``(frame, rows, cols)`` as a baseline file.""" - with h5py.File(path, "w") as f: - f["baseline"] = np.transpose(frames, (0, 2, 1)).astype(np.float32) - - -def test_baseline_trial_mean_matches_numpy(tmp_path: Path) -> None: - """The blockwise mean over kept frames equals numpy's, NaN kept out.""" - rng = np.random.default_rng(1) - frames = rng.random((70, 6, 9)) - frames[:, 0, 0] = np.nan # an invalid pixel - path = tmp_path / "b.h5" - _baseline_file(path, frames) - keep = np.ones(70, bool) - keep[::3] = False - mean, n = baseline_trial_mean(path, keep, chunk=8) - assert n == keep.sum() - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) # the NaN pixel - expect = np.nanmean(frames[keep], axis=0) - np.testing.assert_allclose(mean[1:, 1:], expect[1:, 1:], rtol=1e-6) - assert np.isnan(mean[0, 0]) - - -def test_baseline_trial_mean_checks_frame_count(tmp_path: Path) -> None: - """A frame mask of the wrong length is refused.""" - path = tmp_path / "b.h5" - _baseline_file(path, np.ones((10, 3, 3))) - with pytest.raises(ValueError, match="frame flags"): - baseline_trial_mean(path, np.ones(9, bool)) - - -def test_to_consensus_undoes_a_shift() -> None: - """A shifted trial image lands back on the consensus scene.""" - tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]], [[1, 0, 2], [0, 1, -1]]], float)) - scene = syn.scene(1) - trial = np.full_like(scene, np.nan) - trial[2:, :-1] = scene[:-2, 1:] # trial pixel = consensus pixel + (2, -1) - out = to_consensus(trial, tmap, 1, scene.shape) - ok = np.isfinite(out) - assert ok.sum() > 0.8 * ok.size - np.testing.assert_allclose(out[ok], scene[ok]) - - -def test_to_consensus_places_small_trials_top_left() -> None: - """A trial smaller than the frame is padded at the bottom right.""" - tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]]], float)) - img = np.arange(12.0).reshape(3, 4) - out = to_consensus(img, tmap, 0, (5, 6)) - np.testing.assert_array_equal(out[:3, :4], img) - assert np.isnan(out[3:]).all() and np.isnan(out[:, 4:]).all() - - -def test_network_f0_stack_recovers_the_scene(tmp_path: Path) -> None: - """Per-trial F0 images equal the scaled scene where the trial covers it. - - The trimmed frames do not enter. - """ - s = syn.make_session(tmp_path) - tmap = TrialMap(np.stack([[[1, 0, dr], [0, 1, dc]] for dr, dc in syn.SHIFTS]).astype(float)) - stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] - st = network_f0_stack(s["baselines"], s["moco"], stems, tmap, (syn.H, syn.W), trim_s=0.1) - assert st.images.shape == (syn.N_TRIALS, syn.H, syn.W) - assert (st.n_frames == syn.N_FRAMES - 16).all() - for t in range(syn.N_TRIALS): - expect = syn.consensus_trial(1, t) - ok = np.isfinite(st.images[t]) & np.isfinite(expect) - assert ok.sum() > 0.7 * ok.size - # float16 storage of the baseline - np.testing.assert_allclose(st.images[t][ok], expect[ok], rtol=1e-3) - assert st.attrs["checkpoint"] == "synthetic.pt" - assert st.inputs[0]["baseline"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" - - -def test_network_f0_stack_skips_missing_trials(tmp_path: Path) -> None: - """Trials without a stem, a baseline file or a map stay NaN.""" - s = syn.make_session(tmp_path) - affine = np.zeros((syn.N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - affine[2] = np.nan # trial 3 not aligned - stems = ["E1T1DMD1", None, "E1T3DMD1", "missing"] - st = network_f0_stack(s["baselines"], s["moco"], stems, TrialMap(affine), (syn.H, syn.W)) - assert np.isfinite(st.images[0]).any() - assert all(np.isnan(st.images[t]).all() for t in (1, 2, 3)) - assert list(st.n_frames[1:]) == [0, 0, 0] - - -def test_stack_key_changes_with_inputs() -> None: - """The cache key depends on every part.""" - a = stack_key("x", {"trim_s": 1.0}, np.zeros(3)) - assert a == stack_key("x", {"trim_s": 1.0}, np.zeros(3)) - assert a != stack_key("x", {"trim_s": 0.5}, np.zeros(3)) - assert a != stack_key("x", {"trim_s": 1.0}, np.ones(3)) - - -def test_file_identity_keeps_folders_apart(tmp_path: Path) -> None: - """Two files with the same name, size and modification time have different identities. - - The files are in different folders. - """ - import os - - a = tmp_path / "a" / "x.h5" - b = tmp_path / "b" / "x.h5" - for f in (a, b): - f.parent.mkdir() - f.write_bytes(b"same") - os.utime(f, ns=(10**18, 10**18)) - ia, ib = file_identity(a), file_identity(b) - assert {k: ia[k] for k in ("name", "size", "mtime_ns")} == { - k: ib[k] for k in ("name", "size", "mtime_ns") - } - assert ia != ib - - -def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path: Path) -> None: - """The aligned flags are read once, not per trial. - - Reading them is a scan of every trial's map. - """ - s = syn.make_session(tmp_path) - calls = [] - - class CountingMap(TrialMap): - """A trial map that counts reads of its aligned flags.""" - - @property - def aligned(self) -> np.ndarray: - """The flags, counting the read.""" - calls.append(1) - return TrialMap.aligned.fget(self) - - affine = np.zeros((syn.N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] - network_f0_stack(s["baselines"], s["moco"], stems, CountingMap(affine), (syn.H, syn.W)) - assert len(calls) == 1 - - -def test_trim_dropped_flags_untrimmed_trials() -> None: - """trim_dropped says whether kept_frames had to drop the trim.""" - from giant_python.spine.images import trim_dropped - - rne = np.zeros(20) - keep = kept_frames(rne, 10.0, trim_s=0.3) - assert not trim_dropped(keep, 3) - keep = kept_frames(rne, 10.0, trim_s=1.0) # 10 + 10 frames: nothing left - assert keep.all() and trim_dropped(keep, 10) - assert not trim_dropped(keep, 0) +"""Tests of the per-trial F0 images (:mod:`giant_python.spine.images`).""" + +import warnings +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.spine.images import ( + baseline_trial_mean, + file_identity, + kept_frames, + network_f0_stack, + stack_key, + to_consensus, +) +from giant_python.spine.summary_io import TrialMap + +from . import synthetic as syn + + +def test_kept_frames_trims_both_ends() -> None: + """The first and last round(trim_s * align_hz) frames are left out.""" + keep = kept_frames(np.zeros(100), align_hz=10.0, trim_s=0.5) + assert not keep[:5].any() and not keep[-5:].any() + assert keep[5:95].all() + + +def test_kept_frames_falls_back_when_too_short() -> None: + """A trial too short to trim keeps its frames that are not discarded.""" + keep = kept_frames(np.zeros(10), align_hz=10.0, trim_s=1.0) + assert keep.all() + + +def test_kept_frames_drops_motion_discards() -> None: + """Frames SiLo discards for motion do not enter.""" + rne = np.zeros(400) + rne[200:204] = 1.0 # a sharp rise of the registration error + keep = kept_frames(rne, align_hz=80.0, trim_s=0.0) + assert not keep[200:204].any() + assert keep[:150].all() + + +def _baseline_file(path: Path, frames: np.ndarray) -> None: + """Write frames (frame, rows, cols) as a baseline file.""" + with h5py.File(path, "w") as f: + f["baseline"] = np.transpose(frames, (0, 2, 1)).astype(np.float32) + + +def test_baseline_trial_mean_matches_numpy(tmp_path: Path) -> None: + """The blockwise mean over kept frames equals numpy's, NaN kept out.""" + rng = np.random.default_rng(1) + frames = rng.random((70, 6, 9)) + frames[:, 0, 0] = np.nan # an invalid pixel + path = tmp_path / "b.h5" + _baseline_file(path, frames) + keep = np.ones(70, bool) + keep[::3] = False + mean, n = baseline_trial_mean(path, keep, chunk=8) + assert n == keep.sum() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) # the NaN pixel + expect = np.nanmean(frames[keep], axis=0) + np.testing.assert_allclose(mean[1:, 1:], expect[1:, 1:], rtol=1e-6) + assert np.isnan(mean[0, 0]) + + +def test_baseline_trial_mean_checks_frame_count(tmp_path: Path) -> None: + """A frame mask of the wrong length is refused.""" + path = tmp_path / "b.h5" + _baseline_file(path, np.ones((10, 3, 3))) + with pytest.raises(ValueError, match="frame flags"): + baseline_trial_mean(path, np.ones(9, bool)) + + +def test_to_consensus_undoes_a_shift() -> None: + """A shifted trial image lands back on the consensus scene.""" + tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]], [[1, 0, 2], [0, 1, -1]]], float)) + scene = syn.scene(1) + trial = np.full_like(scene, np.nan) + trial[2:, :-1] = scene[:-2, 1:] # trial pixel = consensus pixel + (2, -1) + out = to_consensus(trial, tmap, 1, scene.shape) + ok = np.isfinite(out) + assert ok.sum() > 0.8 * ok.size + np.testing.assert_allclose(out[ok], scene[ok]) + + +def test_to_consensus_places_small_trials_top_left() -> None: + """A trial smaller than the frame is padded at the bottom right.""" + tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]]], float)) + img = np.arange(12.0).reshape(3, 4) + out = to_consensus(img, tmap, 0, (5, 6)) + np.testing.assert_array_equal(out[:3, :4], img) + assert np.isnan(out[3:]).all() and np.isnan(out[:, 4:]).all() + + +def test_network_f0_stack_recovers_the_scene(tmp_path: Path) -> None: + """Per-trial F0 images equal the scaled scene where the trial covers it. + + The trimmed frames do not enter. + """ + s = syn.make_session(tmp_path) + tmap = TrialMap(np.stack([[[1, 0, dr], [0, 1, dc]] for dr, dc in syn.SHIFTS]).astype(float)) + stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] + st = network_f0_stack(s["baselines"], s["moco"], stems, tmap, (syn.H, syn.W), trim_s=0.1) + assert st.images.shape == (syn.N_TRIALS, syn.H, syn.W) + assert (st.n_frames == syn.N_FRAMES - 16).all() + for t in range(syn.N_TRIALS): + expect = syn.consensus_trial(1, t) + ok = np.isfinite(st.images[t]) & np.isfinite(expect) + assert ok.sum() > 0.7 * ok.size + # float16 storage of the baseline + np.testing.assert_allclose(st.images[t][ok], expect[ok], rtol=1e-3) + assert st.attrs["checkpoint"] == "synthetic.pt" + assert st.inputs[0]["baseline"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" + + +def test_network_f0_stack_skips_missing_trials(tmp_path: Path) -> None: + """Trials without a stem, a baseline file or a map stay NaN.""" + s = syn.make_session(tmp_path) + affine = np.zeros((syn.N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + affine[2] = np.nan # trial 3 not aligned + stems = ["E1T1DMD1", None, "E1T3DMD1", "missing"] + st = network_f0_stack(s["baselines"], s["moco"], stems, TrialMap(affine), (syn.H, syn.W)) + assert np.isfinite(st.images[0]).any() + assert all(np.isnan(st.images[t]).all() for t in (1, 2, 3)) + assert list(st.n_frames[1:]) == [0, 0, 0] + + +def test_stack_key_changes_with_inputs() -> None: + """The cache key depends on every part.""" + a = stack_key("x", {"trim_s": 1.0}, np.zeros(3)) + assert a == stack_key("x", {"trim_s": 1.0}, np.zeros(3)) + assert a != stack_key("x", {"trim_s": 0.5}, np.zeros(3)) + assert a != stack_key("x", {"trim_s": 1.0}, np.ones(3)) + + +def test_file_identity_keeps_folders_apart(tmp_path: Path) -> None: + """Two files with the same name, size and modification time have different identities. + + The files are in different folders. + """ + import os + + a = tmp_path / "a" / "x.h5" + b = tmp_path / "b" / "x.h5" + for f in (a, b): + f.parent.mkdir() + f.write_bytes(b"same") + os.utime(f, ns=(10**18, 10**18)) + ia, ib = file_identity(a), file_identity(b) + assert {k: ia[k] for k in ("name", "size", "mtime_ns")} == { + k: ib[k] for k in ("name", "size", "mtime_ns") + } + assert ia != ib + + +def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path: Path) -> None: + """The aligned flags are read once, not per trial. + + Reading them is a scan of every trial's map. + """ + s = syn.make_session(tmp_path) + calls = [] + + class CountingMap(TrialMap): + """A trial map that counts reads of its aligned flags.""" + + @property + def aligned(self) -> np.ndarray: + """The flags, counting the read.""" + calls.append(1) + return TrialMap.aligned.fget(self) + + affine = np.zeros((syn.N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] + network_f0_stack(s["baselines"], s["moco"], stems, CountingMap(affine), (syn.H, syn.W)) + assert len(calls) == 1 + + +def test_trim_dropped_flags_untrimmed_trials() -> None: + """trim_dropped says whether kept_frames had to drop the trim.""" + from giant_python.spine.images import trim_dropped + + rne = np.zeros(20) + keep = kept_frames(rne, 10.0, trim_s=0.3) + assert not trim_dropped(keep, 3) + keep = kept_frames(rne, 10.0, trim_s=1.0) # 10 + 10 frames: nothing left + assert keep.all() and trim_dropped(keep, 10) + assert not trim_dropped(keep, 0) diff --git a/tests/spine/test_spine_pipeline.py b/tests/spine/test_spine_pipeline.py index fd4eeb69..1f45039e 100644 --- a/tests/spine/test_spine_pipeline.py +++ b/tests/spine/test_spine_pipeline.py @@ -1,729 +1,749 @@ -"""End-to-end tests of ``giant spine`` on a synthetic session.""" - -import json -from pathlib import Path -from typing import NoReturn - -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.spine.pipeline import ( - _stem, - _trials_and_window, - make_spine_summary, - table_trials, -) -from giant_python.spine.product import read_product -from giant_python.spine.readout import norm_log -from giant_python.spine.summary_io import RunSummary, TrialMap - -from . import synthetic as syn - - -@pytest.fixture -def session(tmp_path: Path) -> dict[str, Path]: - """Make the synthetic session's folders.""" - return syn.make_session(tmp_path) - - -def test_run_summary_reads_matlab_orientation(session: dict[str, Path]) -> None: - """Arrays come back in MATLAB's dimension order and orientation.""" - run = RunSummary(session["run"]) - assert run.paths == [1, 2] - assert run.shape(1) == (syn.H, syn.W) - assert run.n_channels(1) == 2 - np.testing.assert_allclose(run.profiles(1), syn.footprints(), atol=1e-7) - stack = run.per_trial_images(1, "per_trial_mean_im", 0) - expect = 1.2 * syn.consensus_trial(1, 2) - np.testing.assert_allclose(stack[2], expect) - labels, masks = run.user_rois(1) - assert labels == ["roi A", "roi B"] and masks.shape == (2, syn.H, syn.W) - act = run.activity(1) - np.testing.assert_allclose(act["mean_dF"][:, 0], 10 * np.arange(4) + 4.5) - - -def test_trial_map_needs_a_base_only_for_affine_maps(session: dict[str, Path]) -> None: - """Shift maps need no index base; true affine ones do.""" - run = RunSummary(session["run"]) - tm = run.trial_map(1) - assert isinstance(tm, TrialMap) and tm.displacement is None - r, c = tm.grid_coords(1, (2, 2)) - np.testing.assert_allclose(r, [[1, 1], [2, 2]]) - - -def test_table_trials(session: dict[str, Path]) -> None: - """Stems from the registered movies, numbers from the raw files.""" - stems, acq = table_trials(session["table"], 2) - assert stems[0] == "E1T1DMD2" - np.testing.assert_array_equal(acq, [2, 3, 4, 5]) - - -def test_readout_writes_a_product(session: dict[str, Path], tmp_path: Path) -> None: - """The readout's images, windows and normalized sizes are consistent. - - A rerun reuses the cache and the output. - """ - out = tmp_path / "out" - rep = make_spine_summary( - session["run"], - session["table"], - out, - baseline_dir=session["baselines"], - moco_dir=session["moco"], - trim_s=0.1, - ) - assert not rep["reused"] - prod = read_product(rep["output"]) - p = prod["paths"][1] - assert set(p["images"]) == { - "mean_ch1", - "mean_ch2", - "f0_silo_ch1", - "f0_silo_ch2", - "f0_net", - } - # the network image equals the run's own F0 image (same scene) - ok = p["valid"] - np.testing.assert_allclose( - p["images"]["f0_net"][:, ok], - p["images"]["f0_silo_ch1"][:, ok], - rtol=1e-3, - ) - # a scene scaled per trial: every source's normalized size is 0 - norm = p["normalized"]["sources"] - assert norm["ok"].all() - np.testing.assert_allclose(norm["f0_net"], 0, atol=2e-3) - np.testing.assert_allclose( - norm["f0_silo_ch1"], - norm_log(p["readout"]["sources"]["f0_silo_ch1"]), - ) - user, user_any = p["readout"]["user"], p["readout"]["user_any"] - assert (user["n_pixels"] > 0).all() - assert "coverage_f0_net" in user_any and "coverage_f0_net" not in user - # the MATLAB-style readout reaches pixels outside the common windows - assert (user_any["coverage_f0_net"] >= 0).all() - assert p["trials"]["acquisition"].tolist() == [2, 3, 4, 5] - assert p["rois"]["sources"].labels[0] == "source 0" - rep2 = make_spine_summary( - session["run"], - session["table"], - out, - baseline_dir=session["baselines"], - moco_dir=session["moco"], - trim_s=0.1, - ) - assert rep2["reused"] and rep2["output"] == rep["output"] - rep3 = make_spine_summary( - session["run"], - session["table"], - out, - baseline_dir=session["baselines"], - moco_dir=session["moco"], - trim_s=0.2, - ) - assert rep3["output"] != rep["output"] - assert not rep3["paths"][1]["f0_reused"] - - -def test_cli_readout_and_images( - session: dict[str, Path], tmp_path: Path, capsys: pytest.CaptureFixture[str] -) -> None: - """``giant spine images`` fills the cache that ``readout`` reuses.""" - out = tmp_path / "cli" - common = [ - str(session["run"]), - "--table", - str(session["table"]), - "--baseline-dir", - str(session["baselines"]), - "--moco-dir", - str(session["moco"]), - "--out-dir", - str(out), - "--trim-s", - "0.1", - "--quiet", - ] - assert main(["spine", "images"] + common) == 0 - rep = json.loads(capsys.readouterr().out) - assert not rep["paths"]["1"]["f0_reused"] - assert main(["spine", "readout"] + common + ["--paths", "1"]) == 0 - rep = json.loads(capsys.readouterr().out) - assert rep["paths"]["1"]["f0_reused"] and list(rep["paths"]) == ["1"] - - -def test_readout_without_baselines(tmp_path: Path) -> None: - """Without baselines the run's own images are read out.""" - s = syn.make_session(tmp_path, with_f0_silo=False) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") - p = read_product(rep["output"])["paths"][2] - assert set(p["images"]) == {"mean_ch1", "mean_ch2"} - - -def test_baselines_need_the_moco_folder(session: dict[str, Path], tmp_path: Path) -> None: - """A baseline folder without the motion-correction folder is refused.""" - with pytest.raises(ValueError, match="both"): - make_spine_summary( - session["run"], - session["table"], - tmp_path, - baseline_dir=session["baselines"], - ) - - -def test_activity_uses_the_activity_channel(tmp_path: Path) -> None: - """Activity comes from ``params/activityChannel``. - - A trial without traces is NaN, not inactive. - """ - s = syn.make_session(tmp_path, activity_channel=2, missing_trial=1) - run = RunSummary(s["run"]) - assert run.activity_channel() == 2 - act = run.activity(1) - np.testing.assert_allclose(act["mean_dF"][[0, 2, 3], 0], 1000 + 10 * np.array([0, 2, 3]) + 4.5) - np.testing.assert_allclose(act["event_frames"][[0, 2, 3], 0], 10) - assert np.isnan(act["mean_dF"][1]).all() - assert np.isnan(act["event_frames"][1]).all() - - -def test_summary_key_follows_the_paths(tmp_path: Path) -> None: - """Different path selections give different summaries.""" - s = syn.make_session(tmp_path) - keys = { - tuple(sel or ()): make_spine_summary(s["run"], s["table"], tmp_path / "out", paths=sel)[ - "key" - ] - for sel in (None, [1], [2]) - } - assert len(set(keys.values())) == 3 - - -def test_network_images_take_a_trial_warp(session: dict[str, Path], tmp_path: Path) -> None: - """The extraction plan's TrialWarp works as the trial map.""" - from giant_python.extraction.raster.alignment import TrialWarp - from giant_python.spine.images import network_f0_stack - - run = RunSummary(session["run"]) - tmap = run.trial_map(1) - stems, _ = table_trials(session["table"], 1) - args = (session["baselines"], session["moco"], stems) - a = network_f0_stack(*args, tmap, run.shape(1), trim_s=0.1) - b = network_f0_stack(*args, TrialWarp(tmap.affine), run.shape(1), trim_s=0.1) - np.testing.assert_allclose(a.images, b.images, equal_nan=True) - assert np.isfinite(a.images).any() - - -def test_write_atomic_gives_each_writer_its_own_file(tmp_path: Path) -> None: - """A writer that starts while another is writing the same file has its own temporary file. - - It does not share the other's temporary file; both finish, and nothing is - left behind. A failed write leaves no file. - """ - from giant_python.spine.pipeline import _write_atomic - - dest = tmp_path / "out" / "x.txt" - - def outer(tmp: Path) -> None: - """Write, with a second writer of the same file in between.""" - tmp.write_text("outer") - _write_atomic(dest, lambda t: t.write_text("inner")) - assert tmp.read_text() == "outer" - - _write_atomic(dest, outer) - assert dest.read_text() == "outer" - assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] - - def fail(tmp: Path) -> NoReturn: - """Write partially, then fail.""" - tmp.write_text("partial") - raise RuntimeError("stop") - - other = tmp_path / "out" / "y.txt" - with pytest.raises(RuntimeError): - _write_atomic(other, fail) - assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] - - -def test_stem_strips_windows_folders() -> None: - """A table written on Windows gives the bare stem on any system.""" - name = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" - assert _stem("C:\\moco\\" + name) == "E1T1DMD1" - assert _stem("/data/moco/" + name) == "E1T1DMD1" - assert _stem("E1T1DMD1.tif") is None - - -def test_network_images_follow_the_runs_discards(tmp_path: Path) -> None: - """Without overrides the network images leave out the frames the run discarded. - - These are ``params/discardInitial_s``; an explicit value wins. - """ - s = syn.make_session(tmp_path, discard_initial_s=0.5) - kw = dict(baseline_dir=s["baselines"], moco_dir=s["moco"], trim_s=0.1) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "a", **kw) - prod = read_product(rep["output"]) - assert prod["attrs"]["settings"]["discard_initial_s"] == 0.5 - n_run = prod["paths"][1]["image_attrs"]["f0_net"]["n_frames"] - # 40 discarded frames at the start, 8 trimmed at the end - assert (n_run == syn.N_FRAMES - 48).all() - rep0 = make_spine_summary(s["run"], s["table"], tmp_path / "b", discard_initial_s=0.0, **kw) - n0 = read_product(rep0["output"])["paths"][1]["image_attrs"]["f0_net"] - assert (n0["n_frames"] == syn.N_FRAMES - 16).all() - - -def test_affine_maps_convert_from_one_based(tmp_path: Path) -> None: - """A true affine map written one-based gives the same positions as the zero-based map. - - The one-based map is GIAnT-MATLAB's, the zero-based one GIAnT-Python's; - both give the same zero-based positions. - """ - lin = np.array([[1.01, 0.02], [-0.015, 0.99]]) - b0 = np.array([1.5, -2.25]) - a0 = np.zeros((syn.N_TRIALS, 2, 3)) - a0[:, :, :2] = lin - a0[:, :, 2] = b0 - # one-based: r1 = A r1' + b1 with r1 = r0 + 1 on both sides - a1 = a0.copy() - a1[:, :, 2] = b0 - lin[:, 0] - lin[:, 1] + 1 - shape = (3, 4) - rr, cc = np.meshgrid(np.arange(3.0), np.arange(4.0), indexing="ij") - expect_r = lin[0, 0] * rr + lin[0, 1] * cc + b0[0] - expect_c = lin[1, 0] * rr + lin[1, 1] * cc + b0[1] - for base, a in ((0, a0), (1, a1)): - s = syn.make_session(tmp_path / f"base{base}", affine=a) - run = RunSummary(s["run"]) - with pytest.raises(ValueError, match="index base"): - run.trial_map(1) - r, c = run.trial_map(1, affine_base=base).grid_coords(2, shape) - np.testing.assert_allclose(r, expect_r, atol=1e-12) - np.testing.assert_allclose(c, expect_c, atol=1e-12) - - -def test_product_records_the_activity_channel(tmp_path: Path) -> None: - """The product says which file channel is the run's activity.""" - s = syn.make_session(tmp_path, activity_channel=2) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "out") - prod = read_product(rep["output"]) - assert prod["paths"][1]["activity_channel"] == 2 - assert {"mean_ch1", "mean_ch2"} <= set(prod["paths"][1]["images"]) - - -def test_displacement_maps_end_to_end(tmp_path: Path) -> None: - """A run with a displacement field puts the network's trials in place through the field. - - The field comes from the patchwise alignment; the affine maps are not used. - """ - kw = dict(trim_s=0.1) - s = syn.make_session(tmp_path / "d", displacement=True) - run = RunSummary(s["run"]) - assert run.trial_map(1).displacement is not None - rep = make_spine_summary( - s["run"], - s["table"], - tmp_path / "d" / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - **kw, - ) - p = read_product(rep["output"])["paths"][1] - ok = p["valid"] - assert ok.sum() > 0.5 * ok.size - np.testing.assert_allclose( - p["images"]["f0_net"][:, ok], - p["images"]["f0_silo_ch1"][:, ok], - rtol=1e-3, - ) - np.testing.assert_allclose(p["normalized"]["sources"]["f0_net"], 0, atol=2e-3) - # the same maps as affine identity alone leave the trials displaced - a = np.zeros((syn.N_TRIALS, 2, 3)) - a[:, :, :2] = np.eye(2) - s0 = syn.make_session(tmp_path / "a", affine=a) - rep0 = make_spine_summary( - s0["run"], - s0["table"], - tmp_path / "a" / "out", - baseline_dir=s0["baselines"], - moco_dir=s0["moco"], - **kw, - ) - p0 = read_product(rep0["output"])["paths"][1] - ok0 = p0["valid"] - net = p0["images"]["f0_net"][1:, ok0] - assert np.abs(net / p0["images"]["f0_silo_ch1"][1:, ok0] - 1).max() > 1e-2 - - -def test_fitted_images_do_not_shrink_the_windows(tmp_path: Path) -> None: - """SILo's own F0 images are read out in the windows of the field images. - - The images have values only at the pixels SILo fitted. The sources (inside - the fitted pixels) read as before, a user ROI partly outside keeps its - readouts of the other images and gets NaN in f0_silo, and the report - counts it. - """ - kw = dict(trim_s=0.1) - full = syn.make_session(tmp_path / "full") - box = syn.make_session(tmp_path / "box", f0_silo_box=(slice(4, 20), slice(5, 25))) - reps, prods = {}, {} - for name, s in (("full", full), ("box", box)): - reps[name] = make_spine_summary( - s["run"], - s["table"], - tmp_path / name / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - **kw, - ) - prods[name] = read_product(reps[name]["output"])["paths"][1] - a, b = prods["full"], prods["box"] - np.testing.assert_array_equal(a["valid"], b["valid"]) - for k in a["readout"]["sources"]: - np.testing.assert_allclose(a["readout"]["sources"][k], b["readout"]["sources"][k]) - for k in a["normalized"]["sources"]: - np.testing.assert_allclose(a["normalized"]["sources"][k], b["normalized"]["sources"][k]) - ua, ub = a["readout"]["user"], b["readout"]["user"] - np.testing.assert_array_equal(ua["n_pixels"], ub["n_pixels"]) - np.testing.assert_allclose(ua["f0_net"], ub["f0_net"]) - assert np.isnan(ub["f0_silo_ch1"][:, 0]).all() # roi A: partly outside - np.testing.assert_allclose(ub["f0_silo_ch1"][:, 1], ua["f0_silo_ch1"][:, 1]) - assert reps["box"]["paths"][1]["not_covered"] == {"user": {"f0_silo_ch1": 1, "f0_silo_ch2": 1}} - assert "not_covered" not in reps["full"]["paths"][1] - assert b["image_attrs"]["f0_silo_ch1"]["covers"] == "fitted" - assert b["image_attrs"]["f0_net"]["covers"] == "field" - # a reused file gives the same report and the same notes again - notes = [] - again = make_spine_summary( - box["run"], - box["table"], - tmp_path / "box" / "out", - baseline_dir=box["baselines"], - moco_dir=box["moco"], - progress=notes.append, - **kw, - ) - assert again["reused"] - for k in ("not_covered", "window_images", "trials_used", "valid_pixels"): - assert again["paths"][1][k] == reps["box"]["paths"][1][k] - assert sum("does not cover" in m for m in notes) == 4 # 2 images x 2 paths - - -def test_no_shared_trial_reads_nothing() -> None: - """Field images without a trial in common leave no trial and no valid pixel. - - They leave a note, rather than windows over the whole frame. - """ - from giant_python.spine.readout import common_valid - - a = np.ones((4, 3, 3)) - b = np.ones((4, 3, 3)) - a[2:] = np.nan - b[:2] = np.nan - images = { - "mean_ch1": (a, {"covers": "field"}), - "f0_net": (b, {"covers": "field"}), - } - notes = [] - used, window = _trials_and_window(1, images, np.full(4, 10), notes.append) - assert used.size == 0 and window == ["mean_ch1", "f0_net"] - assert any("nothing is read out" in m for m in notes) - assert not common_valid([a, b], used).any() - - -def test_acquisition_numbers_from_the_file_name(tmp_path: Path) -> None: - """The acquisition number is read from the raw file's own name. - - Not from a folder that also says TRIAL, with either separator; and a table - whose raw and registered lists differ in length is refused. - """ - from giant_python.io.hdf5 import save_struct_h5 - - reg = np.array( - [[f"E1T{t}DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in (1, 2)]], - dtype=object, - ) - raw = np.array( - [ - [ - "C:\\TRIAL09\\activity_x_DMD1-TRIAL000002.dat", - "/data/TRIAL09/activity_x_DMD1-TRIAL000003.dat", - ] - ], - dtype=object, - ) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(tmp_path), - "savedr": str(tmp_path), - "filename": raw, - "motion_correction": {"fn_reg_ds": reg}, - }, - ) - stems, acq = table_trials(table, 1) - assert stems == ["E1T1DMD1", "E1T2DMD1"] - np.testing.assert_array_equal(acq, [2, 3]) - save_struct_h5( - table, - { - "datadr": str(tmp_path), - "savedr": str(tmp_path), - "filename": raw[:, :1], - "motion_correction": {"fn_reg_ds": reg}, - }, - ) - with pytest.raises(ValueError, match="1 raw files but 2"): - table_trials(table, 1) - - -def test_untrimmed_trials_are_reported(session: dict[str, Path], tmp_path: Path) -> None: - """A trial too short for the trim is averaged whole, as GIAnT-MATLAB does. - - The product, the report and a note say so. - """ - notes = [] - kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"]) - # 160 frames: a 1 s trim at 80 Hz leaves nothing - rep = make_spine_summary( - session["run"], - session["table"], - tmp_path / "long", - trim_s=1.0, - progress=notes.append, - **kw, - ) - p = read_product(rep["output"])["paths"][1] - attrs = p["image_attrs"]["f0_net"] - assert attrs["untrimmed"].astype(bool).all() - assert (attrs["n_frames"] == syn.N_FRAMES).all() - assert rep["paths"][1]["f0_untrimmed"] == [1, 2, 3, 4] - assert sum("too short for the trim" in m for m in notes) == 2 - rep = make_spine_summary(session["run"], session["table"], tmp_path / "short", trim_s=0.1, **kw) - p = read_product(rep["output"])["paths"][1] - assert not p["image_attrs"]["f0_net"]["untrimmed"].any() - assert "f0_untrimmed" not in rep["paths"][1] - - -def test_readout_runs_the_trend_tests(session: dict[str, Path], tmp_path: Path) -> None: - """Every normalized image gets the trend tests over its trials. - - Trial positions are trial-table indices; the test settings change the - output's key but not the network images' cache. - """ - from giant_python.spine.trends import trend_tests - - kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1) - rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) - p = read_product(rep["output"])["paths"][1] - norm = p["normalized"]["sources"] - tr = p["trends"]["sources"] - assert set(tr) == set(norm) - {"ok"} - rec = tr["f0_net"] - rows = rec["trials"] - np.testing.assert_array_equal(rows, np.arange(syn.N_TRIALS)) - direct = trend_tests( - norm["f0_net"][rows], - norm["ok"], - p["trials"]["acquisition"][rows], - n_perm=200, - ) - tested = direct["tested"] - assert tested.any() - np.testing.assert_array_equal(rec["tested"], tested) - for k in ("step_t", "step_p", "brief_t", "resid_p", "shared_r"): - np.testing.assert_array_equal(rec[k], direct[k]) - # positions as trial-table indices where a split or a run was found, - # -1 elsewhere - step = tested & (direct["step_k"] > 0) - assert step.any() - np.testing.assert_array_equal(rec["step_after"][step], rows[direct["step_k"][step] - 1]) - assert (rec["step_after"][~step] == -1).all() - run = tested & (direct["brief_start"] >= 0) - np.testing.assert_array_equal(rec["brief_first"][run], rows[direct["brief_start"][run]]) - assert (rec["brief_first"][~run] == -1).all() - np.testing.assert_array_equal(rec["brief_len"][tested & ~run], 0) - assert rec["attrs"]["n_perm"] == 200 - assert rec["attrs"]["var_share"] == pytest.approx(direct["var_share"]) - summ = rep["paths"][1]["trends"]["f0_net"] - assert summ["tested"] == int(tested.sum()) - assert summ["counts"] == direct["counts"] - rep2 = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=0, **kw) - assert rep2["output"] != rep["output"] and not rep2["reused"] - assert rep2["paths"][1]["f0_reused"] - p2 = read_product(rep2["output"])["paths"][1] - assert np.isnan(p2["trends"]["sources"]["f0_net"]["step_p"]).all() - - -def test_readout_refuses_bad_trend_settings(session: dict[str, Path], tmp_path: Path) -> None: - """Invalid trend settings are refused before anything is read or reused.""" - with pytest.raises(ValueError, match="fdr_q"): - make_spine_summary(session["run"], session["table"], tmp_path / "o", fdr_q=2.0) - with pytest.raises(ValueError, match="min_change"): - make_spine_summary(session["run"], session["table"], tmp_path / "o", min_change=1.5) - assert not (tmp_path / "o").exists() - - -def test_trials_without_numbers_are_noted( - session: dict[str, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A trial whose raw file has no acquisition number is left out of the brief test's runs. - - The summary's notes say so. - """ - import giant_python.spine.pipeline as pl - - real = pl.table_trials - - def no_number(table: Path, path: int) -> tuple[list, np.ndarray]: - """Return the table's trials with trial 2 unnumbered.""" - stems, acq = real(table, path) - acq = acq.copy() - acq[1] = -1 - return stems, acq - - monkeypatch.setattr(pl, "table_trials", no_number) - notes = [] - rep = make_spine_summary( - session["run"], - session["table"], - tmp_path / "o", - n_perm=0, - progress=notes.append, - ) - assert sum("trial(s) 2 have no acquisition number" in m for m in notes) - p = read_product(rep["output"])["paths"][1] - blocks = p["trends"]["sources"]["mean_ch1"]["blocks"] - assert blocks[1] != blocks[0] and blocks[1] != blocks[2] - - -def test_unnumbered_trials_follow_the_path_not_the_image() -> None: - """With some numbered trials on the path, unnumbered trials stay blocks of their own. - - This holds even in an image that covers only them; with no numbers on the - path, the table's order stands in (gaps split). - """ - from giant_python.spine.pipeline import _trends - - vals = np.random.default_rng(0).normal(size=(6, 4)) * 0.1 - norm = {"img": vals.copy(), "ok": np.ones(4, bool)} - norm["img"][[0, 1]] = np.nan # the image covers trials 2-5 only - opts = dict(n_perm=0, fdr_q=0.1, max_brief=3, seed=1, min_change=0.1) - acq = np.array([3, 4, -1, -1, -1, -1]) - tr, _ = _trends(1, norm, acq, opts, 1, lambda m: None, lambda m: None) - np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, 1, 2, 3]) - norm["img"][3] = np.nan # a gap in table order - tr, _ = _trends(1, norm, np.full(6, -1), opts, 1, lambda m: None, lambda m: None) - np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, -1, 1, 1]) - - -def test_readout_calls_and_quality_columns( - session: dict[str, Path], tmp_path: Path, capsys: pytest.CaptureFixture[str] -) -> None: - """The default image and its calls go into the summary and the report. - - Every image but the structural one gets the structural channel's change - at its own split; the windows' motion beyond the trials' shifts is 0 for - shifts. - """ - from giant_python.spine.qc import structural_change - - kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1) - rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) - p = read_product(rep["output"])["paths"][1] - assert p["primary_image"] == "f0_net" - np.testing.assert_allclose(p["readout"]["sources"]["align_px"], 0, atol=1e-9) - norm = p["normalized"]["sources"] - tr = p["trends"]["sources"] - assert "structural_d" not in tr["mean_ch2"] - for name in ("f0_net", "mean_ch1", "f0_silo_ch1"): - rec = tr[name] - assert rec["attrs"]["structural_image"] == "mean_ch2" - assert rec["attrs"]["min_change"] == pytest.approx(0.1) - rows = rec["trials"] - k = np.full(len(rec["tested"]), -1) - has = rec["resid_after"] >= 0 - k[has] = np.searchsorted(rows, rec["resid_after"][has]) + 1 - np.testing.assert_allclose( - rec["structural_d"], - structural_change(norm["mean_ch2"][rows], norm["ok"], k), - ) - expect = ( - rec["tested"] - & (rec["resid_q"] <= 0.1) - & (np.abs(np.expm1(np.nan_to_num(rec["resid_d"]))) >= 0.1) - ) - np.testing.assert_array_equal(rec["call"], expect) - calls = rep["paths"][1]["calls"] - assert calls["image"] == "f0_net" and calls["min_change"] == 0.1 - ids = read_product(rep["output"])["paths"][1]["rois"]["sources"].ids - c = tr["f0_net"]["call"] - d = tr["f0_net"]["resid_d"] - assert calls["up"] == [int(i) + 1 for i in ids[c & (d > 0)]] - assert calls["down"] == [int(i) + 1 for i in ids[c & (d < 0)]] - assert rep["paths"][1]["trends"]["f0_net"]["counts"]["call"] == { - "up": len(calls["up"]), - "down": len(calls["down"]), - } - # the minimum change is a setting of the command (and of the key) - args = [ - str(session["run"]), - "--table", - str(session["table"]), - "--out-dir", - str(tmp_path / "cli"), - "--n-perm", - "0", - "--min-change", - "0.25", - "--quiet", - ] - assert main(["spine", "readout"] + args) == 0 - out = json.loads(capsys.readouterr().out)["output"] - pr = read_product(out) - assert pr["attrs"]["settings"]["trends"]["min_change"] == 0.25 - assert pr["paths"][1]["primary_image"] == "f0_silo_ch1" - - -def test_window_motion_needs_no_affine_base(tmp_path: Path) -> None: - """Affine maps without a given index base still get the column. - - The base moves only the translation. - """ - a = np.zeros((syn.N_TRIALS, 2, 3)) - for t, ang in enumerate((0.0, 0.01, -0.01, 0.02)): - c, s_ = np.cos(ang), np.sin(ang) - a[t] = [[c, -s_, syn.SHIFTS[t][0]], [s_, c, syn.SHIFTS[t][1]]] - s = syn.make_session(tmp_path / "a", affine=a) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "a" / "o") - m = read_product(rep["output"])["paths"][1]["readout"]["sources"]["align_px"] - assert np.isfinite(m).all() and (m > 0).all() - - -def test_default_image_without_trend_tests(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """With too few trials for the trend tests, the default image still comes from sizes. - - It comes from the images with sizes (here the run's F0 of activity - channel 2), and no calls are reported. - """ - import giant_python.spine.pipeline as pl - - monkeypatch.setattr(pl, "_trends", lambda *a, **k: ({}, {})) - s = syn.make_session(tmp_path, activity_channel=2) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") - p = read_product(rep["output"])["paths"][1] - assert "f0_silo_ch2" in p["normalized"]["sources"] - assert p["primary_image"] == "f0_silo_ch2" - assert "calls" not in rep["paths"][1] - - -def test_default_image_needs_finite_sizes(tmp_path: Path) -> None: - """An image that covers no window keeps its key with only NaN sizes. - - It is not the default (here the run's F0 limited to a corner, so the - activity channel's mean takes its place). - """ - s = syn.make_session(tmp_path, f0_silo_box=(slice(0, 2), slice(0, 2))) - rep = make_spine_summary(s["run"], s["table"], tmp_path / "o", n_perm=50) - p = read_product(rep["output"])["paths"][1] - assert np.isnan(p["normalized"]["sources"]["f0_silo_ch1"]).all() - assert p["primary_image"] == "mean_ch1" - assert rep["paths"][1]["calls"]["image"] == "mean_ch1" +"""End-to-end tests of giant spine on a synthetic session.""" + +import json +from pathlib import Path +from typing import NoReturn + +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.spine.pipeline import ( + _stem, + _trials_and_window, + make_spine_summary, + table_trials, +) +from giant_python.spine.product import read_product +from giant_python.spine.readout import norm_log +from giant_python.spine.summary_io import RunSummary, TrialMap + +from . import synthetic as syn + + +@pytest.fixture +def session(tmp_path: Path) -> dict[str, Path]: + """Make the synthetic session's folders. + + Returns + ------- + dict[str, Path] + The session's folders and files by name (including run and table). + """ + return syn.make_session(tmp_path) + + +def test_run_summary_reads_matlab_orientation(session: dict[str, Path]) -> None: + """Arrays come back in MATLAB's dimension order and orientation.""" + run = RunSummary(session["run"]) + assert run.paths == [1, 2] + assert run.shape(1) == (syn.H, syn.W) + assert run.n_channels(1) == 2 + np.testing.assert_allclose(run.profiles(1), syn.footprints(), atol=1e-7) + stack = run.per_trial_images(1, "per_trial_mean_im", 0) + expect = 1.2 * syn.consensus_trial(1, 2) + np.testing.assert_allclose(stack[2], expect) + labels, masks = run.user_rois(1) + assert labels == ["roi A", "roi B"] and masks.shape == (2, syn.H, syn.W) + act = run.activity(1) + np.testing.assert_allclose(act["mean_dF"][:, 0], 10 * np.arange(4) + 4.5) + + +def test_trial_map_needs_a_base_only_for_affine_maps(session: dict[str, Path]) -> None: + """Shift maps need no index base; true affine ones do.""" + run = RunSummary(session["run"]) + tm = run.trial_map(1) + assert isinstance(tm, TrialMap) and tm.displacement is None + r, c = tm.grid_coords(1, (2, 2)) + np.testing.assert_allclose(r, [[1, 1], [2, 2]]) + + +def test_table_trials(session: dict[str, Path]) -> None: + """Stems from the registered movies, numbers from the raw files.""" + stems, acq = table_trials(session["table"], 2) + assert stems[0] == "E1T1DMD2" + np.testing.assert_array_equal(acq, [2, 3, 4, 5]) + + +def test_readout_writes_a_product(session: dict[str, Path], tmp_path: Path) -> None: + """The readout's images, windows and normalized sizes are consistent. + + A rerun reuses the cache and the output. + """ + out = tmp_path / "out" + rep = make_spine_summary( + session["run"], + session["table"], + out, + baseline_dir=session["baselines"], + moco_dir=session["moco"], + trim_s=0.1, + ) + assert not rep["reused"] + prod = read_product(rep["output"]) + p = prod["paths"][1] + assert set(p["images"]) == { + "mean_ch1", + "mean_ch2", + "f0_silo_ch1", + "f0_silo_ch2", + "f0_net", + } + # the network image equals the run's own F0 image (same scene) + ok = p["valid"] + np.testing.assert_allclose( + p["images"]["f0_net"][:, ok], + p["images"]["f0_silo_ch1"][:, ok], + rtol=1e-3, + ) + # a scene scaled per trial: every source's normalized size is 0 + norm = p["normalized"]["sources"] + assert norm["ok"].all() + np.testing.assert_allclose(norm["f0_net"], 0, atol=2e-3) + np.testing.assert_allclose( + norm["f0_silo_ch1"], + norm_log(p["readout"]["sources"]["f0_silo_ch1"]), + ) + user, user_any = p["readout"]["user"], p["readout"]["user_any"] + assert (user["n_pixels"] > 0).all() + assert "coverage_f0_net" in user_any and "coverage_f0_net" not in user + # the MATLAB-style readout reaches pixels outside the common windows + assert (user_any["coverage_f0_net"] >= 0).all() + assert p["trials"]["acquisition"].tolist() == [2, 3, 4, 5] + assert p["rois"]["sources"].labels[0] == "source 0" + rep2 = make_spine_summary( + session["run"], + session["table"], + out, + baseline_dir=session["baselines"], + moco_dir=session["moco"], + trim_s=0.1, + ) + assert rep2["reused"] and rep2["output"] == rep["output"] + rep3 = make_spine_summary( + session["run"], + session["table"], + out, + baseline_dir=session["baselines"], + moco_dir=session["moco"], + trim_s=0.2, + ) + assert rep3["output"] != rep["output"] + assert not rep3["paths"][1]["f0_reused"] + + +def test_cli_readout_and_images( + session: dict[str, Path], tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """``giant spine images`` fills the cache that readout reuses.""" + out = tmp_path / "cli" + common = [ + str(session["run"]), + "--table", + str(session["table"]), + "--baseline-dir", + str(session["baselines"]), + "--moco-dir", + str(session["moco"]), + "--out-dir", + str(out), + "--trim-s", + "0.1", + "--quiet", + ] + assert main(["spine", "images"] + common) == 0 + rep = json.loads(capsys.readouterr().out) + assert not rep["paths"]["1"]["f0_reused"] + assert main(["spine", "readout"] + common + ["--paths", "1"]) == 0 + rep = json.loads(capsys.readouterr().out) + assert rep["paths"]["1"]["f0_reused"] and list(rep["paths"]) == ["1"] + + +def test_readout_without_baselines(tmp_path: Path) -> None: + """Without baselines the run's own images are read out.""" + s = syn.make_session(tmp_path, with_f0_silo=False) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") + p = read_product(rep["output"])["paths"][2] + assert set(p["images"]) == {"mean_ch1", "mean_ch2"} + + +def test_baselines_need_the_moco_folder(session: dict[str, Path], tmp_path: Path) -> None: + """A baseline folder without the motion-correction folder is refused.""" + with pytest.raises(ValueError, match="both"): + make_spine_summary( + session["run"], + session["table"], + tmp_path, + baseline_dir=session["baselines"], + ) + + +def test_activity_uses_the_activity_channel(tmp_path: Path) -> None: + """Activity comes from params/activityChannel. + + A trial without traces is NaN, not inactive. + """ + s = syn.make_session(tmp_path, activity_channel=2, missing_trial=1) + run = RunSummary(s["run"]) + assert run.activity_channel() == 2 + act = run.activity(1) + np.testing.assert_allclose(act["mean_dF"][[0, 2, 3], 0], 1000 + 10 * np.array([0, 2, 3]) + 4.5) + np.testing.assert_allclose(act["event_frames"][[0, 2, 3], 0], 10) + assert np.isnan(act["mean_dF"][1]).all() + assert np.isnan(act["event_frames"][1]).all() + + +def test_summary_key_follows_the_paths(tmp_path: Path) -> None: + """Different path selections give different summaries.""" + s = syn.make_session(tmp_path) + keys = { + tuple(sel or ()): make_spine_summary(s["run"], s["table"], tmp_path / "out", paths=sel)[ + "key" + ] + for sel in (None, [1], [2]) + } + assert len(set(keys.values())) == 3 + + +def test_network_images_take_a_trial_warp(session: dict[str, Path], tmp_path: Path) -> None: + """The extraction plan's TrialWarp works as the trial map.""" + from giant_python.extraction.raster.alignment import TrialWarp + from giant_python.spine.images import network_f0_stack + + run = RunSummary(session["run"]) + tmap = run.trial_map(1) + stems, _ = table_trials(session["table"], 1) + args = (session["baselines"], session["moco"], stems) + a = network_f0_stack(*args, tmap, run.shape(1), trim_s=0.1) + b = network_f0_stack(*args, TrialWarp(tmap.affine), run.shape(1), trim_s=0.1) + np.testing.assert_allclose(a.images, b.images, equal_nan=True) + assert np.isfinite(a.images).any() + + +def test_write_atomic_gives_each_writer_its_own_file(tmp_path: Path) -> None: + """A writer that starts while another is writing the same file has its own temporary file. + + It does not share the other's temporary file; both finish, and nothing is + left behind. A failed write leaves no file. + """ + from giant_python.spine.pipeline import _write_atomic + + dest = tmp_path / "out" / "x.txt" + + def outer(tmp: Path) -> None: + """Write, with a second writer of the same file in between.""" + tmp.write_text("outer") + _write_atomic(dest, lambda t: t.write_text("inner")) + assert tmp.read_text() == "outer" + + _write_atomic(dest, outer) + assert dest.read_text() == "outer" + assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] + + def fail(tmp: Path) -> NoReturn: + """Write partially, then fail. + + Raises + ------ + RuntimeError + Always, after writing the partial file. + """ + tmp.write_text("partial") + raise RuntimeError("stop") + + other = tmp_path / "out" / "y.txt" + with pytest.raises(RuntimeError): + _write_atomic(other, fail) + assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] + + +def test_stem_strips_windows_folders() -> None: + """A table written on Windows gives the bare stem on any system.""" + name = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" + assert _stem("C:\\moco\\" + name) == "E1T1DMD1" + assert _stem("/data/moco/" + name) == "E1T1DMD1" + assert _stem("E1T1DMD1.tif") is None + + +def test_network_images_follow_the_runs_discards(tmp_path: Path) -> None: + """Without overrides the network images leave out the frames the run discarded. + + These are params/discardInitial_s; an explicit value wins. + """ + s = syn.make_session(tmp_path, discard_initial_s=0.5) + kw = dict(baseline_dir=s["baselines"], moco_dir=s["moco"], trim_s=0.1) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "a", **kw) + prod = read_product(rep["output"]) + assert prod["attrs"]["settings"]["discard_initial_s"] == 0.5 + n_run = prod["paths"][1]["image_attrs"]["f0_net"]["n_frames"] + # 40 discarded frames at the start, 8 trimmed at the end + assert (n_run == syn.N_FRAMES - 48).all() + rep0 = make_spine_summary(s["run"], s["table"], tmp_path / "b", discard_initial_s=0.0, **kw) + n0 = read_product(rep0["output"])["paths"][1]["image_attrs"]["f0_net"] + assert (n0["n_frames"] == syn.N_FRAMES - 16).all() + + +def test_affine_maps_convert_from_one_based(tmp_path: Path) -> None: + """A true affine map written one-based gives the same positions as the zero-based map. + + The one-based map is GIAnT-MATLAB's, the zero-based one GIAnT-Python's; + both give the same zero-based positions. + """ + lin = np.array([[1.01, 0.02], [-0.015, 0.99]]) + b0 = np.array([1.5, -2.25]) + a0 = np.zeros((syn.N_TRIALS, 2, 3)) + a0[:, :, :2] = lin + a0[:, :, 2] = b0 + # one-based: r1 = A r1' + b1 with r1 = r0 + 1 on both sides + a1 = a0.copy() + a1[:, :, 2] = b0 - lin[:, 0] - lin[:, 1] + 1 + shape = (3, 4) + rr, cc = np.meshgrid(np.arange(3.0), np.arange(4.0), indexing="ij") + expect_r = lin[0, 0] * rr + lin[0, 1] * cc + b0[0] + expect_c = lin[1, 0] * rr + lin[1, 1] * cc + b0[1] + for base, a in ((0, a0), (1, a1)): + s = syn.make_session(tmp_path / f"base{base}", affine=a) + run = RunSummary(s["run"]) + with pytest.raises(ValueError, match="index base"): + run.trial_map(1) + r, c = run.trial_map(1, affine_base=base).grid_coords(2, shape) + np.testing.assert_allclose(r, expect_r, atol=1e-12) + np.testing.assert_allclose(c, expect_c, atol=1e-12) + + +def test_product_records_the_activity_channel(tmp_path: Path) -> None: + """The product says which file channel is the run's activity.""" + s = syn.make_session(tmp_path, activity_channel=2) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "out") + prod = read_product(rep["output"]) + assert prod["paths"][1]["activity_channel"] == 2 + assert {"mean_ch1", "mean_ch2"} <= set(prod["paths"][1]["images"]) + + +def test_displacement_maps_end_to_end(tmp_path: Path) -> None: + """A run with a displacement field puts the network's trials in place through the field. + + The field comes from the patchwise alignment; the affine maps are not used. + """ + kw = dict(trim_s=0.1) + s = syn.make_session(tmp_path / "d", displacement=True) + run = RunSummary(s["run"]) + assert run.trial_map(1).displacement is not None + rep = make_spine_summary( + s["run"], + s["table"], + tmp_path / "d" / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + **kw, + ) + p = read_product(rep["output"])["paths"][1] + ok = p["valid"] + assert ok.sum() > 0.5 * ok.size + np.testing.assert_allclose( + p["images"]["f0_net"][:, ok], + p["images"]["f0_silo_ch1"][:, ok], + rtol=1e-3, + ) + np.testing.assert_allclose(p["normalized"]["sources"]["f0_net"], 0, atol=2e-3) + # the same maps as affine identity alone leave the trials displaced + a = np.zeros((syn.N_TRIALS, 2, 3)) + a[:, :, :2] = np.eye(2) + s0 = syn.make_session(tmp_path / "a", affine=a) + rep0 = make_spine_summary( + s0["run"], + s0["table"], + tmp_path / "a" / "out", + baseline_dir=s0["baselines"], + moco_dir=s0["moco"], + **kw, + ) + p0 = read_product(rep0["output"])["paths"][1] + ok0 = p0["valid"] + net = p0["images"]["f0_net"][1:, ok0] + assert np.abs(net / p0["images"]["f0_silo_ch1"][1:, ok0] - 1).max() > 1e-2 + + +def test_fitted_images_do_not_shrink_the_windows(tmp_path: Path) -> None: + """SILo's own F0 images are read out in the windows of the field images. + + The images have values only at the pixels SILo fitted. The sources (inside + the fitted pixels) read as before, a user ROI partly outside keeps its + readouts of the other images and gets NaN in f0_silo, and the report + counts it. + """ + kw = dict(trim_s=0.1) + full = syn.make_session(tmp_path / "full") + box = syn.make_session(tmp_path / "box", f0_silo_box=(slice(4, 20), slice(5, 25))) + reps, prods = {}, {} + for name, s in (("full", full), ("box", box)): + reps[name] = make_spine_summary( + s["run"], + s["table"], + tmp_path / name / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + **kw, + ) + prods[name] = read_product(reps[name]["output"])["paths"][1] + a, b = prods["full"], prods["box"] + np.testing.assert_array_equal(a["valid"], b["valid"]) + for k in a["readout"]["sources"]: + np.testing.assert_allclose(a["readout"]["sources"][k], b["readout"]["sources"][k]) + for k in a["normalized"]["sources"]: + np.testing.assert_allclose(a["normalized"]["sources"][k], b["normalized"]["sources"][k]) + ua, ub = a["readout"]["user"], b["readout"]["user"] + np.testing.assert_array_equal(ua["n_pixels"], ub["n_pixels"]) + np.testing.assert_allclose(ua["f0_net"], ub["f0_net"]) + assert np.isnan(ub["f0_silo_ch1"][:, 0]).all() # roi A: partly outside + np.testing.assert_allclose(ub["f0_silo_ch1"][:, 1], ua["f0_silo_ch1"][:, 1]) + assert reps["box"]["paths"][1]["not_covered"] == {"user": {"f0_silo_ch1": 1, "f0_silo_ch2": 1}} + assert "not_covered" not in reps["full"]["paths"][1] + assert b["image_attrs"]["f0_silo_ch1"]["covers"] == "fitted" + assert b["image_attrs"]["f0_net"]["covers"] == "field" + # a reused file gives the same report and the same notes again + notes = [] + again = make_spine_summary( + box["run"], + box["table"], + tmp_path / "box" / "out", + baseline_dir=box["baselines"], + moco_dir=box["moco"], + progress=notes.append, + **kw, + ) + assert again["reused"] + for k in ("not_covered", "window_images", "trials_used", "valid_pixels"): + assert again["paths"][1][k] == reps["box"]["paths"][1][k] + assert sum("does not cover" in m for m in notes) == 4 # 2 images x 2 paths + + +def test_no_shared_trial_reads_nothing() -> None: + """Field images without a trial in common leave no trial and no valid pixel. + + They leave a note, rather than windows over the whole frame. + """ + from giant_python.spine.readout import common_valid + + a = np.ones((4, 3, 3)) + b = np.ones((4, 3, 3)) + a[2:] = np.nan + b[:2] = np.nan + images = { + "mean_ch1": (a, {"covers": "field"}), + "f0_net": (b, {"covers": "field"}), + } + notes = [] + used, window = _trials_and_window(1, images, np.full(4, 10), notes.append) + assert used.size == 0 and window == ["mean_ch1", "f0_net"] + assert any("nothing is read out" in m for m in notes) + assert not common_valid([a, b], used).any() + + +def test_acquisition_numbers_from_the_file_name(tmp_path: Path) -> None: + """The acquisition number is read from the raw file's own name. + + Not from a folder that also says TRIAL, with either separator; and a table + whose raw and registered lists differ in length is refused. + """ + from giant_python.io.hdf5 import save_struct_h5 + + reg = np.array( + [[f"E1T{t}DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in (1, 2)]], + dtype=object, + ) + raw = np.array( + [ + [ + "C:\\TRIAL09\\activity_x_DMD1-TRIAL000002.dat", + "/data/TRIAL09/activity_x_DMD1-TRIAL000003.dat", + ] + ], + dtype=object, + ) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(tmp_path), + "savedr": str(tmp_path), + "filename": raw, + "motion_correction": {"fn_reg_ds": reg}, + }, + ) + stems, acq = table_trials(table, 1) + assert stems == ["E1T1DMD1", "E1T2DMD1"] + np.testing.assert_array_equal(acq, [2, 3]) + save_struct_h5( + table, + { + "datadr": str(tmp_path), + "savedr": str(tmp_path), + "filename": raw[:, :1], + "motion_correction": {"fn_reg_ds": reg}, + }, + ) + with pytest.raises(ValueError, match="1 raw files but 2"): + table_trials(table, 1) + + +def test_untrimmed_trials_are_reported(session: dict[str, Path], tmp_path: Path) -> None: + """A trial too short for the trim is averaged whole, as GIAnT-MATLAB does. + + The product, the report and a note say so. + """ + notes = [] + kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"]) + # 160 frames: a 1 s trim at 80 Hz leaves nothing + rep = make_spine_summary( + session["run"], + session["table"], + tmp_path / "long", + trim_s=1.0, + progress=notes.append, + **kw, + ) + p = read_product(rep["output"])["paths"][1] + attrs = p["image_attrs"]["f0_net"] + assert attrs["untrimmed"].astype(bool).all() + assert (attrs["n_frames"] == syn.N_FRAMES).all() + assert rep["paths"][1]["f0_untrimmed"] == [1, 2, 3, 4] + assert sum("too short for the trim" in m for m in notes) == 2 + rep = make_spine_summary(session["run"], session["table"], tmp_path / "short", trim_s=0.1, **kw) + p = read_product(rep["output"])["paths"][1] + assert not p["image_attrs"]["f0_net"]["untrimmed"].any() + assert "f0_untrimmed" not in rep["paths"][1] + + +def test_readout_runs_the_trend_tests(session: dict[str, Path], tmp_path: Path) -> None: + """Every normalized image gets the trend tests over its trials. + + Trial positions are trial-table indices; the test settings change the + output's key but not the network images' cache. + """ + from giant_python.spine.trends import trend_tests + + kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1) + rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) + p = read_product(rep["output"])["paths"][1] + norm = p["normalized"]["sources"] + tr = p["trends"]["sources"] + assert set(tr) == set(norm) - {"ok"} + rec = tr["f0_net"] + rows = rec["trials"] + np.testing.assert_array_equal(rows, np.arange(syn.N_TRIALS)) + direct = trend_tests( + norm["f0_net"][rows], + norm["ok"], + p["trials"]["acquisition"][rows], + n_perm=200, + ) + tested = direct["tested"] + assert tested.any() + np.testing.assert_array_equal(rec["tested"], tested) + for k in ("step_t", "step_p", "brief_t", "resid_p", "shared_r"): + np.testing.assert_array_equal(rec[k], direct[k]) + # positions as trial-table indices where a split or a run was found, + # -1 elsewhere + step = tested & (direct["step_k"] > 0) + assert step.any() + np.testing.assert_array_equal(rec["step_after"][step], rows[direct["step_k"][step] - 1]) + assert (rec["step_after"][~step] == -1).all() + run = tested & (direct["brief_start"] >= 0) + np.testing.assert_array_equal(rec["brief_first"][run], rows[direct["brief_start"][run]]) + assert (rec["brief_first"][~run] == -1).all() + np.testing.assert_array_equal(rec["brief_len"][tested & ~run], 0) + assert rec["attrs"]["n_perm"] == 200 + assert rec["attrs"]["var_share"] == pytest.approx(direct["var_share"]) + summ = rep["paths"][1]["trends"]["f0_net"] + assert summ["tested"] == int(tested.sum()) + assert summ["counts"] == direct["counts"] + rep2 = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=0, **kw) + assert rep2["output"] != rep["output"] and not rep2["reused"] + assert rep2["paths"][1]["f0_reused"] + p2 = read_product(rep2["output"])["paths"][1] + assert np.isnan(p2["trends"]["sources"]["f0_net"]["step_p"]).all() + + +def test_readout_refuses_bad_trend_settings(session: dict[str, Path], tmp_path: Path) -> None: + """Invalid trend settings are refused before anything is read or reused.""" + with pytest.raises(ValueError, match="fdr_q"): + make_spine_summary(session["run"], session["table"], tmp_path / "o", fdr_q=2.0) + with pytest.raises(ValueError, match="min_change"): + make_spine_summary(session["run"], session["table"], tmp_path / "o", min_change=1.5) + assert not (tmp_path / "o").exists() + + +def test_trials_without_numbers_are_noted( + session: dict[str, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A trial whose raw file has no acquisition number is left out of the brief test's runs. + + The summary's notes say so. + """ + import giant_python.spine.pipeline as pl + + real = pl.table_trials + + def no_number(table: Path, path: int) -> tuple[list, np.ndarray]: + """Return the table's trials with trial 2 unnumbered. + + Returns + ------- + stems : list + The trial stems of the table. + acq : np.ndarray + The acquisition numbers, with trial 2's set to -1. + """ + stems, acq = real(table, path) + acq = acq.copy() + acq[1] = -1 + return stems, acq + + monkeypatch.setattr(pl, "table_trials", no_number) + notes = [] + rep = make_spine_summary( + session["run"], + session["table"], + tmp_path / "o", + n_perm=0, + progress=notes.append, + ) + assert sum("trial(s) 2 have no acquisition number" in m for m in notes) + p = read_product(rep["output"])["paths"][1] + blocks = p["trends"]["sources"]["mean_ch1"]["blocks"] + assert blocks[1] != blocks[0] and blocks[1] != blocks[2] + + +def test_unnumbered_trials_follow_the_path_not_the_image() -> None: + """With some numbered trials on the path, unnumbered trials stay blocks of their own. + + This holds even in an image that covers only them; with no numbers on the + path, the table's order stands in (gaps split). + """ + from giant_python.spine.pipeline import _trends + + vals = np.random.default_rng(0).normal(size=(6, 4)) * 0.1 + norm = {"img": vals.copy(), "ok": np.ones(4, bool)} + norm["img"][[0, 1]] = np.nan # the image covers trials 2-5 only + opts = dict(n_perm=0, fdr_q=0.1, max_brief=3, seed=1, min_change=0.1) + acq = np.array([3, 4, -1, -1, -1, -1]) + tr, _ = _trends(1, norm, acq, opts, 1, lambda m: None, lambda m: None) + np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, 1, 2, 3]) + norm["img"][3] = np.nan # a gap in table order + tr, _ = _trends(1, norm, np.full(6, -1), opts, 1, lambda m: None, lambda m: None) + np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, -1, 1, 1]) + + +def test_readout_calls_and_quality_columns( + session: dict[str, Path], tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """The default image and its calls go into the summary and the report. + + Every image but the structural one gets the structural channel's change + at its own split; the windows' motion beyond the trials' shifts is 0 for + shifts. + """ + from giant_python.spine.qc import structural_change + + kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1) + rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) + p = read_product(rep["output"])["paths"][1] + assert p["primary_image"] == "f0_net" + np.testing.assert_allclose(p["readout"]["sources"]["align_px"], 0, atol=1e-9) + norm = p["normalized"]["sources"] + tr = p["trends"]["sources"] + assert "structural_d" not in tr["mean_ch2"] + for name in ("f0_net", "mean_ch1", "f0_silo_ch1"): + rec = tr[name] + assert rec["attrs"]["structural_image"] == "mean_ch2" + assert rec["attrs"]["min_change"] == pytest.approx(0.1) + rows = rec["trials"] + k = np.full(len(rec["tested"]), -1) + has = rec["resid_after"] >= 0 + k[has] = np.searchsorted(rows, rec["resid_after"][has]) + 1 + np.testing.assert_allclose( + rec["structural_d"], + structural_change(norm["mean_ch2"][rows], norm["ok"], k), + ) + expect = ( + rec["tested"] + & (rec["resid_q"] <= 0.1) + & (np.abs(np.expm1(np.nan_to_num(rec["resid_d"]))) >= 0.1) + ) + np.testing.assert_array_equal(rec["call"], expect) + calls = rep["paths"][1]["calls"] + assert calls["image"] == "f0_net" and calls["min_change"] == 0.1 + ids = read_product(rep["output"])["paths"][1]["rois"]["sources"].ids + c = tr["f0_net"]["call"] + d = tr["f0_net"]["resid_d"] + assert calls["up"] == [int(i) + 1 for i in ids[c & (d > 0)]] + assert calls["down"] == [int(i) + 1 for i in ids[c & (d < 0)]] + assert rep["paths"][1]["trends"]["f0_net"]["counts"]["call"] == { + "up": len(calls["up"]), + "down": len(calls["down"]), + } + # the minimum change is a setting of the command (and of the key) + args = [ + str(session["run"]), + "--table", + str(session["table"]), + "--out-dir", + str(tmp_path / "cli"), + "--n-perm", + "0", + "--min-change", + "0.25", + "--quiet", + ] + assert main(["spine", "readout"] + args) == 0 + out = json.loads(capsys.readouterr().out)["output"] + pr = read_product(out) + assert pr["attrs"]["settings"]["trends"]["min_change"] == 0.25 + assert pr["paths"][1]["primary_image"] == "f0_silo_ch1" + + +def test_window_motion_needs_no_affine_base(tmp_path: Path) -> None: + """Affine maps without a given index base still get the column. + + The base moves only the translation. + """ + a = np.zeros((syn.N_TRIALS, 2, 3)) + for t, ang in enumerate((0.0, 0.01, -0.01, 0.02)): + c, s_ = np.cos(ang), np.sin(ang) + a[t] = [[c, -s_, syn.SHIFTS[t][0]], [s_, c, syn.SHIFTS[t][1]]] + s = syn.make_session(tmp_path / "a", affine=a) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "a" / "o") + m = read_product(rep["output"])["paths"][1]["readout"]["sources"]["align_px"] + assert np.isfinite(m).all() and (m > 0).all() + + +def test_default_image_without_trend_tests(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """With too few trials for the trend tests, the default image still comes from sizes. + + It comes from the images with sizes (here the run's F0 of activity + channel 2), and no calls are reported. + """ + import giant_python.spine.pipeline as pl + + monkeypatch.setattr(pl, "_trends", lambda *a, **k: ({}, {})) + s = syn.make_session(tmp_path, activity_channel=2) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") + p = read_product(rep["output"])["paths"][1] + assert "f0_silo_ch2" in p["normalized"]["sources"] + assert p["primary_image"] == "f0_silo_ch2" + assert "calls" not in rep["paths"][1] + + +def test_default_image_needs_finite_sizes(tmp_path: Path) -> None: + """An image that covers no window keeps its key with only NaN sizes. + + It is not the default (here the run's F0 limited to a corner, so the + activity channel's mean takes its place). + """ + s = syn.make_session(tmp_path, f0_silo_box=(slice(0, 2), slice(0, 2))) + rep = make_spine_summary(s["run"], s["table"], tmp_path / "o", n_perm=50) + p = read_product(rep["output"])["paths"][1] + assert np.isnan(p["normalized"]["sources"]["f0_silo_ch1"]).all() + assert p["primary_image"] == "mean_ch1" + assert rep["paths"][1]["calls"]["image"] == "mean_ch1" diff --git a/tests/spine/test_spine_qc.py b/tests/spine/test_spine_qc.py index 712c26a5..443415a2 100644 --- a/tests/spine/test_spine_qc.py +++ b/tests/spine/test_spine_qc.py @@ -1,174 +1,179 @@ -"""Tests of the readout's quality columns and default image. - -The module under test is :mod:`giant_python.spine.qc`. -""" - -from collections.abc import Sequence - -import numpy as np -import pytest - -from giant_python.spine.qc import ( - primary_image, - structural_change, - structural_image, - window_motion, -) -from giant_python.spine.rois import sources_roiset -from giant_python.spine.summary_io import TrialMap -from giant_python.spine.trends import shared_mode, step_at - -from . import synthetic as syn - - -def _shift_field( - shifts: Sequence[Sequence[float]], bump: tuple[int, int, int, float] | None = None -) -> TrialMap: - """Build a displacement field per trial: the shifts everywhere, plus a bump. - - ``bump`` = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) of - extra row displacement. - """ - T = len(shifts) - disp = np.broadcast_to(np.asarray(shifts, float)[:, :, None, None], (T, 2, syn.H, syn.W)).copy() - if bump is not None: - t, r0, c0, a = bump - rr, cc = np.mgrid[0 : syn.H, 0 : syn.W] - disp[t, 0] += a * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0) - eye = np.zeros((T, 2, 3)) - eye[:, :, :2] = np.eye(2) - return TrialMap(eye, disp) - - -def test_primary_and_structural_images() -> None: - """The default image and the structural image are chosen in order. - - The default image is f0_gain, then f0_net, then the run's own F0 and the - mean of the activity channel; the structural image is the first mean image - of another channel. - """ - names = ["mean_ch1", "mean_ch2", "f0_net", "f0_gain", "f0_silo_ch1"] - assert primary_image(names, 1) == "f0_gain" - assert primary_image(names[:3], 1) == "f0_net" - assert primary_image(["mean_ch1", "mean_ch2", "f0_silo_ch2"], 2) == ("f0_silo_ch2") - assert primary_image(["mean_ch1", "mean_ch2"], 2) == "mean_ch2" - assert primary_image(["f0_silo_ch1"], 2) is None - assert structural_image(names, 1) == "mean_ch2" - assert structural_image(names, 2) == "mean_ch1" - assert structural_image(["mean_ch3", "mean_ch2", "mean_ch1"], 1) == ("mean_ch2") - assert structural_image(["mean_ch1", "f0_net"], 1) is None - - -def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp() -> None: - """Shifts move every window alike (0). - - A local warp in one trial moves the window it covers and hardly the others. - """ - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - trials = np.arange(syn.N_TRIALS) - shape = (syn.H, syn.W) - m0 = window_motion(_shift_field(syn.SHIFTS), rs, valid, trials, shape) - np.testing.assert_allclose(m0, 0, atol=1e-12) - r0, c0 = syn.SOURCES[0] - tm = _shift_field(syn.SHIFTS, bump=(2, r0, c0, 0.8)) - m = window_motion(tm, rs, valid, trials, shape) - assert m[0] > 0.2 - assert m[1] < 0.05 * m[0] - # one trial's offset among four: the spread of (0, 0, a, 0) in rows - idx, w = rs.pixels(0) - w = w / w.sum() - rr, cc = np.divmod(idx, syn.W) - a = (0.8 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0)) @ w - assert m[0] == pytest.approx(np.std([0, 0, a, 0], ddof=1), rel=0.05) - - -def test_window_motion_of_affine_maps_ignores_the_index_base() -> None: - """A rotation moves windows away from the centre. - - The index base only moves the translation, which the column removes. - """ - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - T = 3 - aff = np.zeros((T, 2, 3)) - for t, ang in enumerate((0.0, 0.01, -0.01)): - c, s = np.cos(ang), np.sin(ang) - aff[t] = [[c, -s, 1.0], [s, c, -0.5]] - shifted = aff.copy() - shifted[:, :, 2] += aff[:, :, 0] + aff[:, :, 1] - 1 - shape = (syn.H, syn.W) - m = window_motion(TrialMap(aff), rs, valid, np.arange(T), shape) - m1 = window_motion(TrialMap(shifted), rs, valid, np.arange(T), shape) - assert (m > 0).all() - np.testing.assert_allclose(m, m1, atol=1e-9) - - -def test_window_motion_without_trials_or_pixels_is_nan() -> None: - """Fewer than two aligned trials, or no valid pixel, give NaN.""" - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - shape = (syn.H, syn.W) - tm = _shift_field(syn.SHIFTS) - assert np.isnan(window_motion(tm, rs, valid, [1], shape)).all() - none = np.zeros_like(valid) - assert np.isnan(window_motion(tm, rs, none, [0, 1], shape)).all() - # a trial without a map is left out - tm.displacement[1] = np.nan - m = window_motion(tm, rs, valid, [0, 1, 2], shape) - np.testing.assert_allclose(m, 0, atol=1e-12) - - -def test_structural_change_is_the_step_beyond_the_trend_at_the_split() -> None: - """The structural channel's change at given splits. - - With its own shared trend removed, it is the mean after minus the mean - before. - """ - rng = np.random.default_rng(5) - T, n = 12, 20 - # a shared drift orthogonal to the planted step - step = (np.arange(T) >= 6) - 0.5 - drift = np.linspace(-0.1, 0.1, T) - drift -= (drift @ step) / (step @ step) * step - L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) - L[6:, 0] += 0.15 - L = L - L.mean(0) - ok = np.ones(n, bool) - ok[3] = False - L[2, 4] = np.nan - k = np.full(n, 6) - k[7] = 0 # no split - d = structural_change(L, ok, k) - use = ok & np.isfinite(L).all(0) - x = L[:, use].T - v, _ = shared_mode(x) - _, dd = step_at(x - np.outer(x @ v, v), k[use]) - np.testing.assert_allclose(d[use], dd) - assert np.isnan(d[3]) and np.isnan(d[4]) and np.isnan(d[7]) - assert d[0] == pytest.approx(0.15, abs=0.03) - # too few trials: nothing - assert np.isnan(structural_change(L[:2], ok, np.ones(n, int))).all() - - -def test_structural_change_centres_a_subset_of_trials() -> None: - """Over a subset of the trials the series are not centred. - - An offset per source must not take the place of the shared trend. - """ - rng = np.random.default_rng(8) - T, n = 12, 20 - step = (np.arange(T) >= 6) - 0.5 - drift = np.linspace(-0.1, 0.1, T) - drift -= (drift @ step) / (step @ step) * step - L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) - L[6:, 0] += 0.15 - L = L - L.mean(0) - ok = np.ones(n, bool) - k = np.full(n, 6) - offsets = rng.normal(size=n) * 0.5 - np.testing.assert_allclose( - structural_change(L + offsets, ok, k), - structural_change(L, ok, k), - atol=1e-12, - ) +"""Tests of the readout's quality columns and default image. + +The module under test is :mod:`giant_python.spine.qc`. +""" + +from collections.abc import Sequence + +import numpy as np +import pytest + +from giant_python.spine.qc import ( + primary_image, + structural_change, + structural_image, + window_motion, +) +from giant_python.spine.rois import sources_roiset +from giant_python.spine.summary_io import TrialMap +from giant_python.spine.trends import shared_mode, step_at + +from . import synthetic as syn + + +def _shift_field( + shifts: Sequence[Sequence[float]], bump: tuple[int, int, int, float] | None = None +) -> TrialMap: + """Build a displacement field per trial: the shifts everywhere, plus a bump. + + bump = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) of + extra row displacement. + + Returns + ------- + TrialMap + Identity affines with the per-trial displacement fields. + """ + T = len(shifts) + disp = np.broadcast_to(np.asarray(shifts, float)[:, :, None, None], (T, 2, syn.H, syn.W)).copy() + if bump is not None: + t, r0, c0, a = bump + rr, cc = np.mgrid[0 : syn.H, 0 : syn.W] + disp[t, 0] += a * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0) + eye = np.zeros((T, 2, 3)) + eye[:, :, :2] = np.eye(2) + return TrialMap(eye, disp) + + +def test_primary_and_structural_images() -> None: + """The default image and the structural image are chosen in order. + + The default image is f0_gain, then f0_net, then the run's own F0 and the + mean of the activity channel; the structural image is the first mean image + of another channel. + """ + names = ["mean_ch1", "mean_ch2", "f0_net", "f0_gain", "f0_silo_ch1"] + assert primary_image(names, 1) == "f0_gain" + assert primary_image(names[:3], 1) == "f0_net" + assert primary_image(["mean_ch1", "mean_ch2", "f0_silo_ch2"], 2) == ("f0_silo_ch2") + assert primary_image(["mean_ch1", "mean_ch2"], 2) == "mean_ch2" + assert primary_image(["f0_silo_ch1"], 2) is None + assert structural_image(names, 1) == "mean_ch2" + assert structural_image(names, 2) == "mean_ch1" + assert structural_image(["mean_ch3", "mean_ch2", "mean_ch1"], 1) == ("mean_ch2") + assert structural_image(["mean_ch1", "f0_net"], 1) is None + + +def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp() -> None: + """Shifts move every window alike (0). + + A local warp in one trial moves the window it covers and hardly the others. + """ + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + trials = np.arange(syn.N_TRIALS) + shape = (syn.H, syn.W) + m0 = window_motion(_shift_field(syn.SHIFTS), rs, valid, trials, shape) + np.testing.assert_allclose(m0, 0, atol=1e-12) + r0, c0 = syn.SOURCES[0] + tm = _shift_field(syn.SHIFTS, bump=(2, r0, c0, 0.8)) + m = window_motion(tm, rs, valid, trials, shape) + assert m[0] > 0.2 + assert m[1] < 0.05 * m[0] + # one trial's offset among four: the spread of (0, 0, a, 0) in rows + idx, w = rs.pixels(0) + w = w / w.sum() + rr, cc = np.divmod(idx, syn.W) + a = (0.8 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0)) @ w + assert m[0] == pytest.approx(np.std([0, 0, a, 0], ddof=1), rel=0.05) + + +def test_window_motion_of_affine_maps_ignores_the_index_base() -> None: + """A rotation moves windows away from the centre. + + The index base only moves the translation, which the column removes. + """ + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + T = 3 + aff = np.zeros((T, 2, 3)) + for t, ang in enumerate((0.0, 0.01, -0.01)): + c, s = np.cos(ang), np.sin(ang) + aff[t] = [[c, -s, 1.0], [s, c, -0.5]] + shifted = aff.copy() + shifted[:, :, 2] += aff[:, :, 0] + aff[:, :, 1] - 1 + shape = (syn.H, syn.W) + m = window_motion(TrialMap(aff), rs, valid, np.arange(T), shape) + m1 = window_motion(TrialMap(shifted), rs, valid, np.arange(T), shape) + assert (m > 0).all() + np.testing.assert_allclose(m, m1, atol=1e-9) + + +def test_window_motion_without_trials_or_pixels_is_nan() -> None: + """Fewer than two aligned trials, or no valid pixel, give NaN.""" + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + shape = (syn.H, syn.W) + tm = _shift_field(syn.SHIFTS) + assert np.isnan(window_motion(tm, rs, valid, [1], shape)).all() + none = np.zeros_like(valid) + assert np.isnan(window_motion(tm, rs, none, [0, 1], shape)).all() + # a trial without a map is left out + tm.displacement[1] = np.nan + m = window_motion(tm, rs, valid, [0, 1, 2], shape) + np.testing.assert_allclose(m, 0, atol=1e-12) + + +def test_structural_change_is_the_step_beyond_the_trend_at_the_split() -> None: + """The structural channel's change at given splits. + + With its own shared trend removed, it is the mean after minus the mean + before. + """ + rng = np.random.default_rng(5) + T, n = 12, 20 + # a shared drift orthogonal to the planted step + step = (np.arange(T) >= 6) - 0.5 + drift = np.linspace(-0.1, 0.1, T) + drift -= (drift @ step) / (step @ step) * step + L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) + L[6:, 0] += 0.15 + L = L - L.mean(0) + ok = np.ones(n, bool) + ok[3] = False + L[2, 4] = np.nan + k = np.full(n, 6) + k[7] = 0 # no split + d = structural_change(L, ok, k) + use = ok & np.isfinite(L).all(0) + x = L[:, use].T + v, _ = shared_mode(x) + _, dd = step_at(x - np.outer(x @ v, v), k[use]) + np.testing.assert_allclose(d[use], dd) + assert np.isnan(d[3]) and np.isnan(d[4]) and np.isnan(d[7]) + assert d[0] == pytest.approx(0.15, abs=0.03) + # too few trials: nothing + assert np.isnan(structural_change(L[:2], ok, np.ones(n, int))).all() + + +def test_structural_change_centres_a_subset_of_trials() -> None: + """Over a subset of the trials the series are not centred. + + An offset per source must not take the place of the shared trend. + """ + rng = np.random.default_rng(8) + T, n = 12, 20 + step = (np.arange(T) >= 6) - 0.5 + drift = np.linspace(-0.1, 0.1, T) + drift -= (drift @ step) / (step @ step) * step + L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) + L[6:, 0] += 0.15 + L = L - L.mean(0) + ok = np.ones(n, bool) + k = np.full(n, 6) + offsets = rng.normal(size=n) * 0.5 + np.testing.assert_allclose( + structural_change(L + offsets, ok, k), + structural_change(L, ok, k), + atol=1e-12, + ) diff --git a/tests/spine/test_spine_readout.py b/tests/spine/test_spine_readout.py index b3da326a..5e78f00d 100644 --- a/tests/spine/test_spine_readout.py +++ b/tests/spine/test_spine_readout.py @@ -1,151 +1,151 @@ -"""Tests of the spine-size windows and readout. - -The modules tested are :mod:`giant_python.spine.rois` and -:mod:`giant_python.spine.readout`. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.spine.readout import ( - common_valid, - mask_mean, - norm_log, - project, -) -from giant_python.spine.rois import ( - disks_roiset, - masks_roiset, - nearest, - read_marks, - sources_roiset, - write_marks, -) - -from . import synthetic as syn - - -def test_sources_roiset_is_sparse_and_centred() -> None: - """Footprints are stored as their positive pixels, centroids weighted.""" - fp = syn.footprints() - rs = sources_roiset(fp) - assert len(rs) == len(syn.SOURCES) - for k, (r0, c0) in enumerate(syn.SOURCES): - np.testing.assert_allclose(rs.image(k), fp[k]) - assert abs(rs.rows[k] - r0) < 0.05 and abs(rs.cols[k] - c0) < 0.05 - idx, w = rs.pixels(k) - assert (w > 0).all() and idx.size == (fp[k] > 0).sum() - - -def test_masks_roiset_needs_one_label_per_mask() -> None: - """Labels and masks must agree in number.""" - with pytest.raises(ValueError, match="labels"): - masks_roiset(np.zeros((2, 4, 4), bool), ["a"]) - - -def test_project_is_the_matlab_formula() -> None: - """``F = (h . x) / (h . h)`` with h normalized over the valid pixels.""" - rng = np.random.default_rng(2) - fp = syn.footprints() - imgs = 100 + rng.random((5, syn.H, syn.W)) - valid = np.ones((syn.H, syn.W), bool) - valid[8, 9] = False # the first source's peak pixel is left out - rs = sources_roiset(fp) - got, n_pix = project(imgs, rs, valid) - for k in range(len(rs)): - h = np.where(valid, fp[k], 0).ravel() - h = h / h.sum() - expect = imgs.reshape(5, -1) @ h / (h @ h) - np.testing.assert_allclose(got[:, k], expect) - assert n_pix[0] == (fp[0] > 0).sum() - 1 - - -def test_project_is_scale_equivariant() -> None: - """A uniform brightness change scales every readout by the same factor. - - So it cancels in the normalization. - """ - fp = syn.footprints() - img = syn.scene(1)[None] - rs = sources_roiset(fp) - valid = np.ones(img.shape[1:], bool) - a, _ = project(img, rs, valid) - b, _ = project(0.8 * img, rs, valid) - np.testing.assert_allclose(b, 0.8 * a) - - -def test_common_valid_requires_every_trial_and_stack() -> None: - """A pixel missing in one trial of one stack is not valid.""" - a = np.ones((3, 4, 5)) - b = np.ones((3, 4, 5)) - a[1, 0, 0] = np.nan - b[2, 3, 4] = np.nan - ok = common_valid([a, b], [0, 1, 2]) - assert not ok[0, 0] and not ok[3, 4] and ok.sum() == 18 - assert common_valid([a, b], [0])[0, 0] - # without trials nothing can be compared, so no pixel is valid - assert not common_valid([a, b], []).any() - - -def test_mask_mean_and_coverage() -> None: - """Mean over the mask's pixels with a value; coverage is their share.""" - masks = np.zeros((1, 4, 4), bool) - masks[0, :2, :2] = True - rs = masks_roiset(masks, ["r"]) - imgs = np.ones((2, 4, 4)) * np.array([1.0, 3.0])[:, None, None] - imgs[1, 0, 0] = np.nan - v, cov = mask_mean(imgs, rs) - np.testing.assert_allclose(v[:, 0], [1.0, 3.0]) - np.testing.assert_allclose(cov[:, 0], [1.0, 0.75]) - - -def test_norm_log_matches_spinetrends() -> None: - """Log F, minus each trial's median over the ok ROIs, minus each ROI's mean. - - This is ``normLog`` of ``spineTrends.m``. - """ - rng = np.random.default_rng(3) - f = np.exp(rng.normal(size=(7, 9))) - ok = np.ones(9, bool) - ok[4] = False - lg = np.log(f) - expect = lg - np.median(lg[:, ok], axis=1, keepdims=True) - expect = expect - expect.mean(axis=0, keepdims=True) - np.testing.assert_allclose(norm_log(f, ok), expect) - - -def test_norm_log_removes_a_shared_trend() -> None: - """A brightness factor shared by all ROIs (bleaching) leaves zeros.""" - sizes = np.array([1.0, 2.0, 3.0]) - trend = np.array([1.0, 0.9, 0.8, 0.7]) - out = norm_log(trend[:, None] * sizes[None]) - np.testing.assert_allclose(out, 0, atol=1e-12) - - -def test_nearest_and_disks() -> None: - """Points find the nearest ROI within a distance.""" - rs = disks_roiset([5.0, 10.0], [5.0, 20.0], 2.0, (20, 30)) - assert rs.meta["radius"] == 2.0 - np.testing.assert_array_equal(nearest(rs, [5.5, 10.0, 0.0], [5.0, 21.0, 0.0], 2.5), [0, 1, -1]) - - -def test_marks_round_trip(tmp_path: Path) -> None: - """Marks keep GIAnT-MATLAB's spine_marks.csv columns.""" - marks = [ - { - "Path": 1, - "Source": 59, - "Label": "Growing", - "Note": "", - "Row0": 72.5, - "Col0": 585.45, - "Updated": "2026-10-30 15:54:36", - } - ] - path = tmp_path / "spine_marks.csv" - write_marks(path, marks) - back = read_marks(path) - assert back[0]["Path"] == 1 and back[0]["Label"] == "Growing" - assert back[0]["Row0"] == pytest.approx(72.5) +"""Tests of the spine-size windows and readout. + +The modules tested are :mod:`giant_python.spine.rois` and +:mod:`giant_python.spine.readout`. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.spine.readout import ( + common_valid, + mask_mean, + norm_log, + project, +) +from giant_python.spine.rois import ( + disks_roiset, + masks_roiset, + nearest, + read_marks, + sources_roiset, + write_marks, +) + +from . import synthetic as syn + + +def test_sources_roiset_is_sparse_and_centred() -> None: + """Footprints are stored as their positive pixels, centroids weighted.""" + fp = syn.footprints() + rs = sources_roiset(fp) + assert len(rs) == len(syn.SOURCES) + for k, (r0, c0) in enumerate(syn.SOURCES): + np.testing.assert_allclose(rs.image(k), fp[k]) + assert abs(rs.rows[k] - r0) < 0.05 and abs(rs.cols[k] - c0) < 0.05 + idx, w = rs.pixels(k) + assert (w > 0).all() and idx.size == (fp[k] > 0).sum() + + +def test_masks_roiset_needs_one_label_per_mask() -> None: + """Labels and masks must agree in number.""" + with pytest.raises(ValueError, match="labels"): + masks_roiset(np.zeros((2, 4, 4), bool), ["a"]) + + +def test_project_is_the_matlab_formula() -> None: + """F = (h . x) / (h . h) with h normalized over the valid pixels.""" + rng = np.random.default_rng(2) + fp = syn.footprints() + imgs = 100 + rng.random((5, syn.H, syn.W)) + valid = np.ones((syn.H, syn.W), bool) + valid[8, 9] = False # the first source's peak pixel is left out + rs = sources_roiset(fp) + got, n_pix = project(imgs, rs, valid) + for k in range(len(rs)): + h = np.where(valid, fp[k], 0).ravel() + h = h / h.sum() + expect = imgs.reshape(5, -1) @ h / (h @ h) + np.testing.assert_allclose(got[:, k], expect) + assert n_pix[0] == (fp[0] > 0).sum() - 1 + + +def test_project_is_scale_equivariant() -> None: + """A uniform brightness change scales every readout by the same factor. + + So it cancels in the normalization. + """ + fp = syn.footprints() + img = syn.scene(1)[None] + rs = sources_roiset(fp) + valid = np.ones(img.shape[1:], bool) + a, _ = project(img, rs, valid) + b, _ = project(0.8 * img, rs, valid) + np.testing.assert_allclose(b, 0.8 * a) + + +def test_common_valid_requires_every_trial_and_stack() -> None: + """A pixel missing in one trial of one stack is not valid.""" + a = np.ones((3, 4, 5)) + b = np.ones((3, 4, 5)) + a[1, 0, 0] = np.nan + b[2, 3, 4] = np.nan + ok = common_valid([a, b], [0, 1, 2]) + assert not ok[0, 0] and not ok[3, 4] and ok.sum() == 18 + assert common_valid([a, b], [0])[0, 0] + # without trials nothing can be compared, so no pixel is valid + assert not common_valid([a, b], []).any() + + +def test_mask_mean_and_coverage() -> None: + """Mean over the mask's pixels with a value; coverage is their share.""" + masks = np.zeros((1, 4, 4), bool) + masks[0, :2, :2] = True + rs = masks_roiset(masks, ["r"]) + imgs = np.ones((2, 4, 4)) * np.array([1.0, 3.0])[:, None, None] + imgs[1, 0, 0] = np.nan + v, cov = mask_mean(imgs, rs) + np.testing.assert_allclose(v[:, 0], [1.0, 3.0]) + np.testing.assert_allclose(cov[:, 0], [1.0, 0.75]) + + +def test_norm_log_matches_spinetrends() -> None: + """Log F, minus each trial's median over the ok ROIs, minus each ROI's mean. + + This is normLog of spineTrends.m. + """ + rng = np.random.default_rng(3) + f = np.exp(rng.normal(size=(7, 9))) + ok = np.ones(9, bool) + ok[4] = False + lg = np.log(f) + expect = lg - np.median(lg[:, ok], axis=1, keepdims=True) + expect = expect - expect.mean(axis=0, keepdims=True) + np.testing.assert_allclose(norm_log(f, ok), expect) + + +def test_norm_log_removes_a_shared_trend() -> None: + """A brightness factor shared by all ROIs (bleaching) leaves zeros.""" + sizes = np.array([1.0, 2.0, 3.0]) + trend = np.array([1.0, 0.9, 0.8, 0.7]) + out = norm_log(trend[:, None] * sizes[None]) + np.testing.assert_allclose(out, 0, atol=1e-12) + + +def test_nearest_and_disks() -> None: + """Points find the nearest ROI within a distance.""" + rs = disks_roiset([5.0, 10.0], [5.0, 20.0], 2.0, (20, 30)) + assert rs.meta["radius"] == 2.0 + np.testing.assert_array_equal(nearest(rs, [5.5, 10.0, 0.0], [5.0, 21.0, 0.0], 2.5), [0, 1, -1]) + + +def test_marks_round_trip(tmp_path: Path) -> None: + """Marks keep GIAnT-MATLAB's spine_marks.csv columns.""" + marks = [ + { + "Path": 1, + "Source": 59, + "Label": "Growing", + "Note": "", + "Row0": 72.5, + "Col0": 585.45, + "Updated": "2026-10-30 15:54:36", + } + ] + path = tmp_path / "spine_marks.csv" + write_marks(path, marks) + back = read_marks(path) + assert back[0]["Path"] == 1 and back[0]["Label"] == "Growing" + assert back[0]["Row0"] == pytest.approx(72.5) diff --git a/tests/spine/test_spine_trends.py b/tests/spine/test_spine_trends.py index 2fcb05d7..a35e3036 100644 --- a/tests/spine/test_spine_trends.py +++ b/tests/spine/test_spine_trends.py @@ -1,467 +1,494 @@ -"""Tests of the trend tests (:mod:`giant_python.spine.trends`). - -They test against direct transcriptions of GIAnT-MATLAB's ``spineTrends.m`` and -``spineTrendsResid.m``. -""" - -import math -from typing import Any - -import numpy as np -import pytest - -from giant_python.spine.trends import ( - _median_without, - bh_adjust, - brief_stat, - shared_mode, - step_at, - step_stat, - trend_tests, - trial_blocks, - trial_orders, -) - - -def _step_loop(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """``stepStat2`` as written in MATLAB (rows = series).""" - n, T = x.shape - tb, kb, db = np.zeros(n), np.ones(n, int), np.zeros(n) - for k in range(1, T): - a, b = x[:, :k], x[:, k:] - d = b.mean(1) - a.mean(1) - ss = ((a - a.mean(1, keepdims=True)) ** 2).sum(1) + ( - (b - b.mean(1, keepdims=True)) ** 2 - ).sum(1) - t = d / (np.sqrt(ss / (T - 2)) * math.sqrt(1 / k + 1 / (T - k))) - upd = np.abs(t) > np.abs(tb) - tb[upd], kb[upd], db[upd] = t[upd], k, d[upd] - return tb, kb, db - - -def _brief_loop( - x: np.ndarray, blk: np.ndarray, max_w: int -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """``briefStat`` as written in MATLAB, zero-based, with np.median.""" - n, T = x.shape - tb, db = np.zeros(n), np.zeros(n) - sb, wb = np.zeros(n, int), np.ones(n, int) - dd = np.abs(np.diff(x, axis=1)) - in_blk = blk[1:] == blk[:-1] - for w in range(1, max_w + 1): - for a in range(1, T - w): - e = a + w - 1 - b = blk[a] - if blk[a - 1] != b or blk[e + 1] != b or blk[e] != b: - continue - away = in_blk.copy() - away[a - 1 : e + 1] = False - sg = np.median(dd[:, away], axis=1) / (0.6745 * math.sqrt(2)) - left = [i for i in range(max(a - 2, 0), a) if blk[i] == blk[a]] - right = [i for i in range(e + 1, min(e + 2, T - 1) + 1) if blk[i] == blk[a]] - m = x[:, a : e + 1].mean(1) - ml, mr = x[:, left].mean(1), x[:, right].mean(1) - tl = (m - ml) / (sg * math.sqrt(1 / w + 1 / len(left))) - tr = (m - mr) / (sg * math.sqrt(1 / w + 1 / len(right))) - t = np.sign(tl) * np.minimum(abs(tl), abs(tr)) - t[np.sign(tl) != np.sign(tr)] = 0 - d = m - (ml + mr) / 2 - upd = np.abs(t) > np.abs(tb) - tb[upd], sb[upd], wb[upd], db[upd] = t[upd], a, w, d[upd] - return tb, sb, wb, db - - -def test_trial_blocks_split_at_gaps() -> None: - """A new block starts where the acquisition number jumps by more than 1. - - A repeat or a decrease does not start one, as in MATLAB. - """ - np.testing.assert_array_equal(trial_blocks([2, 3, 4, 7, 8, 8, 6, 10]), [0, 0, 0, 1, 1, 1, 1, 2]) - assert trial_blocks([]).size == 0 - - -def test_trials_without_numbers_are_blocks_of_their_own() -> None: - """A trial without an acquisition number is neither in a brief run nor a neighbour of one. - - With no numbers at all, trials are consecutive. - """ - np.testing.assert_array_equal(trial_blocks([10, 11, -1, -1, 14, 15]), [0, 0, 1, 2, 3, 3]) - np.testing.assert_array_equal(trial_blocks([-1, -1, -1]), [0, 0, 0]) - np.testing.assert_array_equal(trial_blocks([-1, -1, -1], unknown_consecutive=False), [0, 1, 2]) - x = np.zeros((1, 7)) - x[0, 3] = 1.0 # a transient at the trial without a number - x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 - t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, -1, 5, 6, 7]), 1) - assert start[0] != 3 - t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, 4, 5, 6, 7]), 1) - assert start[0] == 3 - - -def test_image_blocks_keep_the_paths_boundaries() -> None: - """A subset of a path's trials keeps the path's block boundaries. - - This holds also with acquisition numbers out of order, and the subset - splits where it skips a trial. - """ - from giant_python.spine.trends import image_blocks - - pb = trial_blocks([1, 5, 2, 3]) # 1 | 5, 2, 3 (a decrease joins) - np.testing.assert_array_equal(pb, [0, 1, 1, 1]) - # without the trial numbered 5, numbers 1, 2, 3 alone would be one block - np.testing.assert_array_equal(image_blocks(pb, [0, 2, 3]), [0, 1, 1]) - np.testing.assert_array_equal(trial_blocks([1, 2, 3]), [0, 0, 0]) - # a skipped trial splits a block - pb = trial_blocks(np.arange(6)) - np.testing.assert_array_equal(image_blocks(pb, [0, 1, 3, 4, 5]), [0, 0, 1, 1, 1]) - # trend_tests takes the blocks as given - x = np.random.default_rng(2).normal(size=(5, 2)) - r = trend_tests(x, np.ones(2, bool), [9, 9, 9, 9, 9], n_perm=0, blocks=[0, 0, 1, 1, 1]) - np.testing.assert_array_equal(r["blocks"], [0, 0, 1, 1, 1]) - with pytest.raises(ValueError, match="blocks"): - trend_tests(x, np.ones(2, bool), np.arange(5), n_perm=0, blocks=[0, 1]) - - -@pytest.mark.parametrize( - "kw, match", - [ - (dict(n_perm=-1), "n_perm"), - (dict(max_brief=0), "max_brief"), - (dict(fdr_q=2.0), "fdr_q"), - (dict(fdr_q=0.0), "fdr_q"), - (dict(seed=-3), "seed"), - (dict(min_change=-0.1), "min_change"), - (dict(min_change=1.0), "min_change"), - (dict(min_change=float("nan")), "min_change"), - ], -) -def test_trend_settings_are_checked(kw: dict[str, Any], match: str) -> None: - """Settings the tests cannot use are refused.""" - with pytest.raises(ValueError, match=match): - trend_tests(np.zeros((5, 2)), np.ones(2, bool), np.arange(5), **kw) - - -def test_step_stat_is_the_matlab_loop() -> None: - """Cumulative sums give MATLAB's statistic, split and size.""" - rng = np.random.default_rng(3) - x = rng.normal(size=(200, 17)) * 0.1 - x[:20, 9:] += 0.3 # some real steps - got = step_stat(x) - ref = _step_loop(x) - np.testing.assert_allclose(got[0], ref[0], rtol=1e-10) - np.testing.assert_array_equal(got[1], ref[1]) - np.testing.assert_allclose(got[2], ref[2], rtol=1e-10, atol=1e-15) - t, d = step_at(x, got[1]) - np.testing.assert_allclose(t, got[0], rtol=1e-10) - np.testing.assert_allclose(d, got[2], rtol=1e-10, atol=1e-15) - - -def test_no_step_or_run_keeps_a_missing_position() -> None: - """A series without a non-zero statistic reports no split and no run (not the first trial). - - So does the summary through the pipeline's mapping. - """ - x = np.zeros((2, 8)) - x[1] = np.arange(8) * 0.01 - t, k, d = step_stat(x) - assert t[0] == 0 and k[0] == 0 and d[0] == 0 - assert k[1] > 0 - # a strictly linear series: every trial is the mean of its neighbours, - # so no run differs from both sides - t, start, length, d = brief_stat(x, np.zeros(8, int), 3) - np.testing.assert_array_equal(t, 0) - np.testing.assert_array_equal(start, -1) - np.testing.assert_array_equal(length, 0) - # blocks of one or two trials leave no run with neighbours - rng = np.random.default_rng(1) - y = rng.normal(size=(3, 6)) - t, start, length, _ = brief_stat(y, trial_blocks([1, 2, 5, 6, 9, 10]), 3) - assert (t == 0).all() and (start == -1).all() and (length == 0).all() - r = trend_tests(x.T, np.ones(2, bool), np.arange(8), n_perm=50) - assert r["tested"].all() - assert r["step_k"][0] == 0 and r["step_p"][0] == 1 - assert r["brief_start"][0] == -1 and r["brief_len"][0] == 0 - - -def test_step_at_out_of_range_is_nan() -> None: - """A split outside 1..T-1 gives NaN.""" - t, d = step_at(np.zeros((2, 5)) + [[0, 1, 2, 3, 4]], [0, 2]) - assert np.isnan(t[0]) and np.isnan(d[0]) and d[1] == 2.5 - - -def test_median_without_matches_numpy() -> None: - """The median once some ranks are taken out equals np.median of what is left. - - Ties included. - """ - rng = np.random.default_rng(5) - for m_all, k in ((9, 2), (10, 3), (12, 4), (5, 4)): - vals = rng.integers(0, 4, size=(300, m_all)).astype(float) - order = np.argsort(vals, axis=1, kind="stable") - srt = np.take_along_axis(vals, order, 1) - rank = np.empty_like(order) - np.put_along_axis(rank, order, np.broadcast_to(np.arange(m_all), order.shape), 1) - cols = np.sort(rng.choice(m_all, size=k, replace=False)) - keep = np.setdiff1d(np.arange(m_all), cols) - got = _median_without(srt, rank[:, cols], m_all - k) - if m_all - k == 0: - assert np.isnan(got).all() - else: - np.testing.assert_array_equal(got, np.median(vals[:, keep], 1)) - - -def test_brief_stat_is_the_matlab_loop() -> None: - """The brief statistic, run and size equal MATLAB's, with blocks.""" - rng = np.random.default_rng(4) - T = 15 - x = rng.normal(size=(300, T)) * 0.1 - x[:30, 6:8] += 0.4 # transient changes - blk = trial_blocks([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16]) - for max_w in (1, 3): - got = brief_stat(x, blk, max_w) - ref = _brief_loop(x, blk, max_w) - np.testing.assert_allclose(got[0], ref[0], rtol=1e-10) - np.testing.assert_array_equal(got[1], ref[1]) - np.testing.assert_array_equal(got[2], ref[2]) - np.testing.assert_allclose(got[3], ref[3], rtol=1e-10, atol=1e-15) - # the planted runs are found - t, start, length, _ = brief_stat(x[:30], blk, 3) - assert (t > 0).mean() > 0.9 - assert np.median(start) == 6 and np.median(length) == 2 - - -def test_brief_stat_keeps_runs_inside_blocks() -> None: - """No run (or its neighbours) crosses a block boundary.""" - x = np.zeros((1, 8)) - x[0, 3] = 1.0 # trial 3 starts block 1: no neighbours before it there - x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 - blk = trial_blocks([1, 2, 3, 10, 11, 12, 13, 14]) - t, start, _, _ = brief_stat(x, blk, 1) - assert start[0] != 3 - - -def test_bh_adjust_is_the_step_up_rule() -> None: - """Q <= level exactly where the step-up rule rejects; NaN stays NaN.""" - rng = np.random.default_rng(6) - p = np.concatenate([rng.uniform(size=80), rng.uniform(0, 0.002, 20)]) - p[5] = np.nan - q = bh_adjust(p) - assert np.isnan(q[5]) - fin = np.flatnonzero(np.isfinite(p)) - ps = np.sort(p[fin]) - m = fin.size - below = np.flatnonzero(ps <= np.arange(1, m + 1) / m * 0.1) - expect = np.zeros(p.size, bool) - if below.size: - expect[fin] = p[fin] <= ps[below[-1]] - np.testing.assert_array_equal(q <= 0.1, expect) - np.testing.assert_allclose(bh_adjust([0.01, 0.04, 0.03]), [0.03, 0.04, 0.04]) - - -def test_shared_mode_sign_and_share() -> None: - """A rank-one pattern is recovered with all the variance, signed positive at the end.""" - v0 = np.linspace(1, -1, 10) - v0 /= np.linalg.norm(v0) - x = np.outer([1.0, -2.0, 0.5], v0) - v, share = shared_mode(x) - np.testing.assert_allclose(v, -v0, atol=1e-12) # v0 ends negative - assert share == pytest.approx(1.0) - v, share = shared_mode(np.zeros((0, 4))) - assert np.isnan(v).all() and np.isnan(share) - - -def _session( - rng: np.random.Generator, n_src: int = 40, T: int = 20, step: float = 0.25 -) -> np.ndarray: - """Normalized-like sizes (trials, sources) with a shared drift and one step. - - Noise, a shared drift (most of the variance, as in real sessions) and - one source with a step after trial 9. - """ - drift = np.linspace(-0.2, 0.2, T) - x = rng.normal(size=(T, n_src)) * 0.05 + drift[:, None] * rng.normal(size=n_src) - x[10:, 0] += step - return x - x.mean(0) - - -def test_trend_tests_find_a_planted_step() -> None: - """A planted step has small p and q. - - Beyond the shared drift, the other sources do not pile up at small p. - """ - rng = np.random.default_rng(7) - x = _session(rng) - ok = np.ones(x.shape[1], bool) - ok[3] = False - r = trend_tests(x, ok, np.arange(2, 22), n_perm=2000, workers=2) - assert r["tested"].sum() == x.shape[1] - 1 and not r["tested"][3] - assert np.isnan(r["step_p"][3]) and r["step_k"][3] == -1 - assert r["step_k"][0] == 10 and r["step_t"][0] > 0 - assert r["step_p"][0] < 0.002 and r["step_q"][0] <= 0.1 - # the shared trend is the drift, not the planted step; the resid test - # is the step test of what is left once each source's part is removed - assert abs(np.corrcoef(r["shared_v"], np.arange(20))[0, 1]) > 0.95 - tested = r["tested"] - lx = x.T[tested] - v = shared_mode(lx)[0] - np.testing.assert_allclose(r["shared_v"], v) - np.testing.assert_allclose(r["shared_loading"][tested], lx @ v) - rt, rk, rd = step_stat(lx - np.outer(lx @ v, v)) - np.testing.assert_allclose(r["resid_t"][tested], rt) - np.testing.assert_array_equal(r["resid_k"][tested], rk) - # every source follows the drift (a real step for the step test); - # beyond it, the others are null - assert (r["step_p"][4:] < 0.05).mean() > 0.5 - assert (r["resid_p"][4:] < 0.05).mean() < 0.2 - assert r["counts"]["step"]["fdr_up"] >= 1 - assert r["shared_v"].shape == (20,) and 0 < r["var_share"] < 1 - - -def test_trend_tests_p_does_not_depend_on_the_others_or_threads() -> None: - """Each source has its own trial orders. - - The step and brief p are the same whichever other sources are tested, - and no p depends on the threads; the beyond-trend test depends on the - tested set through the shared trend. - """ - rng = np.random.default_rng(8) - x = _session(rng, n_src=6, T=12) - acq = np.arange(12) - a = trend_tests(x, np.ones(6, bool), acq, n_perm=500, workers=1) - b = trend_tests(x, np.ones(6, bool), acq, n_perm=500, workers=4) - for key in ("step_p", "brief_p", "resid_p"): - np.testing.assert_array_equal(a[key], b[key]) - ok = np.zeros(6, bool) - ok[[0, 2]] = True - c = trend_tests(x, ok, acq, n_perm=500) - np.testing.assert_array_equal(c["step_p"][[0, 2]], a["step_p"][[0, 2]]) - np.testing.assert_array_equal(c["brief_p"][[0, 2]], a["brief_p"][[0, 2]]) - assert not np.allclose(c["shared_v"], a["shared_v"]) - - -def test_ties_at_the_edge_split_count() -> None: - """One outlying first trial gives p about 2/T, not tiny. - - Every order that puts it first or last gives the same statistic. - """ - rng = np.random.default_rng(9) - T = 20 - x = rng.normal(size=(T, 1)) * 0.01 - x[0, 0] = 1.0 - r = trend_tests(x - x.mean(), np.ones(1, bool), np.arange(T), n_perm=4000) - assert r["step_k"][0] == 1 - assert r["step_p"][0] == pytest.approx(2 / T, abs=0.02) - - -def test_noise_free_edge_outlier_ties_with_its_mirror() -> None: - """A series without spread apart from one end trial has an infinite step statistic. - - The statistic is equal for the series and its mirror image, so every - order that puts the trial at either end ties (p about 2/T). - """ - x = np.zeros((2, 10)) - x[0, -1] = 1.0 - x[1, 0] = 1.0 - t, k, _ = step_stat(x) - assert np.isinf(t).all() and t[0] > 0 > t[1] - np.testing.assert_array_equal(k, [9, 1]) - r = trend_tests(x[:1].T, np.ones(1, bool), np.arange(10), n_perm=4000) - assert r["step_p"][0] == pytest.approx(0.2, abs=0.03) - # step_at agrees at the chosen split, also for a nearly noise-free step - y = np.array([[0.0, 1e-6, 1.0, 1.000001]]) - t, k, d = step_stat(y) - ta, da = step_at(y, k) - assert np.isinf(t[0]) and k[0] == 2 - np.testing.assert_array_equal(ta, t) - np.testing.assert_allclose(da, d) - np.testing.assert_array_equal(step_at(x, [9, 1])[0], step_stat(x)[0]) - - -def test_trend_tests_without_permutations() -> None: - """n_perm 0 gives the statistics without p or q.""" - rng = np.random.default_rng(10) - x = _session(rng, n_src=5, T=10) - r = trend_tests(x, np.ones(5, bool), np.arange(10), n_perm=0) - assert np.isfinite(r["step_t"]).all() and np.isnan(r["step_p"]).all() - assert np.isnan(r["step_q"]).all() - assert r["counts"]["step"]["fdr_up"] == 0 - - -def test_trend_tests_need_three_trials() -> None: - """Fewer than three trials: nothing is tested.""" - r = trend_tests(np.zeros((2, 3)), np.ones(3, bool), [1, 2], n_perm=10) - assert not r["tested"].any() and np.isnan(r["step_t"]).all() - - -def test_permutations_in_chunks_give_the_same_p() -> None: - """The orders are drawn in chunks to bound memory. - - The p-values do not depend on the chunk size. - """ - from giant_python.spine.trends import _perm_p - - rng = np.random.default_rng(11) - x = rng.normal(size=14) - resid = rng.normal(size=14) - blocks = trial_blocks(np.arange(14)) - t_obs = [ - step_stat(x[None])[0][0], - brief_stat(x[None], blocks)[0][0], - step_stat(resid[None])[0][0], - ] - one = _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3) - for rows in (1, 7, 200): - assert _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3, rows) == one - - -def test_trial_orders_are_seeded_permutations() -> None: - """Each row is a permutation; the same seed and source repeat.""" - o = trial_orders(1, 7, 50, 9) - assert (np.sort(o, axis=1) == np.arange(9)).all() - np.testing.assert_array_equal(o, trial_orders(1, 7, 50, 9)) - assert not np.array_equal(o, trial_orders(1, 8, 50, 9)) - assert trial_orders(1, 7, 0, 9).shape == (0, 9) - - -def test_calls_need_q_and_the_minimum_change() -> None: - """A call is a change beyond the shared trend with q <= fdr_q and enough size. - - The relative size must be at least min_change, in either direction; a - small change that the test finds is not called, an untested source - never. - """ - rng = np.random.default_rng(3) - T, n_src = 20, 40 - # a shared drift orthogonal to the planted steps' shape, so that - # removing it leaves the steps whole - step = (np.arange(T) >= 10) - 0.5 - drift = np.linspace(-0.2, 0.2, T) - drift -= (drift @ step) / (step @ step) * step - x = rng.normal(size=(T, n_src)) * 0.005 + drift[:, None] * rng.normal(size=n_src) - x[10:, 0] += 0.2 # +22% - x[10:, 1] += 0.04 # +4%, far above the noise - x[10:, 2] -= 0.2 # -18% - x = x - x.mean(0) - ok = np.ones(n_src, bool) - ok[5] = False - kw = dict(n_perm=2000, workers=2) - r = trend_tests(x, ok, np.arange(T), **kw) - assert r["resid_q"][:3].max() <= 0.1 - assert r["call"][0] and r["call"][2] and not r["call"][1] - assert not r["call"][5] and not r["tested"][5] - # the rule, source by source - expect = ( - r["tested"] & (r["resid_q"] <= 0.1) & (np.abs(np.expm1(np.nan_to_num(r["resid_d"]))) >= 0.1) - ) - np.testing.assert_array_equal(r["call"], expect) - up = int((r["call"] & (r["resid_d"] > 0)).sum()) - down = int((r["call"] & (r["resid_d"] < 0)).sum()) - assert r["counts"]["call"] == {"up": up, "down": down} - assert up >= 1 and down >= 1 - # a lower minimum calls the small change too; the statistics are the same - r3 = trend_tests(x, ok, np.arange(T), min_change=0.03, **kw) - assert r3["call"][1] - np.testing.assert_array_equal(r3["resid_p"], r["resid_p"]) - # without p there are no calls - r0 = trend_tests(x, ok, np.arange(T), n_perm=0) - assert not r0["call"].any() - assert r0["counts"]["call"] == {"up": 0, "down": 0} +"""Tests of the trend tests (:mod:`giant_python.spine.trends`). + +They test against direct transcriptions of GIAnT-MATLAB's spineTrends.m and +spineTrendsResid.m. +""" + +import math +from typing import Any + +import numpy as np +import pytest + +from giant_python.spine.trends import ( + _median_without, + bh_adjust, + brief_stat, + shared_mode, + step_at, + step_stat, + trend_tests, + trial_blocks, + trial_orders, +) + + +def _step_loop(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """stepStat2 as written in MATLAB (rows = series). + + Returns + ------- + t : np.ndarray + The best step statistic of each series. + k : np.ndarray + The split index of that step in each series. + d : np.ndarray + The step size (difference of means) of each series. + """ + n, T = x.shape + tb, kb, db = np.zeros(n), np.ones(n, int), np.zeros(n) + for k in range(1, T): + a, b = x[:, :k], x[:, k:] + d = b.mean(1) - a.mean(1) + ss = ((a - a.mean(1, keepdims=True)) ** 2).sum(1) + ( + (b - b.mean(1, keepdims=True)) ** 2 + ).sum(1) + t = d / (np.sqrt(ss / (T - 2)) * math.sqrt(1 / k + 1 / (T - k))) + upd = np.abs(t) > np.abs(tb) + tb[upd], kb[upd], db[upd] = t[upd], k, d[upd] + return tb, kb, db + + +def _brief_loop( + x: np.ndarray, blk: np.ndarray, max_w: int +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """``briefStat`` as written in MATLAB, zero-based, with np.median. + + Returns + ------- + t : np.ndarray + The best brief-event statistic of each series. + start : np.ndarray + The start index of that event in each series. + width : np.ndarray + The width of that event in each series. + d : np.ndarray + The event size, relative to the mean of its two sides, of each series. + """ + n, T = x.shape + tb, db = np.zeros(n), np.zeros(n) + sb, wb = np.zeros(n, int), np.ones(n, int) + dd = np.abs(np.diff(x, axis=1)) + in_blk = blk[1:] == blk[:-1] + for w in range(1, max_w + 1): + for a in range(1, T - w): + e = a + w - 1 + b = blk[a] + if blk[a - 1] != b or blk[e + 1] != b or blk[e] != b: + continue + away = in_blk.copy() + away[a - 1 : e + 1] = False + sg = np.median(dd[:, away], axis=1) / (0.6745 * math.sqrt(2)) + left = [i for i in range(max(a - 2, 0), a) if blk[i] == blk[a]] + right = [i for i in range(e + 1, min(e + 2, T - 1) + 1) if blk[i] == blk[a]] + m = x[:, a : e + 1].mean(1) + ml, mr = x[:, left].mean(1), x[:, right].mean(1) + tl = (m - ml) / (sg * math.sqrt(1 / w + 1 / len(left))) + tr = (m - mr) / (sg * math.sqrt(1 / w + 1 / len(right))) + t = np.sign(tl) * np.minimum(abs(tl), abs(tr)) + t[np.sign(tl) != np.sign(tr)] = 0 + d = m - (ml + mr) / 2 + upd = np.abs(t) > np.abs(tb) + tb[upd], sb[upd], wb[upd], db[upd] = t[upd], a, w, d[upd] + return tb, sb, wb, db + + +def test_trial_blocks_split_at_gaps() -> None: + """A new block starts where the acquisition number jumps by more than 1. + + A repeat or a decrease does not start one, as in MATLAB. + """ + np.testing.assert_array_equal(trial_blocks([2, 3, 4, 7, 8, 8, 6, 10]), [0, 0, 0, 1, 1, 1, 1, 2]) + assert trial_blocks([]).size == 0 + + +def test_trials_without_numbers_are_blocks_of_their_own() -> None: + """A trial without an acquisition number is neither in a brief run nor a neighbour of one. + + With no numbers at all, trials are consecutive. + """ + np.testing.assert_array_equal(trial_blocks([10, 11, -1, -1, 14, 15]), [0, 0, 1, 2, 3, 3]) + np.testing.assert_array_equal(trial_blocks([-1, -1, -1]), [0, 0, 0]) + np.testing.assert_array_equal(trial_blocks([-1, -1, -1], unknown_consecutive=False), [0, 1, 2]) + x = np.zeros((1, 7)) + x[0, 3] = 1.0 # a transient at the trial without a number + x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 + t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, -1, 5, 6, 7]), 1) + assert start[0] != 3 + t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, 4, 5, 6, 7]), 1) + assert start[0] == 3 + + +def test_image_blocks_keep_the_paths_boundaries() -> None: + """A subset of a path's trials keeps the path's block boundaries. + + This holds also with acquisition numbers out of order, and the subset + splits where it skips a trial. + """ + from giant_python.spine.trends import image_blocks + + pb = trial_blocks([1, 5, 2, 3]) # 1 | 5, 2, 3 (a decrease joins) + np.testing.assert_array_equal(pb, [0, 1, 1, 1]) + # without the trial numbered 5, numbers 1, 2, 3 alone would be one block + np.testing.assert_array_equal(image_blocks(pb, [0, 2, 3]), [0, 1, 1]) + np.testing.assert_array_equal(trial_blocks([1, 2, 3]), [0, 0, 0]) + # a skipped trial splits a block + pb = trial_blocks(np.arange(6)) + np.testing.assert_array_equal(image_blocks(pb, [0, 1, 3, 4, 5]), [0, 0, 1, 1, 1]) + # trend_tests takes the blocks as given + x = np.random.default_rng(2).normal(size=(5, 2)) + r = trend_tests(x, np.ones(2, bool), [9, 9, 9, 9, 9], n_perm=0, blocks=[0, 0, 1, 1, 1]) + np.testing.assert_array_equal(r["blocks"], [0, 0, 1, 1, 1]) + with pytest.raises(ValueError, match="blocks"): + trend_tests(x, np.ones(2, bool), np.arange(5), n_perm=0, blocks=[0, 1]) + + +@pytest.mark.parametrize( + "kw, match", + [ + (dict(n_perm=-1), "n_perm"), + (dict(max_brief=0), "max_brief"), + (dict(fdr_q=2.0), "fdr_q"), + (dict(fdr_q=0.0), "fdr_q"), + (dict(seed=-3), "seed"), + (dict(min_change=-0.1), "min_change"), + (dict(min_change=1.0), "min_change"), + (dict(min_change=float("nan")), "min_change"), + ], +) +def test_trend_settings_are_checked(kw: dict[str, Any], match: str) -> None: + """Settings the tests cannot use are refused.""" + with pytest.raises(ValueError, match=match): + trend_tests(np.zeros((5, 2)), np.ones(2, bool), np.arange(5), **kw) + + +def test_step_stat_is_the_matlab_loop() -> None: + """Cumulative sums give MATLAB's statistic, split and size.""" + rng = np.random.default_rng(3) + x = rng.normal(size=(200, 17)) * 0.1 + x[:20, 9:] += 0.3 # some real steps + got = step_stat(x) + ref = _step_loop(x) + np.testing.assert_allclose(got[0], ref[0], rtol=1e-10) + np.testing.assert_array_equal(got[1], ref[1]) + np.testing.assert_allclose(got[2], ref[2], rtol=1e-10, atol=1e-15) + t, d = step_at(x, got[1]) + np.testing.assert_allclose(t, got[0], rtol=1e-10) + np.testing.assert_allclose(d, got[2], rtol=1e-10, atol=1e-15) + + +def test_no_step_or_run_keeps_a_missing_position() -> None: + """A series without a non-zero statistic reports no split and no run (not the first trial). + + So does the summary through the pipeline's mapping. + """ + x = np.zeros((2, 8)) + x[1] = np.arange(8) * 0.01 + t, k, d = step_stat(x) + assert t[0] == 0 and k[0] == 0 and d[0] == 0 + assert k[1] > 0 + # a strictly linear series: every trial is the mean of its neighbours, + # so no run differs from both sides + t, start, length, d = brief_stat(x, np.zeros(8, int), 3) + np.testing.assert_array_equal(t, 0) + np.testing.assert_array_equal(start, -1) + np.testing.assert_array_equal(length, 0) + # blocks of one or two trials leave no run with neighbours + rng = np.random.default_rng(1) + y = rng.normal(size=(3, 6)) + t, start, length, _ = brief_stat(y, trial_blocks([1, 2, 5, 6, 9, 10]), 3) + assert (t == 0).all() and (start == -1).all() and (length == 0).all() + r = trend_tests(x.T, np.ones(2, bool), np.arange(8), n_perm=50) + assert r["tested"].all() + assert r["step_k"][0] == 0 and r["step_p"][0] == 1 + assert r["brief_start"][0] == -1 and r["brief_len"][0] == 0 + + +def test_step_at_out_of_range_is_nan() -> None: + """A split outside 1..T-1 gives NaN.""" + t, d = step_at(np.zeros((2, 5)) + [[0, 1, 2, 3, 4]], [0, 2]) + assert np.isnan(t[0]) and np.isnan(d[0]) and d[1] == 2.5 + + +def test_median_without_matches_numpy() -> None: + """The median once some ranks are taken out equals np.median of what is left. + + Ties included. + """ + rng = np.random.default_rng(5) + for m_all, k in ((9, 2), (10, 3), (12, 4), (5, 4)): + vals = rng.integers(0, 4, size=(300, m_all)).astype(float) + order = np.argsort(vals, axis=1, kind="stable") + srt = np.take_along_axis(vals, order, 1) + rank = np.empty_like(order) + np.put_along_axis(rank, order, np.broadcast_to(np.arange(m_all), order.shape), 1) + cols = np.sort(rng.choice(m_all, size=k, replace=False)) + keep = np.setdiff1d(np.arange(m_all), cols) + got = _median_without(srt, rank[:, cols], m_all - k) + if m_all - k == 0: + assert np.isnan(got).all() + else: + np.testing.assert_array_equal(got, np.median(vals[:, keep], 1)) + + +def test_brief_stat_is_the_matlab_loop() -> None: + """The brief statistic, run and size equal MATLAB's, with blocks.""" + rng = np.random.default_rng(4) + T = 15 + x = rng.normal(size=(300, T)) * 0.1 + x[:30, 6:8] += 0.4 # transient changes + blk = trial_blocks([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16]) + for max_w in (1, 3): + got = brief_stat(x, blk, max_w) + ref = _brief_loop(x, blk, max_w) + np.testing.assert_allclose(got[0], ref[0], rtol=1e-10) + np.testing.assert_array_equal(got[1], ref[1]) + np.testing.assert_array_equal(got[2], ref[2]) + np.testing.assert_allclose(got[3], ref[3], rtol=1e-10, atol=1e-15) + # the planted runs are found + t, start, length, _ = brief_stat(x[:30], blk, 3) + assert (t > 0).mean() > 0.9 + assert np.median(start) == 6 and np.median(length) == 2 + + +def test_brief_stat_keeps_runs_inside_blocks() -> None: + """No run (or its neighbours) crosses a block boundary.""" + x = np.zeros((1, 8)) + x[0, 3] = 1.0 # trial 3 starts block 1: no neighbours before it there + x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 + blk = trial_blocks([1, 2, 3, 10, 11, 12, 13, 14]) + t, start, _, _ = brief_stat(x, blk, 1) + assert start[0] != 3 + + +def test_bh_adjust_is_the_step_up_rule() -> None: + """Q <= level exactly where the step-up rule rejects; NaN stays NaN.""" + rng = np.random.default_rng(6) + p = np.concatenate([rng.uniform(size=80), rng.uniform(0, 0.002, 20)]) + p[5] = np.nan + q = bh_adjust(p) + assert np.isnan(q[5]) + fin = np.flatnonzero(np.isfinite(p)) + ps = np.sort(p[fin]) + m = fin.size + below = np.flatnonzero(ps <= np.arange(1, m + 1) / m * 0.1) + expect = np.zeros(p.size, bool) + if below.size: + expect[fin] = p[fin] <= ps[below[-1]] + np.testing.assert_array_equal(q <= 0.1, expect) + np.testing.assert_allclose(bh_adjust([0.01, 0.04, 0.03]), [0.03, 0.04, 0.04]) + + +def test_shared_mode_sign_and_share() -> None: + """A rank-one pattern is recovered with all the variance, signed positive at the end.""" + v0 = np.linspace(1, -1, 10) + v0 /= np.linalg.norm(v0) + x = np.outer([1.0, -2.0, 0.5], v0) + v, share = shared_mode(x) + np.testing.assert_allclose(v, -v0, atol=1e-12) # v0 ends negative + assert share == pytest.approx(1.0) + v, share = shared_mode(np.zeros((0, 4))) + assert np.isnan(v).all() and np.isnan(share) + + +def _session( + rng: np.random.Generator, n_src: int = 40, T: int = 20, step: float = 0.25 +) -> np.ndarray: + """Normalized-like sizes (trials, sources) with a shared drift and one step. + + Noise, a shared drift (most of the variance, as in real sessions) and + one source with a step after trial 9. + + Returns + ------- + np.ndarray + The (trials, sources) sizes, with each source's mean removed. + """ + drift = np.linspace(-0.2, 0.2, T) + x = rng.normal(size=(T, n_src)) * 0.05 + drift[:, None] * rng.normal(size=n_src) + x[10:, 0] += step + return x - x.mean(0) + + +def test_trend_tests_find_a_planted_step() -> None: + """A planted step has small p and q. + + Beyond the shared drift, the other sources do not pile up at small p. + """ + rng = np.random.default_rng(7) + x = _session(rng) + ok = np.ones(x.shape[1], bool) + ok[3] = False + r = trend_tests(x, ok, np.arange(2, 22), n_perm=2000, workers=2) + assert r["tested"].sum() == x.shape[1] - 1 and not r["tested"][3] + assert np.isnan(r["step_p"][3]) and r["step_k"][3] == -1 + assert r["step_k"][0] == 10 and r["step_t"][0] > 0 + assert r["step_p"][0] < 0.002 and r["step_q"][0] <= 0.1 + # the shared trend is the drift, not the planted step; the resid test + # is the step test of what is left once each source's part is removed + assert abs(np.corrcoef(r["shared_v"], np.arange(20))[0, 1]) > 0.95 + tested = r["tested"] + lx = x.T[tested] + v = shared_mode(lx)[0] + np.testing.assert_allclose(r["shared_v"], v) + np.testing.assert_allclose(r["shared_loading"][tested], lx @ v) + rt, rk, rd = step_stat(lx - np.outer(lx @ v, v)) + np.testing.assert_allclose(r["resid_t"][tested], rt) + np.testing.assert_array_equal(r["resid_k"][tested], rk) + # every source follows the drift (a real step for the step test); + # beyond it, the others are null + assert (r["step_p"][4:] < 0.05).mean() > 0.5 + assert (r["resid_p"][4:] < 0.05).mean() < 0.2 + assert r["counts"]["step"]["fdr_up"] >= 1 + assert r["shared_v"].shape == (20,) and 0 < r["var_share"] < 1 + + +def test_trend_tests_p_does_not_depend_on_the_others_or_threads() -> None: + """Each source has its own trial orders. + + The step and brief p are the same whichever other sources are tested, + and no p depends on the threads; the beyond-trend test depends on the + tested set through the shared trend. + """ + rng = np.random.default_rng(8) + x = _session(rng, n_src=6, T=12) + acq = np.arange(12) + a = trend_tests(x, np.ones(6, bool), acq, n_perm=500, workers=1) + b = trend_tests(x, np.ones(6, bool), acq, n_perm=500, workers=4) + for key in ("step_p", "brief_p", "resid_p"): + np.testing.assert_array_equal(a[key], b[key]) + ok = np.zeros(6, bool) + ok[[0, 2]] = True + c = trend_tests(x, ok, acq, n_perm=500) + np.testing.assert_array_equal(c["step_p"][[0, 2]], a["step_p"][[0, 2]]) + np.testing.assert_array_equal(c["brief_p"][[0, 2]], a["brief_p"][[0, 2]]) + assert not np.allclose(c["shared_v"], a["shared_v"]) + + +def test_ties_at_the_edge_split_count() -> None: + """One outlying first trial gives p about 2/T, not tiny. + + Every order that puts it first or last gives the same statistic. + """ + rng = np.random.default_rng(9) + T = 20 + x = rng.normal(size=(T, 1)) * 0.01 + x[0, 0] = 1.0 + r = trend_tests(x - x.mean(), np.ones(1, bool), np.arange(T), n_perm=4000) + assert r["step_k"][0] == 1 + assert r["step_p"][0] == pytest.approx(2 / T, abs=0.02) + + +def test_noise_free_edge_outlier_ties_with_its_mirror() -> None: + """A series without spread apart from one end trial has an infinite step statistic. + + The statistic is equal for the series and its mirror image, so every + order that puts the trial at either end ties (p about 2/T). + """ + x = np.zeros((2, 10)) + x[0, -1] = 1.0 + x[1, 0] = 1.0 + t, k, _ = step_stat(x) + assert np.isinf(t).all() and t[0] > 0 > t[1] + np.testing.assert_array_equal(k, [9, 1]) + r = trend_tests(x[:1].T, np.ones(1, bool), np.arange(10), n_perm=4000) + assert r["step_p"][0] == pytest.approx(0.2, abs=0.03) + # step_at agrees at the chosen split, also for a nearly noise-free step + y = np.array([[0.0, 1e-6, 1.0, 1.000001]]) + t, k, d = step_stat(y) + ta, da = step_at(y, k) + assert np.isinf(t[0]) and k[0] == 2 + np.testing.assert_array_equal(ta, t) + np.testing.assert_allclose(da, d) + np.testing.assert_array_equal(step_at(x, [9, 1])[0], step_stat(x)[0]) + + +def test_trend_tests_without_permutations() -> None: + """n_perm 0 gives the statistics without p or q.""" + rng = np.random.default_rng(10) + x = _session(rng, n_src=5, T=10) + r = trend_tests(x, np.ones(5, bool), np.arange(10), n_perm=0) + assert np.isfinite(r["step_t"]).all() and np.isnan(r["step_p"]).all() + assert np.isnan(r["step_q"]).all() + assert r["counts"]["step"]["fdr_up"] == 0 + + +def test_trend_tests_need_three_trials() -> None: + """Fewer than three trials: nothing is tested.""" + r = trend_tests(np.zeros((2, 3)), np.ones(3, bool), [1, 2], n_perm=10) + assert not r["tested"].any() and np.isnan(r["step_t"]).all() + + +def test_permutations_in_chunks_give_the_same_p() -> None: + """The orders are drawn in chunks to bound memory. + + The p-values do not depend on the chunk size. + """ + from giant_python.spine.trends import _perm_p + + rng = np.random.default_rng(11) + x = rng.normal(size=14) + resid = rng.normal(size=14) + blocks = trial_blocks(np.arange(14)) + t_obs = [ + step_stat(x[None])[0][0], + brief_stat(x[None], blocks)[0][0], + step_stat(resid[None])[0][0], + ] + one = _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3) + for rows in (1, 7, 200): + assert _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3, rows) == one + + +def test_trial_orders_are_seeded_permutations() -> None: + """Each row is a permutation; the same seed and source repeat.""" + o = trial_orders(1, 7, 50, 9) + assert (np.sort(o, axis=1) == np.arange(9)).all() + np.testing.assert_array_equal(o, trial_orders(1, 7, 50, 9)) + assert not np.array_equal(o, trial_orders(1, 8, 50, 9)) + assert trial_orders(1, 7, 0, 9).shape == (0, 9) + + +def test_calls_need_q_and_the_minimum_change() -> None: + """A call is a change beyond the shared trend with q <= fdr_q and enough size. + + The relative size must be at least min_change, in either direction; a + small change that the test finds is not called, an untested source + never. + """ + rng = np.random.default_rng(3) + T, n_src = 20, 40 + # a shared drift orthogonal to the planted steps' shape, so that + # removing it leaves the steps whole + step = (np.arange(T) >= 10) - 0.5 + drift = np.linspace(-0.2, 0.2, T) + drift -= (drift @ step) / (step @ step) * step + x = rng.normal(size=(T, n_src)) * 0.005 + drift[:, None] * rng.normal(size=n_src) + x[10:, 0] += 0.2 # +22% + x[10:, 1] += 0.04 # +4%, far above the noise + x[10:, 2] -= 0.2 # -18% + x = x - x.mean(0) + ok = np.ones(n_src, bool) + ok[5] = False + kw = dict(n_perm=2000, workers=2) + r = trend_tests(x, ok, np.arange(T), **kw) + assert r["resid_q"][:3].max() <= 0.1 + assert r["call"][0] and r["call"][2] and not r["call"][1] + assert not r["call"][5] and not r["tested"][5] + # the rule, source by source + expect = ( + r["tested"] & (r["resid_q"] <= 0.1) & (np.abs(np.expm1(np.nan_to_num(r["resid_d"]))) >= 0.1) + ) + np.testing.assert_array_equal(r["call"], expect) + up = int((r["call"] & (r["resid_d"] > 0)).sum()) + down = int((r["call"] & (r["resid_d"] < 0)).sum()) + assert r["counts"]["call"] == {"up": up, "down": down} + assert up >= 1 and down >= 1 + # a lower minimum calls the small change too; the statistics are the same + r3 = trend_tests(x, ok, np.arange(T), min_change=0.03, **kw) + assert r3["call"][1] + np.testing.assert_array_equal(r3["resid_p"], r["resid_p"]) + # without p there are no calls + r0 = trend_tests(x, ok, np.arange(T), n_perm=0) + assert not r0["call"].any() + assert r0["counts"]["call"] == {"up": 0, "down": 0} diff --git a/tests/spine/test_spine_view.py b/tests/spine/test_spine_view.py index b8cb623f..740aaf91 100644 --- a/tests/spine/test_spine_view.py +++ b/tests/spine/test_spine_view.py @@ -1,806 +1,842 @@ -"""Tests of the spine viewer's data, API and HTML export. - -The viewer is :mod:`giant_python.spine.view`; the tests run on a synthetic -session. -""" - -import base64 -import gzip -import json -import re -import threading -import urllib.request -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.spine.pipeline import make_spine_summary -from giant_python.spine.product import read_product -from giant_python.spine.rois import read_marks -from giant_python.spine.view.data import ( - SpineStore, - blur_nan, - late_trials, - robust_z, -) -from giant_python.spine.view.export import export_html, field_key, pack -from giant_python.spine.view.server import make_server - -from . import synthetic as syn - - -@pytest.fixture -def product(tmp_path: Path) -> str: - """Make a synthetic session's spine summary (with network images).""" - s = syn.make_session(tmp_path) - rep = make_spine_summary( - s["run"], - s["table"], - tmp_path / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - n_perm=100, - ) - return rep["output"] - - -def test_blur_nan_ignores_nan() -> None: - """NaN stays NaN and does not pull its neighbours down.""" - img = np.ones((9, 9), np.float32) - img[4, 4] = np.nan - out = blur_nan(img) - assert np.isnan(out[4, 4]) - np.testing.assert_allclose(out[np.isfinite(out)], 1.0, rtol=1e-6) - - -def test_robust_z_and_late_trials() -> None: - """Median and MAD z-scores. - - Late trials are the last block, or the second half of one block. - """ - z = robust_z(np.array([[0.0, 1.0, 2.0, np.nan]])) - assert z[0, 1] == 0 and np.isnan(z[0, 3]) - np.testing.assert_array_equal(late_trials([0, 0, 1, 1, 1]), [0, 0, 1, 1, 1]) - np.testing.assert_array_equal(late_trials([0, 0, 0, 0]), [0, 0, 1, 1]) - - -def test_normalized_field_and_change(product: str) -> None: - """Each trial is divided by its median over the common pixels. - - The change view compares blurred trials, with a brightness in [0, 1]. - """ - store = SpineStore([(None, product)]) - pr = store.products[0] - stack = read_product(product)["paths"][1]["images"]["mean_ch1"] - nz = pr.normalized(1, "mean_ch1") - common = np.isfinite(stack).all(axis=0) - for t in range(stack.shape[0]): - med = np.median(stack[t][common]) - np.testing.assert_allclose(nz["stack"][t], stack[t] / med, rtol=1e-6) - np.testing.assert_allclose( - pr.field(1, "mean_ch1", -1, "image", "")[0], - np.nanmean(nz["stack"], axis=0), - rtol=1e-6, - ) - ch = pr.field(1, "mean_ch1", 2, "change", "average") - assert ch.shape == (2,) + stack.shape[1:] - b = ch[1] - assert np.nanmin(b) >= 0 and np.nanmax(b) <= 1 - cp = pr.change_prep(1, "mean_ch1") - expect = cp["blurred"][2] / cp["mean"] - 1 - np.testing.assert_allclose(ch[0], expect, rtol=1e-5, equal_nan=True) - prev = pr.field(1, "mean_ch1", 2, "change", "previous")[0] - np.testing.assert_allclose( - prev, - cp["blurred"][2] / cp["blurred"][1] - 1, - rtol=1e-5, - equal_nan=True, - ) - # the first trial of a block has no previous trial - assert np.isnan(pr.field(1, "mean_ch1", 0, "change", "previous")[0]).all() - act = pr.field(1, "", -1, "activity", "") - assert act.shape == (1,) + stack.shape[1:] - - -def test_store_sources_roi_and_crops(product: str) -> None: - """Sources carry sizes and trends. - - A window and its crops sit on the same grid around the source. - """ - store = SpineStore([("syn", product)], crop_half=4) - meta = store.meta() - p1 = meta["products"][0]["paths"][1] - assert meta["products"][0]["name"] == "syn" - assert "f0_net" in p1["trends"] and p1["n_sources"] == len(syn.SOURCES) - src = store.sources(0, 1) - prod = read_product(product)["paths"][1] - np.testing.assert_allclose( - np.array(src["normalized"]["f0_net"], float), - prod["normalized"]["sources"]["f0_net"], - ) - assert src["trends"]["f0_net"]["attrs"]["n_perm"] == 100 - roi = store.roi(0, 1, 0) - assert roi["size"] == 9 and np.array(roi["weights"]).shape == (9, 9) - r0, c0 = roi["origin"] - w = prod["rois"]["sources"].image(0) - np.testing.assert_allclose(np.array(roi["weights"]), w[r0 : r0 + 9, c0 : c0 + 9], atol=1e-6) - crops = store.crops(0, 1, 0, "mean_ch1", "image", "average") - n_t = len(prod["trials"]["acquisition"]) - assert crops.shape == (1, n_t + 1, 9, 9) - full = store.products[0].normalized(1, "mean_ch1")["stack"] - np.testing.assert_allclose(crops[0, 1:], full[:, r0 : r0 + 9, c0 : c0 + 9], rtol=1e-6) - ch = store.crops(0, 1, 0, "mean_ch1", "change", "average") - assert ch.shape == (2, n_t + 1, 9, 9) - - -def test_marks_attach_by_position(product: str, tmp_path: Path) -> None: - """A mark is stored with its source's position. - - It attaches to the nearest source within 2.5 px; clearing removes it. - """ - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - got = store.set_mark(0, 1, 1, "Growing", "a note") - assert got["by_source"][1]["label"] == "Growing" - rows = read_marks(marks) - assert rows[0]["Source"] == "2" and rows[0]["Note"] == "a note" - rs = read_product(product)["paths"][1]["rois"]["sources"] - assert rows[0]["Row0"] == pytest.approx(rs.rows[1]) - # a second mark on the same source replaces the first - store.set_mark(0, 1, 1, "Shrinking", "") - assert len(read_marks(marks)) == 1 - assert store.marks_for(0, 1)["by_source"][1]["label"] == "Shrinking" - # a mark far from every source does not attach - rows = read_marks(marks) + [dict(rows[0], Row0=0.0, Col0=0.0, Label="Unsure")] - from giant_python.spine.rois import write_marks - - write_marks(marks, rows) - assert store.marks_for(0, 1)["unattached"] == 1 - store.set_mark(0, 1, 1, "", "") - assert 1 not in store.marks_for(0, 1)["by_source"] - with pytest.raises(ValueError, match="unknown mark"): - store.set_mark(0, 1, 1, "Big", "") - - -def test_product_is_read_again_when_it_changes(product: str, tmp_path: Path) -> None: - """A rewritten product shows on the next request.""" - import os - import shutil - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - store = SpineStore([(None, copy)]) - first = store.sources(0, 1)["normalized"]["f0_net"] - import h5py - - with h5py.File(copy, "r+") as f: - d = f["Path1/normalized/sources/f0_net"] - d[...] = d[()] + 1 - st = os.stat(copy) - os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - again = store.sources(0, 1)["normalized"]["f0_net"] - a = np.array(first, float) - np.testing.assert_allclose(np.array(again, float), a + 1) - - -def _get(url: str) -> dict | np.ndarray: - """GET and decode JSON or float32.""" - with urllib.request.urlopen(url) as r: - body = r.read() - if r.headers.get("Content-Type") == "application/json": - return json.loads(body) - shape = json.loads(r.headers["X-Shape"]) - return np.frombuffer(body, np.float32).reshape(shape) - - -def test_server_answers_the_api(product: str, tmp_path: Path) -> None: - """The page and every API route answer; a mark is written by POST.""" - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - base = f"http://127.0.0.1:{srv.server_address[1]}" - try: - with urllib.request.urlopen(base + "/") as r: - assert b"Spine size viewer" in r.read() - meta = _get(base + "/api/meta") - assert meta["products"][0]["paths"]["1"]["n_sources"] == 3 - src = _get(base + "/api/sources?prod=0&path=1") - assert src["n"] == 3 - f = _get(base + "/api/field?prod=0&path=1&image=f0_net&trial=1") - assert f.shape == (1, syn.H, syn.W) - c = _get(base + "/api/crops?prod=0&path=1&id=0&image=f0_net&view=change") - assert c.shape[0] == 2 - roi = _get(base + "/api/roi?prod=0&path=1&id=2") - assert roi["id"] == 2 - req = urllib.request.Request( - base + "/api/mark", - data=json.dumps({"prod": 0, "path": 1, "id": 0, "label": "Unsure"}).encode(), - headers={"Content-Type": "application/json"}, - ) - with urllib.request.urlopen(req) as r: - assert json.loads(r.read())["by_source"]["0"]["label"] == "Unsure" - assert read_marks(marks)[0]["Label"] == "Unsure" - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(base + "/api/field?prod=0&path=7&image=x") - assert e.value.code == 404 - finally: - srv.shutdown() - srv.server_close() - - -def _static(page: str) -> dict: - """Extract the data embedded in an exported page.""" - m = re.search( - r'", - page, - ) - return json.loads(gzip.decompress(base64.b64decode(m.group(1)))) - - -def _unpack(e: dict) -> np.ndarray: - """Decode an embedded array (as the page's ``unpack``).""" - parts = [] - for layer in e["layers"]: - q = np.frombuffer(base64.b64decode(layer["b64"]), np.uint8) - v = layer["offset"] + layer["scale"] * q.astype(np.float64) - parts.append(np.where(q == 255, np.nan, v)) - return np.concatenate(parts).reshape(e["shape"]) - - -def test_pack_round_trips_within_a_code() -> None: - """uint8 codes keep values within half a step and NaN as NaN.""" - rng = np.random.default_rng(0) - a = rng.normal(1, 0.1, (1, 20, 30)).astype(np.float32) - a[0, 3, 4] = np.nan - e = pack(a, "image") - back = _unpack(e) - assert np.isnan(back[0, 3, 4]) - step = e["layers"][0]["scale"] - inside = np.isfinite(a) & (a >= e["layers"][0]["offset"]) - inside &= a <= e["layers"][0]["offset"] + 254 * step - np.testing.assert_allclose(back[inside], a[inside], atol=step / 2 + 1e-7) - ch = np.stack([np.full((4, 4), 0.1), np.full((4, 4), 0.5)]) - back = _unpack(pack(ch, "change")) - np.testing.assert_allclose(back, ch, atol=0.003) - - -def test_export_html_embeds_the_viewer_data(product: str, tmp_path: Path) -> None: - """The page holds the meta, the sources, the mean fields and some crops. - - The crops are those of the chosen sources; the page holds nothing that - needs the server. - """ - out = tmp_path / "page.html" - rep = export_html(product, out, sources=[2], name="syn") - page = out.read_text(encoding="utf-8") - assert "Spine sizes syn" in page - data = _static(page) - assert data["meta"]["marks_file"] is None - assert data["sources"]["1"]["n"] == 3 - key = field_key(1, "f0_net", -1, "image", "") - assert key in data["fields"] - assert field_key(1, "f0_net", -1, "change", "") in data["fields"] - assert rep["sources"][1] == [2] - assert "1|1" in data["rois"] and "1|0" not in data["rois"] - crop_keys = [k for k in data["crops"] if k.startswith("1|1|")] - assert crop_keys and all("f0_" in k for k in crop_keys) - store = SpineStore([(None, product)]) - mean = store.products[0].field(1, "f0_net", -1, "image", "") - e = data["fields"][key] - back = _unpack(e) - fin = np.isfinite(mean) - step = e["layers"][0]["scale"] - lo = e["layers"][0]["offset"] - inside = fin & (mean >= lo) & (mean <= lo + 254 * step) - np.testing.assert_allclose(back[inside], mean[inside], atol=step) - - -def test_cli_export(product: str, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """Giant spine export-html writes the page and reports it.""" - out = tmp_path / "e.html" - assert main(["spine", "export-html", product, "--out", str(out), "--top", "1"]) == 0 - rep = json.loads(capsys.readouterr().out) - assert rep["output"] == str(out) and out.is_file() - - -def test_pick_sources_marked_first_then_by_q_and_size() -> None: - """The export's crops go to the marked sources, then by q. - - Ties at the permutation floor go to the larger statistic. - """ - from giant_python.spine.view.export import pick_sources - - nan = float("nan") - tr = { - "step_q": [0.5, 1e-4, 1e-4, nan, 0.02], - "step_t": [1.0, 3.0, 6.0, nan, 2.5], - "brief_q": [0.9, 0.9, 0.9, nan, 0.9], - "brief_t": [1.0, 1.0, 1.0, nan, 1.0], - "resid_q": [0.04, 0.9, 0.9, nan, 0.9], - "resid_t": [2.0, 1.0, 1.0, nan, 1.0], - } - src = {"n": 5, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} - assert pick_sources(src, "f0", 3) == [0, 2, 1, 4] - assert pick_sources(src, "f0", 0) == [0] - - -def test_marks_need_json_from_this_server(product: str, tmp_path: Path) -> None: - """The mark endpoint refuses bodies that are not JSON and foreign origins. - - Bodies that are not JSON could be sent by a cross-origin page without a - preflight; requests whose Origin is another site are refused too. - """ - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - base = f"http://127.0.0.1:{srv.server_address[1]}" - body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() - try: - for headers, code in ( - ({"Content-Type": "text/plain"}, 415), - ( - { - "Content-Type": "application/json", - "Origin": "http://example.com", - }, - 403, - ), - ): - req = urllib.request.Request(base + "/api/mark", data=body, headers=headers) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == code - assert not marks.exists() - req = urllib.request.Request( - base + "/api/mark", - data=body, - headers={"Content-Type": "application/json", "Origin": base}, - ) - with urllib.request.urlopen(req) as r: - assert r.status == 200 - assert read_marks(marks)[0]["Label"] == "Unsure" - finally: - srv.shutdown() - srv.server_close() - - -def test_sources_without_sources_keep_the_fields(product: str, tmp_path: Path) -> None: - """A path without sources answers with the same, empty, fields.""" - store = SpineStore([(None, product)]) - pr = store.products[0] - pr.small()["paths"][1]["rois"].pop("sources") - src = store.sources(0, 1) - assert src["n"] == 0 and src["trends"] == {} and src["ids"] == [] - assert src["marks"] == {"by_source": {}, "unattached": 0} - - -def test_cache_keys_follow_the_file(product: str, tmp_path: Path) -> None: - """A result made from the old file is not served after the file changes. - - Even if it lands in the cache after the reload. - """ - import os - import shutil - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - store = SpineStore([(None, copy)]) - pr = store.products[0] - old = pr.normalized(1, "mean_ch1") - gen = pr._gen - st = os.stat(copy) - os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - pr.small() - assert pr._gen == gen + 1 - # a late insert under the old generation's key is never read - pr._cache.get((gen, "norm", 1, "mean_ch1"), lambda: "stale") - new = pr.normalized(1, "mean_ch1") - assert new is not old and not isinstance(new, str) - - -def test_server_refuses_untrusted_hosts(product: str, tmp_path: Path) -> None: - """Requests naming another host (DNS rebinding) get nothing. - - Marks from an origin that is not this server's trusted names are refused. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - port = srv.server_address[1] - base = f"http://127.0.0.1:{port}" - try: - req = urllib.request.Request(base + "/api/meta", headers={"Host": f"evil.example:{port}"}) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == 403 - req = urllib.request.Request(base + "/api/meta", headers={"Host": f"localhost:{port}"}) - with urllib.request.urlopen(req) as r: - assert r.status == 200 - body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() - for origin in ( - f"http://evil.example:{port}", - f"https://127.0.0.1:{port}", - ): - req = urllib.request.Request( - base + "/api/mark", - data=body, - headers={ - "Content-Type": "application/json", - "Origin": origin, - "Host": f"127.0.0.1:{port}", - }, - ) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == 403 - finally: - srv.shutdown() - srv.server_close() - - -def test_export_refuses_unknown_paths(product: str, tmp_path: Path) -> None: - """Asking for a path the summary does not have is an error. - - Not an empty page. - """ - with pytest.raises(ValueError, match="no path"): - export_html(product, tmp_path / "p.html", paths=[7]) - assert not (tmp_path / "p.html").exists() - - -def test_pick_sources_uses_the_strongest_test_at_the_smallest_q() -> None: - """Among tests tied at a source's smallest q, the largest statistic wins. - - It breaks ties between sources. - """ - from giant_python.spine.view.export import pick_sources - - tr = { - "step_q": [1e-3, 1e-3], - "step_t": [2.0, 6.0], - "brief_q": [1e-3, 0.5], - "brief_t": [20.0, 1.0], - "resid_q": [0.9, 0.9], - "resid_t": [1.0, 1.0], - } - src = {"n": 2, "trends": {"f0": tr}, "marks": {}} - assert pick_sources(src, "f0", 1) == [0] - - -def test_marks_keep_their_order_within_a_path(product: str, tmp_path: Path) -> None: - """Two marks with the same time that land on one source. - - The one written later wins, whatever their rows. - """ - from giant_python.spine.rois import write_marks - - store = SpineStore([(None, product)], tmp_path / "marks.csv") - rs = read_product(product)["paths"][1]["rois"]["sources"] - r, c = float(rs.rows[0]), float(rs.cols[0]) - base = { - "Path": 1, - "Source": 1, - "Note": "", - "Col0": c, - "Updated": "2026-01-01 00:00:00", - } - write_marks( - tmp_path / "marks.csv", - [ - dict(base, Label="Growing", Row0=r + 0.5), - dict(base, Label="Shrinking", Row0=r - 0.5), - ], - ) - assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" - # a write through the store keeps the order within the path - store.set_mark(0, 1, 1, "Unsure", "") - rows = read_marks(tmp_path / "marks.csv") - assert [m["Label"] for m in rows] == ["Growing", "Shrinking", "Unsure"] - assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" - - -def test_pick_sources_keeps_infinite_statistics_first() -> None: - """An infinite statistic (a change without noise) ranks first. - - Among equal q-values. - """ - from giant_python.spine.view.export import pick_sources - - inf = float("inf") - tr = {f"{t}_{f}": [None, None] for t in ("brief", "resid") for f in ("q", "t")} - tr.update({"step_q": [1e-4, 1e-4], "step_t": [6.0, inf]}) - src = {"n": 2, "trends": {"f0": tr}, "marks": {}} - assert pick_sources(src, "f0", 1) == [1] - - -def test_summary_without_rois_loads(product: str, tmp_path: Path) -> None: - """A summary with no sources and no user ROIs (no rois group) loads.""" - import shutil - - import h5py - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - for n in ("Path1", "Path2"): - if f"{n}/rois" in f: - del f[f"{n}/rois"] - store = SpineStore([(None, copy)]) - assert store.sources(0, 1)["n"] == 0 - assert store.meta()["products"][0]["paths"][1]["n_sources"] == 0 - - -def test_server_on_ipv6_loopback_and_port_80_names(product: str) -> None: - """The server binds an IPv6 literal, and at port 80 trusts portless names. - - Those are the names without a port, as browsers send them. - """ - import socket as so - - from giant_python.spine.view.server import _bracket, allowed_hosts - - assert _bracket("::1") == "[::1]" and _bracket("localhost") == "localhost" - at80 = allowed_hosts("127.0.0.1", 80) - assert "127.0.0.1" in at80 and "localhost:80" in at80 - assert "127.0.0.1" not in allowed_hosts("127.0.0.1", 8790) - assert allowed_hosts("0.0.0.0", 8790) == frozenset() - if not so.has_ipv6: - pytest.skip("no IPv6") - store = SpineStore([(None, product)]) - try: - srv = make_server(store, host="::1", port=0) - except OSError: - pytest.skip("no IPv6 loopback") - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - port = srv.server_address[1] - try: - assert f"[::1]:{port}" in srv.RequestHandlerClass.allowed - with urllib.request.urlopen(f"http://[::1]:{port}/api/meta") as r: - assert r.status == 200 - finally: - srv.shutdown() - srv.server_close() - - -def test_a_note_alone_keeps_the_label(product: str, tmp_path: Path) -> None: - """A note saved on its own keeps the label the source has at that moment. - - Unsure without one. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - got = store.set_mark(0, 1, 0, None, "first note") - assert got["by_source"][0]["label"] == "Unsure" - store.set_mark(0, 1, 0, "Growing", "first note") - got = store.set_mark(0, 1, 0, None, "second note") - assert got["by_source"][0] == { - "label": "Growing", - "note": "second note", - "updated": got["by_source"][0]["updated"], - } - assert len(read_marks(tmp_path / "marks.csv")) == 1 - - -def test_export_refuses_unknown_sources_and_images(product: str, tmp_path: Path) -> None: - """Source numbers and crop images the summary lacks are errors.""" - with pytest.raises(ValueError, match="no source"): - export_html(product, tmp_path / "p.html", sources=[99]) - with pytest.raises(ValueError, match="no image"): - export_html(product, tmp_path / "p.html", crop_images=["f0_nope"]) - assert not (tmp_path / "p.html").exists() - - -def test_export_crops_only_the_images_asked_for(product: str, tmp_path: Path) -> None: - """With --crop-images, a path that lacks them gets no crops. - - Rather than every image. - """ - import h5py - - out = tmp_path / "p.html" - copy = tmp_path / "copy.h5" - import shutil - - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - del f["Path2/images/f0_net"] - export_html(copy, out, sources=[1], crop_images=["f0_net"]) - data = _static(out.read_text(encoding="utf-8")) - assert any(k.startswith("1|0|f0_net|") for k in data["crops"]) - assert not [k for k in data["crops"] if k.startswith("2|")] - - -def test_cache_makes_a_value_once_for_concurrent_requests() -> None: - """Concurrent requests for a value being made wait for it. - - Instead of making it again. - """ - import time as _t - - from giant_python.spine.view.data import _Lru - - cache = _Lru(4) - calls = [] - - def make() -> str: - """Make a slow value.""" - calls.append(1) - _t.sleep(0.2) - return "v" - - out = [] - ths = [threading.Thread(target=lambda: out.append(cache.get("k", make))) for _ in range(5)] - for th in ths: - th.start() - for th in ths: - th.join() - assert out == ["v"] * 5 and len(calls) == 1 - assert cache.making == {} - - -def test_cache_is_bounded_by_bytes() -> None: - """Values are evicted, oldest first, once their arrays exceed the budget. - - The newest stays even when it alone is larger. - """ - from giant_python.spine.view.data import _Lru - - cache = _Lru(3000) - for k in range(4): - cache.get(k, lambda: {"a": np.zeros(125)}) # 1000 bytes each - assert list(cache.d) == [1, 2, 3] - cache.get("big", lambda: np.zeros(1000)) - assert list(cache.d) == ["big"] - - -def test_cache_lock_stays_while_requests_wait() -> None: - """The lock of a key being made stays while any request still uses it. - - Even if the value is evicted meanwhile: a later request for the key waits - on the same lock instead of computing in parallel. - """ - import time as _t - - from giant_python.spine.view.data import _Lru - - cache = _Lru(1) # every new value evicts the previous one - running = [] - peak = [] - - def make() -> np.ndarray: - """Make a slow value that records how many are being made at once.""" - running.append(1) - peak.append(len(running)) - _t.sleep(0.05) - running.pop() - return np.zeros(10) - - def worker() -> None: - """Ask for the key, then for another (evicting it).""" - cache.get("k", make) - cache.get(object(), lambda: np.zeros(10)) - - ths = [threading.Thread(target=worker) for _ in range(6)] - for th in ths: - th.start() - for th in ths: - th.join() - assert max(peak) == 1 - assert cache.making == {} - - -def test_mark_refused_when_the_source_moved(product: str, tmp_path: Path) -> None: - """A mark that names a position other than the source's is refused. - - The summary changed under an open page; the mark writes nothing. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - rs = read_product(product)["paths"][1]["rois"]["sources"] - with pytest.raises(ValueError, match="changed"): - store.set_mark(0, 1, 1, "Growing", "", row=0.0, col=0.0) - assert not (tmp_path / "marks.csv").exists() - got = store.set_mark(0, 1, 1, "Growing", "", row=float(rs.rows[1]), col=float(rs.cols[1])) - assert got["by_source"][1]["label"] == "Growing" - - -def test_change_needs_only_its_own_cache_entry(product: str) -> None: - """change() reads everything it needs from the change record. - - So it does not reload the normalized stack (no thrashing when the two do - not fit together in the cache). - """ - store = SpineStore([(None, product)]) - pr = store.products[0] - pr.change_prep(1, "mean_ch1") - calls = [] - real = pr.normalized - pr.normalized = lambda *a: calls.append(a) or real(*a) - for t in (-1, 0, 2): - pr.change(1, "mean_ch1", t, "average") - assert calls == [] - - -def test_default_image_calls_and_window_motion_reach_the_page(product: str) -> None: - """The page gets the default image, the calls and the windows' motion. - - That is, the summary's default image, the calls and structural change of - each image's tests, and the windows' motion. - """ - store = SpineStore([(None, product)]) - p1 = store.meta()["products"][0]["paths"][1] - assert p1["primary_image"] == "f0_net" - src = store.sources(0, 1) - assert len(src["align_px"]) == src["n"] - assert src["trends"]["f0_net"]["attrs"]["structural_image"] == "mean_ch2" - assert len(src["trends"]["f0_net"]["call"]) == src["n"] - assert len(src["trends"]["f0_net"]["structural_d"]) == src["n"] - from importlib.resources import files - - page = files("giant_python.spine.view").joinpath("page.html").read_text(encoding="utf-8") - for key in ('["call", "call"]', '"structural_d"', '"align_px"'): - assert key in page - - -def test_summaries_before_format_4_still_load(product: str, tmp_path: Path) -> None: - """Summaries before format 4 still load. - - Without the default image, the calls or the window motion (format 3), the - page gets None for the image and NaN (null) motion. - """ - import shutil - - import h5py - - copy = tmp_path / "v3.h5" - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - for n in ("Path1", "Path2"): - g = f[n] - del g.attrs["primary_image"] - del g["readout/sources/align_px"] - for name in g["trends/sources"]: - t = g[f"trends/sources/{name}"] - for k in ("call", "structural_d"): - if k in t: - del t[k] - store = SpineStore([(None, copy)]) - assert store.meta()["products"][0]["paths"][1]["primary_image"] is None - src = store.sources(0, 1) - assert np.isnan(np.array(src["align_px"], float)).all() - assert "call" not in src["trends"]["f0_net"] - assert read_product(copy)["paths"][1]["primary_image"] is None - - -def test_pick_sources_takes_the_calls_first() -> None: - """The export's crops go to the marked sources, then to the calls. - - The calls are taken by q, then the rest by the smallest q. - """ - from giant_python.spine.view.export import pick_sources, primary_image - - tr = { - "step_q": [0.5, 1e-4, 0.2, 0.9], - "step_t": [1.0, 6.0, 2.0, 1.0], - "brief_q": [0.9, 0.9, 0.9, 0.9], - "brief_t": [1.0, 1.0, 1.0, 1.0], - "resid_q": [0.9, 0.9, 0.05, 0.01], - "resid_t": [1.0, 1.0, 3.0, 4.0], - "call": [False, False, True, True], - } - src = {"n": 4, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} - assert pick_sources(src, "f0", 3) == [0, 3, 2, 1] - # a marked call does not take one of the top places - src["marks"] = {"by_source": {"3": {}}} - assert pick_sources(src, "f0", 1) == [3, 2] - assert primary_image(["f0_net", "f0_gain"], "f0_net") == "f0_net" - assert primary_image(["f0_net", "f0_gain"], "gone") == "f0_gain" - assert primary_image(["f0_net", "f0_gain"]) == "f0_gain" +"""Tests of the spine viewer's data, API and HTML export. + +The viewer is :mod:`giant_python.spine.view`; the tests run on a synthetic +session. +""" + +import base64 +import gzip +import json +import re +import threading +import urllib.request +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.spine.pipeline import make_spine_summary +from giant_python.spine.product import read_product +from giant_python.spine.rois import read_marks +from giant_python.spine.view.data import ( + SpineStore, + blur_nan, + late_trials, + robust_z, +) +from giant_python.spine.view.export import export_html, field_key, pack +from giant_python.spine.view.server import make_server + +from . import synthetic as syn + + +@pytest.fixture +def product(tmp_path: Path) -> str: + """Make a synthetic session's spine summary (with network images). + + Returns + ------- + str + Path of the spine summary file. + """ + s = syn.make_session(tmp_path) + rep = make_spine_summary( + s["run"], + s["table"], + tmp_path / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + n_perm=100, + ) + return rep["output"] + + +def test_blur_nan_ignores_nan() -> None: + """NaN stays NaN and does not pull its neighbours down.""" + img = np.ones((9, 9), np.float32) + img[4, 4] = np.nan + out = blur_nan(img) + assert np.isnan(out[4, 4]) + np.testing.assert_allclose(out[np.isfinite(out)], 1.0, rtol=1e-6) + + +def test_robust_z_and_late_trials() -> None: + """Median and MAD z-scores. + + Late trials are the last block, or the second half of one block. + """ + z = robust_z(np.array([[0.0, 1.0, 2.0, np.nan]])) + assert z[0, 1] == 0 and np.isnan(z[0, 3]) + np.testing.assert_array_equal(late_trials([0, 0, 1, 1, 1]), [0, 0, 1, 1, 1]) + np.testing.assert_array_equal(late_trials([0, 0, 0, 0]), [0, 0, 1, 1]) + + +def test_normalized_field_and_change(product: str) -> None: + """Each trial is divided by its median over the common pixels. + + The change view compares blurred trials, with a brightness in [0, 1]. + """ + store = SpineStore([(None, product)]) + pr = store.products[0] + stack = read_product(product)["paths"][1]["images"]["mean_ch1"] + nz = pr.normalized(1, "mean_ch1") + common = np.isfinite(stack).all(axis=0) + for t in range(stack.shape[0]): + med = np.median(stack[t][common]) + np.testing.assert_allclose(nz["stack"][t], stack[t] / med, rtol=1e-6) + np.testing.assert_allclose( + pr.field(1, "mean_ch1", -1, "image", "")[0], + np.nanmean(nz["stack"], axis=0), + rtol=1e-6, + ) + ch = pr.field(1, "mean_ch1", 2, "change", "average") + assert ch.shape == (2,) + stack.shape[1:] + b = ch[1] + assert np.nanmin(b) >= 0 and np.nanmax(b) <= 1 + cp = pr.change_prep(1, "mean_ch1") + expect = cp["blurred"][2] / cp["mean"] - 1 + np.testing.assert_allclose(ch[0], expect, rtol=1e-5, equal_nan=True) + prev = pr.field(1, "mean_ch1", 2, "change", "previous")[0] + np.testing.assert_allclose( + prev, + cp["blurred"][2] / cp["blurred"][1] - 1, + rtol=1e-5, + equal_nan=True, + ) + # the first trial of a block has no previous trial + assert np.isnan(pr.field(1, "mean_ch1", 0, "change", "previous")[0]).all() + act = pr.field(1, "", -1, "activity", "") + assert act.shape == (1,) + stack.shape[1:] + + +def test_store_sources_roi_and_crops(product: str) -> None: + """Sources carry sizes and trends. + + A window and its crops sit on the same grid around the source. + """ + store = SpineStore([("syn", product)], crop_half=4) + meta = store.meta() + p1 = meta["products"][0]["paths"][1] + assert meta["products"][0]["name"] == "syn" + assert "f0_net" in p1["trends"] and p1["n_sources"] == len(syn.SOURCES) + src = store.sources(0, 1) + prod = read_product(product)["paths"][1] + np.testing.assert_allclose( + np.array(src["normalized"]["f0_net"], float), + prod["normalized"]["sources"]["f0_net"], + ) + assert src["trends"]["f0_net"]["attrs"]["n_perm"] == 100 + roi = store.roi(0, 1, 0) + assert roi["size"] == 9 and np.array(roi["weights"]).shape == (9, 9) + r0, c0 = roi["origin"] + w = prod["rois"]["sources"].image(0) + np.testing.assert_allclose(np.array(roi["weights"]), w[r0 : r0 + 9, c0 : c0 + 9], atol=1e-6) + crops = store.crops(0, 1, 0, "mean_ch1", "image", "average") + n_t = len(prod["trials"]["acquisition"]) + assert crops.shape == (1, n_t + 1, 9, 9) + full = store.products[0].normalized(1, "mean_ch1")["stack"] + np.testing.assert_allclose(crops[0, 1:], full[:, r0 : r0 + 9, c0 : c0 + 9], rtol=1e-6) + ch = store.crops(0, 1, 0, "mean_ch1", "change", "average") + assert ch.shape == (2, n_t + 1, 9, 9) + + +def test_marks_attach_by_position(product: str, tmp_path: Path) -> None: + """A mark is stored with its source's position. + + It attaches to the nearest source within 2.5 px; clearing removes it. + """ + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + got = store.set_mark(0, 1, 1, "Growing", "a note") + assert got["by_source"][1]["label"] == "Growing" + rows = read_marks(marks) + assert rows[0]["Source"] == "2" and rows[0]["Note"] == "a note" + rs = read_product(product)["paths"][1]["rois"]["sources"] + assert rows[0]["Row0"] == pytest.approx(rs.rows[1]) + # a second mark on the same source replaces the first + store.set_mark(0, 1, 1, "Shrinking", "") + assert len(read_marks(marks)) == 1 + assert store.marks_for(0, 1)["by_source"][1]["label"] == "Shrinking" + # a mark far from every source does not attach + rows = read_marks(marks) + [dict(rows[0], Row0=0.0, Col0=0.0, Label="Unsure")] + from giant_python.spine.rois import write_marks + + write_marks(marks, rows) + assert store.marks_for(0, 1)["unattached"] == 1 + store.set_mark(0, 1, 1, "", "") + assert 1 not in store.marks_for(0, 1)["by_source"] + with pytest.raises(ValueError, match="unknown mark"): + store.set_mark(0, 1, 1, "Big", "") + + +def test_product_is_read_again_when_it_changes(product: str, tmp_path: Path) -> None: + """A rewritten product shows on the next request.""" + import os + import shutil + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + store = SpineStore([(None, copy)]) + first = store.sources(0, 1)["normalized"]["f0_net"] + import h5py + + with h5py.File(copy, "r+") as f: + d = f["Path1/normalized/sources/f0_net"] + d[...] = d[()] + 1 + st = os.stat(copy) + os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + again = store.sources(0, 1)["normalized"]["f0_net"] + a = np.array(first, float) + np.testing.assert_allclose(np.array(again, float), a + 1) + + +def _get(url: str) -> dict | np.ndarray: + """GET and decode JSON or float32. + + Returns + ------- + dict or np.ndarray + The parsed JSON for a JSON response, else the float32 array shaped by X-Shape. + """ + with urllib.request.urlopen(url) as r: + body = r.read() + if r.headers.get("Content-Type") == "application/json": + return json.loads(body) + shape = json.loads(r.headers["X-Shape"]) + return np.frombuffer(body, np.float32).reshape(shape) + + +def test_server_answers_the_api(product: str, tmp_path: Path) -> None: + """The page and every API route answer; a mark is written by POST.""" + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + try: + with urllib.request.urlopen(base + "/") as r: + assert b"Spine size viewer" in r.read() + meta = _get(base + "/api/meta") + assert meta["products"][0]["paths"]["1"]["n_sources"] == 3 + src = _get(base + "/api/sources?prod=0&path=1") + assert src["n"] == 3 + f = _get(base + "/api/field?prod=0&path=1&image=f0_net&trial=1") + assert f.shape == (1, syn.H, syn.W) + c = _get(base + "/api/crops?prod=0&path=1&id=0&image=f0_net&view=change") + assert c.shape[0] == 2 + roi = _get(base + "/api/roi?prod=0&path=1&id=2") + assert roi["id"] == 2 + req = urllib.request.Request( + base + "/api/mark", + data=json.dumps({"prod": 0, "path": 1, "id": 0, "label": "Unsure"}).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req) as r: + assert json.loads(r.read())["by_source"]["0"]["label"] == "Unsure" + assert read_marks(marks)[0]["Label"] == "Unsure" + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + "/api/field?prod=0&path=7&image=x") + assert e.value.code == 404 + finally: + srv.shutdown() + srv.server_close() + + +def _static(page: str) -> dict: + """Extract the data embedded in an exported page. + + Returns + ------- + dict + The page's decoded static data. + """ + m = re.search( + r'", + page, + ) + return json.loads(gzip.decompress(base64.b64decode(m.group(1)))) + + +def _unpack(e: dict) -> np.ndarray: + """Decode an embedded array (as the page's unpack). + + Returns + ------- + np.ndarray + The decoded layers (NaN where the code is 255), shaped as e["shape"]. + """ + parts = [] + for layer in e["layers"]: + q = np.frombuffer(base64.b64decode(layer["b64"]), np.uint8) + v = layer["offset"] + layer["scale"] * q.astype(np.float64) + parts.append(np.where(q == 255, np.nan, v)) + return np.concatenate(parts).reshape(e["shape"]) + + +def test_pack_round_trips_within_a_code() -> None: + """uint8 codes keep values within half a step and NaN as NaN.""" + rng = np.random.default_rng(0) + a = rng.normal(1, 0.1, (1, 20, 30)).astype(np.float32) + a[0, 3, 4] = np.nan + e = pack(a, "image") + back = _unpack(e) + assert np.isnan(back[0, 3, 4]) + step = e["layers"][0]["scale"] + inside = np.isfinite(a) & (a >= e["layers"][0]["offset"]) + inside &= a <= e["layers"][0]["offset"] + 254 * step + np.testing.assert_allclose(back[inside], a[inside], atol=step / 2 + 1e-7) + ch = np.stack([np.full((4, 4), 0.1), np.full((4, 4), 0.5)]) + back = _unpack(pack(ch, "change")) + np.testing.assert_allclose(back, ch, atol=0.003) + + +def test_export_html_embeds_the_viewer_data(product: str, tmp_path: Path) -> None: + """The page holds the meta, the sources, the mean fields and some crops. + + The crops are those of the chosen sources; the page holds nothing that + needs the server. + """ + out = tmp_path / "page.html" + rep = export_html(product, out, sources=[2], name="syn") + page = out.read_text(encoding="utf-8") + assert "Spine sizes syn" in page + data = _static(page) + assert data["meta"]["marks_file"] is None + assert data["sources"]["1"]["n"] == 3 + key = field_key(1, "f0_net", -1, "image", "") + assert key in data["fields"] + assert field_key(1, "f0_net", -1, "change", "") in data["fields"] + assert rep["sources"][1] == [2] + assert "1|1" in data["rois"] and "1|0" not in data["rois"] + crop_keys = [k for k in data["crops"] if k.startswith("1|1|")] + assert crop_keys and all("f0_" in k for k in crop_keys) + store = SpineStore([(None, product)]) + mean = store.products[0].field(1, "f0_net", -1, "image", "") + e = data["fields"][key] + back = _unpack(e) + fin = np.isfinite(mean) + step = e["layers"][0]["scale"] + lo = e["layers"][0]["offset"] + inside = fin & (mean >= lo) & (mean <= lo + 254 * step) + np.testing.assert_allclose(back[inside], mean[inside], atol=step) + + +def test_cli_export(product: str, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Giant spine export-html writes the page and reports it.""" + out = tmp_path / "e.html" + assert main(["spine", "export-html", product, "--out", str(out), "--top", "1"]) == 0 + rep = json.loads(capsys.readouterr().out) + assert rep["output"] == str(out) and out.is_file() + + +def test_pick_sources_marked_first_then_by_q_and_size() -> None: + """The export's crops go to the marked sources, then by q. + + Ties at the permutation floor go to the larger statistic. + """ + from giant_python.spine.view.export import pick_sources + + nan = float("nan") + tr = { + "step_q": [0.5, 1e-4, 1e-4, nan, 0.02], + "step_t": [1.0, 3.0, 6.0, nan, 2.5], + "brief_q": [0.9, 0.9, 0.9, nan, 0.9], + "brief_t": [1.0, 1.0, 1.0, nan, 1.0], + "resid_q": [0.04, 0.9, 0.9, nan, 0.9], + "resid_t": [2.0, 1.0, 1.0, nan, 1.0], + } + src = {"n": 5, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} + assert pick_sources(src, "f0", 3) == [0, 2, 1, 4] + assert pick_sources(src, "f0", 0) == [0] + + +def test_marks_need_json_from_this_server(product: str, tmp_path: Path) -> None: + """The mark endpoint refuses bodies that are not JSON and foreign origins. + + Bodies that are not JSON could be sent by a cross-origin page without a + preflight; requests whose Origin is another site are refused too. + """ + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() + try: + for headers, code in ( + ({"Content-Type": "text/plain"}, 415), + ( + { + "Content-Type": "application/json", + "Origin": "http://example.com", + }, + 403, + ), + ): + req = urllib.request.Request(base + "/api/mark", data=body, headers=headers) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == code + assert not marks.exists() + req = urllib.request.Request( + base + "/api/mark", + data=body, + headers={"Content-Type": "application/json", "Origin": base}, + ) + with urllib.request.urlopen(req) as r: + assert r.status == 200 + assert read_marks(marks)[0]["Label"] == "Unsure" + finally: + srv.shutdown() + srv.server_close() + + +def test_sources_without_sources_keep_the_fields(product: str, tmp_path: Path) -> None: + """A path without sources answers with the same, empty, fields.""" + store = SpineStore([(None, product)]) + pr = store.products[0] + pr.small()["paths"][1]["rois"].pop("sources") + src = store.sources(0, 1) + assert src["n"] == 0 and src["trends"] == {} and src["ids"] == [] + assert src["marks"] == {"by_source": {}, "unattached": 0} + + +def test_cache_keys_follow_the_file(product: str, tmp_path: Path) -> None: + """A result made from the old file is not served after the file changes. + + Even if it lands in the cache after the reload. + """ + import os + import shutil + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + store = SpineStore([(None, copy)]) + pr = store.products[0] + old = pr.normalized(1, "mean_ch1") + gen = pr._gen + st = os.stat(copy) + os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + pr.small() + assert pr._gen == gen + 1 + # a late insert under the old generation's key is never read + pr._cache.get((gen, "norm", 1, "mean_ch1"), lambda: "stale") + new = pr.normalized(1, "mean_ch1") + assert new is not old and not isinstance(new, str) + + +def test_server_refuses_untrusted_hosts(product: str, tmp_path: Path) -> None: + """Requests naming another host (DNS rebinding) get nothing. + + Marks from an origin that is not this server's trusted names are refused. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + port = srv.server_address[1] + base = f"http://127.0.0.1:{port}" + try: + req = urllib.request.Request(base + "/api/meta", headers={"Host": f"evil.example:{port}"}) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == 403 + req = urllib.request.Request(base + "/api/meta", headers={"Host": f"localhost:{port}"}) + with urllib.request.urlopen(req) as r: + assert r.status == 200 + body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() + for origin in ( + f"http://evil.example:{port}", + f"https://127.0.0.1:{port}", + ): + req = urllib.request.Request( + base + "/api/mark", + data=body, + headers={ + "Content-Type": "application/json", + "Origin": origin, + "Host": f"127.0.0.1:{port}", + }, + ) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == 403 + finally: + srv.shutdown() + srv.server_close() + + +def test_export_refuses_unknown_paths(product: str, tmp_path: Path) -> None: + """Asking for a path the summary does not have is an error. + + Not an empty page. + """ + with pytest.raises(ValueError, match="no path"): + export_html(product, tmp_path / "p.html", paths=[7]) + assert not (tmp_path / "p.html").exists() + + +def test_pick_sources_uses_the_strongest_test_at_the_smallest_q() -> None: + """Among tests tied at a source's smallest q, the largest statistic wins. + + It breaks ties between sources. + """ + from giant_python.spine.view.export import pick_sources + + tr = { + "step_q": [1e-3, 1e-3], + "step_t": [2.0, 6.0], + "brief_q": [1e-3, 0.5], + "brief_t": [20.0, 1.0], + "resid_q": [0.9, 0.9], + "resid_t": [1.0, 1.0], + } + src = {"n": 2, "trends": {"f0": tr}, "marks": {}} + assert pick_sources(src, "f0", 1) == [0] + + +def test_marks_keep_their_order_within_a_path(product: str, tmp_path: Path) -> None: + """Two marks with the same time that land on one source. + + The one written later wins, whatever their rows. + """ + from giant_python.spine.rois import write_marks + + store = SpineStore([(None, product)], tmp_path / "marks.csv") + rs = read_product(product)["paths"][1]["rois"]["sources"] + r, c = float(rs.rows[0]), float(rs.cols[0]) + base = { + "Path": 1, + "Source": 1, + "Note": "", + "Col0": c, + "Updated": "2026-01-01 00:00:00", + } + write_marks( + tmp_path / "marks.csv", + [ + dict(base, Label="Growing", Row0=r + 0.5), + dict(base, Label="Shrinking", Row0=r - 0.5), + ], + ) + assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" + # a write through the store keeps the order within the path + store.set_mark(0, 1, 1, "Unsure", "") + rows = read_marks(tmp_path / "marks.csv") + assert [m["Label"] for m in rows] == ["Growing", "Shrinking", "Unsure"] + assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" + + +def test_pick_sources_keeps_infinite_statistics_first() -> None: + """An infinite statistic (a change without noise) ranks first. + + Among equal q-values. + """ + from giant_python.spine.view.export import pick_sources + + inf = float("inf") + tr = {f"{t}_{f}": [None, None] for t in ("brief", "resid") for f in ("q", "t")} + tr.update({"step_q": [1e-4, 1e-4], "step_t": [6.0, inf]}) + src = {"n": 2, "trends": {"f0": tr}, "marks": {}} + assert pick_sources(src, "f0", 1) == [1] + + +def test_summary_without_rois_loads(product: str, tmp_path: Path) -> None: + """A summary with no sources and no user ROIs (no rois group) loads.""" + import shutil + + import h5py + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + for n in ("Path1", "Path2"): + if f"{n}/rois" in f: + del f[f"{n}/rois"] + store = SpineStore([(None, copy)]) + assert store.sources(0, 1)["n"] == 0 + assert store.meta()["products"][0]["paths"][1]["n_sources"] == 0 + + +def test_server_on_ipv6_loopback_and_port_80_names(product: str) -> None: + """The server binds an IPv6 literal, and at port 80 trusts portless names. + + Those are the names without a port, as browsers send them. + """ + import socket as so + + from giant_python.spine.view.server import _bracket, allowed_hosts + + assert _bracket("::1") == "[::1]" and _bracket("localhost") == "localhost" + at80 = allowed_hosts("127.0.0.1", 80) + assert "127.0.0.1" in at80 and "localhost:80" in at80 + assert "127.0.0.1" not in allowed_hosts("127.0.0.1", 8790) + assert allowed_hosts("0.0.0.0", 8790) == frozenset() + if not so.has_ipv6: + pytest.skip("no IPv6") + store = SpineStore([(None, product)]) + try: + srv = make_server(store, host="::1", port=0) + except OSError: + pytest.skip("no IPv6 loopback") + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + port = srv.server_address[1] + try: + assert f"[::1]:{port}" in srv.RequestHandlerClass.allowed + with urllib.request.urlopen(f"http://[::1]:{port}/api/meta") as r: + assert r.status == 200 + finally: + srv.shutdown() + srv.server_close() + + +def test_a_note_alone_keeps_the_label(product: str, tmp_path: Path) -> None: + """A note saved on its own keeps the label the source has at that moment. + + Unsure without one. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + got = store.set_mark(0, 1, 0, None, "first note") + assert got["by_source"][0]["label"] == "Unsure" + store.set_mark(0, 1, 0, "Growing", "first note") + got = store.set_mark(0, 1, 0, None, "second note") + assert got["by_source"][0] == { + "label": "Growing", + "note": "second note", + "updated": got["by_source"][0]["updated"], + } + assert len(read_marks(tmp_path / "marks.csv")) == 1 + + +def test_export_refuses_unknown_sources_and_images(product: str, tmp_path: Path) -> None: + """Source numbers and crop images the summary lacks are errors.""" + with pytest.raises(ValueError, match="no source"): + export_html(product, tmp_path / "p.html", sources=[99]) + with pytest.raises(ValueError, match="no image"): + export_html(product, tmp_path / "p.html", crop_images=["f0_nope"]) + assert not (tmp_path / "p.html").exists() + + +def test_export_crops_only_the_images_asked_for(product: str, tmp_path: Path) -> None: + """With --crop-images, a path that lacks them gets no crops. + + Rather than every image. + """ + import h5py + + out = tmp_path / "p.html" + copy = tmp_path / "copy.h5" + import shutil + + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + del f["Path2/images/f0_net"] + export_html(copy, out, sources=[1], crop_images=["f0_net"]) + data = _static(out.read_text(encoding="utf-8")) + assert any(k.startswith("1|0|f0_net|") for k in data["crops"]) + assert not [k for k in data["crops"] if k.startswith("2|")] + + +def test_cache_makes_a_value_once_for_concurrent_requests() -> None: + """Concurrent requests for a value being made wait for it. + + Instead of making it again. + """ + import time as _t + + from giant_python.spine.view.data import _Lru + + cache = _Lru(4) + calls = [] + + def make() -> str: + """Make a slow value. + + Returns + ------- + str + The value, "v". + """ + calls.append(1) + _t.sleep(0.2) + return "v" + + out = [] + ths = [threading.Thread(target=lambda: out.append(cache.get("k", make))) for _ in range(5)] + for th in ths: + th.start() + for th in ths: + th.join() + assert out == ["v"] * 5 and len(calls) == 1 + assert cache.making == {} + + +def test_cache_is_bounded_by_bytes() -> None: + """Values are evicted, oldest first, once their arrays exceed the budget. + + The newest stays even when it alone is larger. + """ + from giant_python.spine.view.data import _Lru + + cache = _Lru(3000) + for k in range(4): + cache.get(k, lambda: {"a": np.zeros(125)}) # 1000 bytes each + assert list(cache.d) == [1, 2, 3] + cache.get("big", lambda: np.zeros(1000)) + assert list(cache.d) == ["big"] + + +def test_cache_lock_stays_while_requests_wait() -> None: + """The lock of a key being made stays while any request still uses it. + + Even if the value is evicted meanwhile: a later request for the key waits + on the same lock instead of computing in parallel. + """ + import time as _t + + from giant_python.spine.view.data import _Lru + + cache = _Lru(1) # every new value evicts the previous one + running = [] + peak = [] + + def make() -> np.ndarray: + """Make a slow value that records how many are being made at once. + + Returns + ------- + np.ndarray + A zero array of 10 values. + """ + running.append(1) + peak.append(len(running)) + _t.sleep(0.05) + running.pop() + return np.zeros(10) + + def worker() -> None: + """Ask for the key, then for another (evicting it).""" + cache.get("k", make) + cache.get(object(), lambda: np.zeros(10)) + + ths = [threading.Thread(target=worker) for _ in range(6)] + for th in ths: + th.start() + for th in ths: + th.join() + assert max(peak) == 1 + assert cache.making == {} + + +def test_mark_refused_when_the_source_moved(product: str, tmp_path: Path) -> None: + """A mark that names a position other than the source's is refused. + + The summary changed under an open page; the mark writes nothing. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + rs = read_product(product)["paths"][1]["rois"]["sources"] + with pytest.raises(ValueError, match="changed"): + store.set_mark(0, 1, 1, "Growing", "", row=0.0, col=0.0) + assert not (tmp_path / "marks.csv").exists() + got = store.set_mark(0, 1, 1, "Growing", "", row=float(rs.rows[1]), col=float(rs.cols[1])) + assert got["by_source"][1]["label"] == "Growing" + + +def test_change_needs_only_its_own_cache_entry(product: str) -> None: + """change() reads everything it needs from the change record. + + So it does not reload the normalized stack (no thrashing when the two do + not fit together in the cache). + """ + store = SpineStore([(None, product)]) + pr = store.products[0] + pr.change_prep(1, "mean_ch1") + calls = [] + real = pr.normalized + pr.normalized = lambda *a: calls.append(a) or real(*a) + for t in (-1, 0, 2): + pr.change(1, "mean_ch1", t, "average") + assert calls == [] + + +def test_default_image_calls_and_window_motion_reach_the_page(product: str) -> None: + """The page gets the default image, the calls and the windows' motion. + + That is, the summary's default image, the calls and structural change of + each image's tests, and the windows' motion. + """ + store = SpineStore([(None, product)]) + p1 = store.meta()["products"][0]["paths"][1] + assert p1["primary_image"] == "f0_net" + src = store.sources(0, 1) + assert len(src["align_px"]) == src["n"] + assert src["trends"]["f0_net"]["attrs"]["structural_image"] == "mean_ch2" + assert len(src["trends"]["f0_net"]["call"]) == src["n"] + assert len(src["trends"]["f0_net"]["structural_d"]) == src["n"] + from importlib.resources import files + + page = files("giant_python.spine.view").joinpath("page.html").read_text(encoding="utf-8") + for key in ('["call", "call"]', '"structural_d"', '"align_px"'): + assert key in page + + +def test_summaries_before_format_4_still_load(product: str, tmp_path: Path) -> None: + """Summaries before format 4 still load. + + Without the default image, the calls or the window motion (format 3), the + page gets None for the image and NaN (null) motion. + """ + import shutil + + import h5py + + copy = tmp_path / "v3.h5" + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + for n in ("Path1", "Path2"): + g = f[n] + del g.attrs["primary_image"] + del g["readout/sources/align_px"] + for name in g["trends/sources"]: + t = g[f"trends/sources/{name}"] + for k in ("call", "structural_d"): + if k in t: + del t[k] + store = SpineStore([(None, copy)]) + assert store.meta()["products"][0]["paths"][1]["primary_image"] is None + src = store.sources(0, 1) + assert np.isnan(np.array(src["align_px"], float)).all() + assert "call" not in src["trends"]["f0_net"] + assert read_product(copy)["paths"][1]["primary_image"] is None + + +def test_pick_sources_takes_the_calls_first() -> None: + """The export's crops go to the marked sources, then to the calls. + + The calls are taken by q, then the rest by the smallest q. + """ + from giant_python.spine.view.export import pick_sources, primary_image + + tr = { + "step_q": [0.5, 1e-4, 0.2, 0.9], + "step_t": [1.0, 6.0, 2.0, 1.0], + "brief_q": [0.9, 0.9, 0.9, 0.9], + "brief_t": [1.0, 1.0, 1.0, 1.0], + "resid_q": [0.9, 0.9, 0.05, 0.01], + "resid_t": [1.0, 1.0, 3.0, 4.0], + "call": [False, False, True, True], + } + src = {"n": 4, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} + assert pick_sources(src, "f0", 3) == [0, 3, 2, 1] + # a marked call does not take one of the top places + src["marks"] = {"by_source": {"3": {}}} + assert pick_sources(src, "f0", 1) == [3, 2] + assert primary_image(["f0_net", "f0_gain"], "f0_net") == "f0_net" + assert primary_image(["f0_net", "f0_gain"], "gone") == "f0_gain" + assert primary_image(["f0_net", "f0_gain"]) == "f0_gain" diff --git a/tests/trial_table/__init__.py b/tests/trial_table/__init__.py index 29b8cf3a..475c7f0f 100644 --- a/tests/trial_table/__init__.py +++ b/tests/trial_table/__init__.py @@ -1 +1 @@ -"""Tests of the SLAP2 trial-table builder.""" +"""Tests of the SLAP2 trial-table builder.""" diff --git a/tests/trial_table/test_build_slap2.py b/tests/trial_table/test_build_slap2.py index e9fdcb82..ae99200f 100644 --- a/tests/trial_table/test_build_slap2.py +++ b/tests/trial_table/test_build_slap2.py @@ -1,587 +1,625 @@ -"""Tests of the SLAP2 trial-table builder (ports of GIAnT-MATLAB's tests). - -The per-file reader is replaced by a table of line counts and first-line -times, so no SLAP2 data are needed; reference stacks are small TIFFs with -SLAP2's per-page JSON descriptions. A separate test builds a MATLAB v7.3 -``datetime`` by hand to check the ``.meta`` decoder. -""" - -import datetime -import json -import math -import os -import struct -import warnings -from collections.abc import Sequence -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2 import first_line_timestamp, read_mat_datetime_ms -from giant_python.pipeline import trial_table as tt -from giant_python.pipeline.trial_table import ( - DatInfo, - TrialTableWarning, - acquisition_order, - build_trial_table_slap2, - matlab_linspace, - trim_trial_table, -) - -LINE_PERIOD_S = 1e-4 -START = datetime.datetime(2024, 2, 1, 12, 0, 0) - - -def datenum(t: datetime.datetime) -> float: - """MATLAB datenum of a naive local datetime.""" - midnight = t.replace(hour=0, minute=0, second=0, microsecond=0) - return t.toordinal() + 366 + (t - midnight).total_seconds() / 86400 - - -class FakeSession: - """A data folder whose .dat files are empty, with a fake reader.""" - - def __init__(self, root: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Create the data folder and put the fake reader in place.""" - self.dir = root / "data" - self.dir.mkdir() - self.info = {} - monkeypatch.setattr(tt, "read_dat_info", self.read) - - def read(self, path: str | Path) -> DatInfo: - """Read a file's line count and first-line time (the fake reader).""" - lines, first = self.info[Path(path).name] - return DatInfo(lines, first, LINE_PERIOD_S) - - def dat( - self, - name: str, - lines: int | np.integer, - mtime: datetime.datetime, - first_line: datetime.datetime | None = None, - ) -> None: - """Add an empty .dat file with its line count, file time and first-line time.""" - p = self.dir / name - p.write_bytes(b"") - stamp = mtime.timestamp() - os.utime(p, (stamp, stamp)) - first = math.nan if first_line is None else datenum(first_line) - self.info[name] = (lines, first) - - def triggered( - self, lines1: Sequence[int], lines2: Sequence[int] - ) -> tuple[list[str], list[str]]: - """Add triggered recordings of both paths with the given line counts.""" - dmd1 = [f"acq_DMD1-TRIAL{k:06d}.dat" for k in range(1, len(lines1) + 1)] - dmd2 = [f"acq_DMD2-TRIAL{k:06d}.dat" for k in range(1, len(lines2) + 1)] - for k, (name, n) in enumerate(zip(dmd1, lines1), start=1): - self.dat(name, n, START + datetime.timedelta(minutes=k)) - for k, (name, n) in enumerate(zip(dmd2, lines2), start=1): - self.dat(name, n, START + datetime.timedelta(minutes=k)) - return dmd1, dmd2 - - def references(self) -> None: - """Write a small reference stack per path, described as SLAP2 does.""" - import tifffile - - ref = self.dir / "reference" - ref.mkdir() - rng = np.random.default_rng(0) - for dmd in (1, 2): - with tifffile.TiffWriter(ref / f"acq_DMD{dmd}_CONFIG1-REFERENCE.tif") as tw: - for z in (0, 1, 2): - for ch in (1, 2): - desc = { - "channel": ch, - "z": z, - "dmdPixel2SampleTransform": np.eye(3).tolist(), - } - page = rng.random((8, 6)).astype(np.float32) - tw.write(page, description=json.dumps(desc), metadata=None) - - def mtimes(self, names: Sequence[str]) -> np.ndarray: - """Return the files' modification times as MATLAB datenums.""" - return np.array([tt._mtime_datenum(self.dir / n) for n in names]) - - def build(self, save_dir: Path, **kw: float | bool | None) -> dict: - """Build the trial table of this folder.""" - return build_trial_table_slap2(self.dir, save_dir, **kw) - - -@pytest.fixture -def session(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> FakeSession: - """Provide a fake session in a temporary folder.""" - return FakeSession(tmp_path, monkeypatch) - - -def test_triggered_trials(session: FakeSession, tmp_path: Path) -> None: - """Triggered recordings of both paths give one trial per file pair.""" - lines = [100000, 120000, 110000] - dmd1, dmd2 = session.triggered(lines, lines) - session.references() - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["epoch"], np.ones((2, 3))) - np.testing.assert_array_equal(t["true_trial_ix"], np.tile([1, 2, 3], (2, 1))) - s2 = t["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.ones((2, 3))) - np.testing.assert_array_equal(s2["last_line"], np.tile(lines, (2, 1))) - ends = session.mtimes(dmd1) - np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), ends, rtol=0, atol=1e-9) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - ends - np.array(lines) * LINE_PERIOD_S / 86400, - rtol=0, - atol=1e-9, - ) - - -def test_triggered_trial_line_mismatch(session: FakeSession, tmp_path: Path) -> None: - """A file holding two trials back to back is lined up with the other path.""" - # DMD1's trial number failed to increment: its second file holds DMD2's - # second and third trials back to back - dmd1, dmd2 = session.triggered([100000, 220000], [100000, 100000, 120000]) - session.references() - s = session.build(tmp_path / "out") - assert s["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] - s2 = s["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], [[1, 1, 100001], [1, 1, 1]]) - np.testing.assert_array_equal( - s2["last_line"], [[100000, 100000, 220000], [100000, 100000, 120000]] - ) - dn1, dn2 = session.mtimes(dmd1), session.mtimes(dmd2) - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - [dn1[0], dn2[1], dn1[1]], - rtol=0, - atol=1e-9, - ) - - -def test_order_from_file_names_not_mod_times(session: FakeSession, tmp_path: Path) -> None: - """Acquisitions are ordered by the time in their names, not by file times.""" - # copies carry upload times: DMD1's are scrambled within a few seconds, - # DMD2's identical; the earlier acquisition sorts last alphabetically - acqs = [("spont_20250314_101500", 2), ("activity_20250314_111223", 12)] - dmd1 = [f"{a}_DMD1-TRIAL{k:06d}.dat" for a, n in acqs for k in range(1, n + 1)] - dmd2 = [n.replace("DMD1", "DMD2") for n in dmd1] - lines = 100000 + 100 * np.arange(1, len(dmd1) + 1) - upload = datetime.datetime(2026, 8, 27, 10, 53, 33) - for k, (a, b) in enumerate(zip(dmd1, dmd2), start=1): - session.dat(a, lines[k - 1], upload + datetime.timedelta(seconds=(7 * k) % 5)) - session.dat(b, lines[k - 1], upload) - session.references() - with pytest.warns(TrialTableWarning, match="do not look like acquisition times"): - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["true_trial_ix"][0], np.arange(1, len(dmd1) + 1)) - np.testing.assert_array_equal(t["slap2_info"]["last_line"], np.tile(lines, (2, 1))) - np.testing.assert_allclose( - t["slap2_info"]["trial_end_time_from_pc"].ravel(), - session.mtimes(dmd1), - rtol=0, - atol=1e-9, - ) - - -def test_file_order_falls_back_to_mod_time(session: FakeSession, tmp_path: Path) -> None: - """Without a time in the names, files are ordered by modification time.""" - names = ["b_DMD1.dat", "a_DMD1.dat"] - for k, n in enumerate(names, start=1): - t = START + datetime.timedelta(minutes=k) - session.dat(n, 100000, t) - session.dat(n.replace("DMD1", "DMD2"), 100000, t) - session.references() - with pytest.warns(TrialTableWarning, match="modification time"): - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [ - names, - [n.replace("DMD1", "DMD2") for n in names], - ] - - -def test_trial_times_from_line_clock(session: FakeSession, tmp_path: Path) -> None: - """Trial times come from the line clock, which shows gaps the line counts hide.""" - # DMD1's second file holds trials 2 and 3, with a 0.5 s gap that the line - # count alone doesn't show; mtimes are identical upload times - starts = [ - datetime.datetime(2025, 3, 14, 11, 12, 55) + datetime.timedelta(seconds=s) - for s in (0, 10.5, 21) - ] - upload = datetime.datetime(2026, 8, 27, 10, 53, 33) - dmd1 = [f"activity_20250314_111223_DMD1-TRIAL{k:06d}.dat" for k in (1, 2)] - dmd2 = [f"activity_20250314_111223_DMD2-TRIAL{k:06d}.dat" for k in (1, 2, 3)] - session.dat(dmd1[0], 100000, upload, starts[0]) - session.dat(dmd1[1], 220000, upload, starts[1]) - for name, n, s in zip(dmd2, (100000, 100000, 120000), starts): - session.dat(name, n, upload, s) - session.references() - with warnings.catch_warnings(): - warnings.simplefilter("error") - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] - days = np.array([datenum(s) for s in starts]) - s2 = t["slap2_info"] - np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days, rtol=0, atol=1e-9) - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - days + np.array([100000, 100000, 120000]) * LINE_PERIOD_S / 86400, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_trials_and_times(session: FakeSession, tmp_path: Path) -> None: - """A continuous recording is cut into trials with times from the line clock.""" - lines = 450000 - t0 = datetime.datetime(2025, 3, 14, 11, 12, 55) - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START, t0) - # later files of the recording are skipped (their line counts unknown) - for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): - (session.dir / n).write_bytes(b"") - session.references() - t = session.build(tmp_path / "out") - edges = np.array([1, 150001, 300001, 450001], dtype=float) - assert t["filename"].tolist() == [[names[0]] * 3, [names[1]] * 3] - s2 = t["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.tile(edges[:3], (2, 1))) - np.testing.assert_array_equal(s2["last_line"], np.tile(edges[1:], (2, 1))) - days = datenum(t0) + (edges - 1) * LINE_PERIOD_S / 86400 - np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days[:3], rtol=0, atol=1e-9) - np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), days[1:], rtol=0, atol=1e-9) - - -def test_multicycle_times_from_mtime(session: FakeSession, tmp_path: Path) -> None: - """Without the line clock, a continuous recording's times come from file times.""" - lines = 450000 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - edges = np.array([1, 150001, 300001, 450001], dtype=float) - dn = session.mtimes(names[:1])[0] - to_days = LINE_PERIOD_S / 86400 - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - dn - (lines - edges[1:]) * to_days, - rtol=0, - atol=1e-9, - ) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - dn - (lines - edges[:3]) * to_days, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_times_from_last_file_mtime(session: FakeSession, tmp_path: Path) -> None: - """Without the line clock, a CYCLE-split recording ends at its last file's modification time. - - MATLAB takes the first file's. - """ - lines = 450000 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - end = START + datetime.timedelta(seconds=30) - for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): - (session.dir / n).write_bytes(b"") - os.utime(session.dir / n, (end.timestamp(), end.timestamp())) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - last = session.mtimes(["acq_DMD1-CYCLE-000001.dat"])[0] - edges = np.array([1, 150001, 300001, 450001], dtype=float) - to_days = LINE_PERIOD_S / 86400 - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - last - (lines - edges[1:]) * to_days, - rtol=0, - atol=1e-9, - ) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - last - (lines - edges[:3]) * to_days, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_edges_are_matlab_linspace(session: FakeSession, tmp_path: Path) -> None: - """The trial edges of a continuous recording are MATLAB's linspace values.""" - # 3 trials of 599838 lines: the edges are fractional, as MATLAB's - lines = 599837 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - edges = matlab_linspace(1, lines + 1, 4) - assert edges[1] != round(edges[1]) - np.testing.assert_array_equal(s2["first_line"][0], edges[:3]) - np.testing.assert_array_equal(s2["last_line"][0], edges[1:]) - - -def test_matlab_linspace_values() -> None: - """matlab_linspace reproduces values computed in MATLAB.""" - # values from MATLAB R2023b: linspace(1, 599838, 4) - y = matlab_linspace(1, 599838, 4) - assert y[0] == 1 and y[-1] == 599838 - assert y[1] == 1 + (1 * (599838 - 1)) / 3 - assert y[2] == 1 + (2 * (599838 - 1)) / 3 - - -def test_reference_stack(session: FakeSession, tmp_path: Path) -> None: - """Each path's reference stack is found and stored.""" - session.triggered([100000], [100000]) - session.references() - t = session.build(tmp_path / "out") - for path in ("Path1", "Path2"): - ref = t["slap2_info"]["ref_stack"][path] - np.testing.assert_array_equal(ref["channels"], [1, 2]) - np.testing.assert_array_equal(ref["Zs"], [0, 1, 2]) - np.testing.assert_array_equal(ref["dmdPixel2SampleTransform"], np.eye(3)) - assert ref["IM"].shape == ( - 6, - 8, - 6, - ) # columns x rows x pages, as MATLAB - assert ref["IM"].dtype == np.float32 - - -def test_write_trial_table_h5(session: FakeSession, tmp_path: Path) -> None: - """The written trial_table.h5 holds the table in MATLAB's column-major layout.""" - dmd1, dmd2 = session.triggered([100000, 120000], [100000, 120000]) - session.references() - out = tmp_path / "out" - built = session.build(out) - t = load_struct_h5(out / "trial_table.h5") - assert t["datadr"] == str(session.dir) - assert t["savedr"] == str(out) - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["slap2_info"]["last_line"], [[100000, 120000]] * 2) - np.testing.assert_array_equal( - t["slap2_info"]["ref_stack"]["Path1"]["IM"], - built["slap2_info"]["ref_stack"]["Path1"]["IM"], - ) - with h5py.File(out / "trial_table.h5", "r") as h: - # stored column-major, as MATLAB's saveStructToH5 writes it - assert h["filename"].shape == (2, 2) - assert h["slap2_info/first_line"].shape == (2, 2) - assert h["slap2_info/ref_stack/Path1/IM"].shape == (6, 8, 6) - assert h["slap2_info/ref_stack/Path1/Zs"].shape == (3, 1) - assert h["row_major"][()].item() == 0 - - -def test_max_duration_trims_and_keeps_untrimmed(session: FakeSession, tmp_path: Path) -> None: - """max_duration_s trims the table and also writes the untrimmed one.""" - session.triggered([100000, 120000, 110000], [100000, 120000, 110000]) - session.references() - out = tmp_path / "out" - t = session.build(out, max_duration_s=15.0) # 10 s + 5 s of the 12 s trial - assert (out / "trial_table_untrimmed.h5").exists() - s2 = load_struct_h5(out / "trial_table.h5")["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.ones((2, 2))) - np.testing.assert_array_equal(s2["last_line"], [[100000, 50000]] * 2) - assert t["filename"].shape == (2, 2) - assert np.asarray(s2["trial_start_time_inferred"]).size == 2 - full = load_struct_h5(out / "trial_table_untrimmed.h5") - assert full["filename"].shape == (2, 3) - - -def test_trim_keeps_whole_trials_before_the_limit() -> None: - """Trimming keeps the trials that start before the limit and shortens the last.""" - table = { - "filename": np.array([["a", "b"], ["c", "d"]], dtype=object), - "true_trial_ix": np.array([[1.0, 2.0], [1.0, 2.0]]), - "epoch": np.ones((2, 2)), - "slap2_info": { - "first_line": np.ones((2, 2)), - "last_line": np.full((2, 2), 1000.0), - "trial_end_time_from_pc": np.array([[1.0, 2.0]]), - "trial_start_time_inferred": np.array([[0.5, 1.5]]), - }, - } - out, info = trim_trial_table(table, 0.15, 1e-4) # 0.1 s trials - assert info["n_trials_kept"] == 2 and info["last_trial_shortened"] - keep = math.floor((0.15 - 1000 * 1e-4) / 1e-4) # 499 in floating point, as in MATLAB - np.testing.assert_array_equal(out["slap2_info"]["last_line"], [[1000, keep]] * 2) - out, info = trim_trial_table(table, 1.0, 1e-4) - assert info["n_trials_kept"] == 2 and not info["last_trial_shortened"] - with pytest.raises(ValueError): - trim_trial_table(table, 0.0, 1e-4) - - -def test_no_reference_stack_error(session: FakeSession, tmp_path: Path) -> None: - """A session without a reference stack raises FileNotFoundError.""" - session.triggered([100000], [100000]) - with pytest.raises(FileNotFoundError): - session.build(tmp_path / "out") - - -def test_unaligned_dmds_error(session: FakeSession, tmp_path: Path) -> None: - """Paths whose recordings do not line up raise an error.""" - session.triggered([100000], [150000]) - session.references() - with pytest.raises(ValueError, match="lining up"): - session.build(tmp_path / "out") - - -def test_unmatched_trailing_recordings_warn(session: FakeSession, tmp_path: Path) -> None: - """Data left after the last trial that lines up is left out, as in MATLAB, with a warning.""" - session.triggered([100000, 100000], [100000]) - session.references() - with pytest.warns(TrialTableWarning, match="100000 lines of DMD1"): - t = session.build(tmp_path / "out") - assert t["filename"].shape == (2, 1) - - -def test_no_trials_error(session: FakeSession, tmp_path: Path) -> None: - """A session in which no trial lines up warns and raises.""" - session.triggered([100000], []) - session.references() - with pytest.warns(TrialTableWarning, match="left out"): - with pytest.raises(ValueError, match="No trials"): - session.build(tmp_path / "out") - - -@pytest.mark.filterwarnings("ignore:Could not read acquisition times") -def test_mixed_continuous_and_triggered_error(session: FakeSession, tmp_path: Path) -> None: - """Continuous and triggered recordings in one folder raise an error.""" - session.triggered([100000], [100000]) - for n in ("acq2_DMD1-CYCLE-000000.dat", "acq2_DMD2-CYCLE-000000.dat"): - session.dat(n, 450000, START + datetime.timedelta(minutes=5)) - session.references() - with pytest.raises(ValueError, match="both continuous"): - session.build(tmp_path / "out") - - -def test_acquisition_order() -> None: - """Files sort by acquisition time and trial number; ambiguous names are refused.""" - names = [ - "a_20250314_111223_DMD1-TRIAL000010.dat", - "a_20250314_111223_DMD1-TRIAL000002.dat", - "b_20250314_101500_DMD1-TRIAL000001.dat", - ] - order, ok = acquisition_order(names) - assert ok and order.tolist() == [2, 1, 0] - order, ok = acquisition_order(["x_DMD1-TRIAL000002.dat", "x_DMD1-TRIAL000001.dat"]) - assert ok and order.tolist() == [1, 0] - _, ok = acquisition_order(["b_DMD1.dat", "a_DMD1.dat"]) - assert not ok - _, ok = acquisition_order(["x_DMD1.dat", "x_DMD1-CYCLE-000000.dat"]) - assert not ok # same position - - -def _write_mat_datetime(path: Path, ms: complex, tz: str = "") -> None: - """Write a v7.3 MAT file holding ``fpgaTimeReference`` as MATLAB writes it. - - The ``FileWrapper__`` blob lists strings, one class (datetime) and one - object whose properties are ``data`` (cell 0) and, when given, ``tz`` - (cell 1). - """ - strings = [b"data", b"datetime", b"fmt", b"tz"] - names = b"".join(s + b"\0" for s in strings) - names += b"\0" * (-len(names) % 8) - classes = struct.pack("<8I", 0, 0, 0, 0, 0, 2, 0, 0) - objects = struct.pack("<12I", 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1) - props = [(1, 1, 0)] + ([(4, 1, 1)] if tz else []) - words = [0, 0, len(props)] + [v for p in props for v in p] - words += [0] * (len(words) % 2) - sets = struct.pack(f"<{len(words)}I", *words) - o0 = 40 + len(names) - o1 = o0 + len(classes) - o2 = o1 - o3 = o2 + len(objects) - o4 = o3 + len(sets) - header = struct.pack(" None: - """The .meta decoder reads an unzoned MATLAB datetime.""" - # 2025-03-14 09:30:20.5 wall clock, unzoned - ms = ( - datetime.datetime(2025, 3, 14, 9, 30, 20, 500000) - datetime.datetime(1970, 1, 1) - ).total_seconds() * 1000 - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(ms, -8.6e-5)) - assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 8.6e-5, abs=1e-9) - assert read_mat_datetime_ms(p, "missing") is None - # zoned: data is UTC; the wall clock in Los Angeles is 7 h earlier in March - _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") - assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 7 * 3600e3) - - -def test_read_mat_datetime_offset_across_dst(tmp_path: Path) -> None: - """The offset is elapsed time. - - 01:30 PST plus two hours on the day DST starts is 04:30 PDT (MATLAB: - datetime + seconds). - """ - utc = datetime.datetime(2025, 3, 9, 9, 30) # 01:30 in Los Angeles (PST) - ms = (utc - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") - wall = read_mat_datetime_ms(p, "fpgaTimeReference", offset_ms=2 * 3600e3) - expected = datetime.datetime(2025, 3, 9, 4, 30) - datetime.datetime(1970, 1, 1) - assert wall == pytest.approx(expected.total_seconds() * 1000, abs=1e-6) - - -@pytest.mark.parametrize("n", [0, 2]) -def test_read_mat_datetime_needs_one_value(tmp_path: Path, n: int) -> None: - """An empty or multi-element reference gives None, not an error or the first value. - - File times are used instead. - """ - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(1.7e12, 0)) - with h5py.File(p, "r+") as h: - del h["#refs#/c"] - h["#refs#"].create_dataset("c", data=np.zeros((1, n), [("real", " None: - """The first line's timestamp is read from the .dat file, after a magic-number check.""" - - class File: - """A stand-in for the SLAP2 data-file object.""" - - datFileName = str(tmp_path / "x.dat") - header = {"firstCycleOffsetBytes": 16} - - line = struct.pack(" float: + """MATLAB datenum of a naive local datetime. + + Returns + ------- + float + Days since MATLAB's datenum origin, with the time of day as a fraction. + """ + midnight = t.replace(hour=0, minute=0, second=0, microsecond=0) + return t.toordinal() + 366 + (t - midnight).total_seconds() / 86400 + + +class FakeSession: + """A data folder whose .dat files are empty, with a fake reader.""" + + def __init__(self, root: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Create the data folder and put the fake reader in place.""" + self.dir = root / "data" + self.dir.mkdir() + self.info = {} + monkeypatch.setattr(tt, "read_dat_info", self.read) + + def read(self, path: str | Path) -> DatInfo: + """Read a file's line count and first-line time (the fake reader). + + Returns + ------- + DatInfo + The line count, first-line time and line period registered for the file. + """ + lines, first = self.info[Path(path).name] + return DatInfo(lines, first, LINE_PERIOD_S) + + def dat( + self, + name: str, + lines: int | np.integer, + mtime: datetime.datetime, + first_line: datetime.datetime | None = None, + ) -> None: + """Add an empty .dat file with its line count, file time and first-line time.""" + p = self.dir / name + p.write_bytes(b"") + stamp = mtime.timestamp() + os.utime(p, (stamp, stamp)) + first = math.nan if first_line is None else datenum(first_line) + self.info[name] = (lines, first) + + def triggered( + self, lines1: Sequence[int], lines2: Sequence[int] + ) -> tuple[list[str], list[str]]: + """Add triggered recordings of both paths with the given line counts. + + Returns + ------- + dmd1 : list of str + File names of path 1's recordings. + dmd2 : list of str + File names of path 2's recordings. + """ + dmd1 = [f"acq_DMD1-TRIAL{k:06d}.dat" for k in range(1, len(lines1) + 1)] + dmd2 = [f"acq_DMD2-TRIAL{k:06d}.dat" for k in range(1, len(lines2) + 1)] + for k, (name, n) in enumerate(zip(dmd1, lines1), start=1): + self.dat(name, n, START + datetime.timedelta(minutes=k)) + for k, (name, n) in enumerate(zip(dmd2, lines2), start=1): + self.dat(name, n, START + datetime.timedelta(minutes=k)) + return dmd1, dmd2 + + def references(self) -> None: + """Write a small reference stack per path, described as SLAP2 does.""" + import tifffile + + ref = self.dir / "reference" + ref.mkdir() + rng = np.random.default_rng(0) + for dmd in (1, 2): + with tifffile.TiffWriter(ref / f"acq_DMD{dmd}_CONFIG1-REFERENCE.tif") as tw: + for z in (0, 1, 2): + for ch in (1, 2): + desc = { + "channel": ch, + "z": z, + "dmdPixel2SampleTransform": np.eye(3).tolist(), + } + page = rng.random((8, 6)).astype(np.float32) + tw.write(page, description=json.dumps(desc), metadata=None) + + def mtimes(self, names: Sequence[str]) -> np.ndarray: + """Return the files' modification times as MATLAB datenums. + + Returns + ------- + np.ndarray + One datenum per file name, in the order given. + """ + return np.array([tt._mtime_datenum(self.dir / n) for n in names]) + + def build(self, save_dir: Path, **kw: float | bool | None) -> dict: + """Build the trial table of this folder. + + Returns + ------- + dict + The trial table built by build_trial_table_slap2. + """ + return build_trial_table_slap2(self.dir, save_dir, **kw) + + +@pytest.fixture +def session(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> FakeSession: + """Provide a fake session in a temporary folder. + + Returns + ------- + FakeSession + A session whose reader is replaced by a fake one. + """ + return FakeSession(tmp_path, monkeypatch) + + +def test_triggered_trials(session: FakeSession, tmp_path: Path) -> None: + """Triggered recordings of both paths give one trial per file pair.""" + lines = [100000, 120000, 110000] + dmd1, dmd2 = session.triggered(lines, lines) + session.references() + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["epoch"], np.ones((2, 3))) + np.testing.assert_array_equal(t["true_trial_ix"], np.tile([1, 2, 3], (2, 1))) + s2 = t["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.ones((2, 3))) + np.testing.assert_array_equal(s2["last_line"], np.tile(lines, (2, 1))) + ends = session.mtimes(dmd1) + np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), ends, rtol=0, atol=1e-9) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + ends - np.array(lines) * LINE_PERIOD_S / 86400, + rtol=0, + atol=1e-9, + ) + + +def test_triggered_trial_line_mismatch(session: FakeSession, tmp_path: Path) -> None: + """A file holding two trials back to back is lined up with the other path.""" + # DMD1's trial number failed to increment: its second file holds DMD2's + # second and third trials back to back + dmd1, dmd2 = session.triggered([100000, 220000], [100000, 100000, 120000]) + session.references() + s = session.build(tmp_path / "out") + assert s["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] + s2 = s["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], [[1, 1, 100001], [1, 1, 1]]) + np.testing.assert_array_equal( + s2["last_line"], [[100000, 100000, 220000], [100000, 100000, 120000]] + ) + dn1, dn2 = session.mtimes(dmd1), session.mtimes(dmd2) + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + [dn1[0], dn2[1], dn1[1]], + rtol=0, + atol=1e-9, + ) + + +def test_order_from_file_names_not_mod_times(session: FakeSession, tmp_path: Path) -> None: + """Acquisitions are ordered by the time in their names, not by file times.""" + # copies carry upload times: DMD1's are scrambled within a few seconds, + # DMD2's identical; the earlier acquisition sorts last alphabetically + acqs = [("spont_20250314_101500", 2), ("activity_20250314_111223", 12)] + dmd1 = [f"{a}_DMD1-TRIAL{k:06d}.dat" for a, n in acqs for k in range(1, n + 1)] + dmd2 = [n.replace("DMD1", "DMD2") for n in dmd1] + lines = 100000 + 100 * np.arange(1, len(dmd1) + 1) + upload = datetime.datetime(2026, 8, 27, 10, 53, 33) + for k, (a, b) in enumerate(zip(dmd1, dmd2), start=1): + session.dat(a, lines[k - 1], upload + datetime.timedelta(seconds=(7 * k) % 5)) + session.dat(b, lines[k - 1], upload) + session.references() + with pytest.warns(TrialTableWarning, match="do not look like acquisition times"): + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["true_trial_ix"][0], np.arange(1, len(dmd1) + 1)) + np.testing.assert_array_equal(t["slap2_info"]["last_line"], np.tile(lines, (2, 1))) + np.testing.assert_allclose( + t["slap2_info"]["trial_end_time_from_pc"].ravel(), + session.mtimes(dmd1), + rtol=0, + atol=1e-9, + ) + + +def test_file_order_falls_back_to_mod_time(session: FakeSession, tmp_path: Path) -> None: + """Without a time in the names, files are ordered by modification time.""" + names = ["b_DMD1.dat", "a_DMD1.dat"] + for k, n in enumerate(names, start=1): + t = START + datetime.timedelta(minutes=k) + session.dat(n, 100000, t) + session.dat(n.replace("DMD1", "DMD2"), 100000, t) + session.references() + with pytest.warns(TrialTableWarning, match="modification time"): + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [ + names, + [n.replace("DMD1", "DMD2") for n in names], + ] + + +def test_trial_times_from_line_clock(session: FakeSession, tmp_path: Path) -> None: + """Trial times come from the line clock, which shows gaps the line counts hide.""" + # DMD1's second file holds trials 2 and 3, with a 0.5 s gap that the line + # count alone doesn't show; mtimes are identical upload times + starts = [ + datetime.datetime(2025, 3, 14, 11, 12, 55) + datetime.timedelta(seconds=s) + for s in (0, 10.5, 21) + ] + upload = datetime.datetime(2026, 8, 27, 10, 53, 33) + dmd1 = [f"activity_20250314_111223_DMD1-TRIAL{k:06d}.dat" for k in (1, 2)] + dmd2 = [f"activity_20250314_111223_DMD2-TRIAL{k:06d}.dat" for k in (1, 2, 3)] + session.dat(dmd1[0], 100000, upload, starts[0]) + session.dat(dmd1[1], 220000, upload, starts[1]) + for name, n, s in zip(dmd2, (100000, 100000, 120000), starts): + session.dat(name, n, upload, s) + session.references() + with warnings.catch_warnings(): + warnings.simplefilter("error") + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] + days = np.array([datenum(s) for s in starts]) + s2 = t["slap2_info"] + np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days, rtol=0, atol=1e-9) + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + days + np.array([100000, 100000, 120000]) * LINE_PERIOD_S / 86400, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_trials_and_times(session: FakeSession, tmp_path: Path) -> None: + """A continuous recording is cut into trials with times from the line clock.""" + lines = 450000 + t0 = datetime.datetime(2025, 3, 14, 11, 12, 55) + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START, t0) + # later files of the recording are skipped (their line counts unknown) + for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): + (session.dir / n).write_bytes(b"") + session.references() + t = session.build(tmp_path / "out") + edges = np.array([1, 150001, 300001, 450001], dtype=float) + assert t["filename"].tolist() == [[names[0]] * 3, [names[1]] * 3] + s2 = t["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.tile(edges[:3], (2, 1))) + np.testing.assert_array_equal(s2["last_line"], np.tile(edges[1:], (2, 1))) + days = datenum(t0) + (edges - 1) * LINE_PERIOD_S / 86400 + np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days[:3], rtol=0, atol=1e-9) + np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), days[1:], rtol=0, atol=1e-9) + + +def test_multicycle_times_from_mtime(session: FakeSession, tmp_path: Path) -> None: + """Without the line clock, a continuous recording's times come from file times.""" + lines = 450000 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + edges = np.array([1, 150001, 300001, 450001], dtype=float) + dn = session.mtimes(names[:1])[0] + to_days = LINE_PERIOD_S / 86400 + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + dn - (lines - edges[1:]) * to_days, + rtol=0, + atol=1e-9, + ) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + dn - (lines - edges[:3]) * to_days, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_times_from_last_file_mtime(session: FakeSession, tmp_path: Path) -> None: + """Without the line clock, a CYCLE-split recording ends at its last file's modification time. + + MATLAB takes the first file's. + """ + lines = 450000 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + end = START + datetime.timedelta(seconds=30) + for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): + (session.dir / n).write_bytes(b"") + os.utime(session.dir / n, (end.timestamp(), end.timestamp())) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + last = session.mtimes(["acq_DMD1-CYCLE-000001.dat"])[0] + edges = np.array([1, 150001, 300001, 450001], dtype=float) + to_days = LINE_PERIOD_S / 86400 + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + last - (lines - edges[1:]) * to_days, + rtol=0, + atol=1e-9, + ) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + last - (lines - edges[:3]) * to_days, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_edges_are_matlab_linspace(session: FakeSession, tmp_path: Path) -> None: + """The trial edges of a continuous recording are MATLAB's linspace values.""" + # 3 trials of 599838 lines: the edges are fractional, as MATLAB's + lines = 599837 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + edges = matlab_linspace(1, lines + 1, 4) + assert edges[1] != round(edges[1]) + np.testing.assert_array_equal(s2["first_line"][0], edges[:3]) + np.testing.assert_array_equal(s2["last_line"][0], edges[1:]) + + +def test_matlab_linspace_values() -> None: + """matlab_linspace reproduces values computed in MATLAB.""" + # values from MATLAB R2023b: linspace(1, 599838, 4) + y = matlab_linspace(1, 599838, 4) + assert y[0] == 1 and y[-1] == 599838 + assert y[1] == 1 + (1 * (599838 - 1)) / 3 + assert y[2] == 1 + (2 * (599838 - 1)) / 3 + + +def test_reference_stack(session: FakeSession, tmp_path: Path) -> None: + """Each path's reference stack is found and stored.""" + session.triggered([100000], [100000]) + session.references() + t = session.build(tmp_path / "out") + for path in ("Path1", "Path2"): + ref = t["slap2_info"]["ref_stack"][path] + np.testing.assert_array_equal(ref["channels"], [1, 2]) + np.testing.assert_array_equal(ref["Zs"], [0, 1, 2]) + np.testing.assert_array_equal(ref["dmdPixel2SampleTransform"], np.eye(3)) + assert ref["IM"].shape == ( + 6, + 8, + 6, + ) # columns x rows x pages, as MATLAB + assert ref["IM"].dtype == np.float32 + + +def test_write_trial_table_h5(session: FakeSession, tmp_path: Path) -> None: + """The written trial_table.h5 holds the table in MATLAB's column-major layout.""" + dmd1, dmd2 = session.triggered([100000, 120000], [100000, 120000]) + session.references() + out = tmp_path / "out" + built = session.build(out) + t = load_struct_h5(out / "trial_table.h5") + assert t["datadr"] == str(session.dir) + assert t["savedr"] == str(out) + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["slap2_info"]["last_line"], [[100000, 120000]] * 2) + np.testing.assert_array_equal( + t["slap2_info"]["ref_stack"]["Path1"]["IM"], + built["slap2_info"]["ref_stack"]["Path1"]["IM"], + ) + with h5py.File(out / "trial_table.h5", "r") as h: + # stored column-major, as MATLAB's saveStructToH5 writes it + assert h["filename"].shape == (2, 2) + assert h["slap2_info/first_line"].shape == (2, 2) + assert h["slap2_info/ref_stack/Path1/IM"].shape == (6, 8, 6) + assert h["slap2_info/ref_stack/Path1/Zs"].shape == (3, 1) + assert h["row_major"][()].item() == 0 + + +def test_max_duration_trims_and_keeps_untrimmed(session: FakeSession, tmp_path: Path) -> None: + """max_duration_s trims the table and also writes the untrimmed one.""" + session.triggered([100000, 120000, 110000], [100000, 120000, 110000]) + session.references() + out = tmp_path / "out" + t = session.build(out, max_duration_s=15.0) # 10 s + 5 s of the 12 s trial + assert (out / "trial_table_untrimmed.h5").exists() + s2 = load_struct_h5(out / "trial_table.h5")["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.ones((2, 2))) + np.testing.assert_array_equal(s2["last_line"], [[100000, 50000]] * 2) + assert t["filename"].shape == (2, 2) + assert np.asarray(s2["trial_start_time_inferred"]).size == 2 + full = load_struct_h5(out / "trial_table_untrimmed.h5") + assert full["filename"].shape == (2, 3) + + +def test_trim_keeps_whole_trials_before_the_limit() -> None: + """Trimming keeps the trials that start before the limit and shortens the last.""" + table = { + "filename": np.array([["a", "b"], ["c", "d"]], dtype=object), + "true_trial_ix": np.array([[1.0, 2.0], [1.0, 2.0]]), + "epoch": np.ones((2, 2)), + "slap2_info": { + "first_line": np.ones((2, 2)), + "last_line": np.full((2, 2), 1000.0), + "trial_end_time_from_pc": np.array([[1.0, 2.0]]), + "trial_start_time_inferred": np.array([[0.5, 1.5]]), + }, + } + out, info = trim_trial_table(table, 0.15, 1e-4) # 0.1 s trials + assert info["n_trials_kept"] == 2 and info["last_trial_shortened"] + keep = math.floor((0.15 - 1000 * 1e-4) / 1e-4) # 499 in floating point, as in MATLAB + np.testing.assert_array_equal(out["slap2_info"]["last_line"], [[1000, keep]] * 2) + out, info = trim_trial_table(table, 1.0, 1e-4) + assert info["n_trials_kept"] == 2 and not info["last_trial_shortened"] + with pytest.raises(ValueError): + trim_trial_table(table, 0.0, 1e-4) + + +def test_no_reference_stack_error(session: FakeSession, tmp_path: Path) -> None: + """A session without a reference stack raises FileNotFoundError.""" + session.triggered([100000], [100000]) + with pytest.raises(FileNotFoundError): + session.build(tmp_path / "out") + + +def test_unaligned_dmds_error(session: FakeSession, tmp_path: Path) -> None: + """Paths whose recordings do not line up raise an error.""" + session.triggered([100000], [150000]) + session.references() + with pytest.raises(ValueError, match="lining up"): + session.build(tmp_path / "out") + + +def test_unmatched_trailing_recordings_warn(session: FakeSession, tmp_path: Path) -> None: + """Data left after the last trial that lines up is left out, as in MATLAB, with a warning.""" + session.triggered([100000, 100000], [100000]) + session.references() + with pytest.warns(TrialTableWarning, match="100000 lines of DMD1"): + t = session.build(tmp_path / "out") + assert t["filename"].shape == (2, 1) + + +def test_no_trials_error(session: FakeSession, tmp_path: Path) -> None: + """A session in which no trial lines up warns and raises.""" + session.triggered([100000], []) + session.references() + with pytest.warns(TrialTableWarning, match="left out"): + with pytest.raises(ValueError, match="No trials"): + session.build(tmp_path / "out") + + +@pytest.mark.filterwarnings("ignore:Could not read acquisition times") +def test_mixed_continuous_and_triggered_error(session: FakeSession, tmp_path: Path) -> None: + """Continuous and triggered recordings in one folder raise an error.""" + session.triggered([100000], [100000]) + for n in ("acq2_DMD1-CYCLE-000000.dat", "acq2_DMD2-CYCLE-000000.dat"): + session.dat(n, 450000, START + datetime.timedelta(minutes=5)) + session.references() + with pytest.raises(ValueError, match="both continuous"): + session.build(tmp_path / "out") + + +def test_acquisition_order() -> None: + """Files sort by acquisition time and trial number; ambiguous names are refused.""" + names = [ + "a_20250314_111223_DMD1-TRIAL000010.dat", + "a_20250314_111223_DMD1-TRIAL000002.dat", + "b_20250314_101500_DMD1-TRIAL000001.dat", + ] + order, ok = acquisition_order(names) + assert ok and order.tolist() == [2, 1, 0] + order, ok = acquisition_order(["x_DMD1-TRIAL000002.dat", "x_DMD1-TRIAL000001.dat"]) + assert ok and order.tolist() == [1, 0] + _, ok = acquisition_order(["b_DMD1.dat", "a_DMD1.dat"]) + assert not ok + _, ok = acquisition_order(["x_DMD1.dat", "x_DMD1-CYCLE-000000.dat"]) + assert not ok # same position + + +def _write_mat_datetime(path: Path, ms: complex, tz: str = "") -> None: + """Write a v7.3 MAT file holding fpgaTimeReference as MATLAB writes it. + + The ``FileWrapper__`` blob lists strings, one class (datetime) and one + object whose properties are data (cell 0) and, when given, tz + (cell 1). + """ + strings = [b"data", b"datetime", b"fmt", b"tz"] + names = b"".join(s + b"\0" for s in strings) + names += b"\0" * (-len(names) % 8) + classes = struct.pack("<8I", 0, 0, 0, 0, 0, 2, 0, 0) + objects = struct.pack("<12I", 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1) + props = [(1, 1, 0)] + ([(4, 1, 1)] if tz else []) + words = [0, 0, len(props)] + [v for p in props for v in p] + words += [0] * (len(words) % 2) + sets = struct.pack(f"<{len(words)}I", *words) + o0 = 40 + len(names) + o1 = o0 + len(classes) + o2 = o1 + o3 = o2 + len(objects) + o4 = o3 + len(sets) + header = struct.pack(" None: + """The .meta decoder reads an unzoned MATLAB datetime.""" + # 2025-03-14 09:30:20.5 wall clock, unzoned + ms = ( + datetime.datetime(2025, 3, 14, 9, 30, 20, 500000) - datetime.datetime(1970, 1, 1) + ).total_seconds() * 1000 + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(ms, -8.6e-5)) + assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 8.6e-5, abs=1e-9) + assert read_mat_datetime_ms(p, "missing") is None + # zoned: data is UTC; the wall clock in Los Angeles is 7 h earlier in March + _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") + assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 7 * 3600e3) + + +def test_read_mat_datetime_offset_across_dst(tmp_path: Path) -> None: + """The offset is elapsed time. + + 01:30 PST plus two hours on the day DST starts is 04:30 PDT (MATLAB: + datetime + seconds). + """ + utc = datetime.datetime(2025, 3, 9, 9, 30) # 01:30 in Los Angeles (PST) + ms = (utc - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") + wall = read_mat_datetime_ms(p, "fpgaTimeReference", offset_ms=2 * 3600e3) + expected = datetime.datetime(2025, 3, 9, 4, 30) - datetime.datetime(1970, 1, 1) + assert wall == pytest.approx(expected.total_seconds() * 1000, abs=1e-6) + + +@pytest.mark.parametrize("n", [0, 2]) +def test_read_mat_datetime_needs_one_value(tmp_path: Path, n: int) -> None: + """An empty or multi-element reference gives None, not an error or the first value. + + File times are used instead. + """ + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(1.7e12, 0)) + with h5py.File(p, "r+") as h: + del h["#refs#/c"] + h["#refs#"].create_dataset("c", data=np.zeros((1, n), [("real", " None: + """The first line's timestamp is read from the .dat file, after a magic-number check.""" + + class File: + """A stand-in for the SLAP2 data-file object.""" + + datFileName = str(tmp_path / "x.dat") + header = {"firstCycleOffsetBytes": 16} + + line = struct.pack(" TrialWarp: - """Each trial's map from the canvas to its registered frame.""" - shifts = np.array([[0.3, -0.4], [-0.6, 0.5]]) - if mode == "rigid": - return TrialWarp.from_shifts(shifts) - nodes = np.array([[10.0, 10.0], [10.0, 50.0], [30.0, 10.0], [30.0, 50.0]]) - rng = np.random.default_rng(1) - disp = shifts[:, None, :] + rng.uniform(-0.6, 0.6, (N_TRIALS, 4, 2)) - affine = np.zeros((N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - affine[:, :, 2] = shifts - return TrialWarp(affine, nodes, 15.0, disp) - - -def gaussian( - shape: tuple[int, int], - centre: Sequence[float], - sigma: float = SIGMA, - at: tuple[np.ndarray, np.ndarray] | None = None, -) -> np.ndarray: - """Build a Gaussian image summing to 1 on the canvas grid (zero beyond 3 sigma). - - With ``at = (rows, cols)``, the same function evaluated at those canvas - positions instead of the grid. - """ - rr, cc = np.mgrid[: shape[0], : shape[1]] - - def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: - """Evaluate the truncated, unnormalized Gaussian.""" - d2 = (r - centre[0]) ** 2 + (c - centre[1]) ** 2 - return np.where(d2 > (3 * sigma) ** 2, 0.0, np.exp(-d2 / (2 * sigma**2))) - - z = f(rr, cc).sum() - return (f(rr, cc) if at is None else f(*at)) / z - - -def traces(n200: int, n_src: int) -> np.ndarray: - """Denoised traces ``(n200, sources)``: decaying events.""" - rng = np.random.default_rng(2) - x = np.zeros((n200, n_src)) - k = np.exp(-np.arange(40) / 4.8) - for s in range(n_src): - spikes = np.zeros(n200) - spikes[rng.choice(np.arange(20, n200 - 50), 6, replace=False)] = rng.uniform(20, 80, 6) - x[:, s] = np.convolve(spikes, k)[:n200] - return x - - -def _put(g: h5py.Group, name: str, a: npt.ArrayLike) -> None: - """Write ``a`` as MATLAB would (h5py shows the axes reversed).""" - a = np.asarray(a) - g.create_dataset(name, data=a.T if a.ndim > 1 else a) - - -def _strings(a: npt.ArrayLike) -> np.ndarray: - """Convert to a string array for the trial table.""" - return np.asarray(a, dtype=object).astype(h5py.string_dtype()) - - -def write_session(root: Path, mode: str = "rigid", n80: int = 120) -> dict[str, Any]: - """Write the synthetic session under ``root``. - - Returns a dict of its folders, the warp and the true trial-frame - footprints and traces. - """ - root = Path(root) - moco, base, run = (root / x for x in ("moco", "base", "run")) - for d in (moco, base, run / "source_extraction"): - d.mkdir(parents=True, exist_ok=True) - warp = make_warp(mode) - n_src = CENTRES.shape[0] - ds = 1.0 + DT80 * np.arange(n80) - lines = np.ceil(1.0 + 53.4 * np.arange(int(ds[-1] / 53.4) + 1)) - n200 = lines.size - x200 = [traces(n200, n_src) * (1 + 0.2 * t) for t in range(N_TRIALS)] - true_fp, movies = [], [] - for t in range(N_TRIALS): - w, _ = frame_weights(lines, np.zeros(n200, bool), ds, DT80, 3 * DT80) - x80 = (w.T @ x200[t]).T # (sources, frames) - qr, qc = np.mgrid[:H, :W].astype(float) - at = warp.inverse(t, qr, qc) # canvas position of each trial pixel - fps = np.stack([gaussian((H, W), c, at=at) for c in CENTRES]) - mov = BASELINE + np.einsum("sab,sf->fab", fps, x80) - true_fp.append(fps) - movies.append(mov.astype(np.float32)) - stem = f"E1T{t + 1}DMD1" - with h5py.File(moco / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5", "w") as f: - f["mov"] = movies[-1].transpose(0, 2, 1) # (pages, cols, rows) - with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["DSframes"] = ds[:, None] - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = np.zeros((n80, 1)) - with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: - f["baseline"] = np.full((n80, W, H), BASELINE, np.float16) - _write_table(run / "trial_table.h5", run, moco) - _write_summaries(run / "source_extraction", warp, lines, x200, mode) - return { - "run": run, - "moco": moco, - "base": base, - "warp": warp, - "true_fp": true_fp, - "movies": movies, - "x200": x200, - "lines": lines, - "ds": ds, - } - - -def _write_table(path: Path, savedr: Path, moco: Path) -> None: - """Write a one-path, two-trial trial table (row-major).""" - names = [f"E1T{t + 1}DMD1" for t in range(N_TRIALS)] - with h5py.File(path, "w") as f: - f["row_major"] = np.array([[1]], np.uint8) - f["filename"] = _strings([[f"x-TRIAL{t + 1:06d}.dat" for t in range(N_TRIALS)]]) - g = f.create_group("motion_correction") - g["fn_reg_ds"] = _strings([[f"{n}_REGISTERED_DOWNSAMPLED-80Hz.h5" for n in names]]) - g["fn_adata"] = _strings([[f"{n}_ALIGNMENTDATA.h5" for n in names]]) - f["savedr"] = _strings([[str(savedr)]]) - f["datadr"] = _strings([[str(savedr / "raw")]]) - - -def _write_summaries( - out: Path, warp: TrialWarp, lines: np.ndarray, x200: list[np.ndarray], mode: str -) -> None: - """Both summaries of the synthetic run.""" - n_src, total = CENTRES.shape[0], lines.size * N_TRIALS - fp = np.stack([gaussian((H, W), c) for c in CENTRES]) # canvas - with h5py.File(out / "experiment_summary.h5", "w") as f: - p = f.create_group("params") - for k, v in ( - ("numChannels", 1), - ("activityChannel", 1), - ("alignHz", 80.0), - ("analyzeHz", 200.0), - ("motionThresh", 2.0), - ("discardInitial_s", 0.0), - ("nanThresh", 0.33), - ("peakth", 8.0), - ): - p[k] = np.array([[v]]) - p["validKernel"] = np.ones((5, 5)) - p["interTrialAlignment"] = mode - g = f.create_group("Path1") - act = fp.sum(0) - _put(g, "visualizations/act_im", act[None]) - _put(g, "visualizations/mean_im", (BASELINE + act)[None, None]) - rc = np.column_stack([np.zeros(n_src), CENTRES]) - _put( - g, - "visualizations/act_im_peaks", - np.column_stack([np.zeros(n_src), np.round(CENTRES)]), - ) - fi = "frame_info" - _put( - g, - f"{fi}/trial_num_frames", - np.full((N_TRIALS, 1), lines.size, np.int32), - ) - _put( - g, - f"{fi}/frame_line_idxs", - np.tile(lines, N_TRIALS)[:, None].astype(np.int32), - ) - _put(g, f"{fi}/discard_frames", np.zeros((total, 1), np.int8)) - _put(g, f"{fi}/trial_alignment_affine", warp.affine) - if mode == "patchwise": - disp = np.zeros((N_TRIALS, 2, H, W), np.float32) - rr, cc = np.mgrid[:H, :W] - for t in range(N_TRIALS): - r_t, c_t = warp.grid_coords(t, (H, W)) - disp[t, 0], disp[t, 1] = r_t - rr, c_t - cc - _put(g, f"{fi}/trial_alignment_displacement", disp) - _put(g, "sources/spatial/coords", rc) - _put(g, "sources/spatial/profiles", fp[:, None].astype(np.float32)) - x = np.concatenate(x200, 0) # (total, sources) - for name, val in ( - ("dF_denoised", x), - ("dF_ls", x + 1.0), - ("events", np.zeros_like(x)), - ("F0", np.full_like(x, 50.0)), - ): - _put(g, f"sources/temporal/{name}", val.T[:, None, :]) - _put(g, "sources/temporal/SNR", np.arange(1.0, n_src + 1)[:, None]) - _put(g, "sources/temporal/kinetic_score", np.full((n_src, 1), 0.8)) - _put( - g, - "sources/temporal/kinetic_n_events", - np.full((n_src, 1), 6, np.int32), - ) - _put(g, "sources/rejected/seed_coords", np.array([[0.0, 5.0, 5.0]])) - _put(g, "sources/rejected/kinetic_score", np.array([[0.1]])) - _put(g, "sources/rejected/kinetic_n_events", np.array([[3]], np.int32)) - with h5py.File(out / "per_trial_summary.h5", "w") as f: - g = f.create_group("Path1") - _put( - g, - "visualizations/per_trial_act_im", - np.stack([fp.sum(0)] * N_TRIALS)[:, None], - ) - _put( - g, - "visualizations/per_trial_mean_im", - np.stack([BASELINE + fp.sum(0)] * N_TRIALS)[:, None, None], - ) - _put( - g, - "sources/spatial/per_trial_profiles", - np.stack([fp[:, None]] * N_TRIALS).astype(np.float32), - ) - coords = np.zeros((N_TRIALS, n_src, 3)) - coords[:, :, 1:] = CENTRES - _put(g, "sources/spatial/per_trial_coords", coords) +"""A small synthetic SILo run for the viewer's tests. + +Writes what giant view reads, in the layout giant silo writes it +(the summaries in MATLAB's orientation, h5py's axes reversed): a trial +table, two trials of one path with registered 80 Hz movies (HDF5) and +alignment files, network baselines, and both summaries. The movie is a +constant baseline plus every source's footprint in the trial's frame (the +canvas Gaussian evaluated, exactly, at the map's inverse of each trial +pixel: SILo reads a trial's data through the same map) times its 200 Hz +trace averaged into the 80 Hz frames with the given weights. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import numpy.typing as npt + +from giant_python.extraction.raster.alignment import TrialWarp +from giant_python.viewer.render import frame_weights + +H, W = 40, 60 +N_TRIALS = 2 +DT80 = 134 +SIGMA = 1.33 +CENTRES = np.array([[12.3, 15.6], [20.0, 30.4], [28.7, 44.2]]) +BASELINE = 10.0 + + +def make_warp(mode: str) -> TrialWarp: + """Each trial's map from the canvas to its registered frame. + + Returns + ------- + TrialWarp + The two trials' maps: shifts only for "rigid", otherwise with a patchwise displacement + field. + """ + shifts = np.array([[0.3, -0.4], [-0.6, 0.5]]) + if mode == "rigid": + return TrialWarp.from_shifts(shifts) + nodes = np.array([[10.0, 10.0], [10.0, 50.0], [30.0, 10.0], [30.0, 50.0]]) + rng = np.random.default_rng(1) + disp = shifts[:, None, :] + rng.uniform(-0.6, 0.6, (N_TRIALS, 4, 2)) + affine = np.zeros((N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + affine[:, :, 2] = shifts + return TrialWarp(affine, nodes, 15.0, disp) + + +def gaussian( + shape: tuple[int, int], + centre: Sequence[float], + sigma: float = SIGMA, + at: tuple[np.ndarray, np.ndarray] | None = None, +) -> np.ndarray: + """Build a Gaussian image summing to 1 on the canvas grid (zero beyond 3 sigma). + + With at = (rows, cols), the same function evaluated at those canvas + positions instead of the grid. + + Returns + ------- + np.ndarray + The Gaussian image, normalized by its sum on the grid. + """ + rr, cc = np.mgrid[: shape[0], : shape[1]] + + def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: + """Evaluate the truncated, unnormalized Gaussian. + + Returns + ------- + np.ndarray + The Gaussian at (r, c), zero beyond 3 sigma from the centre. + """ + d2 = (r - centre[0]) ** 2 + (c - centre[1]) ** 2 + return np.where(d2 > (3 * sigma) ** 2, 0.0, np.exp(-d2 / (2 * sigma**2))) + + z = f(rr, cc).sum() + return (f(rr, cc) if at is None else f(*at)) / z + + +def traces(n200: int, n_src: int) -> np.ndarray: + """Denoised traces (n200, sources): decaying events. + + Returns + ------- + np.ndarray + The (n200, n_src) traces: six random events per source, each decaying exponentially. + """ + rng = np.random.default_rng(2) + x = np.zeros((n200, n_src)) + k = np.exp(-np.arange(40) / 4.8) + for s in range(n_src): + spikes = np.zeros(n200) + spikes[rng.choice(np.arange(20, n200 - 50), 6, replace=False)] = rng.uniform(20, 80, 6) + x[:, s] = np.convolve(spikes, k)[:n200] + return x + + +def _put(g: h5py.Group, name: str, a: npt.ArrayLike) -> None: + """Write a as MATLAB would (h5py shows the axes reversed).""" + a = np.asarray(a) + g.create_dataset(name, data=a.T if a.ndim > 1 else a) + + +def _strings(a: npt.ArrayLike) -> np.ndarray: + """Convert to a string array for the trial table. + + Returns + ------- + np.ndarray + The values as an object array with h5py's string dtype. + """ + return np.asarray(a, dtype=object).astype(h5py.string_dtype()) + + +def write_session(root: Path, mode: str = "rigid", n80: int = 120) -> dict[str, Any]: + """Write the synthetic session under root. + + Returns + ------- + dict + Its folders (run, moco, base), the warp, the true trial-frame footprints + (true_fp) and the movies, the 200 Hz traces (x200), their frame lines and + the 80 Hz frame times (ds). + """ + root = Path(root) + moco, base, run = (root / x for x in ("moco", "base", "run")) + for d in (moco, base, run / "source_extraction"): + d.mkdir(parents=True, exist_ok=True) + warp = make_warp(mode) + n_src = CENTRES.shape[0] + ds = 1.0 + DT80 * np.arange(n80) + lines = np.ceil(1.0 + 53.4 * np.arange(int(ds[-1] / 53.4) + 1)) + n200 = lines.size + x200 = [traces(n200, n_src) * (1 + 0.2 * t) for t in range(N_TRIALS)] + true_fp, movies = [], [] + for t in range(N_TRIALS): + w, _ = frame_weights(lines, np.zeros(n200, bool), ds, DT80, 3 * DT80) + x80 = (w.T @ x200[t]).T # (sources, frames) + qr, qc = np.mgrid[:H, :W].astype(float) + at = warp.inverse(t, qr, qc) # canvas position of each trial pixel + fps = np.stack([gaussian((H, W), c, at=at) for c in CENTRES]) + mov = BASELINE + np.einsum("sab,sf->fab", fps, x80) + true_fp.append(fps) + movies.append(mov.astype(np.float32)) + stem = f"E1T{t + 1}DMD1" + with h5py.File(moco / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5", "w") as f: + f["mov"] = movies[-1].transpose(0, 2, 1) # (pages, cols, rows) + with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["DSframes"] = ds[:, None] + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = np.zeros((n80, 1)) + with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: + f["baseline"] = np.full((n80, W, H), BASELINE, np.float16) + _write_table(run / "trial_table.h5", run, moco) + _write_summaries(run / "source_extraction", warp, lines, x200, mode) + return { + "run": run, + "moco": moco, + "base": base, + "warp": warp, + "true_fp": true_fp, + "movies": movies, + "x200": x200, + "lines": lines, + "ds": ds, + } + + +def _write_table(path: Path, savedr: Path, moco: Path) -> None: + """Write a one-path, two-trial trial table (row-major).""" + names = [f"E1T{t + 1}DMD1" for t in range(N_TRIALS)] + with h5py.File(path, "w") as f: + f["row_major"] = np.array([[1]], np.uint8) + f["filename"] = _strings([[f"x-TRIAL{t + 1:06d}.dat" for t in range(N_TRIALS)]]) + g = f.create_group("motion_correction") + g["fn_reg_ds"] = _strings([[f"{n}_REGISTERED_DOWNSAMPLED-80Hz.h5" for n in names]]) + g["fn_adata"] = _strings([[f"{n}_ALIGNMENTDATA.h5" for n in names]]) + f["savedr"] = _strings([[str(savedr)]]) + f["datadr"] = _strings([[str(savedr / "raw")]]) + + +def _write_summaries( + out: Path, warp: TrialWarp, lines: np.ndarray, x200: list[np.ndarray], mode: str +) -> None: + """Both summaries of the synthetic run.""" + n_src, total = CENTRES.shape[0], lines.size * N_TRIALS + fp = np.stack([gaussian((H, W), c) for c in CENTRES]) # canvas + with h5py.File(out / "experiment_summary.h5", "w") as f: + p = f.create_group("params") + for k, v in ( + ("numChannels", 1), + ("activityChannel", 1), + ("alignHz", 80.0), + ("analyzeHz", 200.0), + ("motionThresh", 2.0), + ("discardInitial_s", 0.0), + ("nanThresh", 0.33), + ("peakth", 8.0), + ): + p[k] = np.array([[v]]) + p["validKernel"] = np.ones((5, 5)) + p["interTrialAlignment"] = mode + g = f.create_group("Path1") + act = fp.sum(0) + _put(g, "visualizations/act_im", act[None]) + _put(g, "visualizations/mean_im", (BASELINE + act)[None, None]) + rc = np.column_stack([np.zeros(n_src), CENTRES]) + _put( + g, + "visualizations/act_im_peaks", + np.column_stack([np.zeros(n_src), np.round(CENTRES)]), + ) + fi = "frame_info" + _put( + g, + f"{fi}/trial_num_frames", + np.full((N_TRIALS, 1), lines.size, np.int32), + ) + _put( + g, + f"{fi}/frame_line_idxs", + np.tile(lines, N_TRIALS)[:, None].astype(np.int32), + ) + _put(g, f"{fi}/discard_frames", np.zeros((total, 1), np.int8)) + _put(g, f"{fi}/trial_alignment_affine", warp.affine) + if mode == "patchwise": + disp = np.zeros((N_TRIALS, 2, H, W), np.float32) + rr, cc = np.mgrid[:H, :W] + for t in range(N_TRIALS): + r_t, c_t = warp.grid_coords(t, (H, W)) + disp[t, 0], disp[t, 1] = r_t - rr, c_t - cc + _put(g, f"{fi}/trial_alignment_displacement", disp) + _put(g, "sources/spatial/coords", rc) + _put(g, "sources/spatial/profiles", fp[:, None].astype(np.float32)) + x = np.concatenate(x200, 0) # (total, sources) + for name, val in ( + ("dF_denoised", x), + ("dF_ls", x + 1.0), + ("events", np.zeros_like(x)), + ("F0", np.full_like(x, 50.0)), + ): + _put(g, f"sources/temporal/{name}", val.T[:, None, :]) + _put(g, "sources/temporal/SNR", np.arange(1.0, n_src + 1)[:, None]) + _put(g, "sources/temporal/kinetic_score", np.full((n_src, 1), 0.8)) + _put( + g, + "sources/temporal/kinetic_n_events", + np.full((n_src, 1), 6, np.int32), + ) + _put(g, "sources/rejected/seed_coords", np.array([[0.0, 5.0, 5.0]])) + _put(g, "sources/rejected/kinetic_score", np.array([[0.1]])) + _put(g, "sources/rejected/kinetic_n_events", np.array([[3]], np.int32)) + with h5py.File(out / "per_trial_summary.h5", "w") as f: + g = f.create_group("Path1") + _put( + g, + "visualizations/per_trial_act_im", + np.stack([fp.sum(0)] * N_TRIALS)[:, None], + ) + _put( + g, + "visualizations/per_trial_mean_im", + np.stack([BASELINE + fp.sum(0)] * N_TRIALS)[:, None, None], + ) + _put( + g, + "sources/spatial/per_trial_profiles", + np.stack([fp[:, None]] * N_TRIALS).astype(np.float32), + ) + coords = np.zeros((N_TRIALS, n_src, 3)) + coords[:, :, 1:] = CENTRES + _put(g, "sources/spatial/per_trial_coords", coords) diff --git a/tests/viewer/test_viewer_render.py b/tests/viewer/test_viewer_render.py index 4ae8682f..7ec8ed53 100644 --- a/tests/viewer/test_viewer_render.py +++ b/tests/viewer/test_viewer_render.py @@ -1,384 +1,405 @@ -"""Rendering of SILo's activity in a trial's movie (giant view).""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.viewer.render import ( - KERNELS, - TrialMap, - exact_weights, - frame_weights, - interp_weights, - kernel_dt, - kernel_weights, - place_footprints, -) -from giant_python.viewer.run import SiloRun, footprint_width -from giant_python.viewer.trial import Session, load_trial, render_dt - -from .synthetic import ( - CENTRES, - N_TRIALS, - H, - W, - gaussian, - make_warp, - write_session, -) - - -def _exporter_weights( - lines200: np.ndarray, disc: np.ndarray, ds: np.ndarray, dt: float, half: float -) -> tuple[np.ndarray, np.ndarray]: - """Run the exporter's loop (exportF0TrainingData.m), as a dense matrix.""" - wk = np.zeros((lines200.size, ds.size)) - share = np.zeros(ds.size) - for j in range(ds.size): - d = lines200 - ds[j] - sel = np.flatnonzero(np.abs(d) <= half) - w = np.exp(-np.abs(d[sel]) / dt) - share[j] = w[disc[sel]].sum() / max(w.sum(), np.finfo(float).eps) - keep = ~disc[sel] - if keep.any(): - wk[sel[keep], j] = w[keep] / w[keep].sum() - return wk, share - - -def test_frame_weights_match_the_exporter() -> None: - """Weights and discard shares equal the exporter's loop.""" - rng = np.random.default_rng(0) - lines200 = np.ceil(1 + 53.4 * np.arange(400)) - disc = rng.random(400) < 0.1 - ds = 1.0 + 134 * np.arange(150) + 7 - w, share = frame_weights(lines200, disc, ds, 134, 402) - ref, ref_share = _exporter_weights(lines200, disc, ds, 134, 402) - np.testing.assert_allclose(w.toarray(), ref, atol=1e-12) - np.testing.assert_allclose(share, ref_share, atol=1e-12) - full = np.asarray(w.sum(0)).ravel() - assert np.allclose(full[full > 0], 1.0) - - -def test_kernel_dt_and_matched_kernel() -> None: - """Dt from DSframes; the matched kernel removes the 200 Hz part.""" - assert kernel_dt(1 + 134 * np.arange(10), None, 2.5) == 134 - assert kernel_dt(np.array([5.0]), np.arange(0, 540, 54.0), 2.5) == 135 - lines = np.ceil(1 + 53.4 * np.arange(100)) - assert render_dt("exporter", 134, lines) == 134 - assert render_dt("matched", 134, lines) == pytest.approx(np.sqrt(134**2 - 54**2)) - with pytest.raises(ValueError): - render_dt("other", 134, lines) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_trial_map_inverse(mode: str) -> None: - """The map's inverse undoes it (and agrees with TrialWarp's).""" - warp = make_warp(mode) - rng = np.random.default_rng(3) - r, c = rng.uniform(3, H - 3, 200), rng.uniform(3, W - 3, 200) - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - rr, cc = np.mgrid[:H, :W] - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - fr, fc = m.forward(r, c) - er, ec = warp.coords(t, r, c) - tol = 1e-9 if mode == "rigid" else 2e-3 # bilinear field - np.testing.assert_allclose(fr, er, atol=tol) - np.testing.assert_allclose(fc, ec, atol=tol) - ir, ic = m.inverse(er, ec) - wr, wc = warp.inverse(t, er, ec) - np.testing.assert_allclose(ir, wr, atol=tol) - np.testing.assert_allclose(ic, wc, atol=tol) - - -def test_affine_map_inverse_is_exact() -> None: - """An affine map's inverse is exact.""" - a = np.array([[1.01, 0.02, 0.4], [-0.015, 0.99, -0.3]]) - m = TrialMap(a) - r, c = np.array([3.0, 10.5]), np.array([7.0, 2.25]) - fr, fc = m.forward(r, c) - ir, ic = m.inverse(fr, fc) - np.testing.assert_allclose(ir, r, atol=1e-12) - np.testing.assert_allclose(ic, c, atol=1e-12) - - -def _fp_tuple(img: np.ndarray, s: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Convert a canvas footprint image to ``(rows, cols, sources, values)``.""" - r, c = np.nonzero(img) - return r, c, np.full(r.size, s), img[r, c] - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_place_footprints_moves_them_through_the_map(mode: str) -> None: - """A placed footprint lands at the mapped centroid. - - Its sum changes only by the map's local area factor (a few percent for - this bend). - """ - warp = make_warp(mode) - parts = [_fp_tuple(gaussian((H, W), c), s) for s, c in enumerate(CENTRES)] - fp = tuple(np.concatenate(x) for x in zip(*parts)) - rr, cc = np.mgrid[:H, :W] - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - h = place_footprints(fp, CENTRES.shape[0], m, (H, W)).toarray() - for s in range(CENTRES.shape[0]): - img = h[:, s].reshape(H, W) - tol = 0.01 if mode == "rigid" else 0.05 - assert img.sum() == pytest.approx(1.0, abs=tol) - cen = [(img * rr).sum() / img.sum(), (img * cc).sum() / img.sum()] - want = warp.coords(t, *CENTRES[s]) - np.testing.assert_allclose(cen, np.ravel(want), atol=0.02) - - -def test_place_footprints_blur_keeps_the_sum() -> None: - """A blurred footprint still sums to (about) 1.""" - m = TrialMap(np.array([[1.0, 0, 0.2], [0, 1.0, -0.1]])) - fp = _fp_tuple(gaussian((H, W), CENTRES[1]), 0) - h = place_footprints(fp, 1, m, (H, W), sigma=0.75).toarray() - assert h.sum() == pytest.approx(1.0, abs=0.01) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_rendered_activity_reproduces_the_movie(tmp_path: Path, mode: str) -> None: - """The rendered activity of a synthetic run has the movie's flux and centroids. - - On a synthetic run whose movie is footprints x 80 Hz traces plus a - baseline, the rendered activity has the movie's flux and centroids at - every source (rigid and patchwise maps); pixel by pixel it differs by - the bilinear interpolation of a 1.33 px footprint (up to ~12% at - a half-pixel shift). - """ - syn = write_session(tmp_path, mode) - run = SiloRun(syn["run"], "net") - assert run.path(1).alignment == mode - session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) - for t in range(N_TRIALS): - tr = load_trial([run], session, 1, t) - assert tr.layers == [ - "movie", - "activity:net", - "residual:net", - "baseline", - "residual-baseline:net", - ] - lay = tr.runs[0] - act = np.asarray((lay.footprints @ lay.x80["exporter"]).T) - signal = tr.movie - 10.0 - assert np.nanmax(np.abs(signal - act)) < 0.15 * np.nanmax(signal) - f = tr.busiest_frame() - for s in range(CENTRES.shape[0]): - want = np.ravel(syn["warp"].coords(t, *CENTRES[s])) - near = np.hypot(tr.rows - want[0], tr.cols - want[1]) < 4 - a, m = act[:, near].sum(1), signal[:, near].sum(1) - np.testing.assert_allclose(a, m, atol=0.02 * m.max()) - for img in (act[f, near], signal[f, near]): - cen = ( - np.array([ - (img * tr.rows[near]).sum(), - (img * tr.cols[near]).sum(), - ]) - / img.sum() - ) - np.testing.assert_allclose(cen, want, atol=0.03) - fr = tr.frame(f, 4) - assert fr.shape == (5, tr.N) - np.testing.assert_allclose(fr[2], fr[0] - fr[1], atol=1e-4) - tc, n = tr.trace(int(lay.kept_rc[0, 0]), int(lay.kept_rc[0, 1]), 1) - assert n == 9 and tc.shape == (5, tr.T) - np.testing.assert_allclose(tc[3], 10.0, atol=0.01) - # the matched kernel is narrower: same totals, sharper peaks - xm, xe = lay.x80["matched"], lay.x80["exporter"] - np.testing.assert_allclose(xm.sum(1), xe.sum(1), rtol=0.02) - assert (xm.max(1) > xe.max(1)).all() - fm = tr.frame(f, 1, "matched") - assert fm.shape == (5, tr.N) and not np.array_equal(fm[1], fr[1]) - - -def test_run_reader(tmp_path: Path) -> None: - """Sources, images, traces and per-trial footprints of a run.""" - syn = write_session(tmp_path, "rigid") - run = SiloRun(syn["run"], "r") - p = run.path(1) - assert p.shape == (H, W) and p.sources.n == 3 - np.testing.assert_allclose(p.sources.rc, CENTRES) - assert p.sources.rejected_rc.tolist() == [[5.0, 5.0]] - assert run.describe()["validKernel"] == 5 - tr = run.traces(1) - assert tr["dF_denoised"].shape == (2 * syn["lines"].size, 3) - fps = run.footprints(1) - assert len(fps) == N_TRIALS and fps[0][3].sum() == pytest.approx(3.0) - patch, r0, c0 = run.profile_patch(1, 0) - assert patch.shape == (15, 15) - w = footprint_width(gaussian((H, W), CENTRES[0]), *CENTRES[0]) - assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 - - -def test_movie_found_by_stem(tmp_path: Path) -> None: - """A table naming a TIFF finds the HDF5 movie, as SILo does.""" - import h5py - - syn = write_session(tmp_path, "rigid") - table = syn["run"] / "trial_table.h5" - with h5py.File(table, "r+") as f: - names = f["motion_correction/fn_reg_ds"][()].astype(str) - del f["motion_correction/fn_reg_ds"] - f["motion_correction/fn_reg_ds"] = ( - np.char.replace(names, ".h5", ".tif").astype(object).astype(h5py.string_dtype()) - ) - session = Session(table, syn["moco"], syn["base"]) - assert session.has_movie(0, 0) - assert session.movie_file(0, 0).suffix == ".h5" - - -def test_kernels_follow_each_runs_frame_lines(tmp_path: Path) -> None: - """Each run's matched kernel comes from its own 200 Hz frame lines.""" - syn = write_session(tmp_path, "rigid") - session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) - a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") - b.path(1).lines = ( - b.path(1).lines * 0 + np.arange(b.path(1).lines.size) * 30.0 + 1 - ) # another analysis rate: dt200 30 lines - tr = load_trial([a, b], session, 1, 0) - ka, kb = tr.runs[0].kernels["matched"][0], tr.runs[1].kernels["matched"][0] - assert ka == pytest.approx(np.sqrt(134**2 - 54**2)) - assert kb == pytest.approx(np.sqrt(134**2 - 30**2)) - assert set(tr.info["render_dt_lines"]) == {"a", "b"} - - -def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float) -> np.ndarray: - """Frames formed from a densely sampled signal as weighted means. - - One sample per line, line ``i + 1`` holds ``x[i]``; the weights are - ``exp(-|dline| / dt)`` within ``reach`` lines of each frame's line. - """ - lines = np.arange(1, x.size + 1, dtype=float) - out = np.empty(at.size) - for j, a in enumerate(at): - sel = np.abs(lines - a) <= reach - w = np.exp(-np.abs(lines[sel] - a) / dt) - out[j] = (w * x[sel]).sum() / w.sum() - return out - - -def test_exact_kernel_undoes_the_double_smoothing() -> None: - """The exact kernel turns 200 Hz frames into the movie's 80 Hz frames to about 1%. - - On densely sampled data (kernels not truncated); the exporter's kernel - loses ~10% of a fast event's peak, the matched one ~5%. - """ - n = 60000 - x = np.zeros(n) - k = np.exp(-np.arange(1200) / 150.0) # ~14 ms decay at 10.7 kHz lines - for onset in range(4000, n - 5000, 7919): - x[onset : onset + k.size] += 100 * k - dt80, dt200, reach = 134, 54, 12 - lines200 = np.arange(1, n, dt200, dtype=float) - ds = np.arange(1, n, dt80, dtype=float) + 17 - f200 = _formed(x, lines200, dt200, reach * dt200) - f80 = _formed(x, ds, dt80, reach * dt80) - none = np.zeros(lines200.size, bool) - ok = (ds > 3000) & (ds < n - 3000) - peak, rms = {}, {} - for kern in KERNELS: - w, share, info = kernel_weights(kern, lines200, none, ds, dt80, reach * dt80) - assert np.allclose(share, 0) - via = w.T @ f200 - peak[kern] = via[ok].max() / f80[ok].max() - rms[kern] = np.sqrt(np.mean((via[ok] - f80[ok]) ** 2)) / np.sqrt(np.mean(f80[ok] ** 2)) - if kern == "exact": - assert info["r"] == pytest.approx((54 / 134) ** 2) - assert peak["exact"] == pytest.approx(1.0, abs=0.01) - assert rms["exact"] < 0.015 - assert peak["exporter"] < 0.95 - assert peak["exporter"] < peak["matched"] < peak["exact"] - assert rms["exact"] < rms["matched"] < rms["exporter"] - - -def test_interp_weights_skip_discarded_frames() -> None: - """Interpolation uses kept neighbours only, holds at the ends.""" - lines = np.array([10.0, 20, 30, 40, 50]) - keep = np.array([True, True, False, True, True]) - w = interp_weights(lines, keep, np.array([5.0, 25, 35, 45, 60])).toarray() - np.testing.assert_allclose(w.sum(0), 1.0) - assert w[0, 0] == 1 and w[4, 4] == 1 # nearest kept beyond the ends - np.testing.assert_allclose(w[[1, 3], 1], [0.75, 0.25]) # 20..40 - np.testing.assert_allclose(w[[1, 3], 2], [0.25, 0.75]) - assert not w[2].any() - assert interp_weights(lines, np.zeros(5, bool), lines).nnz == 0 - one = interp_weights(lines, keep & (lines == 40), lines).toarray() - assert (one[3] == 1).all() - - -def test_exact_weights_with_discarded_frames() -> None: - """Columns sum to 1; discarded frames get no weight. - - A frame with no kept 200 Hz frame within reach stays empty, as the - exporter's. - """ - rng = np.random.default_rng(4) - lines200 = np.ceil(1 + 53.4 * np.arange(400)) - disc = rng.random(400) < 0.1 - disc[200:240] = True # a long gap: frames in it have nothing in reach - ds = 1.0 + 134 * np.arange(150) + 7 - w, share, r = exact_weights(lines200, disc, ds, 134, 54, 402) - ref, ref_share = frame_weights(lines200, disc, ds, 134, 402) - np.testing.assert_allclose(share, ref_share) - tot = np.asarray(w.sum(0)).ravel() - empty = np.asarray(ref.sum(0)).ravel() == 0 - assert empty.any() and np.allclose(tot[empty], 0) - np.testing.assert_allclose(tot[~empty], 1.0) - assert not w.toarray()[disc].any() - assert r == pytest.approx((54 / 134) ** 2) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_cubic_placement_keeps_the_shape(mode: str) -> None: - """Moved by a fraction of a pixel, a footprint keeps its flux with either interpolation. - - The cubic spline also keeps its peak, where bilinear interpolation blurs - it. - """ - warp = make_warp(mode) - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - rr, cc = np.mgrid[:H, :W] - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - qr, qc = np.mgrid[:H, :W].astype(float) - at = warp.inverse(t, qr, qc) - err = {} - for order in (1, 3): - for s, centre in enumerate(CENTRES): - fp = gaussian((H, W), centre) - r, c = np.nonzero(fp) - fps = (r, c, np.zeros(r.size, int), fp[r, c]) - h = place_footprints(fps, 1, m, (H, W), interp_order=order) - img = h.toarray()[:, 0].reshape(H, W) - want = gaussian((H, W), centre, at=at) - assert img.sum() == pytest.approx(want.sum(), rel=0.01) - err.setdefault(order, []).append(np.abs(img - want).max() / want.max()) - assert max(err[3]) < 0.02 - assert max(err[3]) < max(err[1]) - - -def test_matched_kernel_with_one_frame() -> None: - """With one 200 Hz frame the matched kernel keeps the movie's dt. - - As render_dt does, and it still renders the frame. - """ - w, _, info = kernel_weights( - "matched", np.array([100.0]), np.zeros(1, bool), np.array([90.0]), 134 - ) - assert info["dt"] == 134 and render_dt("matched", 134, [100.0]) == 134 - assert w.toarray()[0, 0] == pytest.approx(1.0) +"""Rendering of SILo's activity in a trial's movie (giant view).""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.viewer.render import ( + KERNELS, + TrialMap, + exact_weights, + frame_weights, + interp_weights, + kernel_dt, + kernel_weights, + place_footprints, +) +from giant_python.viewer.run import SiloRun, footprint_width +from giant_python.viewer.trial import Session, load_trial, render_dt + +from .synthetic import ( + CENTRES, + N_TRIALS, + H, + W, + gaussian, + make_warp, + write_session, +) + + +def _exporter_weights( + lines200: np.ndarray, disc: np.ndarray, ds: np.ndarray, dt: float, half: float +) -> tuple[np.ndarray, np.ndarray]: + """Run the exporter's loop (exportF0TrainingData.m), as a dense matrix. + + Returns + ------- + weights : np.ndarray + (lines200.size, ds.size) weights of the kept 200 Hz lines in each frame, + each column normalized to sum to 1 (all zero when every line is discarded). + share : np.ndarray + Share of each frame's kernel weight that falls on discarded lines. + """ + wk = np.zeros((lines200.size, ds.size)) + share = np.zeros(ds.size) + for j in range(ds.size): + d = lines200 - ds[j] + sel = np.flatnonzero(np.abs(d) <= half) + w = np.exp(-np.abs(d[sel]) / dt) + share[j] = w[disc[sel]].sum() / max(w.sum(), np.finfo(float).eps) + keep = ~disc[sel] + if keep.any(): + wk[sel[keep], j] = w[keep] / w[keep].sum() + return wk, share + + +def test_frame_weights_match_the_exporter() -> None: + """Weights and discard shares equal the exporter's loop.""" + rng = np.random.default_rng(0) + lines200 = np.ceil(1 + 53.4 * np.arange(400)) + disc = rng.random(400) < 0.1 + ds = 1.0 + 134 * np.arange(150) + 7 + w, share = frame_weights(lines200, disc, ds, 134, 402) + ref, ref_share = _exporter_weights(lines200, disc, ds, 134, 402) + np.testing.assert_allclose(w.toarray(), ref, atol=1e-12) + np.testing.assert_allclose(share, ref_share, atol=1e-12) + full = np.asarray(w.sum(0)).ravel() + assert np.allclose(full[full > 0], 1.0) + + +def test_kernel_dt_and_matched_kernel() -> None: + """Dt from DSframes; the matched kernel removes the 200 Hz part.""" + assert kernel_dt(1 + 134 * np.arange(10), None, 2.5) == 134 + assert kernel_dt(np.array([5.0]), np.arange(0, 540, 54.0), 2.5) == 135 + lines = np.ceil(1 + 53.4 * np.arange(100)) + assert render_dt("exporter", 134, lines) == 134 + assert render_dt("matched", 134, lines) == pytest.approx(np.sqrt(134**2 - 54**2)) + with pytest.raises(ValueError): + render_dt("other", 134, lines) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_trial_map_inverse(mode: str) -> None: + """The map's inverse undoes it (and agrees with TrialWarp's).""" + warp = make_warp(mode) + rng = np.random.default_rng(3) + r, c = rng.uniform(3, H - 3, 200), rng.uniform(3, W - 3, 200) + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + rr, cc = np.mgrid[:H, :W] + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + fr, fc = m.forward(r, c) + er, ec = warp.coords(t, r, c) + tol = 1e-9 if mode == "rigid" else 2e-3 # bilinear field + np.testing.assert_allclose(fr, er, atol=tol) + np.testing.assert_allclose(fc, ec, atol=tol) + ir, ic = m.inverse(er, ec) + wr, wc = warp.inverse(t, er, ec) + np.testing.assert_allclose(ir, wr, atol=tol) + np.testing.assert_allclose(ic, wc, atol=tol) + + +def test_affine_map_inverse_is_exact() -> None: + """An affine map's inverse is exact.""" + a = np.array([[1.01, 0.02, 0.4], [-0.015, 0.99, -0.3]]) + m = TrialMap(a) + r, c = np.array([3.0, 10.5]), np.array([7.0, 2.25]) + fr, fc = m.forward(r, c) + ir, ic = m.inverse(fr, fc) + np.testing.assert_allclose(ir, r, atol=1e-12) + np.testing.assert_allclose(ic, c, atol=1e-12) + + +def _fp_tuple(img: np.ndarray, s: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Convert a canvas footprint image to (rows, cols, sources, values). + + Returns + ------- + tuple of np.ndarray + The row and column of each non-zero pixel, the source index s repeated + for each pixel, and the pixel values. + """ + r, c = np.nonzero(img) + return r, c, np.full(r.size, s), img[r, c] + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_place_footprints_moves_them_through_the_map(mode: str) -> None: + """A placed footprint lands at the mapped centroid. + + Its sum changes only by the map's local area factor (a few percent for + this bend). + """ + warp = make_warp(mode) + parts = [_fp_tuple(gaussian((H, W), c), s) for s, c in enumerate(CENTRES)] + fp = tuple(np.concatenate(x) for x in zip(*parts)) + rr, cc = np.mgrid[:H, :W] + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + h = place_footprints(fp, CENTRES.shape[0], m, (H, W)).toarray() + for s in range(CENTRES.shape[0]): + img = h[:, s].reshape(H, W) + tol = 0.01 if mode == "rigid" else 0.05 + assert img.sum() == pytest.approx(1.0, abs=tol) + cen = [(img * rr).sum() / img.sum(), (img * cc).sum() / img.sum()] + want = warp.coords(t, *CENTRES[s]) + np.testing.assert_allclose(cen, np.ravel(want), atol=0.02) + + +def test_place_footprints_blur_keeps_the_sum() -> None: + """A blurred footprint still sums to (about) 1.""" + m = TrialMap(np.array([[1.0, 0, 0.2], [0, 1.0, -0.1]])) + fp = _fp_tuple(gaussian((H, W), CENTRES[1]), 0) + h = place_footprints(fp, 1, m, (H, W), sigma=0.75).toarray() + assert h.sum() == pytest.approx(1.0, abs=0.01) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_rendered_activity_reproduces_the_movie(tmp_path: Path, mode: str) -> None: + """The rendered activity of a synthetic run has the movie's flux and centroids. + + On a synthetic run whose movie is footprints x 80 Hz traces plus a + baseline, the rendered activity has the movie's flux and centroids at + every source (rigid and patchwise maps); pixel by pixel it differs by + the bilinear interpolation of a 1.33 px footprint (up to ~12% at + a half-pixel shift). + """ + syn = write_session(tmp_path, mode) + run = SiloRun(syn["run"], "net") + assert run.path(1).alignment == mode + session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) + for t in range(N_TRIALS): + tr = load_trial([run], session, 1, t) + assert tr.layers == [ + "movie", + "activity:net", + "residual:net", + "baseline", + "residual-baseline:net", + ] + lay = tr.runs[0] + act = np.asarray((lay.footprints @ lay.x80["exporter"]).T) + signal = tr.movie - 10.0 + assert np.nanmax(np.abs(signal - act)) < 0.15 * np.nanmax(signal) + f = tr.busiest_frame() + for s in range(CENTRES.shape[0]): + want = np.ravel(syn["warp"].coords(t, *CENTRES[s])) + near = np.hypot(tr.rows - want[0], tr.cols - want[1]) < 4 + a, m = act[:, near].sum(1), signal[:, near].sum(1) + np.testing.assert_allclose(a, m, atol=0.02 * m.max()) + for img in (act[f, near], signal[f, near]): + cen = ( + np.array([ + (img * tr.rows[near]).sum(), + (img * tr.cols[near]).sum(), + ]) + / img.sum() + ) + np.testing.assert_allclose(cen, want, atol=0.03) + fr = tr.frame(f, 4) + assert fr.shape == (5, tr.N) + np.testing.assert_allclose(fr[2], fr[0] - fr[1], atol=1e-4) + tc, n = tr.trace(int(lay.kept_rc[0, 0]), int(lay.kept_rc[0, 1]), 1) + assert n == 9 and tc.shape == (5, tr.T) + np.testing.assert_allclose(tc[3], 10.0, atol=0.01) + # the matched kernel is narrower: same totals, sharper peaks + xm, xe = lay.x80["matched"], lay.x80["exporter"] + np.testing.assert_allclose(xm.sum(1), xe.sum(1), rtol=0.02) + assert (xm.max(1) > xe.max(1)).all() + fm = tr.frame(f, 1, "matched") + assert fm.shape == (5, tr.N) and not np.array_equal(fm[1], fr[1]) + + +def test_run_reader(tmp_path: Path) -> None: + """Sources, images, traces and per-trial footprints of a run.""" + syn = write_session(tmp_path, "rigid") + run = SiloRun(syn["run"], "r") + p = run.path(1) + assert p.shape == (H, W) and p.sources.n == 3 + np.testing.assert_allclose(p.sources.rc, CENTRES) + assert p.sources.rejected_rc.tolist() == [[5.0, 5.0]] + assert run.describe()["validKernel"] == 5 + tr = run.traces(1) + assert tr["dF_denoised"].shape == (2 * syn["lines"].size, 3) + fps = run.footprints(1) + assert len(fps) == N_TRIALS and fps[0][3].sum() == pytest.approx(3.0) + patch, r0, c0 = run.profile_patch(1, 0) + assert patch.shape == (15, 15) + w = footprint_width(gaussian((H, W), CENTRES[0]), *CENTRES[0]) + assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 + + +def test_movie_found_by_stem(tmp_path: Path) -> None: + """A table naming a TIFF finds the HDF5 movie, as SILo does.""" + import h5py + + syn = write_session(tmp_path, "rigid") + table = syn["run"] / "trial_table.h5" + with h5py.File(table, "r+") as f: + names = f["motion_correction/fn_reg_ds"][()].astype(str) + del f["motion_correction/fn_reg_ds"] + f["motion_correction/fn_reg_ds"] = ( + np.char.replace(names, ".h5", ".tif").astype(object).astype(h5py.string_dtype()) + ) + session = Session(table, syn["moco"], syn["base"]) + assert session.has_movie(0, 0) + assert session.movie_file(0, 0).suffix == ".h5" + + +def test_kernels_follow_each_runs_frame_lines(tmp_path: Path) -> None: + """Each run's matched kernel comes from its own 200 Hz frame lines.""" + syn = write_session(tmp_path, "rigid") + session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) + a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") + b.path(1).lines = ( + b.path(1).lines * 0 + np.arange(b.path(1).lines.size) * 30.0 + 1 + ) # another analysis rate: dt200 30 lines + tr = load_trial([a, b], session, 1, 0) + ka, kb = tr.runs[0].kernels["matched"][0], tr.runs[1].kernels["matched"][0] + assert ka == pytest.approx(np.sqrt(134**2 - 54**2)) + assert kb == pytest.approx(np.sqrt(134**2 - 30**2)) + assert set(tr.info["render_dt_lines"]) == {"a", "b"} + + +def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float) -> np.ndarray: + """Frames formed from a densely sampled signal as weighted means. + + One sample per line, line i + 1 holds x[i]; the weights are + ``exp(-|dline| / dt)`` within reach lines of each frame's line. + + Returns + ------- + np.ndarray + One weighted-mean value per entry of at. + """ + lines = np.arange(1, x.size + 1, dtype=float) + out = np.empty(at.size) + for j, a in enumerate(at): + sel = np.abs(lines - a) <= reach + w = np.exp(-np.abs(lines[sel] - a) / dt) + out[j] = (w * x[sel]).sum() / w.sum() + return out + + +def test_exact_kernel_undoes_the_double_smoothing() -> None: + """The exact kernel turns 200 Hz frames into the movie's 80 Hz frames to about 1%. + + On densely sampled data (kernels not truncated); the exporter's kernel + loses ~10% of a fast event's peak, the matched one ~5%. + """ + n = 60000 + x = np.zeros(n) + k = np.exp(-np.arange(1200) / 150.0) # ~14 ms decay at 10.7 kHz lines + for onset in range(4000, n - 5000, 7919): + x[onset : onset + k.size] += 100 * k + dt80, dt200, reach = 134, 54, 12 + lines200 = np.arange(1, n, dt200, dtype=float) + ds = np.arange(1, n, dt80, dtype=float) + 17 + f200 = _formed(x, lines200, dt200, reach * dt200) + f80 = _formed(x, ds, dt80, reach * dt80) + none = np.zeros(lines200.size, bool) + ok = (ds > 3000) & (ds < n - 3000) + peak, rms = {}, {} + for kern in KERNELS: + w, share, info = kernel_weights(kern, lines200, none, ds, dt80, reach * dt80) + assert np.allclose(share, 0) + via = w.T @ f200 + peak[kern] = via[ok].max() / f80[ok].max() + rms[kern] = np.sqrt(np.mean((via[ok] - f80[ok]) ** 2)) / np.sqrt(np.mean(f80[ok] ** 2)) + if kern == "exact": + assert info["r"] == pytest.approx((54 / 134) ** 2) + assert peak["exact"] == pytest.approx(1.0, abs=0.01) + assert rms["exact"] < 0.015 + assert peak["exporter"] < 0.95 + assert peak["exporter"] < peak["matched"] < peak["exact"] + assert rms["exact"] < rms["matched"] < rms["exporter"] + + +def test_interp_weights_skip_discarded_frames() -> None: + """Interpolation uses kept neighbours only, holds at the ends.""" + lines = np.array([10.0, 20, 30, 40, 50]) + keep = np.array([True, True, False, True, True]) + w = interp_weights(lines, keep, np.array([5.0, 25, 35, 45, 60])).toarray() + np.testing.assert_allclose(w.sum(0), 1.0) + assert w[0, 0] == 1 and w[4, 4] == 1 # nearest kept beyond the ends + np.testing.assert_allclose(w[[1, 3], 1], [0.75, 0.25]) # 20..40 + np.testing.assert_allclose(w[[1, 3], 2], [0.25, 0.75]) + assert not w[2].any() + assert interp_weights(lines, np.zeros(5, bool), lines).nnz == 0 + one = interp_weights(lines, keep & (lines == 40), lines).toarray() + assert (one[3] == 1).all() + + +def test_exact_weights_with_discarded_frames() -> None: + """Columns sum to 1; discarded frames get no weight. + + A frame with no kept 200 Hz frame within reach stays empty, as the + exporter's. + """ + rng = np.random.default_rng(4) + lines200 = np.ceil(1 + 53.4 * np.arange(400)) + disc = rng.random(400) < 0.1 + disc[200:240] = True # a long gap: frames in it have nothing in reach + ds = 1.0 + 134 * np.arange(150) + 7 + w, share, r = exact_weights(lines200, disc, ds, 134, 54, 402) + ref, ref_share = frame_weights(lines200, disc, ds, 134, 402) + np.testing.assert_allclose(share, ref_share) + tot = np.asarray(w.sum(0)).ravel() + empty = np.asarray(ref.sum(0)).ravel() == 0 + assert empty.any() and np.allclose(tot[empty], 0) + np.testing.assert_allclose(tot[~empty], 1.0) + assert not w.toarray()[disc].any() + assert r == pytest.approx((54 / 134) ** 2) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_cubic_placement_keeps_the_shape(mode: str) -> None: + """Moved by a fraction of a pixel, a footprint keeps its flux with either interpolation. + + The cubic spline also keeps its peak, where bilinear interpolation blurs + it. + """ + warp = make_warp(mode) + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + rr, cc = np.mgrid[:H, :W] + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + qr, qc = np.mgrid[:H, :W].astype(float) + at = warp.inverse(t, qr, qc) + err = {} + for order in (1, 3): + for s, centre in enumerate(CENTRES): + fp = gaussian((H, W), centre) + r, c = np.nonzero(fp) + fps = (r, c, np.zeros(r.size, int), fp[r, c]) + h = place_footprints(fps, 1, m, (H, W), interp_order=order) + img = h.toarray()[:, 0].reshape(H, W) + want = gaussian((H, W), centre, at=at) + assert img.sum() == pytest.approx(want.sum(), rel=0.01) + err.setdefault(order, []).append(np.abs(img - want).max() / want.max()) + assert max(err[3]) < 0.02 + assert max(err[3]) < max(err[1]) + + +def test_matched_kernel_with_one_frame() -> None: + """With one 200 Hz frame the matched kernel keeps the movie's dt. + + As render_dt does, and it still renders the frame. + """ + w, _, info = kernel_weights( + "matched", np.array([100.0]), np.zeros(1, bool), np.array([90.0]), 134 + ) + assert info["dt"] == 134 and render_dt("matched", 134, [100.0]) == 134 + assert w.toarray()[0, 0] == pytest.approx(1.0) diff --git a/tests/viewer/test_viewer_server.py b/tests/viewer/test_viewer_server.py index 6229f8d4..0bf25fb9 100644 --- a/tests/viewer/test_viewer_server.py +++ b/tests/viewer/test_viewer_server.py @@ -1,137 +1,153 @@ -"""API smoke test of the giant view server.""" - -import argparse -import json -import threading -import urllib.error -import urllib.request -from collections.abc import Iterator -from email.message import Message -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.cli import build_parser -from giant_python.viewer.server import Store, make_server, make_store - -from .synthetic import N_TRIALS, H, W, write_session - - -@pytest.fixture -def server(tmp_path: Path) -> Iterator[tuple[str, Store]]: - """Start a running server on a synthetic session with two runs.""" - syn = write_session(tmp_path, "patchwise") - args = build_parser().parse_args([ - "view", - f"net={syn['run']}", - f"other={syn['run']}", - "--moco-dir", - str(syn["moco"]), - "--baseline-dir", - str(syn["base"]), - "--port", - "0", - "--no-browser", - ]) - assert isinstance(args, argparse.Namespace) and args.command == "view" - store = make_store(args) - srv = make_server(store, "127.0.0.1", 0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - yield f"http://127.0.0.1:{srv.server_address[1]}", store - srv.shutdown() - srv.server_close() - - -def _get(url: str) -> tuple[bytes, Message]: - """Body and headers of a GET.""" - with urllib.request.urlopen(url, timeout=60) as r: - return r.read(), r.headers - - -def test_api(server: tuple[str, Store]) -> None: - """Every endpoint answers with the expected shapes.""" - base, store = server - body, _ = _get(base + "/") - assert b"SILo run viewer" in body - meta = json.loads(_get(base + "/api/meta")[0]) - assert [r["name"] for r in meta["runs"]] == ["net", "other"] - assert meta["paths"][0]["alignment"] == ["patchwise", "patchwise"] - assert len(meta["paths"][0]["trials"]) == N_TRIALS - src = json.loads(_get(base + "/api/sources?path=1")[0]) - assert src["shape"] == [H, W] and len(src["runs"]["net"]["kept"]) == 3 - img, hd = _get(base + "/api/image?path=1&run=net&kind=trial_act&trial=1") - assert json.loads(hd["X-Shape"]) == [H, W] - assert np.frombuffer(img, np.float32).size == H * W - s = json.loads(_get(base + "/api/source?path=1&run=net&id=1")[0]) - assert len(s["trial_rc"]) == N_TRIALS and s["events"] - tb, hd = _get(base + "/api/source_traces?path=1&run=net&id=1") - assert np.frombuffer(tb, np.float32).size == 4 * store.runs[0].path(1).lines.size - st = json.loads(_get(base + "/api/trial?path=1&trial=0")[0]) - n_layers = len(st["layers"]) - assert n_layers == 1 + 2 * 2 + 1 + 2 # movie, 2 runs x 2, base, 2 res - n = len(st["rows"]) - fr, hd = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4") - assert np.frombuffer(fr, np.float32).size == n_layers * n - fm, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=matched") - assert np.frombuffer(fm, np.float32).size == n_layers * n - fx, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=exact") - assert np.frombuffer(fx, np.float32).size == n_layers * n - tc, hd = _get(base + "/api/trace?path=1&trial=0&r=20&c=30&rad=1") - assert int(hd["X-Pixels"]) == 9 - assert np.frombuffer(tc, np.float32).size == n_layers * st["shape"][0] - assert json.loads(_get(base + "/api/progress?key=1/0")[0]) == {"msg": ""} - - -def test_api_errors(server: tuple[str, Store]) -> None: - """Unknown paths and bad keys are errors, not crashes.""" - base, _ = server - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/nothing") - assert e.value.code == 404 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/source?path=1&run=nobody&id=0") - assert e.value.code == 400 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/frame?path=1&trial=0") - assert e.value.code == 400 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/frame?path=1&trial=0&t=3&kernel=other") - assert e.value.code == 400 - - -def test_runs_must_share_the_activity_channel(tmp_path: Path) -> None: - """Runs read with different activity channels are not compared.""" - from giant_python.viewer.run import SiloRun - from giant_python.viewer.server import Store - from giant_python.viewer.trial import Session - - syn = write_session(tmp_path, "rigid") - a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") - b.params["activityChannel"] = 2 - session = Session(syn["run"] / "trial_table.h5", syn["moco"]) - with pytest.raises(ValueError, match="activityChannel"): - Store([a, b], session) - # a run without numChannels counts as 2 channels, as the loader reads it - b.params["activityChannel"] = 1 - a.params["numChannels"] = 2 - b.params.pop("numChannels") - Store([a, b], session) - a.params["numChannels"] = 1 - with pytest.raises(ValueError, match="numChannels"): - Store([a, b], session) - - -def test_large_valid_kernel_is_reported(tmp_path: Path) -> None: - """A 9 x 9 support (81 values) is still described.""" - import h5py - - from giant_python.viewer.run import SiloRun - - syn = write_session(tmp_path, "rigid") - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["params/validKernel"] - f["params/validKernel"] = np.ones((9, 9)) - assert SiloRun(syn["run"]).describe()["validKernel"] == 9 +"""API smoke test of the giant view server.""" + +import argparse +import json +import threading +import urllib.error +import urllib.request +from collections.abc import Iterator +from email.message import Message +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.cli import build_parser +from giant_python.viewer.server import Store, make_server, make_store + +from .synthetic import N_TRIALS, H, W, write_session + + +@pytest.fixture +def server(tmp_path: Path) -> Iterator[tuple[str, Store]]: + """Start a running server on a synthetic session with two runs. + + Yields + ------ + url : str + The server's address. + store : Store + The store of runs the server serves. + """ + syn = write_session(tmp_path, "patchwise") + args = build_parser().parse_args([ + "view", + f"net={syn['run']}", + f"other={syn['run']}", + "--moco-dir", + str(syn["moco"]), + "--baseline-dir", + str(syn["base"]), + "--port", + "0", + "--no-browser", + ]) + assert isinstance(args, argparse.Namespace) and args.command == "view" + store = make_store(args) + srv = make_server(store, "127.0.0.1", 0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + yield f"http://127.0.0.1:{srv.server_address[1]}", store + srv.shutdown() + srv.server_close() + + +def _get(url: str) -> tuple[bytes, Message]: + """Body and headers of a GET. + + Returns + ------- + body : bytes + The response body. + headers : Message + The response headers. + """ + with urllib.request.urlopen(url, timeout=60) as r: + return r.read(), r.headers + + +def test_api(server: tuple[str, Store]) -> None: + """Every endpoint answers with the expected shapes.""" + base, store = server + body, _ = _get(base + "/") + assert b"SILo run viewer" in body + meta = json.loads(_get(base + "/api/meta")[0]) + assert [r["name"] for r in meta["runs"]] == ["net", "other"] + assert meta["paths"][0]["alignment"] == ["patchwise", "patchwise"] + assert len(meta["paths"][0]["trials"]) == N_TRIALS + src = json.loads(_get(base + "/api/sources?path=1")[0]) + assert src["shape"] == [H, W] and len(src["runs"]["net"]["kept"]) == 3 + img, hd = _get(base + "/api/image?path=1&run=net&kind=trial_act&trial=1") + assert json.loads(hd["X-Shape"]) == [H, W] + assert np.frombuffer(img, np.float32).size == H * W + s = json.loads(_get(base + "/api/source?path=1&run=net&id=1")[0]) + assert len(s["trial_rc"]) == N_TRIALS and s["events"] + tb, hd = _get(base + "/api/source_traces?path=1&run=net&id=1") + assert np.frombuffer(tb, np.float32).size == 4 * store.runs[0].path(1).lines.size + st = json.loads(_get(base + "/api/trial?path=1&trial=0")[0]) + n_layers = len(st["layers"]) + assert n_layers == 1 + 2 * 2 + 1 + 2 # movie, 2 runs x 2, base, 2 res + n = len(st["rows"]) + fr, hd = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4") + assert np.frombuffer(fr, np.float32).size == n_layers * n + fm, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=matched") + assert np.frombuffer(fm, np.float32).size == n_layers * n + fx, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=exact") + assert np.frombuffer(fx, np.float32).size == n_layers * n + tc, hd = _get(base + "/api/trace?path=1&trial=0&r=20&c=30&rad=1") + assert int(hd["X-Pixels"]) == 9 + assert np.frombuffer(tc, np.float32).size == n_layers * st["shape"][0] + assert json.loads(_get(base + "/api/progress?key=1/0")[0]) == {"msg": ""} + + +def test_api_errors(server: tuple[str, Store]) -> None: + """Unknown paths and bad keys are errors, not crashes.""" + base, _ = server + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/nothing") + assert e.value.code == 404 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/source?path=1&run=nobody&id=0") + assert e.value.code == 400 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/frame?path=1&trial=0") + assert e.value.code == 400 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/frame?path=1&trial=0&t=3&kernel=other") + assert e.value.code == 400 + + +def test_runs_must_share_the_activity_channel(tmp_path: Path) -> None: + """Runs read with different activity channels are not compared.""" + from giant_python.viewer.run import SiloRun + from giant_python.viewer.server import Store + from giant_python.viewer.trial import Session + + syn = write_session(tmp_path, "rigid") + a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") + b.params["activityChannel"] = 2 + session = Session(syn["run"] / "trial_table.h5", syn["moco"]) + with pytest.raises(ValueError, match="activityChannel"): + Store([a, b], session) + # a run without numChannels counts as 2 channels, as the loader reads it + b.params["activityChannel"] = 1 + a.params["numChannels"] = 2 + b.params.pop("numChannels") + Store([a, b], session) + a.params["numChannels"] = 1 + with pytest.raises(ValueError, match="numChannels"): + Store([a, b], session) + + +def test_large_valid_kernel_is_reported(tmp_path: Path) -> None: + """A 9 x 9 support (81 values) is still described.""" + import h5py + + from giant_python.viewer.run import SiloRun + + syn = write_session(tmp_path, "rigid") + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["params/validKernel"] + f["params/validKernel"] = np.ones((9, 9)) + assert SiloRun(syn["run"]).describe()["validKernel"] == 9 From 7d2c4e5798877102e7e7ad78385b01d5c5e1d5b9 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 14:30:25 -0800 Subject: [PATCH 10/14] merge with main --- examples/extract_band.py | 3 +- pyproject.toml | 120 +- src/giant_python/__init__.py | 38 +- src/giant_python/annotator/__init__.py | 8 +- src/giant_python/annotator/files.py | 365 +++-- src/giant_python/annotator/server.py | 532 ++++-- src/giant_python/annotator/session.py | 561 +++++-- src/giant_python/annotator/state.py | 129 +- src/giant_python/cli.py | 224 ++- src/giant_python/cli_silo.py | 265 +-- src/giant_python/cli_spine.py | 70 +- src/giant_python/export/f0_injected.py | 8 +- src/giant_python/export/f0_layout.py | 33 +- src/giant_python/export/f0_mask.py | 5 +- src/giant_python/export/f0_training.py | 835 +++++++--- src/giant_python/extraction/band/activity.py | 13 +- .../extraction/band/annotation.py | 13 +- .../extraction/band/background.py | 8 +- src/giant_python/extraction/band/geometry.py | 10 +- src/giant_python/extraction/band/inputs.py | 15 +- .../extraction/band/localization.py | 28 +- .../extraction/band/motion_binning.py | 8 +- src/giant_python/extraction/band/operators.py | 16 +- .../extraction/band/result_assembly.py | 7 +- .../extraction/band/summary_images.py | 7 +- src/giant_python/extraction/band/traces.py | 26 +- .../extraction/band/trial_data.py | 3 +- src/giant_python/extraction/band/workflow.py | 9 +- .../extraction/raster/alignment.py | 1048 ++++++++---- .../extraction/raster/annotations.py | 24 +- .../extraction/raster/baseline_map.py | 309 ++-- .../extraction/raster/container.py | 24 +- .../extraction/raster/kinetics.py | 124 +- .../extraction/raster/localization.py | 457 ++++-- src/giant_python/extraction/raster/null.py | 797 +++++---- src/giant_python/extraction/raster/peaks.py | 23 +- src/giant_python/extraction/raster/plan.py | 695 +++++--- .../extraction/raster/refit_test.py | 91 +- src/giant_python/extraction/raster/results.py | 407 +++-- src/giant_python/extraction/raster/seeding.py | 239 +-- src/giant_python/extraction/raster/solver.py | 471 +++--- .../extraction/raster/solver_baseline.py | 607 ++++--- .../extraction/raster/solver_fits.py | 616 +++++-- .../extraction/raster/solver_setup.py | 295 ++-- src/giant_python/extraction/raster/spots.py | 4 +- .../extraction/raster/stage_files.py | 22 +- src/giant_python/extraction/raster/summary.py | 584 ++++--- src/giant_python/extraction/raster/trial.py | 454 ++++-- .../extraction/raster/trial_data.py | 1150 +++++++++---- src/giant_python/extraction/raster/wmf.py | 442 +++-- src/giant_python/gui/parameters_gui.py | 5 +- src/giant_python/io/annotations.py | 5 +- src/giant_python/io/experiment_summary.py | 502 ++++-- src/giant_python/io/hdf5.py | 8 +- src/giant_python/io/slap2.py | 10 +- src/giant_python/io/slap2_raster.py | 23 +- src/giant_python/io/tiff.py | 3 +- src/giant_python/io/trial_table.py | 5 +- src/giant_python/models/__init__.py | 6 +- src/giant_python/models/experiment_summary.py | 251 +-- src/giant_python/models/params.py | 737 +++++---- src/giant_python/models/trial_table.py | 29 +- src/giant_python/numerics/baseline.py | 4 +- src/giant_python/numerics/morphology.py | 4 +- src/giant_python/numerics/peaks.py | 10 +- src/giant_python/parallel.py | 235 ++- src/giant_python/pipeline/__init__.py | 2 +- src/giant_python/pipeline/annotate.py | 4 +- src/giant_python/pipeline/extract.py | 6 +- src/giant_python/pipeline/pipeline.py | 20 +- src/giant_python/pipeline/reg_stats.py | 92 +- src/giant_python/pipeline/register.py | 187 ++- src/giant_python/pipeline/silo.py | 1429 +++++++++++------ src/giant_python/pipeline/silo_baseline.py | 302 ++-- src/giant_python/pipeline/silo_collect.py | 237 ++- src/giant_python/pipeline/silo_session.py | 480 ++++-- src/giant_python/pipeline/silo_solve.py | 620 +++++-- src/giant_python/pipeline/silo_spots.py | 762 ++++++--- src/giant_python/pipeline/trial_table.py | 28 +- src/giant_python/progress.py | 4 +- src/giant_python/registration/compensation.py | 9 +- src/giant_python/registration/frames.py | 395 +++-- src/giant_python/registration/growth.py | 7 +- .../registration/interpolation.py | 3 +- src/giant_python/registration/matching.py | 16 +- src/giant_python/registration/multiroi.py | 19 +- src/giant_python/registration/outputs.py | 15 +- src/giant_python/registration/sources.py | 5 +- .../registration/stats/geometry.py | 10 +- src/giant_python/registration/stats/io.py | 9 +- src/giant_python/simulation/injection.py | 129 +- src/giant_python/simulation/render.py | 6 +- src/giant_python/spine/coverage.py | 130 +- src/giant_python/spine/images.py | 212 ++- src/giant_python/spine/parallel.py | 216 ++- src/giant_python/spine/pipeline.py | 578 ++++--- src/giant_python/spine/product.py | 2 +- src/giant_python/spine/summary_io.py | 4 +- src/giant_python/spine/trends.py | 375 +++-- src/giant_python/spine/view/export.py | 2 +- src/giant_python/viewer/render.py | 14 +- src/giant_python/viewer/run.py | 17 +- src/giant_python/viewer/server.py | 3 +- src/giant_python/viewer/trial.py | 9 +- tests/annotator/__init__.py | 2 +- tests/annotator/synthetic.py | 96 +- tests/annotator/test_annotator.py | 245 +-- tests/export/test_f0_layout.py | 8 +- tests/export/test_f0_training.py | 6 +- tests/raster/alignment_synthetic.py | 2 +- tests/raster/data/compare_matlab_wmf.py | 85 +- tests/raster/data/make_matlab_wmf_h5.py | 2 +- tests/raster/test_raster_alignment.py | 2 +- tests/raster/test_raster_alignment_modes.py | 511 +++--- tests/raster/test_raster_container.py | 95 +- tests/raster/test_raster_core_f0.py | 180 ++- tests/raster/test_raster_f0_images.py | 16 +- tests/raster/test_raster_kinetics.py | 100 +- tests/raster/test_raster_localization.py | 281 ++-- tests/raster/test_raster_null.py | 399 +++-- tests/raster/test_raster_peaks.py | 12 +- tests/raster/test_raster_plan.py | 552 ++++--- tests/raster/test_raster_results.py | 404 +++-- tests/raster/test_raster_seed_acceptance.py | 18 +- tests/raster/test_raster_seeding.py | 67 +- tests/raster/test_raster_silo_load_ahead.py | 215 ++- tests/raster/test_raster_silo_local.py | 302 ++-- tests/raster/test_raster_silo_network.py | 486 +++--- tests/raster/test_raster_silo_params.py | 191 ++- tests/raster/test_raster_silo_stages.py | 698 +++++--- tests/raster/test_raster_solver.py | 10 +- .../test_raster_solver_baseline_modes.py | 6 +- tests/raster/test_raster_solver_fits.py | 17 +- .../raster/test_raster_solver_fits_bitwise.py | 226 ++- tests/raster/test_raster_solver_setup.py | 26 +- tests/raster/test_raster_spots.py | 274 ++-- tests/raster/test_raster_summary.py | 340 ++-- tests/raster/test_raster_summary_model.py | 2 +- tests/raster/test_raster_trial.py | 144 +- tests/raster/test_raster_trial_data.py | 700 ++++---- tests/raster/test_raster_variance_interp.py | 196 +-- tests/raster/test_raster_wmf.py | 179 ++- tests/raster/test_raster_wmf_deblend.py | 8 +- tests/raster/wmf_reference.py | 37 +- tests/registration/test_cli.py | 103 +- tests/registration/test_curtain.py | 5 +- tests/registration/test_growth.py | 2 +- tests/registration/test_kernels.py | 2 +- tests/registration/test_reg_stats.py | 10 +- tests/registration/test_synthetic.py | 14 +- tests/simulation/test_injection.py | 12 +- tests/spine/conftest.py | 36 +- tests/spine/test_spine_coverage.py | 195 ++- tests/spine/test_spine_gains.py | 24 +- tests/spine/test_spine_images.py | 194 ++- tests/spine/test_spine_parallel.py | 441 +++-- tests/spine/test_spine_pipeline.py | 469 +++--- tests/spine/test_spine_trends.py | 256 +-- tests/viewer/test_viewer_render.py | 2 +- 159 files changed, 19119 insertions(+), 10223 deletions(-) diff --git a/examples/extract_band.py b/examples/extract_band.py index bdfe855d..6e38c75f 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 ( diff --git a/pyproject.toml b/pyproject.toml index cb5229c9..28bbc571 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,14 +1,14 @@ [build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" [project] name = "giant-python" 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" @@ -39,57 +39,73 @@ 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.version] +source = "vcs" +fallback-version = "0.0.0" + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +packages = ["src/giant_python"] + +[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 = 100 -[tool.setuptools.packages.find] -where = ["src"] - -[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.ruff.lint] +select = ["I", "E", "F", "W", "ANN", "W505", "D", "DOC"] + +[tool.ruff.lint.pycodestyle] +max-doc-length = 100 + +[tool.ruff.lint.pydocstyle] +convention = "numpy" -[tool.setuptools.dynamic] -version = {attr = "giant_python.__version__"} - -[tool.black] -line-length = 79 -target_version = ['py310'] -exclude = ''' - -( - /( - \.eggs # exclude a few common directories in the - | \.git # root of the project - | \.hg - | \.mypy_cache - | \.venv - | _build - | build - | dist - | .conda - )/ - | .gitignore -) -''' - -[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/src/giant_python/__init__.py b/src/giant_python/__init__.py index 7e473415..e68d9a27 100644 --- a/src/giant_python/__init__.py +++ b/src/giant_python/__init__.py @@ -1,9 +1,9 @@ -"""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. @@ -56,8 +56,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 +86,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/f0_injected.py b/src/giant_python/export/f0_injected.py index 9905174e..d9a91449 100644 --- a/src/giant_python/export/f0_injected.py +++ b/src/giant_python/export/f0_injected.py @@ -40,7 +40,7 @@ from dataclasses import asdict, replace from pathlib import Path from types import SimpleNamespace -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING import numpy as np @@ -140,7 +140,7 @@ def kernel_lines(layout: RasterLayout, align_hz: float) -> int: int The frame kernel, in lines. """ - return int(math.ceil((1.0 / layout.line_period_s) / float(align_hz))) + return math.ceil((1.0 / layout.line_period_s) / float(align_hz)) def injected_frames( @@ -513,7 +513,7 @@ def _selection(options: ExportOptions, truth: dict, originals: list) -> tuple: def export_injected( copy_dir: str | Path, out_dir: str | Path, - options: Optional[ExportOptions] = None, + options: ExportOptions | None = None, device: str = "cpu", expected: bool = False, log: Callable[[str], None] = print, @@ -620,7 +620,7 @@ def export_injected( def add_arguments(p: argparse.ArgumentParser) -> None: - """Add arguments for ``giant export-f0-injected``.""" + """Add arguments for giant export-f0-injected.""" p.add_argument( "copy", help="the injected copy's folder (trial_table.h5 registered, raw/, " diff --git a/src/giant_python/export/f0_layout.py b/src/giant_python/export/f0_layout.py index c2059684..c3b77ec2 100644 --- a/src/giant_python/export/f0_layout.py +++ b/src/giant_python/export/f0_layout.py @@ -44,8 +44,9 @@ import argparse import logging import time +from collections.abc import Sequence from pathlib import Path -from typing import TYPE_CHECKING, Optional, Sequence, Union +from typing import TYPE_CHECKING import h5py import numpy as np @@ -193,7 +194,7 @@ def sharing_slots(layout: RasterLayout) -> tuple: return np.where(jump, -1, nxt), start, end -def layout_path(movie_path: Union[str, Path]) -> Path: +def layout_path(movie_path: str | Path) -> Path: """Return the layout file of a registered movie. _REGISTERED_DOWNSAMPLED-80Hz.h5 (or .tif) gives @@ -322,7 +323,7 @@ def pulse_statistics( """ 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] @@ -780,11 +781,11 @@ 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: """Build the layout record of one registered trial and path. @@ -931,7 +932,7 @@ def trial_layout( } -def write_layout(path: Union[str, Path], record: dict) -> None: +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. @@ -959,7 +960,7 @@ 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 @@ -1016,7 +1017,7 @@ def _corner_values(image: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> np. 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: """Return registered frames of the samples of a layout file's slots. @@ -1071,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) @@ -1132,15 +1133,15 @@ 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. diff --git a/src/giant_python/export/f0_mask.py b/src/giant_python/export/f0_mask.py index 3b5a6adc..2e74c868 100644 --- a/src/giant_python/export/f0_mask.py +++ b/src/giant_python/export/f0_mask.py @@ -27,7 +27,6 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Optional import numpy as np from numpy.typing import ArrayLike @@ -220,11 +219,11 @@ def _disk(r: float) -> np.ndarray: def activity_mask( H: sparse.spmatrix | None, - tm: Optional[np.ndarray], + 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: """Build the trial's activity mask in the crop. 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 a6bd161f..47e9a1f1 100644 --- a/src/giant_python/extraction/band/activity.py +++ b/src/giant_python/extraction/band/activity.py @@ -2,19 +2,16 @@ 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 @@ -93,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, diff --git a/src/giant_python/extraction/band/annotation.py b/src/giant_python/extraction/band/annotation.py index 2b6b9c8a..e3570d6e 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 @@ -77,7 +76,7 @@ def _stdin_is_tty() -> bool: return bool(getattr(sys.stdin, "isatty", lambda: False)()) -def resolve_interactivity(override: Optional[bool] = None) -> bool: +def resolve_interactivity(override: bool | None = None) -> bool: """Resolve override, then GIANT_HEADLESS, then terminal detection. Returns @@ -134,12 +133,12 @@ def load_annotations_h5(annotations_path: str, n_dmds: int, user_roi_geo: dict) 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. @@ -176,10 +175,10 @@ def resolve_user_rois( 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. @@ -236,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, diff --git a/src/giant_python/extraction/band/background.py b/src/giant_python/extraction/band/background.py index 24b05ce1..1a66391f 100644 --- a/src/giant_python/extraction/band/background.py +++ b/src/giant_python/extraction/band/background.py @@ -2,8 +2,6 @@ from __future__ import annotations -from typing import Tuple - import numpy as np import pandas as pd from numpy.typing import DTypeLike @@ -63,7 +61,7 @@ def _collect_interp_columns( # Preserve scientific parity with the reference interpolation branches. -def _interp_columns( # noqa: C901 +def _interp_columns( out: np.ndarray, rows_by_col: dict[int, np.ndarray], idxs_by_col: dict[int, np.ndarray], @@ -185,7 +183,7 @@ def build_interp_data( width: int = 1280, 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 @@ -438,7 +436,7 @@ 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 diff --git a/src/giant_python/extraction/band/geometry.py b/src/giant_python/extraction/band/geometry.py index 0b3bf106..9c081ec3 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 @@ -138,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 @@ -210,7 +208,7 @@ def selected_pixels_2d_for_plane( plane_z: int, dmd_pixels_per_column: int, dmd_pixels_per_row: int, -) -> Tuple[np.ndarray, np.ndarray]: +) -> tuple[np.ndarray, np.ndarray]: """Return the in-plane [row, col] coords of one z-plane's pixels. Parameters diff --git a/src/giant_python/extraction/band/inputs.py b/src/giant_python/extraction/band/inputs.py index 54ce2183..fc449044 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,7 +21,7 @@ from .geometry import build_combined_psf, threshold_and_crop_psf -def load_lookup_table(path: Union[str, Path], n_dmds: int) -> dict: +def load_lookup_table(path: str | Path, n_dmds: int) -> dict: """Load the band-registration lookup table (bandRegLookupTable.h5). Parameters @@ -81,7 +80,7 @@ def _ref_stack_group(ref_stack: dict, dmd_ix: int) -> dict: return group -def find_reference_file(datadr: Union[str, Path], dmd_ix: int) -> Optional[str]: +def find_reference_file(datadr: str | Path, dmd_ix: int) -> str | None: """Find the REFERENCE tif for a DMD under datadr (recursive glob). Parameters @@ -108,10 +107,10 @@ def find_reference_file(datadr: Union[str, Path], dmd_ix: int) -> Optional[str]: 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 @@ -192,7 +191,7 @@ def load_psf(dilation: int, n_dmds: int) -> dict: 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 @@ -232,7 +231,7 @@ def _resolve_fn_adata(fn_adata: np.ndarray, moco_save_dr: str) -> np.ndarray: 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; @@ -298,7 +297,7 @@ 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. diff --git a/src/giant_python/extraction/band/localization.py b/src/giant_python/extraction/band/localization.py index 3d6ce61c..5ee7d515 100644 --- a/src/giant_python/extraction/band/localization.py +++ b/src/giant_python/extraction/band/localization.py @@ -36,7 +36,7 @@ from __future__ import annotations -from typing import List, cast +from typing import cast import numpy as np import torch @@ -192,11 +192,11 @@ def build_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 @@ -325,7 +325,7 @@ def solve_phi_motion(x: torch.Tensor, data_motion: torch.Tensor) -> torch.Tensor 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, @@ -365,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, @@ -374,7 +374,7 @@ 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 @@ -411,7 +411,7 @@ def multiplicative_nmf( list of torch.Tensor 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. @@ -448,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, @@ -593,7 +593,7 @@ def reorder_sources( 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, @@ -639,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, @@ -705,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, diff --git a/src/giant_python/extraction/band/motion_binning.py b/src/giant_python/extraction/band/motion_binning.py index 98bacb1e..e16c8e42 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 @@ -40,7 +38,7 @@ 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 @@ -79,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 diff --git a/src/giant_python/extraction/band/operators.py b/src/giant_python/extraction/band/operators.py index e1a7e2a5..43165fc0 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,7 +13,7 @@ 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_facx up-sampled cubic-spline interpolation @@ -103,7 +103,7 @@ def shrink_psf(psf2d: np.ndarray, scale_y: float = 1.0, scale_x: float = 0.75) - 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, @@ -137,7 +137,7 @@ def gaussian_kernel_2d(sigma: float, truncate: float = 4.0) -> Tuple[torch.Tenso 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. @@ -185,7 +185,7 @@ def build_motion_h_matrices( sel_pix_idxs: np.ndarray, num_super_pixels: int, dmd_pixels_per_row: int, -) -> List[torch.Tensor]: +) -> 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 @@ -212,7 +212,7 @@ def build_motion_h_matrices( 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( @@ -231,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( @@ -239,7 +239,7 @@ def build_sparse_h( psf2d: np.ndarray, dmd_pixels_per_column: int, dmd_pixels_per_row: int, -) -> Tuple[np.ndarray, np.ndarray]: +) -> 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) diff --git a/src/giant_python/extraction/band/result_assembly.py b/src/giant_python/extraction/band/result_assembly.py index 0922466d..8b97ba89 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 @@ -48,8 +47,8 @@ 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) @@ -67,7 +66,7 @@ def _with_nan_channel(arr: np.ndarray, num_channels: int) -> np.ndarray: return out -def _dmd_user_rois(user_rois: Optional[dict], key: str) -> tuple: +def _dmd_user_rois(user_rois: dict | None, key: str) -> tuple: """Select one DMD's resolved ROI masks, labels and superpixels. Returns diff --git a/src/giant_python/extraction/band/summary_images.py b/src/giant_python/extraction/band/summary_images.py index 1d1f63e4..b9a35675 100644 --- a/src/giant_python/extraction/band/summary_images.py +++ b/src/giant_python/extraction/band/summary_images.py @@ -22,12 +22,13 @@ 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 @@ -338,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, @@ -452,7 +453,7 @@ def phase_matched_nanmedian( # noqa: C901 order = np.argsort(keys, kind="stable") 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: diff --git a/src/giant_python/extraction/band/traces.py b/src/giant_python/extraction/band/traces.py index a43ba571..a7c82580 100644 --- a/src/giant_python/extraction/band/traces.py +++ b/src/giant_python/extraction/band/traces.py @@ -26,7 +26,7 @@ from __future__ import annotations -from typing import List, Optional, Tuple, cast +from typing import cast import numpy as np import torch @@ -131,7 +131,7 @@ 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) @@ -270,8 +270,8 @@ 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. @@ -406,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: @@ -439,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: @@ -476,7 +476,7 @@ def _compute_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, @@ -493,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. @@ -706,11 +706,11 @@ 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. diff --git a/src/giant_python/extraction/band/trial_data.py b/src/giant_python/extraction/band/trial_data.py index 94d74690..a065c7b2 100644 --- a/src/giant_python/extraction/band/trial_data.py +++ b/src/giant_python/extraction/band/trial_data.py @@ -11,7 +11,6 @@ from __future__ import annotations import os -from typing import Optional import numpy as np @@ -209,7 +208,7 @@ 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, diff --git a/src/giant_python/extraction/band/workflow.py b/src/giant_python/extraction/band/workflow.py index b8bd0b24..a5a102e1 100644 --- a/src/giant_python/extraction/band/workflow.py +++ b/src/giant_python/extraction/band/workflow.py @@ -8,7 +8,6 @@ from __future__ import annotations from pathlib import Path -from typing import Optional, Union import numpy as np from torch import Tensor @@ -55,7 +54,7 @@ def _resolve_session_user_rois( trial_table: dict, lookup: dict, annotations: AnnotationOptions, -) -> Optional[dict]: +) -> dict | None: """Load session annotations or invoke the configured drawing fallback. Returns @@ -76,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, @@ -198,7 +197,7 @@ def _process_dmd( params: BandSiloParams, lookup: dict, psf: dict, - user_rois: Optional[dict] = None, + user_rois: dict | None = None, *, acquisition: ResolvedAcquisition, execution: ExecutionOptions, @@ -240,7 +239,7 @@ def _process_dmd( ) 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: int) -> Optional[dict]: + def _read(trial_ix: int) -> dict | None: """Read one low-resolution trial in acquisition order. Returns 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 91428404..14700dc8 100644 --- a/src/giant_python/extraction/raster/annotations.py +++ b/src/giant_python/extraction/raster/annotations.py @@ -24,9 +24,9 @@ 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 @@ -56,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: @@ -110,7 +110,7 @@ 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]: +def _array(f: h5py.File, path: str) -> np.ndarray | None: """Read a numeric array in MATLAB's orientation, or None. Returns @@ -125,7 +125,7 @@ def _array(f: h5py.File, path: str) -> Optional[np.ndarray]: return a.T if a.ndim >= 2 else a -def _coords(a: Optional[np.ndarray], zero_indexed: bool) -> np.ndarray | None: +def _coords(a: np.ndarray | None, zero_indexed: bool) -> np.ndarray | None: """H5 coordinates as images.roi [x, y] (one-based). Returns @@ -141,7 +141,7 @@ def _coords(a: Optional[np.ndarray], zero_indexed: bool) -> np.ndarray | None: return xy[0] if xy.shape[0] == 1 else xy -def _scalar(a: Optional[np.ndarray]) -> Optional[float]: +def _scalar(a: np.ndarray | None) -> float | None: """First element of an array as a float, or None. Returns @@ -161,7 +161,7 @@ def _type(raw: str) -> 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: str | Path) -> list: @@ -219,7 +219,7 @@ def read_annotations(path: str | Path) -> list: return out -def annotation_trial(fn: str, fn_reg_ds: Sequence[str]) -> Optional[int]: +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 @@ -351,7 +351,7 @@ 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 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 f7f8969b..83663850 100644 --- a/src/giant_python/extraction/raster/container.py +++ b/src/giant_python/extraction/raster/container.py @@ -53,11 +53,13 @@ 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 Any, Optional, Sequence, Union +from typing import Any import h5py import numpy as np @@ -175,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 @@ -197,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 @@ -418,11 +420,11 @@ def write_container( subproblem_sources: Sequence, consensus_shape: Sequence[int], params: object | None = None, - source: Optional[dict] = None, - compression: Optional[str] = COMPRESSION, + 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. @@ -488,7 +490,7 @@ def write_container( pix_flat, pix_off = _ragged(subproblem_pixels, n_px, "pixels") 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 {}) @@ -612,7 +614,7 @@ def _split(flat: np.ndarray, offsets: np.ndarray) -> list: list One int64 index array per list. """ - return [flat[a:b].astype(np.int64) for a, b in zip(offsets[:-1], offsets[1:])] + return [flat[a:b].astype(np.int64) for a, b in itertools.pairwise(offsets)] def read_container(path: str | Path, data: bool = True) -> Container: @@ -686,7 +688,7 @@ def _read_rows(ds: h5py.Dataset, 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: SolverParams | None = None, ) -> Subproblem: 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 54fac237..b9d7f71a 100644 --- a/src/giant_python/extraction/raster/peaks.py +++ b/src/giant_python/extraction/raster/peaks.py @@ -32,9 +32,8 @@ import numpy as np import numpy.typing as npt -import scipy.ndimage as ndimage -import scipy.sparse as sparse from numpy.lib.stride_tricks import sliding_window_view +from scipy import ndimage, sparse from scipy.optimize import OptimizeResult, least_squares from scipy.special import erf @@ -220,15 +219,15 @@ def _fit( 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: @@ -331,7 +330,7 @@ def _explore( 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, 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 dae0bbd4..8d468921 100644 --- a/src/giant_python/extraction/raster/refit_test.py +++ b/src/giant_python/extraction/raster/refit_test.py @@ -33,6 +33,7 @@ from __future__ import annotations +import itertools import math from collections.abc import Callable, Sequence from dataclasses import dataclass, replace @@ -199,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()) @@ -223,15 +224,13 @@ def score_refit( 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 @@ -253,21 +252,19 @@ def by_size(events: list[dict], edges: Sequence[float] = SIZE_EDGES) -> list[dic 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 @@ -307,21 +304,21 @@ def q(name: str, pct: float) -> float: 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 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 4bd4c24a..4abceefb 100644 --- a/src/giant_python/extraction/raster/spots.py +++ b/src/giant_python/extraction/raster/spots.py @@ -643,13 +643,13 @@ def event_test(events: dict, source_rc: np.ndarray, settings: SpotSettings, seed keep = ( 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]) + w, _v = np.linalg.eigh(fits[0].covs[0]) out.update( K=int(best.K), bic_gain=bic_gain(fits), diff --git a/src/giant_python/extraction/raster/stage_files.py b/src/giant_python/extraction/raster/stage_files.py index 288e8e26..7885932f 100644 --- a/src/giant_python/extraction/raster/stage_files.py +++ b/src/giant_python/extraction/raster/stage_files.py @@ -40,7 +40,7 @@ import os from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING import h5py import numpy as np @@ -78,12 +78,12 @@ 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": + def trial_images(self) -> TrialImages: """Return the plan stage's input. A :class:`~giant_python.extraction.raster.plan.TrialImages`. @@ -128,10 +128,10 @@ def write_localization( 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). @@ -161,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) @@ -201,7 +201,7 @@ def peaks_file(path: str | Path) -> Path: return path.with_name(path.stem + ".peaks.h5") -def _sidecar_peaks(path: str | Path) -> Optional[np.ndarray]: +def _sidecar_peaks(path: str | Path) -> np.ndarray | None: """Peaks from a localization file's sidecar, or None. Returns @@ -216,7 +216,7 @@ def _sidecar_peaks(path: str | Path) -> Optional[np.ndarray]: return f["peaks"][()] -def localization_attrs(path: str | Path) -> Optional[dict]: +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. 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 3bfa5764..47fae395 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,7 +33,7 @@ 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 @@ -92,7 +91,7 @@ def run_parameter_gui( row += 1 result: dict[ str, - Optional[tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]], + tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] | None, ] = {"options": None} def on_ok() -> None: diff --git a/src/giant_python/io/annotations.py b/src/giant_python/io/annotations.py index 5659765f..855e03b7 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 @@ -25,7 +24,7 @@ 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 @@ -46,7 +45,7 @@ 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. 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 2878a467..08822a05 100644 --- a/src/giant_python/io/hdf5.py +++ b/src/giant_python/io/hdf5.py @@ -16,7 +16,7 @@ """ from pathlib import Path -from typing import Any, Union, cast +from typing import Any, cast import h5py import numpy as np @@ -126,7 +126,7 @@ 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 @@ -156,7 +156,7 @@ def load_struct_h5(path: Union[str, Path]) -> dict: return _read_group(f, row_major) -def to_serializable(val: object) -> Any: # noqa: ANN401 - mirrors the structure of ``val`` +def to_serializable(val: object) -> Any: # noqa: ANN401 """Convert nested NumPy values to ordinary Python parameter values. Returns @@ -269,7 +269,7 @@ def write_matlab_value(grp: h5py.Group, key: str, value: dict | npt.ArrayLike) - 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 diff --git a/src/giant_python/io/slap2.py b/src/giant_python/io/slap2.py index 6b662ac2..e8584188 100644 --- a/src/giant_python/io/slap2.py +++ b/src/giant_python/io/slap2.py @@ -7,7 +7,7 @@ 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 @@ -27,7 +27,7 @@ def _reshape_1d(src: dict, key: str) -> np.ndarray | None: 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. @@ -77,7 +77,7 @@ def getLineData( """Read a batch using the vendor reader's unchanged contract.""" -def is_cycle_split(path: Union[str, Path]) -> bool: +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. @@ -245,7 +245,7 @@ def _text(value: object) -> str: return str(value) -def read_mat_datetime_ms(path: Union[str, Path], name: str, offset_ms: float = 0.0) -> float | None: +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 @@ -306,7 +306,7 @@ def read_mat_datetime_ms(path: Union[str, Path], name: str, offset_ms: float = 0 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 diff --git a/src/giant_python/io/slap2_raster.py b/src/giant_python/io/slap2_raster.py index 1404438b..33e2e424 100644 --- a/src/giant_python/io/slap2_raster.py +++ b/src/giant_python/io/slap2_raster.py @@ -29,10 +29,9 @@ """ import logging -from collections.abc import Iterator +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 @@ -98,7 +97,7 @@ class RasterLayout: 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 @@ -116,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: @@ -218,7 +217,7 @@ def _dmd_curtain(meta: object, n_rows: int) -> tuple[np.ndarray | None, np.ndarr 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 @@ -319,8 +318,8 @@ def _file_spans(layout: RasterLayout, c0: int, c1: int) -> Iterator[tuple[int, i 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: @@ -394,7 +393,7 @@ 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 @@ -478,10 +477,10 @@ def lit_mirrors(layout: RasterLayout, rows: ArrayLike, cols: ArrayLike) -> np.nd 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 diff --git a/src/giant_python/io/tiff.py b/src/giant_python/io/tiff.py index 6366d439..7342b0ec 100644 --- a/src/giant_python/io/tiff.py +++ b/src/giant_python/io/tiff.py @@ -1,12 +1,11 @@ """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 diff --git a/src/giant_python/io/trial_table.py b/src/giant_python/io/trial_table.py index 086e1a75..90a9817d 100644 --- a/src/giant_python/io/trial_table.py +++ b/src/giant_python/io/trial_table.py @@ -1,7 +1,6 @@ """Faithful trial-table schema decoding, without runtime file discovery.""" from pathlib import Path -from typing import Optional, Union import numpy as np @@ -9,7 +8,7 @@ from .hdf5 import load_struct_h5 -def slap2_info_from_raw(slap2: Optional[dict]) -> Slap2Info | None: +def slap2_info_from_raw(slap2: dict | None) -> Slap2Info | None: """Decode recognized SLAP2 metadata; keep absent metadata absent. Returns @@ -30,7 +29,7 @@ def slap2_info_from_raw(slap2: Optional[dict]) -> Slap2Info | None: return Slap2Info(**{key: slap2[key] for key in names if key in slap2}) -def read_trial_table(path: Union[str, Path]) -> TrialTable: +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. diff --git a/src/giant_python/models/__init__.py b/src/giant_python/models/__init__.py index 59f2a3a6..baf05c0b 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 134d4a11..ef0e9fec 100644 --- a/src/giant_python/models/trial_table.py +++ b/src/giant_python/models/trial_table.py @@ -4,7 +4,6 @@ from dataclasses import dataclass, field from pathlib import Path -from typing import Optional, Union import numpy as np @@ -28,10 +27,10 @@ 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 @@ -65,19 +64,19 @@ 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 diff --git a/src/giant_python/numerics/baseline.py b/src/giant_python/numerics/baseline.py index 8844100d..d4669fb8 100644 --- a/src/giant_python/numerics/baseline.py +++ b/src/giant_python/numerics/baseline.py @@ -11,8 +11,6 @@ from __future__ import annotations -from typing import Tuple - import numpy as np import pandas as pd from scipy.interpolate import PchipInterpolator @@ -158,7 +156,7 @@ def assemble_dff( f0_ls: np.ndarray, denoise_window: int, hull_window: int, -) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: +) -> 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 diff --git a/src/giant_python/numerics/morphology.py b/src/giant_python/numerics/morphology.py index f0751d3c..6cd6386a 100644 --- a/src/giant_python/numerics/morphology.py +++ b/src/giant_python/numerics/morphology.py @@ -2,14 +2,12 @@ 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. diff --git a/src/giant_python/numerics/peaks.py b/src/giant_python/numerics/peaks.py index 89f4e1b0..4f0b5a8b 100644 --- a/src/giant_python/numerics/peaks.py +++ b/src/giant_python/numerics/peaks.py @@ -23,10 +23,10 @@ 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 @@ -124,7 +124,7 @@ def gaussian_peaks_integrated(theta: np.ndarray, yxdata: np.ndarray) -> np.ndarr 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 @@ -394,7 +394,7 @@ def _fit_isotropic_then_anisotropic( 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]: +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 @@ -470,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 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 96219f9c..0db74b8d 100644 --- a/src/giant_python/pipeline/__init__.py +++ b/src/giant_python/pipeline/__init__.py @@ -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 0f2e5d40..3e243949 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: diff --git a/src/giant_python/pipeline/extract.py b/src/giant_python/pipeline/extract.py index 1267f35c..2904060d 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,7 +22,7 @@ def _require_band_mode( microscope: str, - scan_mode: Optional[str], + scan_mode: str | None, ) -> None: """Reject unsupported routing before loading data or a backend. @@ -45,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: diff --git a/src/giant_python/pipeline/pipeline.py b/src/giant_python/pipeline/pipeline.py index 364b17b7..313aad4e 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 Any, Optional +from typing import Any from ..models.experiment_summary import ExperimentSummary from ..models.params import ( @@ -57,7 +57,7 @@ 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.""" self.microscope = microscope @@ -65,18 +65,18 @@ def __init__( 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: Any, # noqa: ANN401 - forwarded to ``Pipeline.__init__`` - ) -> "Pipeline": + **kwargs: Any, # noqa: ANN401 + ) -> Pipeline: """Start a session from a trial-table path or loaded metadata. Parameters @@ -134,7 +134,7 @@ 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 @@ -159,7 +159,7 @@ def annotate(self) -> "Pipeline": self.annotations = replace(policy, enabled=True) return self - def extract(self) -> "Pipeline": + def extract(self) -> Pipeline: """Run source extraction, storing self.summary. Returns diff --git a/src/giant_python/pipeline/reg_stats.py b/src/giant_python/pipeline/reg_stats.py index 2a6f12f3..fd2d5d0a 100644 --- a/src/giant_python/pipeline/reg_stats.py +++ b/src/giant_python/pipeline/reg_stats.py @@ -19,9 +19,9 @@ import json import logging import os -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import TYPE_CHECKING, Optional, Sequence, Union +from typing import TYPE_CHECKING import h5py import numpy as np @@ -69,7 +69,7 @@ def _vector(f: h5py.File, name: str) -> np.ndarray: return np.asarray(f[name][()], dtype=np.float64).ravel() -def read_alignment(path: Union[str, Path]) -> dict: +def read_alignment(path: str | Path) -> dict: """Read what the statistics need from an alignment file. Returns @@ -164,10 +164,10 @@ def _compensation_record(grp: h5py.Group, row_major: bool) -> dict: def _check_compensation( - dat: Union[str, Path], + dat: str | Path, source: PlainFrames | CompensatedFrames, ds: np.ndarray, - saved: Optional[dict], + saved: dict | None, ) -> None: """Refuse a trial whose online compensation differs from the one its registration saved. @@ -192,9 +192,7 @@ def _check_compensation( ) -def registration_params( - alignment: dict, table_settings: Optional[dict] -) -> MultiRoiRegistrationParams: +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 @@ -223,12 +221,12 @@ def registration_params( def _source( - dat: Union[str, Path], + dat: str | Path, first: float, last: float, alignment: dict, params: MultiRoiRegistrationParams, - device: Union[str, torch.device], + device: str | torch.device, ) -> tuple[RasterLayout, PlainFrames | CompensatedFrames, np.ndarray]: """Open the trial's frame source, checked against the alignment file. @@ -321,14 +319,14 @@ def _var_factor_reader(path: Path) -> Iterator[np.ndarray]: def trial_stats( - dat: Union[str, Path], + dat: str | Path, first: float, last: float, - movie: Union[str, Path], - adata: Union[str, Path], - out: Union[str, Path], - device: Union[str, torch.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. @@ -369,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): @@ -462,7 +460,7 @@ def _stats_job(job: dict) -> dict: return {"out": str(job["out"]), "error": repr(exc)} -def _table_settings(path: Path) -> Optional[dict]: +def _table_settings(path: Path) -> dict | None: """Read the trial table's motion_correction/align_params (or None). Returns @@ -492,7 +490,7 @@ def _grid(value: npt.ArrayLike, shape: tuple[int, ...]) -> np.ndarray: def _selected( - shape: tuple[int, ...], paths: Optional[Sequence[int]], trials: Optional[Sequence[int]] + 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). @@ -548,33 +546,31 @@ def _jobs(tt: TrialTable, files: np.ndarray, opts: dict) -> tuple[list[dict], li 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. @@ -618,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 66db855f..5c6eb318 100644 --- a/src/giant_python/pipeline/trial_table.py +++ b/src/giant_python/pipeline/trial_table.py @@ -21,15 +21,15 @@ from __future__ import annotations import datetime +import itertools import json import math import os import re import warnings -from collections.abc import Iterable +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 @@ -69,7 +69,7 @@ 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 @@ -186,7 +186,7 @@ def _name_timestamp(stamp: str) -> float: return t.toordinal() + 366 + (t.hour * 3600 + t.minute * 60 + t.second) / 86400.0 -def acquisition_order(names: Sequence[str]) -> Tuple[np.ndarray, bool]: +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 @@ -343,7 +343,7 @@ def _json_array(value: npt.ArrayLike) -> np.ndarray: return arr -def read_reference_stack(path: Union[str, Path]) -> dict: +def read_reference_stack(path: str | Path) -> dict: """Read a SLAP2 reference stack, as buildTrialTableSLAP2 stores it. Parameters @@ -377,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): @@ -405,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 @@ -540,7 +540,7 @@ def _continuous_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 @@ -626,7 +626,7 @@ def _rows(values: npt.ArrayLike, n: int, dtype: npt.DTypeLike = np.float64) -> n def _write_tables( - table: dict, out_dir: Union[str, Path], max_duration_s: Optional[float], line_period_s: float + 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). @@ -650,9 +650,9 @@ def _write_tables( 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. @@ -747,7 +747,7 @@ def build_trial_table_slap2( 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 diff --git a/src/giant_python/progress.py b/src/giant_python/progress.py index a76b5ef2..e4915343 100644 --- a/src/giant_python/progress.py +++ b/src/giant_python/progress.py @@ -10,7 +10,7 @@ from __future__ import annotations -from typing import Iterable, Optional +from collections.abc import Iterable def log(message: str, verbose: bool) -> None: @@ -32,7 +32,7 @@ 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. diff --git a/src/giant_python/registration/compensation.py b/src/giant_python/registration/compensation.py index 97833d34..d4ccd6ed 100644 --- a/src/giant_python/registration/compensation.py +++ b/src/giant_python/registration/compensation.py @@ -14,7 +14,6 @@ """ from dataclasses import dataclass -from typing import Tuple import numpy as np from numpy.typing import ArrayLike @@ -67,15 +66,15 @@ 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: np.ndarray, y: np.ndarray, switch_lines: np.ndarray, - lead: Tuple[int, int] = Y_LEAD, + lead: tuple[int, int] = Y_LEAD, ) -> np.ndarray: """Y on the DMD: each change of the header y applied lead earlier. @@ -105,7 +104,7 @@ def dmd_y( def line_offsets( - layout: RasterLayout, lines: Tuple[int, int], lead: Tuple[int, int] = Y_LEAD + layout: RasterLayout, lines: tuple[int, int], lead: tuple[int, int] = Y_LEAD ) -> LineOffsets: """Read the headers covering lines (getLineOnlineOffsets). 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 44feeea7..c9bde122 100644 --- a/src/giant_python/registration/growth.py +++ b/src/giant_python/registration/growth.py @@ -40,7 +40,6 @@ import logging from collections.abc import Iterable, Sequence from dataclasses import dataclass, field -from typing import List, Optional import numpy as np import torch @@ -220,7 +219,7 @@ 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 @@ -817,7 +816,7 @@ def _resolve(self, k: int, g: int, jump: float) -> None: self.step[order] = saved["step"] # ---------------------------------------------------------------- run - def run(self, max_rounds: Optional[int] = None) -> tuple[np.ndarray, GrowthQC]: + def run(self, max_rounds: int | None = None) -> tuple[np.ndarray, GrowthQC]: """Align every frame. Returns @@ -937,7 +936,7 @@ def seeds_from_consensus( 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 diff --git a/src/giant_python/registration/interpolation.py b/src/giant_python/registration/interpolation.py index b79f3db2..cc20ee1a 100644 --- a/src/giant_python/registration/interpolation.py +++ b/src/giant_python/registration/interpolation.py @@ -9,7 +9,6 @@ """ import math -from typing import Tuple import numpy as np import torch @@ -37,7 +36,7 @@ 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 diff --git a/src/giant_python/registration/matching.py b/src/giant_python/registration/matching.py index 61b0d9c5..b812dc19 100644 --- a/src/giant_python/registration/matching.py +++ b/src/giant_python/registration/matching.py @@ -11,8 +11,6 @@ (frames x pixels) @ (pixels x shifts). """ -from typing import Tuple - import torch @@ -26,7 +24,7 @@ def shift_tables( cols: torch.Tensor, search: int, dtype: torch.dtype = torch.float32, -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: +) -> 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 @@ -71,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. @@ -118,7 +116,7 @@ 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 @@ -161,7 +159,7 @@ def peak_motion(corr: torch.Tensor, search: int) -> Tuple[torch.Tensor, torch.Te return -mot, peak -def peak_index(corr: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, 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 @@ -174,7 +172,7 @@ def peak_index(corr: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Te 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] @@ -216,7 +214,7 @@ def match_maps( cols: torch.Tensor, search: int, dtype: torch.dtype = torch.float32, -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Like :func:`match`, also returning the correlation maps. Returns @@ -312,7 +310,7 @@ def match( cols: torch.Tensor, search: int, dtype: torch.dtype = torch.float32, -) -> Tuple[torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor]: """Register frames to a template (xcorr2_nans_weighted). Parameters diff --git a/src/giant_python/registration/multiroi.py b/src/giant_python/registration/multiroi.py index d3dccbd7..c007724a 100644 --- a/src/giant_python/registration/multiroi.py +++ b/src/giant_python/registration/multiroi.py @@ -19,7 +19,6 @@ 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 @@ -105,7 +104,7 @@ 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) @@ -165,7 +164,7 @@ 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)) @@ -396,7 +395,7 @@ def _write_stats(self, fields: dict) -> Path | None: return None return tmp - def finish(self, fields: dict, settings: Optional[dict] = None) -> None: + 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 @@ -509,7 +508,7 @@ def register_grow( params: MultiRoiRegistrationParams, sink: OutputSink, dtype: torch.dtype, - timer: Optional[Timer] = None, + timer: Timer | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, GrowthQC]: """Batched growth from seed frames, then rendering in frame order. @@ -669,7 +668,7 @@ def open_trial( def trial_stats( source: PlainFrames | CompensatedFrames, ds: np.ndarray, margin: int, n_channels: int -) -> Optional[StatsWorker]: +) -> 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 @@ -745,12 +744,12 @@ def _template_and_sink( 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, + 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, diff --git a/src/giant_python/registration/outputs.py b/src/giant_python/registration/outputs.py index 2e2a5cd7..137b99c6 100644 --- a/src/giant_python/registration/outputs.py +++ b/src/giant_python/registration/outputs.py @@ -26,7 +26,6 @@ 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 @@ -167,7 +166,7 @@ def __init__( 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), @@ -230,7 +229,7 @@ class MovieWriter: def __init__( self, - path: Union[str, Path], + path: str | Path, shape: tuple[int, int], n_pages: int, tiff: bool = True, @@ -320,7 +319,7 @@ class AlignmentFile: def __init__( self, - path: Union[str, Path], + path: str | Path, var_shape: tuple[int, int], n_frames: int, deflate: int = 1, @@ -344,7 +343,7 @@ def write_var_factor(self, index: int, var_factor: np.ndarray) -> None: """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 @@ -385,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. @@ -417,7 +416,7 @@ 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 diff --git a/src/giant_python/registration/sources.py b/src/giant_python/registration/sources.py index cf43a3ac..e985f921 100644 --- a/src/giant_python/registration/sources.py +++ b/src/giant_python/registration/sources.py @@ -18,7 +18,6 @@ """ from dataclasses import dataclass -from typing import Optional import numpy as np import torch @@ -102,7 +101,7 @@ 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) -> None: """Trim the window to the valid pixels' bounding box. @@ -145,7 +144,7 @@ def frames(self, times: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]: vals, fresh = self.former.frames(times, self.dt) return vals[:, :, self.pixels], fresh[:, self.pixels] - def references(self, times: ArrayLike) -> Optional[np.ndarray]: + def references(self, times: ArrayLike) -> np.ndarray | None: """Frame reference offsets (none without compensation). Returns diff --git a/src/giant_python/registration/stats/geometry.py b/src/giant_python/registration/stats/geometry.py index 115e0000..bbebd399 100644 --- a/src/giant_python/registration/stats/geometry.py +++ b/src/giant_python/registration/stats/geometry.py @@ -253,7 +253,7 @@ class FrameGeometry: """ def __init__( - self, source: "PlainFrames | CompensatedFrames", ds: npt.ArrayLike, margin: int + self, source: PlainFrames | CompensatedFrames, ds: npt.ArrayLike, margin: int ) -> None: """Pixel tables of the window and the frames' kernel range. @@ -686,10 +686,10 @@ def _norms( 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) -> tuple[list[int], torch.Tensor]: """Corner k's partners and the rows of the single sums it needs. diff --git a/src/giant_python/registration/stats/io.py b/src/giant_python/registration/stats/io.py index f54131ee..b142f546 100644 --- a/src/giant_python/registration/stats/io.py +++ b/src/giant_python/registration/stats/io.py @@ -14,7 +14,6 @@ import json from datetime import datetime from pathlib import Path -from typing import Union import h5py import numpy as np @@ -34,7 +33,7 @@ _REGISTERED = "_REGISTERED_DOWNSAMPLED-" -def stats_path(movie_path: Union[str, Path]) -> Path: +def stats_path(movie_path: str | Path) -> Path: """Return the statistics file of a registered movie. _REGISTERED_DOWNSAMPLED-80Hz.h5 (or .tif) gives @@ -86,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 @@ -143,7 +142,7 @@ def _attr(v: object) -> object: return v -def read_stats(path: Union[str, Path]) -> dict: +def read_stats(path: str | Path) -> dict: """Read a statistics file, with maps as (channels, rows, cols). Returns diff --git a/src/giant_python/simulation/injection.py b/src/giant_python/simulation/injection.py index b54af3c2..4a712a61 100644 --- a/src/giant_python/simulation/injection.py +++ b/src/giant_python/simulation/injection.py @@ -76,11 +76,10 @@ import sys import time import warnings -from collections.abc import Callable, Iterator +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 @@ -210,8 +209,8 @@ class InjectionSettings: ('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 @@ -222,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" @@ -271,8 +270,10 @@ def __post_init__(self) -> None: 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 @@ -404,7 +405,7 @@ class Events: size: np.ndarray @classmethod - def empty(cls) -> "Events": + def empty(cls) -> Events: """No events. Returns @@ -416,7 +417,7 @@ def empty(cls) -> "Events": return cls(z.astype(np.int64), z.astype(np.int64), z, z.astype(np.int64), z) @classmethod - def concat(cls, parts: Sequence["Events"]) -> "Events": + def concat(cls, parts: Sequence[Events]) -> Events: """Events of several parts, in order. Returns @@ -447,7 +448,7 @@ def __len__(self) -> int: """ return int(self.source.size) - def select(self, mask: np.ndarray) -> "Events": + def select(self, mask: np.ndarray) -> Events: """Select the events where mask is true. Returns @@ -568,7 +569,7 @@ def train(mean: float, n: int) -> tuple[np.ndarray, int]: def event_traces( events: Events, n_sources: int, - lines: Tuple[int, int], + lines: tuple[int, int], line_period_s: float, settings: InjectionSettings, ) -> np.ndarray: @@ -597,8 +598,8 @@ def event_traces( 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 @@ -632,7 +633,7 @@ 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 @@ -682,7 +683,7 @@ class ImageFootprint: kind = "image" - def __init__(self, image: ArrayLike, center: Optional[Sequence[float]] = None) -> None: + def __init__(self, image: ArrayLike, center: Sequence[float] | None = None) -> None: """Normalize the image and find its support radius. Raises @@ -755,7 +756,7 @@ def footprint_patch( footprint: Callable[[ArrayLike, ArrayLike], np.ndarray], position: Sequence[float] | np.ndarray, half: int, -) -> Tuple[np.ndarray, list]: +) -> tuple[np.ndarray, list]: """Sample a footprint on the integer pixels around a position. Returns @@ -800,7 +801,7 @@ 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: @@ -823,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: @@ -927,10 +928,10 @@ 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 @@ -977,7 +978,7 @@ 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: @@ -990,7 +991,7 @@ def place_sources( return np.array(chosen).reshape(-1, 2), n_cand -def _highpass(x: np.ndarray, sigma: float) -> Tuple[np.ndarray, np.ndarray]: +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. @@ -1168,11 +1169,11 @@ 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]: + def shape(self) -> tuple[int, int]: """Registered frame (rows, cols). Returns @@ -1183,7 +1184,7 @@ def shape(self) -> Tuple[int, int]: 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). @@ -1249,7 +1250,7 @@ def _continuous(alignment: Alignment) -> np.ndarray: return move -def continuous_motion(alignment: Alignment) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: +def continuous_motion(alignment: Alignment) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """DS frame times and the motion to interpolate (onlineCompensation). Returns @@ -1314,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. @@ -1347,7 +1348,7 @@ def trial_geometry( return TrialGeometry(lo, np.ascontiguousarray(shift.T), comp is not None) -def trial_lines(layout: RasterLayout, first: float, last: float) -> Tuple[int, int]: +def trial_lines(layout: RasterLayout, first: float, last: float) -> tuple[int, int]: """Whole lines of a trial's (possibly fractional) line range. Returns @@ -1360,8 +1361,8 @@ def trial_lines(layout: RasterLayout, first: float, last: float) -> Tuple[int, i ValueError If the line range holds no whole line. """ - lo = max(1, int(math.ceil(float(first)))) - hi = min(layout.total_lines, int(math.floor(float(last)))) + 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 @@ -1447,7 +1448,7 @@ 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()] @@ -1539,7 +1540,7 @@ class InjectionStats: render_seconds: float = 0.0 -def _file_spans(layout: RasterLayout, c0: int, c1: int) -> Iterator[Tuple[int, int, int, int]]: +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 @@ -1657,7 +1658,7 @@ def inject_samples( # ------------------------------------------------------------ session level -def meta_path(dat: Union[str, Path]) -> Path: +def meta_path(dat: str | Path) -> Path: """Return the .meta file of a .dat file (as GIAnT's loadMetadata). Returns @@ -1768,7 +1769,7 @@ def write_copy_table( keep: np.ndarray, data_dir: Path, save_dir: Path, - paths: Optional[Sequence[int]] = None, + paths: Sequence[int] | None = None, ) -> Path: """Write the trial table of the injected copy (save_dir/trial_table.h5). @@ -1868,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. @@ -1998,7 +1999,7 @@ def expected_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) @@ -2099,7 +2100,7 @@ def calibrate_frame_peaks( """ 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 @@ -2175,7 +2176,7 @@ def calibrate_frame_peaks( return gain -def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]: +def _inject_trial(ctx: dict, k: int, t: int) -> tuple[dict, Events]: """Inject one trial-path (see :func:`inject_session`). Returns @@ -2264,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): @@ -2496,20 +2497,20 @@ def calibrate(index: np.ndarray, *key: int) -> np.ndarray: 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. @@ -2679,7 +2680,7 @@ def _code_version() -> str: def write_truth( - path: Union[str, Path], + path: str | Path, paths: dict, settings: InjectionSettings, placement: PlacementSettings, @@ -2734,7 +2735,7 @@ def write_truth( 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) @@ -2787,7 +2788,7 @@ 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 @@ -2823,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"]) @@ -2832,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"]) @@ -2905,7 +2906,7 @@ 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 @@ -2957,7 +2958,7 @@ def record_copy_registration(out_dir: Union[str, Path]) -> dict: # --------------------------------------------------------------------- CLI -def _read_per_path(path: Optional[str]) -> dict: +def _read_per_path(path: str | None) -> dict: """{dmd: array} from an HDF5 file with datasets path1, ... Returns @@ -3078,7 +3079,7 @@ def build_parser() -> argparse.ArgumentParser: return ap -def _settings_from_args(args: argparse.Namespace) -> Tuple[InjectionSettings, PlacementSettings]: +def _settings_from_args(args: argparse.Namespace) -> tuple[InjectionSettings, PlacementSettings]: """Build the settings of inject. Returns @@ -3129,7 +3130,7 @@ def _json_default(x: object) -> list | str: return str(x) -def main(argv: Optional[Sequence[str]] = None) -> int: +def main(argv: Sequence[str] | None = None) -> int: """Run inject or compare; print a JSON summary. Returns diff --git a/src/giant_python/simulation/render.py b/src/giant_python/simulation/render.py index a6be12ef..a4292805 100644 --- a/src/giant_python/simulation/render.py +++ b/src/giant_python/simulation/render.py @@ -19,8 +19,8 @@ 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 @@ -83,7 +83,7 @@ def _source( return src -def frame_motion(alignment: Alignment, times: np.ndarray, refs: Optional[np.ndarray]) -> np.ndarray: +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 @@ -121,7 +121,7 @@ def iter_registered_frames( chunk: int = 64, offset_rc: tuple[float, float] = (0.0, 0.0), exclusive: bool = False, -) -> Iterator[Tuple[np.ndarray, torch.Tensor, torch.Tensor]]: +) -> Iterator[tuple[np.ndarray, torch.Tensor, torch.Tensor]]: """Yield registered frames of samples, a chunk of frames at a time. Parameters 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/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 ed66c98f..0a85da02 100644 --- a/src/giant_python/spine/product.py +++ b/src/giant_python/spine/product.py @@ -321,7 +321,7 @@ def read_product(path: str | Path) -> dict: attrs["inputs"] = json.loads(attrs.get("inputs", "{}")) attrs["report"] = json.loads(attrs.get("report", "{}")) out["attrs"] = attrs - for key in f.keys(): + for key in f: if not key.startswith("Path"): continue g = f[key] diff --git a/src/giant_python/spine/summary_io.py b/src/giant_python/spine/summary_io.py index dac31fc5..90c55a56 100644 --- a/src/giant_python/spine/summary_io.py +++ b/src/giant_python/spine/summary_io.py @@ -225,9 +225,7 @@ def __init__(self, run_dir: str | Path) -> None: raise ValueError(f"no {EXPERIMENT_SUMMARY} in {self.run_dir}") with h5py.File(self.experiment_path, "r") as f: self._row_major = _row_major(f) - self.paths = sorted( - int(k[4:]) for k in f.keys() if k.startswith("Path") and k[4:].isdigit() - ) + self.paths = sorted(int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()) def _exp(self) -> h5py.File: """Open the experiment summary for reading. diff --git a/src/giant_python/spine/trends.py b/src/giant_python/spine/trends.py index 02b67db1..b910dcc6 100644 --- a/src/giant_python/spine/trends.py +++ b/src/giant_python/spine/trends.py @@ -1,66 +1,72 @@ -"""Trend tests of normalized spine sizes: ports of GIAnT-MATLAB's -``spineTrends.m`` and ``spineTrendsResid.m``. +"""Trend tests of normalized spine sizes. + +Ports of GIAnT-MATLAB's spineTrends.m and spineTrendsResid.m. The input is a source's normalized size across the trials of a session (:func:`~giant_python.spine.readout.norm_log`). Two statistics look for a change, both directions: -``step`` - For each split ``k`` (the first ``k`` trials against the rest), the t +step + For each split k (the first k trials against the rest), the t statistic of mean(after) - mean(before) with the pooled SD; the source's statistic is the largest ``|t|`` over splits, signed (:func:`step_stat`). -``brief`` - A transient change that comes back: each run of 1 to ``max_len`` +brief + A transient change that comes back: each run of 1 to max_len consecutive trials with trials on both sides (within a block of consecutive acquisition numbers) is compared with the up to 2 trials before it and the up to 2 after it. The noise SD is the median trial-to-trial difference away from the run, divided by - ``0.6745 sqrt(2)`` (insensitive to slow drift, and not inflated by the + 0.6745 sqrt(2) (insensitive to slow drift, and not inflated by the change itself). The run's statistic is the smaller of the two t's when both have the same sign (else 0); the source's is the largest ``|.|`` over runs, signed (:func:`brief_stat`). -``p`` comes from random trial orders of the same source: +p comes from random trial orders of the same source: ``(1 + #{|stat(perm)| >= |stat|}) / (n_perm + 1)``, and the q-values from Benjamini-Hochberg across the tested sources (:func:`bh_adjust`). -A permuted statistic within a relative ``1e-9`` of the observed one counts -as a tie (``>=``): the step at the first or last split depends only on +A permuted statistic within a relative 1e-9 of the observed one counts +as a tie (>=): the step at the first or last split depends only on which trial stands alone, so every order that puts the same trial there gives the same statistic up to rounding. A trend shared by the sources (bleaching beyond the per-trial median, -focus) is the first right singular vector ``v`` of the tested sources' +focus) is the first right singular vector v of the tested sources' normalized sizes, signed so that its last three trials sum to a positive -number (:func:`shared_mode`). Each source's part of it, ``(L . v) v``, is -removed and the step test is run again on what is left (``resid``), as in -``spineTrendsResid.m``. Since ``v`` comes from all tested sources, a +number (:func:`shared_mode`). Each source's part of it, (L . v) v, is +removed and the step test is run again on what is left (resid), as in +spineTrendsResid.m. Since v comes from all tested sources, a source's beyond-trend statistic and p depend on which sources are tested; its step and brief statistics and p do not. -A source is *called* (``call``) when its change beyond the shared trend has -``q <= fdr_q`` and a relative size ``|exp(resid_d) - 1|`` of at least -``min_change`` (default 10%). The step and brief tests see the shared trend +A source is *called* (call) when its change beyond the shared trend has +q <= fdr_q and a relative size ``|exp(resid_d) - 1|`` of at least +min_change (default 10%). The step and brief tests see the shared trend too, so most sources of a session with a strong trend pass them; they are kept for context. On 780125 the per-trial measurement noise of a size is about 0.25% and its spread within a few consecutive trials about 2.5%, so 10% asks for a change several times what short-term fluctuations give. Differences from the MATLAB scripts: the permutations come from numpy's -generator seeded per source (``(seed, source)``), so p agrees with MATLAB's +generator seeded per source ((seed, source)), so p agrees with MATLAB's within Monte Carlo error; all tests of one source use the same trial orders; ties count as above (in MATLAB, rounding decided whether a tie counted, so its p at the first or last split could be far too small); -and ``spineTrends.m``'s correlation with the shared mode takes the -sign of ``spineTrendsResid.m``'s ``v`` (MATLAB's own SVD sign there is +and spineTrends.m's correlation with the shared mode takes the +sign of spineTrendsResid.m's v (MATLAB's own SVD sign there is arbitrary). """ from __future__ import annotations import math +from collections.abc import Callable, Iterable, Iterator +from concurrent.futures import Executor import numpy as np +import numpy.typing as npt + +from .parallel import LazyPool # MATLAB's constant for a normal SD from a median absolute deviation _MAD_SD = 0.6745 @@ -71,15 +77,16 @@ _SS_RTOL = 1e-10 -def trial_blocks(acquisition, unknown_consecutive: bool = True) -> np.ndarray: - """Blocks of consecutive acquisition numbers, as ``spineTrends.m``: - a new block starts where the number jumps by more than 1. +def trial_blocks(acquisition: npt.ArrayLike, unknown_consecutive: bool = True) -> np.ndarray: + """Return blocks of consecutive acquisition numbers, as spineTrends.m. + + A new block starts where the number jumps by more than 1. A trial without a number (negative, as :func:`~giant_python.spine.pipeline.table_trials` reports it) is a block of its own, so that it is neither in a brief run nor one of its neighbours; when no trial has a number, the trials are taken as - consecutive (one block) unless ``unknown_consecutive`` is False (for a + consecutive (one block) unless unknown_consecutive is False (for a subset of trials whose path has numbers elsewhere). Parameters @@ -104,9 +111,10 @@ def trial_blocks(acquisition, unknown_consecutive: bool = True) -> np.ndarray: return np.cumsum(new).astype(np.int64) -def image_blocks(path_blocks, rows) -> np.ndarray: - """Blocks of a subset of a path's trials (an image's trials with - values): a new block starts where the path's block changes or where +def image_blocks(path_blocks: npt.ArrayLike, rows: npt.ArrayLike) -> np.ndarray: + """Return blocks of a subset of a path's trials (an image's trials with values). + + A new block starts where the path's block changes or where the subset skips a trial, so that no brief run or neighbour reaches across a block boundary or a missing trial, whatever the order of the acquisition numbers. @@ -133,29 +141,34 @@ def image_blocks(path_blocks, rows) -> np.ndarray: def check_trend_settings( - n_perm, fdr_q, max_brief, seed, min_change=0.1 + n_perm: int, fdr_q: float, max_brief: int, seed: int, min_change: float = 0.1 ) -> None: - """Refuse settings the tests cannot use (ValueError): ``n_perm`` must - be at least 0, ``max_brief`` at least 1, ``fdr_q`` in (0, 1], - ``seed`` at least 0 (numpy's seed sequences take no negative - numbers) and ``min_change`` in [0, 1) (a shrinking spine cannot change - by 100% or more).""" + """Refuse settings the tests cannot use (ValueError). + + n_perm must be at least 0, max_brief at least 1, fdr_q in (0, 1], + seed at least 0 (numpy's seed sequences take no negative + numbers) and min_change in [0, 1) (a shrinking spine cannot change + by 100% or more). + + Raises + ------ + ValueError + If a setting is outside the range given above. + """ if not 0 <= min_change < 1: raise ValueError(f"min_change must be in [0, 1), not {min_change}") if int(n_perm) != n_perm or n_perm < 0: raise ValueError(f"n_perm must be a whole number >= 0, not {n_perm}") if int(max_brief) != max_brief or max_brief < 1: - raise ValueError( - f"max_brief must be a whole number >= 1, not {max_brief}" - ) + raise ValueError(f"max_brief must be a whole number >= 1, not {max_brief}") if not 0 < fdr_q <= 1: raise ValueError(f"fdr_q must be in (0, 1], not {fdr_q}") if int(seed) != seed or seed < 0: raise ValueError(f"seed must be a whole number >= 0, not {seed}") -def step_stat(x: np.ndarray): - """The largest ``|t|`` of a step over all splits, per row. +def step_stat(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return the largest ``|t|`` of a step over all splits, per row. Parameters ---------- @@ -166,9 +179,9 @@ def step_stat(x: np.ndarray): t : ndarray of float64, shape (series,) Signed t of mean(after) - mean(before) at the best split (0 when no split gives a non-zero t; infinite when the groups of a split have - no spread, within ``1e-10`` of the series' sum of squares). + no spread, within 1e-10 of the series' sum of squares). k : ndarray of int, shape (series,) - Trials before the step at that split, 1 to ``trials - 1``; 0 when + Trials before the step at that split, 1 to trials - 1; 0 when no split gives a non-zero t (MATLAB reports 1 there). d : ndarray of float64, shape (series,) mean(after) - mean(before) at that split (0 without one). @@ -204,20 +217,20 @@ def step_stat(x: np.ndarray): return t_best, k_best, d_best -def step_at(x: np.ndarray, k): - """The step statistic at given splits (``spineTrends.m``'s ``stepAt``). +def step_at(x: np.ndarray, k: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray]: + """Return the step statistic at given splits (spineTrends.m's stepAt). Parameters ---------- x : ndarray of shape (series, trials) k : array_like of int, shape (series,) - Trials before the step, 1 to ``trials - 1``. + Trials before the step, 1 to trials - 1. Returns ------- t, d : ndarray of float64, shape (series,) As :func:`step_stat` at those splits (with its rule for groups - without spread); NaN where ``k`` is out of range. + without spread); NaN where k is out of range. """ x = np.asarray(x, dtype=np.float64) k = np.asarray(k, dtype=np.int64).ravel() @@ -233,20 +246,24 @@ def step_at(x: np.ndarray, k): if ss <= _SS_RTOL * ((x[i] - x[i].mean()) ** 2).sum(): ss = 0.0 with np.errstate(invalid="ignore", divide="ignore"): - t[i] = d[i] / ( - math.sqrt(ss / (T - 2)) * math.sqrt(1 / k[i] + 1 / (T - k[i])) - ) + t[i] = d[i] / (math.sqrt(ss / (T - 2)) * math.sqrt(1 / k[i] + 1 / (T - k[i]))) return t, d -def _kth_without(srt, removed, j: int) -> np.ndarray: - """Per row, the ``j``-th smallest (zero-based) of the sorted values - ``srt`` once the elements of ranks ``removed`` are taken out. +def _kth_without(srt: np.ndarray, removed: np.ndarray, j: int) -> np.ndarray: + """Return, per row, the j-th smallest (zero-based) of the sorted values srt. - The answer is the sorted element at the smallest index ``i`` with - ``i - #{removed <= i} = j``, which the iteration - ``i <- j + #{removed <= i}`` reaches from ``i = j`` in at most - ``removed.shape[1] + 1`` steps (it stops early once ``i`` is fixed). + The elements of ranks removed are taken out first. + + The answer is the sorted element at the smallest index i with + i - #{removed <= i} = j, which the iteration + i <- j + #{removed <= i} reaches from i = j in at most + removed.shape[1] + 1 steps (it stops early once i is fixed). + + Returns + ------- + np.ndarray + The selected value of each row. """ i = np.full(srt.shape[0], j, np.int64) for _ in range(removed.shape[1] + 1): @@ -257,21 +274,27 @@ def _kth_without(srt, removed, j: int) -> np.ndarray: return np.take_along_axis(srt, i[:, None], axis=1)[:, 0] -def _median_without(srt, removed, m: int) -> np.ndarray: - """Per row, the median of the ``m`` sorted values left once the elements - of ranks ``removed`` are taken out (as ``median`` of what is left).""" +def _median_without(srt: np.ndarray, removed: np.ndarray, m: int) -> np.ndarray: + """Return, per row, the median of the m sorted values left. + + The elements of ranks removed are taken out (as median of what is left). + + Returns + ------- + np.ndarray + The median of each row; NaN when no value is left. + """ if m <= 0: return np.full(srt.shape[0], np.nan) if m % 2: return _kth_without(srt, removed, (m - 1) // 2) - return ( - _kth_without(srt, removed, m // 2 - 1) - + _kth_without(srt, removed, m // 2) - ) / 2 + return (_kth_without(srt, removed, m // 2 - 1) + _kth_without(srt, removed, m // 2)) / 2 -def brief_stat(x: np.ndarray, blocks, max_len: int = 3): - """The strongest transient change of 1 to ``max_len`` trials, per row. +def brief_stat( + x: np.ndarray, blocks: npt.ArrayLike, max_len: int = 3 +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Return the strongest transient change of 1 to max_len trials, per row. Parameters ---------- @@ -311,9 +334,7 @@ def brief_stat(x: np.ndarray, blocks, max_len: int = 3): order = np.argsort(sub, axis=1, kind="stable") srt = np.take_along_axis(sub, order, axis=1) rank = np.empty_like(order) - np.put_along_axis( - rank, order, np.broadcast_to(np.arange(m_all), order.shape), axis=1 - ) + np.put_along_axis(rank, order, np.broadcast_to(np.arange(m_all), order.shape), axis=1) col_of = np.full(T - 1, -1, np.int64) col_of[cols] = np.arange(m_all) for w in range(1, max_len + 1): @@ -324,15 +345,9 @@ def brief_stat(x: np.ndarray, blocks, max_len: int = 3): continue # the steps that touch the run (a-1 .. e) are all within the block removed = rank[:, col_of[a - 1 : e + 1]] - sg = _median_without(srt, removed, m_all - (w + 1)) / ( - _MAD_SD * math.sqrt(2) - ) + sg = _median_without(srt, removed, m_all - (w + 1)) / (_MAD_SD * math.sqrt(2)) left = [i for i in range(max(a - 2, 0), a) if blocks[i] == b] - right = [ - i - for i in range(e + 1, min(e + 2, T - 1) + 1) - if blocks[i] == b - ] + right = [i for i in range(e + 1, min(e + 2, T - 1) + 1) if blocks[i] == b] m = x[:, a : e + 1].mean(axis=1) ml = x[:, left].mean(axis=1) mr = x[:, right].mean(axis=1) @@ -350,12 +365,17 @@ def brief_stat(x: np.ndarray, blocks, max_len: int = 3): return t_best, s_best, w_best, d_best -def bh_adjust(p) -> np.ndarray: +def bh_adjust(p: npt.ArrayLike) -> np.ndarray: """Benjamini-Hochberg adjusted p-values (q-values). - A test passes FDR ``q`` exactly when its q-value is at most ``q``, the - same decision as ``spineTrends.m``'s step-up rule. NaN entries are left + A test passes FDR q exactly when its q-value is at most q, the + same decision as spineTrends.m's step-up rule. NaN entries are left out of the count and stay NaN. + + Returns + ------- + np.ndarray + The q-value of each p-value (NaN where the p-value is not finite). """ p = np.asarray(p, dtype=np.float64).ravel() out = np.full(p.shape, np.nan) @@ -370,8 +390,8 @@ def bh_adjust(p) -> np.ndarray: return out -def shared_mode(x: np.ndarray): - """The trend shared by the rows: the first right singular vector. +def shared_mode(x: np.ndarray) -> tuple[np.ndarray, float]: + """Return the trend shared by the rows: the first right singular vector. Parameters ---------- @@ -382,7 +402,7 @@ def shared_mode(x: np.ndarray): ------- v : ndarray of float64, shape (trials,) Unit vector, signed so that its last three entries sum to a - positive number (``spineTrendsResid.m``); NaN without rows. + positive number (spineTrendsResid.m); NaN without rows. var_share : float Share of the variance (sum of squares) it carries. """ @@ -398,7 +418,13 @@ def shared_mode(x: np.ndarray): def _corr(x: np.ndarray, v: np.ndarray) -> np.ndarray: - """Pearson correlation of each row of ``x`` with ``v``.""" + """Return the Pearson correlation of each row of x with v. + + Returns + ------- + np.ndarray + The correlation of each row, shape (series,). + """ xc = x - x.mean(axis=1, keepdims=True) vc = v - v.mean() with np.errstate(invalid="ignore", divide="ignore"): @@ -410,22 +436,38 @@ def _corr(x: np.ndarray, v: np.ndarray) -> np.ndarray: _ORDER_CELLS = 1_000_000 -def trial_orders(seed: int, source: int, n_perm: int, n_trials: int): - """The random trial orders of one source: ``(n_perm, n_trials)`` indices - from numpy's generator seeded with ``(seed, source)``, so that the +def trial_orders(seed: int, source: int, n_perm: int, n_trials: int) -> np.ndarray: + """Return the random trial orders of one source. + + These are (n_perm, n_trials) indices + from numpy's generator seeded with (seed, source), so that the orders, and the step and brief p-values, do not depend on which other sources are tested (the beyond-trend p does, through the shared trend - estimated from all tested sources).""" + estimated from all tested sources). + + Returns + ------- + np.ndarray + Integer trial indices, shape (n_perm, n_trials). + """ if n_perm <= 0: return np.zeros((0, n_trials), np.int64) - return np.concatenate( - list(_order_chunks(seed, source, n_perm, n_trials, n_perm)) - ) + return np.concatenate(list(_order_chunks(seed, source, n_perm, n_trials, n_perm))) + +def _order_chunks( + seed: int, source: int, n_perm: int, n_trials: int, rows: int +) -> Iterator[np.ndarray]: + """Yield :func:`trial_orders` in chunks of up to rows orders. -def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): - """:func:`trial_orders` in chunks of up to ``rows`` orders (the same - orders: the generator permutes row after row).""" + These are the same orders: the generator permutes row after row. + + Yields + ------ + np.ndarray + Trial indices of the next chunk, shape (m, n_trials) with + m <= rows. + """ rng = np.random.default_rng([int(seed), int(source)]) done = 0 while done < n_perm: @@ -458,11 +500,26 @@ def _order_chunks(seed, source, n_perm: int, n_trials: int, rows: int): def _perm_p( - x, resid, t_obs, seed, source, n_perm, blocks, max_brief, rows=None -): - """One source's permutation p-values of the step, brief and resid - tests (``t_obs``: the observed statistics, in that order), from the - trial orders in chunks of ``rows`` (default: about a million cells).""" + x: np.ndarray, + resid: np.ndarray, + t_obs: npt.ArrayLike, + seed: int, + source: int, + n_perm: int, + blocks: np.ndarray, + max_brief: int, + rows: int | None = None, +) -> list[float]: + """Return one source's permutation p-values of the step, brief and resid tests. + + The observed statistics are t_obs, in that order. The p-values come from the + trial orders in chunks of rows (default: about a million cells). + + Returns + ------- + list of float + The permutation p-values of the step, brief and resid tests, in that order. + """ if rows is None: rows = max(1, _ORDER_CELLS // max(1, x.size)) hits = np.zeros(3, np.int64) @@ -479,27 +536,37 @@ def _perm_p( return [(1 + h) / (n_perm + 1) for h in hits] -def _perm_job(args): - """:func:`_perm_p` of one source (a pool task).""" +def _perm_job( + args: tuple[np.ndarray, np.ndarray, list[float], int, int, int, np.ndarray, int], +) -> list[float]: + """Return :func:`_perm_p` of one source (a pool task). + + Returns + ------- + list of float + The permutation p-values of the step, brief and resid tests. + """ return _perm_p(*args) def _permute( - out, - idx, - x, - resid, - seed, - n_perm, - blocks, - max_brief, - workers, - progress, - pool=None, + out: dict, + idx: np.ndarray, + x: np.ndarray, + resid: np.ndarray, + seed: int, + n_perm: int, + blocks: np.ndarray, + max_brief: int, + workers: int | None, + progress: Callable[[int, int], None] | None, + pool: Executor | LazyPool | None = None, ) -> None: - """Fill ``out``'s step, brief and resid p-values of the sources ``idx`` - (rows of ``x`` and ``resid``): in ``pool`` (worker processes) when - given, else in ``workers`` threads (numpy releases the GIL).""" + """Fill out's step, brief and resid p-values of the sources idx. + + These are rows of x and resid: in pool (worker processes) when + given, else in workers threads (numpy releases the GIL). + """ import os from concurrent.futures import ThreadPoolExecutor from contextlib import closing @@ -508,14 +575,22 @@ def _permute( names = ("step", "brief", "resid") - def task(j): - """The arguments of the j-th tested source's p-values.""" + def task( + j: int, + ) -> tuple[np.ndarray, np.ndarray, list[float], int, int, int, np.ndarray, int]: + """Return the arguments of the j-th tested source's p-values. + + Returns + ------- + tuple + Arguments of :func:`_perm_p` for that source. + """ s = idx[j] t_obs = [out[f"{nm}_t"][s] for nm in names] return (x[j], resid[j], t_obs, seed, s, n_perm, blocks, max_brief) - def store(results): - """Put each source's p-values in ``out``.""" + def store(results: Iterable[list[float]]) -> None: + """Put each source's p-values in out.""" for j, ps in enumerate(results): for nm, pv in zip(names, ps): out[f"{nm}_p"][idx[j]] = pv @@ -535,20 +610,20 @@ def store(results): def trend_tests( norm: np.ndarray, - ok, - acquisition, + ok: npt.ArrayLike, + acquisition: npt.ArrayLike, n_perm: int = 20000, fdr_q: float = 0.1, max_brief: int = 3, seed: int = 1, workers: int | None = None, - progress=None, + progress: Callable[[int, int], None] | None = None, unknown_consecutive: bool = True, - blocks=None, + blocks: npt.ArrayLike | None = None, min_change: float = 0.1, - pool=None, + pool: Executor | LazyPool | None = None, ) -> dict: - """The step, brief and beyond-trend tests of every source. + """Return the step, brief and beyond-trend tests of every source. Parameters ---------- @@ -573,44 +648,50 @@ def trend_tests( Threads for the permutations (default: up to 8, one per CPU); the result does not depend on it. progress : callable, optional - Called with ``(done, total)`` as sources are tested. + Called with (done, total) as sources are tested. unknown_consecutive : bool Passed to :func:`trial_blocks`. blocks : array_like of int, shape (trials,), optional The trials' blocks, given instead of deriving them from - ``acquisition`` (:func:`image_blocks` for a subset of a path's + acquisition (:func:`image_blocks` for a subset of a path's trials). min_change : float Smallest relative change beyond the shared trend that makes a call - (``call``), in [0, 1). + (call), in [0, 1). pool : concurrent.futures.Executor, optional Worker processes for the permutations, one source per task (:func:`~giant_python.spine.parallel.make_pool`), used instead of - ``workers`` threads; the result does not depend on it. + workers threads; the result does not depend on it. Returns ------- dict - Per source (arrays of length ``sources``; NaN, or -1 for the + Per source (arrays of length sources; NaN, or -1 for the indices, where untested): - * ``tested`` (bool); - * ``step_t``, ``step_k`` (trials before the step, 1 to - ``trials - 1``; 0 for a tested source without a step), - ``step_d``, ``step_p``, ``step_q``; - * ``brief_t``, ``brief_start`` (zero-based first trial of the - run; -1 for a tested source without a run), ``brief_len`` (0 - without a run), ``brief_d``, ``brief_p``, ``brief_q``; - * ``resid_*``: the step test beyond the shared trend; - * ``shared_loading`` (``L . v``) and ``shared_r`` (correlation of - the source's sizes with ``v``); - * ``call`` (bool): a change beyond the shared trend with - ``resid_q <= fdr_q`` and a relative size ``|exp(resid_d) - 1|`` - of at least ``min_change``; - - and ``shared_v`` (trials,), ``var_share``, ``blocks`` (trials,) and - ``counts``: per test the sources with p < 0.05 and with - ``q <= fdr_q``, up and down, and the calls up and down. + * tested (bool); + * step_t, step_k (trials before the step, 1 to + trials - 1; 0 for a tested source without a step), + step_d, step_p, step_q; + * brief_t, brief_start (zero-based first trial of the + run; -1 for a tested source without a run), brief_len (0 + without a run), brief_d, brief_p, brief_q; + * resid_*: the step test beyond the shared trend; + * shared_loading (L . v) and shared_r (correlation of + the source's sizes with v); + * call (bool): a change beyond the shared trend with + resid_q <= fdr_q and a relative size ``|exp(resid_d) - 1|`` + of at least min_change; + + and shared_v (trials,), var_share, blocks (trials,) and + counts: per test the sources with p < 0.05 and with + q <= fdr_q, up and down, and the calls up and down. + + Raises + ------ + ValueError + If a setting is out of range (:func:`check_trend_settings`), or the + number of blocks differs from the number of trials. """ check_trend_settings(n_perm, fdr_q, max_brief, seed, min_change) L = np.asarray(norm, dtype=np.float64).T # (sources, trials) @@ -674,11 +755,7 @@ def trend_tests( } with np.errstate(invalid="ignore"): d = out["resid_d"] - out["call"] = ( - tested - & (out["resid_q"] <= fdr_q) - & (np.abs(np.expm1(d)) >= min_change) - ) + out["call"] = tested & (out["resid_q"] <= fdr_q) & (np.abs(np.expm1(d)) >= min_change) counts["call"] = { "up": int(np.count_nonzero(out["call"] & (d > 0))), "down": int(np.count_nonzero(out["call"] & (d < 0))), diff --git a/src/giant_python/spine/view/export.py b/src/giant_python/spine/view/export.py index 229143f0..72fa58f3 100644 --- a/src/giant_python/spine/view/export.py +++ b/src/giant_python/spine/view/export.py @@ -124,7 +124,7 @@ def primary_image(names: Collection[str], recorded: str | None = None) -> str | for nm in _PREFER: if nm in names: return nm - return sorted(names)[0] if names else None + return min(names) if names else None def pick_sources(src: dict, image: str | None, top: int) -> list: diff --git a/src/giant_python/viewer/render.py b/src/giant_python/viewer/render.py index f4ba0ffc..6cffa85d 100644 --- a/src/giant_python/viewer/render.py +++ b/src/giant_python/viewer/render.py @@ -58,9 +58,9 @@ def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float) -> int: """ ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel() if ds_lines.size > 1: - return int(math.ceil(np.mean(np.diff(ds_lines)))) + return math.ceil(np.mean(np.diff(ds_lines))) step = np.median(np.diff(np.asarray(lines200, dtype=np.float64))) - return int(math.ceil(step * ratio)) + return math.ceil(step * ratio) def frame_weights( @@ -431,15 +431,15 @@ def _place_one( values : np.ndarray The footprint's values at those pixels. """ - margin = 2 + int(math.ceil(3 * sigma)) + int(interp > 1) + margin = 2 + math.ceil(3 * sigma) + int(interp > 1) patch, r0, c0 = _patch(rows, cols, vals, margin) h, w = patch.shape pr, pc = np.mgrid[r0 : r0 + h, c0 : c0 + w] tr, tc = tmap.forward(pr, pc) - lo_r = max(0, int(math.floor(np.min(tr)))) - hi_r = min(shape[0] - 1, int(math.ceil(np.max(tr)))) - lo_c = max(0, int(math.floor(np.min(tc)))) - hi_c = min(shape[1] - 1, int(math.ceil(np.max(tc)))) + lo_r = max(0, math.floor(np.min(tr))) + hi_r = min(shape[0] - 1, math.ceil(np.max(tr))) + lo_c = max(0, math.floor(np.min(tc))) + hi_c = min(shape[1] - 1, math.ceil(np.max(tc))) if hi_r < lo_r or hi_c < lo_c: return np.zeros(0, np.int64), np.zeros(0) qr, qc = np.mgrid[lo_r : hi_r + 1, lo_c : hi_c + 1] diff --git a/src/giant_python/viewer/run.py b/src/giant_python/viewer/run.py index 3adb85ec..4a997956 100644 --- a/src/giant_python/viewer/run.py +++ b/src/giant_python/viewer/run.py @@ -19,7 +19,6 @@ import threading from dataclasses import dataclass, field from pathlib import Path -from typing import Optional import h5py import numpy as np @@ -90,7 +89,7 @@ def find_summaries(run_dir: str | Path) -> Path: ) -def _plan_file(run_dir: Path, summaries: Path, d: int) -> Optional[Path]: +def _plan_file(run_dir: Path, summaries: Path, d: int) -> Path | None: """Find the plan file of path d (one-based), if the run kept it. Returns @@ -159,7 +158,7 @@ class Sources: rejected_rc: np.ndarray rejected_score: np.ndarray rejected_n_events: np.ndarray - unused_seeds: Optional[np.ndarray] = None + unused_seeds: np.ndarray | None = None @property def n(self) -> int: @@ -219,8 +218,8 @@ class PathData: shape: tuple act_im: np.ndarray mean_im: np.ndarray - trial_act: Optional[np.ndarray] - trial_mean: Optional[np.ndarray] + trial_act: np.ndarray | None + trial_mean: np.ndarray | None n_frames: np.ndarray lines: np.ndarray discard: np.ndarray @@ -228,8 +227,8 @@ class PathData: sources: Sources alignment: str = "rigid" _traces: dict = field(default_factory=dict, repr=False) - _footprints: Optional[list] = field(default=None, repr=False) - _trial_rc: Optional[np.ndarray] = field(default=None, repr=False) + _footprints: list | None = field(default=None, repr=False) + _trial_rc: np.ndarray | None = field(default=None, repr=False) @property def offsets(self) -> np.ndarray: @@ -262,7 +261,7 @@ class SiloRun: Label shown on the page (default: the folder's name). """ - def __init__(self, run_dir: str | Path, name: Optional[str] = None) -> None: + def __init__(self, run_dir: str | Path, name: str | None = None) -> None: """Open the run and read its parameters.""" self.run_dir = Path(run_dir) self.summaries = find_summaries(self.run_dir) @@ -597,7 +596,7 @@ def _unused_seeds(plan_path: Path) -> np.ndarray: The (k, 2) row and column of each such seed. """ with h5py.File(plan_path, "r") as f: - g = f["sources"] if "sources" in f else f + g = f.get("sources", f) seeds = np.asarray(g["seeds"][()], np.float64).reshape(-1, 4) rows = np.asarray(g["rows"][()]).ravel() cols = np.asarray(g["cols"][()]).ravel() diff --git a/src/giant_python/viewer/server.py b/src/giant_python/viewer/server.py index 9a32ea42..80df5e03 100644 --- a/src/giant_python/viewer/server.py +++ b/src/giant_python/viewer/server.py @@ -45,7 +45,6 @@ from collections.abc import Iterable from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from typing import Optional from urllib.parse import parse_qs, urlparse import numpy as np @@ -575,7 +574,7 @@ def _run_args(items: Iterable[str]) -> list: return out -def _default_table(run_dir: Path) -> Optional[Path]: +def _default_table(run_dir: Path) -> Path | None: """Find a trial table in or above a run folder. Returns diff --git a/src/giant_python/viewer/trial.py b/src/giant_python/viewer/trial.py index 0a020aeb..6462f4c7 100644 --- a/src/giant_python/viewer/trial.py +++ b/src/giant_python/viewer/trial.py @@ -19,7 +19,6 @@ import threading from dataclasses import dataclass, field from pathlib import Path, PurePath -from typing import Optional import h5py import numpy as np @@ -151,7 +150,7 @@ def has_movie(self, d: int, t: int) -> bool: return False return self.movie_file(d, t).exists() and self.alignment_file(d, t).exists() - def baseline_file(self, d: int, t: int) -> Optional[Path]: + def baseline_file(self, d: int, t: int) -> Path | None: """Find the trial's network baseline, if there is one. Returns @@ -285,7 +284,7 @@ class TrialMovie: mean: np.ndarray discard: np.ndarray movie: np.ndarray - baseline: Optional[np.ndarray] + baseline: np.ndarray | None runs: list info: dict = field(default_factory=dict) kernel: str = "matched" @@ -672,7 +671,7 @@ def load_trial( ) -def _read_baseline(path: Optional[Path], shape: tuple, flat: np.ndarray) -> np.ndarray | None: +def _read_baseline(path: Path | None, shape: tuple, flat: np.ndarray) -> np.ndarray | None: """Read a network baseline at the valid pixels, float16 (frames, N). Returns @@ -737,7 +736,7 @@ def source_events( p = run.path(d) x = run.traces(d)["dF_denoised"][:, s] hz = float(run.param("analyzeHz", 200.0)) - gap = max(1, int(math.ceil(0.25 * hz))) + gap = max(1, math.ceil(0.25 * hz)) out = [] for t in range(p.n_frames.size): span = p.trial_span(t) diff --git a/tests/annotator/__init__.py b/tests/annotator/__init__.py index 0a161382..44910f71 100644 --- a/tests/annotator/__init__.py +++ b/tests/annotator/__init__.py @@ -1 +1 @@ -"""Tests of ``giant annotate-raster`` (:mod:`giant_python.annotator`).""" +"""Tests of giant annotate-raster (:mod:`giant_python.annotator`).""" diff --git a/tests/annotator/synthetic.py b/tests/annotator/synthetic.py index cca08103..5616fb5d 100644 --- a/tests/annotator/synthetic.py +++ b/tests/annotator/synthetic.py @@ -1,7 +1,10 @@ -"""A synthetic registered raster session for the annotator's tests: a -trial table and alignment files in GIAnT-MATLAB's layout, whose mean -images are one scene moved, dimmed or blurred by known amounts.""" +"""A synthetic registered raster session for the annotator's tests. +The session is a trial table and alignment files in GIAnT-MATLAB's layout, whose mean +images are one scene moved, dimmed or blurred by known amounts. +""" + +from collections.abc import Sequence from pathlib import Path import h5py @@ -13,19 +16,57 @@ def scene(seed: int = 0) -> np.ndarray: - """A smooth positive image, ``(rows + 40, cols + 40)``, from which the - trials' frames are cut.""" + """Return a smooth positive image from which the trials' frames are cut. + + Parameters + ---------- + seed : int + Seed of the random generator. + + Returns + ------- + np.ndarray + The image, (rows + 40, cols + 40). + """ rng = np.random.default_rng(seed) big = rng.random((FRAME[0] + 40, FRAME[1] + 40)) return 2.0 + 20.0 * ndimage.gaussian_filter(big, 1.5) -def frame(base, shift=(0, 0), origin=(0, 0), shape=FRAME, gain=1.0, blur=0.0): - """One trial's two-channel mean image, ``(rows, cols, 2)``. +def frame( + base: np.ndarray, + shift: tuple[int, int] = (0, 0), + origin: tuple[int, int] = (0, 0), + shape: tuple[int, int] = FRAME, + gain: float = 1.0, + blur: float = 0.0, +) -> np.ndarray: + """Return one trial's two-channel mean image, (rows, cols, 2). - The frame shows the scene from ``origin`` on, moved by ``shift`` - (``image[r, c] = scene[20 + origin + r - shift]``), NaN in a border of + The frame shows the scene from origin on, moved by shift + (image[r, c] = scene[20 + origin + r - shift]), NaN in a border of :data:`MARGIN` px. + + Parameters + ---------- + base : np.ndarray + The scene the frame is cut from. + shift : tuple[int, int] + Row and column shift of the scene. + origin : tuple[int, int] + Row and column of the frame's top left corner in the scene. + shape : tuple[int, int] + Rows and columns of the frame. + gain : float + Factor the image is multiplied by. + blur : float + Standard deviation of the Gaussian blur in px; no blur if zero. + + Returns + ------- + np.ndarray + The float32 mean image, (rows, cols, 2), with the second channel half + the first and NaN in a border of :data:`MARGIN` px. """ r0 = 20 + origin[0] - shift[0] c0 = 20 + origin[1] - shift[1] @@ -40,15 +81,19 @@ def frame(base, shift=(0, 0), origin=(0, 0), shape=FRAME, gain=1.0, blur=0.0): return out -def _strings(f, name, grid): - """A paths x trials grid of strings, column-major as MATLAB writes.""" - f.create_dataset( - name, data=np.array(grid, dtype=object).T, dtype=h5py.string_dtype() - ) +def _strings(f: h5py.File, name: str, grid: list[list[str]]) -> None: + """Write a paths x trials grid of strings, column-major as MATLAB writes.""" + f.create_dataset(name, data=np.array(grid, dtype=object).T, dtype=h5py.string_dtype()) -def write_alignment(path, mean, crop=(0, 0), failed=False, motion=None): - """An alignment file with the fields the annotator reads.""" +def write_alignment( + path: str | Path, + mean: np.ndarray, + crop: tuple[float, float] = (0, 0), + failed: bool = False, + motion: np.ndarray | None = None, +) -> None: + """Write an alignment file with the fields the annotator reads.""" n = 160 rng = np.random.default_rng(abs(hash(Path(path).name)) % 2**32) motion = 0.3 * rng.standard_normal((2, n)) if motion is None else motion @@ -67,21 +112,26 @@ def write_alignment(path, mean, crop=(0, 0), failed=False, motion=None): g[f"onlineMotion{k}shift"] = np.full((1, n), v) -def make_session(tmp, trials, n_paths=1, failed=()): +def make_session( + tmp: str | Path, + trials: Sequence[dict[str, object] | None], + n_paths: int = 1, + failed: Sequence[int] = (), +) -> Path: """Write a session and return its trial table's path. Parameters ---------- tmp : Path - Folder to write into (``savedr``). + Folder to write into (savedr). trials : list of dict - One entry per trial: keyword arguments of :func:`frame` (``shift``, - ``origin``, ``shape``, ``gain``, ``blur``); None for a trial + One entry per trial: keyword arguments of :func:`frame` (shift, + origin, shape, gain, blur); None for a trial without files. n_paths : int Paths, all with the same trials. failed : sequence of int - Zero-based trials flagged in the table's ``registration_failed``. + Zero-based trials flagged in the table's registration_failed. Returns ------- @@ -118,7 +168,5 @@ def make_session(tmp, trials, n_paths=1, failed=()): flags[:, list(failed)] = 1 f["motion_correction/registration_failed"] = flags.T f.create_dataset("savedr", data=str(tmp), dtype=h5py.string_dtype()) - f["slap2_info/trial_start_time_inferred"] = ( - 730000.0 + np.arange(n) * 20 / 86400 - )[None] + f["slap2_info/trial_start_time_inferred"] = (730000.0 + np.arange(n) * 20 / 86400)[None] return table diff --git a/tests/annotator/test_annotator.py b/tests/annotator/test_annotator.py index 547840fa..d1d26900 100644 --- a/tests/annotator/test_annotator.py +++ b/tests/annotator/test_annotator.py @@ -1,5 +1,7 @@ -"""Tests of the raster annotator: the session's canvas and statistics, -the annotation file, and the server.""" +"""Tests of the raster annotator. + +The session's canvas and statistics, the annotation file, and the server. +""" import json import shutil @@ -7,7 +9,10 @@ import threading import urllib.error import urllib.request +from collections.abc import Iterator from contextlib import contextmanager +from http.client import HTTPMessage +from pathlib import Path import h5py import numpy as np @@ -41,15 +46,19 @@ @pytest.fixture -def session(tmp_path): - """Six trials of one scene, moved by :data:`SHIFTS`, on two paths.""" - table = syn.make_session( - tmp_path, [{"shift": s} for s in SHIFTS], n_paths=2 - ) +def session(tmp_path: Path) -> AnnotatorSession: + """Six trials of one scene, moved by :data:`SHIFTS`, on two paths. + + Returns + ------- + AnnotatorSession + The annotator session opened on that trial table. + """ + table = syn.make_session(tmp_path, [{"shift": s} for s in SHIFTS], n_paths=2) return AnnotatorSession.open(table) -def test_matcher_finds_a_shift(): +def test_matcher_finds_a_shift() -> None: """The matcher returns the shift that maps an image onto the template.""" base = syn.scene()[:60, :80].astype(np.float32) base[:, :10] = np.nan @@ -57,7 +66,7 @@ def test_matcher_finds_a_shift(): assert _Matcher(base, 10).shift(moved) == (3, -5) -def test_trials_are_aligned_on_the_canvas(session): +def test_trials_are_aligned_on_the_canvas(session: AnnotatorSession) -> None: """Moved trials land on the same canvas pixels, relative to the anchor.""" p = session.path(0) assert p.present.all() and not p.failed.any() @@ -70,7 +79,7 @@ def test_trials_are_aligned_on_the_canvas(session): assert p.good.all() -def test_canvas_and_trial_coordinates_invert(session): +def test_canvas_and_trial_coordinates_invert(session: AnnotatorSession) -> None: """A canvas point maps to a trial's frame and back.""" p = session.path(0) xy = np.array([[12.5, 30.25], [40.0, 7.0]]) @@ -84,9 +93,8 @@ def test_canvas_and_trial_coordinates_invert(session): assert img[0, r, c] == mean[r + off[0], c + off[1], 0] -def test_frame_origins_place_the_trials(tmp_path): - """Trials with another frame origin and size show the same scene at the - same canvas pixels.""" +def test_frame_origins_place_the_trials(tmp_path: Path) -> None: + """Trials with another frame origin and size show the same scene at the same canvas pixels.""" trials = [{}, {}, {"origin": (0, 12), "shape": (60, 68)}, {}] p = AnnotatorSession.open(syn.make_session(tmp_path, trials)).path(0) assert p.frame_shape[2].tolist() == [60, 68] @@ -98,9 +106,11 @@ def test_frame_origins_place_the_trials(tmp_path): assert p.stats["match"][2] > 0.999 -def test_statistics_flag_dim_blurred_and_failed_trials(tmp_path): - """A dim trial is dim, a blurred one less sharp and a worse match, and - the table's flag and missing files are kept.""" +def test_statistics_flag_dim_blurred_and_failed_trials(tmp_path: Path) -> None: + """A dim trial is dim, a blurred one less sharp and a worse match. + + The table's flag and missing files are kept. + """ trials = [{}, {}, {"gain": 0.5}, {"blur": 3.0}, {}, None, {}, {}] table = syn.make_session(tmp_path, trials, failed=[4]) p = AnnotatorSession.open(table).path(0) @@ -118,13 +128,13 @@ def test_statistics_flag_dim_blurred_and_failed_trials(tmp_path): assert mean.shape == (2,) + p.shape and np.isfinite(mean).any() -def test_chunks_follow_the_raw_files(session): +def test_chunks_follow_the_raw_files(session: AnnotatorSession) -> None: """Consecutive trials of one raw file form an acquisition.""" assert session.chunks(0) == [(0, 2), (3, 5)] assert session.start_min[1] == pytest.approx(1 / 3, abs=1e-3) -def test_cache_is_reused_until_a_file_changes(tmp_path): +def test_cache_is_reused_until_a_file_changes(tmp_path: Path) -> None: """A second session reads the cache; a changed alignment file rebuilds.""" table = syn.make_session(tmp_path, [{"shift": s} for s in SHIFTS]) first = AnnotatorSession.open(table).path(0) @@ -138,18 +148,18 @@ def test_cache_is_reused_until_a_file_changes(tmp_path): for k, v in first.stats.items(): assert np.array_equal(again.stats[k], v, equal_nan=True) moco = tmp_path / "motion_correction" - syn.write_alignment( - moco / "E1T1DMD1_ALIGNMENTDATA.h5", syn.frame(syn.scene(), gain=2.0) - ) + syn.write_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5", syn.frame(syn.scene(), gain=2.0)) changed = AnnotatorSession.open(table).path(0) assert cache.stat().st_mtime_ns != stamp assert changed.stats["bright_ch1"][0] > 1.5 -def test_clean_state_fits_labels_and_drops_what_is_invalid(): - """Labels fit their kind and are unique over the whole session; bad - ROIs go, and so do the exclusion zones and trial marks that earlier - versions kept.""" +def test_clean_state_fits_labels_and_drops_what_is_invalid() -> None: + """Labels fit their kind and are unique over the whole session. + + Bad ROIs go, and so do the exclusion zones and trial marks that earlier + versions kept. + """ tri = [[1, 1], [9, 1], [5, 8]] raw = { "paths": [ @@ -204,9 +214,11 @@ def test_clean_state_fits_labels_and_drops_what_is_invalid(): clean_state({"paths": [{"rois": [{"kind": "zzz"}]}]}, 1) -def test_polygon_mask_and_outline(): - """A polygon covers the pixels whose centres it contains, and a mask's - outline gives the mask back.""" +def test_polygon_mask_and_outline() -> None: + """A polygon covers the pixels whose centres it contains. + + A mask's outline gives the mask back. + """ mask = polygon_mask([[2, 3], [6, 3], [6, 8], [2, 8]], (12, 10)) want = np.zeros((12, 10), bool) want[3:8, 2:6] = True @@ -236,21 +248,15 @@ def test_polygon_mask_and_outline(): } -def test_the_file_is_what_silo_reads(session, tmp_path): - """Somata and ROIs are written as SILo's reader expects, in the anchor - trial's frame.""" - out = files.write_annotations( - tmp_path / "a" / "annotations.h5", session, STATE - ) +def test_the_file_is_what_silo_reads(session: AnnotatorSession, tmp_path: Path) -> None: + """Somata and ROIs are written as SILo's reader expects, in the anchor trial's frame.""" + out = files.write_annotations(tmp_path / "a" / "annotations.h5", session, STATE) p = session.path(0) off = p.frame_offset[p.anchor] entries = read_annotations(out) assert [e.path for e in entries] == [1, 2] assert entries[0].fn == p.stems[p.anchor] - assert ( - files.anchor_stems(out, 2)[1] - == session.path(1).stems[session.path(1).anchor] - ) + assert files.anchor_stems(out, 2)[1] == session.path(1).stems[session.path(1).anchor] assert [(r.label, r.is_soma) for r in entries[0].rois] == [ ("soma1", True), ("dendrite", False), @@ -260,9 +266,7 @@ def test_the_file_is_what_silo_reads(session, tmp_path): want[15 + off[0] : 27 + off[0], 20 + off[1] : 32 + off[1]] = True assert soma.type == "polygon" and np.array_equal(soma.mask, want) # images.roi [x, y], one-based pixel centres - assert np.allclose( - soma.position[0], [20 + off[1] + 0.5, 15 + off[0] + 0.5] - ) + assert np.allclose(soma.position[0], [20 + off[1] + 0.5, 15 + off[0] + 0.5]) with h5py.File(out, "r") as f: assert f["schema_version"][()].item() == 2 assert f["coords_zero_indexed"][()].item() == 1 @@ -271,16 +275,17 @@ def test_the_file_is_what_silo_reads(session, tmp_path): assert f["Path1/roi_001/label"].dtype == np.uint16 -def test_the_state_comes_back_and_survives_a_new_canvas(session, tmp_path): - """A saved state is restored exactly, also on a canvas with another - origin (the polygons are stored in the anchor trial's frame).""" +def test_the_state_comes_back_and_survives_a_new_canvas( + session: AnnotatorSession, tmp_path: Path +) -> None: + """A saved state is restored exactly, also on a canvas with another origin. + + The polygons are stored in the anchor trial's frame. + """ out = files.write_annotations(tmp_path / "annotations.h5", session, STATE) want = clean_state(STATE, 2) assert files.read_state(out, session) == want - assert ( - files.anchor_stems(out, 2)[0] - == session.path(0).stems[session.path(0).anchor] - ) + assert files.anchor_stems(out, 2)[0] == session.path(0).stems[session.path(0).anchor] other = AnnotatorSession.open(session.table_path, cache=False) anchors = files.anchor_stems(out, 2) p = other.path(0, anchors[0]) @@ -292,9 +297,11 @@ def test_the_state_comes_back_and_survives_a_new_canvas(session, tmp_path): assert np.allclose(b - a, [2, -3]) -def test_a_matlab_file_is_imported_and_kept(session, tmp_path): - """ROIs of a file the annotator did not write are read as polygons in - canvas coordinates, and the file is copied aside before it is replaced.""" +def test_a_matlab_file_is_imported_and_kept(session: AnnotatorSession, tmp_path: Path) -> None: + """ROIs of a file the annotator did not write are read as polygons in canvas coordinates. + + The file is copied aside before it is replaced. + """ out = tmp_path / "annotations.h5" p = session.path(0) drawn = 2 # the trial the MATLAB annotation was drawn on @@ -304,9 +311,7 @@ def test_a_matlab_file_is_imported_and_kept(session, tmp_path): g = f.create_group("Path1") g["fn"] = files._chars(p.stems[drawn]) g["n_rois"] = np.array([[2]], np.uint32) - files._write_roi( - g.create_group("roi_001"), "soma1", pts, p.frame_shape[drawn] - ) + files._write_roi(g.create_group("roi_001"), "soma1", pts, p.frame_shape[drawn]) circle = g.create_group("roi_002") circle["type"] = files._chars("images.roi.Circle") circle["label"] = files._chars("ring") @@ -325,9 +330,7 @@ def test_a_matlab_file_is_imported_and_kept(session, tmp_path): ("roi", "ring"), ] assert np.allclose(rois[0]["points"], data.trial_to_canvas(pts, drawn)) - ring = polygon_mask( - data.canvas_to_trial(rois[1]["points"], drawn), mask.shape - ) + ring = polygon_mask(data.canvas_to_trial(rois[1]["points"], drawn), mask.shape) assert np.array_equal(ring, mask.astype(bool)) before = out.read_bytes() files.write_annotations(out, fresh, state) @@ -340,8 +343,15 @@ def test_a_matlab_file_is_imported_and_kept(session, tmp_path): assert np.array_equal(again.rois[0].mask, polygon_mask(pts, mask.shape)) -def _get(url): - """A GET's JSON body, or its bytes and headers.""" +def _get(url: str) -> dict | tuple[bytes, HTTPMessage]: + """Fetch a GET's JSON body, or its bytes and headers. + + Returns + ------- + dict or tuple[bytes, HTTPMessage] + The decoded JSON body if the response is JSON; else the body bytes + and the response headers. + """ with urllib.request.urlopen(url, timeout=30) as r: body = r.read() if r.headers["Content-Type"] == "application/json": @@ -349,14 +359,21 @@ def _get(url): return body, r.headers -def _post(url, obj, ctype="application/json", origin=None): - """A POST's status and JSON body.""" +def _post( + url: str, obj: dict, ctype: str = "application/json", origin: str | None = None +) -> tuple[int, dict]: + """Send a POST and return its status and JSON body. + + Returns + ------- + tuple[int, dict] + The HTTP status code and the decoded JSON body (also for an HTTP + error status). + """ headers = {"Content-Type": ctype} if origin: headers["Origin"] = origin - req = urllib.request.Request( - url, data=json.dumps(obj).encode(), headers=headers - ) + req = urllib.request.Request(url, data=json.dumps(obj).encode(), headers=headers) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read()) @@ -364,9 +381,11 @@ def _post(url, obj, ctype="application/json", origin=None): return e.code, json.loads(e.read()) -def test_server_serves_the_page_and_saves(session): - """The server answers the page's requests and writes the file on a - POST of the state; other origins and content types are refused.""" +def test_server_serves_the_page_and_saves(session: AnnotatorSession) -> None: + """The server answers the page's requests and writes the file on a POST of the state. + + Other origins and content types are refused. + """ store = AnnotatorStore(session) srv = make_server(store, port=0) thread = threading.Thread(target=srv.serve_forever, daemon=True) @@ -431,20 +450,18 @@ def test_server_serves_the_page_and_saves(session): assert again.had_file and again.state == store.state -def test_browse_lists_folders_and_tables(session, tmp_path): - """The Open dialog's listing names subfolders and trial tables, finds - tables below a folder and says which sessions have annotations.""" - files.write_annotations( - tmp_path / "annotations" / "annotations.h5", session, STATE - ) +def test_browse_lists_folders_and_tables(session: AnnotatorSession, tmp_path: Path) -> None: + """The Open dialog's listing names subfolders and trial tables. + + It finds tables below a folder and says which sessions have annotations. + """ + files.write_annotations(tmp_path / "annotations" / "annotations.h5", session, STATE) other = tmp_path / "sub" / "deep" syn.make_session(other, [{}, {}]) here = browse(tmp_path) assert here["dir"] == str(tmp_path.resolve()) assert "sub" in here["dirs"] and here["parent"] == str(tmp_path.parent) - assert [(t["name"], t["annotated"]) for t in here["tables"]] == [ - ("trial_table.h5", True) - ] + assert [(t["name"], t["annotated"]) for t in here["tables"]] == [("trial_table.h5", True)] assert "found" not in here found = browse(tmp_path, find=True)["found"] assert [(t["name"], t["annotated"]) for t in found] == [ @@ -457,9 +474,11 @@ def test_browse_lists_folders_and_tables(session, tmp_path): assert session_label(other / "trial_table.h5") == "sub/deep" -def test_server_opens_and_switches_sessions(tmp_path): - """Started without a session, the server lists folders, opens the - session the page names, switches to another and closes it.""" +def test_server_opens_and_switches_sessions(tmp_path: Path) -> None: + """Started without a session, the server lists folders. + + It opens the session the page names, switches to another and closes it. + """ first = syn.make_session(tmp_path / "a" / "out", [{}, {}, {}]) second = syn.make_session(tmp_path / "b" / "out", [{}, {}]) srv = make_server(None, port=0) @@ -481,9 +500,7 @@ def test_server_opens_and_switches_sessions(tmp_path): {"table": str(first), "session_id": meta["session_id"]}, ) assert code == 200 and meta["n_trials"] == 3 - assert meta["label"] == "a/out" and meta["browse"] == str( - first.parent.parent - ) + assert meta["label"] == "a/out" and meta["browse"] == str(first.parent.parent) assert ( _post( base + "/api/state", @@ -510,9 +527,7 @@ def test_server_opens_and_switches_sessions(tmp_path): ) assert code == 400 and "no trial table" in err["error"] assert _get(base + "/api/meta")["n_trials"] == 2 - code, meta = _post( - base + "/api/close", {"session_id": meta["session_id"]} - ) + code, meta = _post(base + "/api/close", {"session_id": meta["session_id"]}) assert code == 200 and meta["empty"] code, meta = _post( base + "/api/open", @@ -524,11 +539,9 @@ def test_server_opens_and_switches_sessions(tmp_path): srv.server_close() -def test_cli_has_the_command(): +def test_cli_has_the_command() -> None: """``giant annotate-raster`` parses its table and options.""" - args = build_parser().parse_args( - ["annotate-raster", "t.h5", "--port", "0", "--no-browser"] - ) + args = build_parser().parse_args(["annotate-raster", "t.h5", "--port", "0", "--no-browser"]) assert args.command == "annotate-raster" assert args.trial_table == "t.h5" and args.no_browser assert args.max_shift == 15 and args.annotations is None @@ -537,8 +550,14 @@ def test_cli_has_the_command(): @contextmanager -def _serve(store): - """Run a loopback annotator server for the duration of a test.""" +def _serve(store: AnnotatorStore) -> Iterator[str]: + """Run a loopback annotator server for the duration of a test. + + Yields + ------ + str + The base URL of the server. + """ srv = make_server(store, port=0) threading.Thread(target=srv.serve_forever, daemon=True).start() try: @@ -548,7 +567,7 @@ def _serve(store): srv.server_close() -def test_stale_tab_cannot_write_after_a_switch(tmp_path): +def test_stale_tab_cannot_write_after_a_switch(tmp_path: Path) -> None: """Switching one tab invalidates the other tab's save, Open and Close.""" a = syn.make_session(tmp_path / "a", [{}, {}]) b = syn.make_session(tmp_path / "b", [{}, {}]) @@ -589,7 +608,7 @@ def test_stale_tab_cannot_write_after_a_switch(tmp_path): assert path.read_bytes() == before -def test_stale_tab_cannot_overwrite_a_save_in_the_same_session(session): +def test_stale_tab_cannot_overwrite_a_save_in_the_same_session(session: AnnotatorSession) -> None: """A second tab's old snapshot cannot erase an ROI the first tab added.""" store = AnnotatorStore(session) store.set_state({"paths": [{"rois": STATE["paths"][0]["rois"][:1]}]}) @@ -629,7 +648,7 @@ def test_stale_tab_cannot_overwrite_a_save_in_the_same_session(session): assert store.file.read_bytes() == before -def test_wider_trial_roi_cannot_silently_clip(tmp_path): +def test_wider_trial_roi_cannot_silently_clip(tmp_path: Path) -> None: """A visible ROI outside the anchor is rejected and SILo keeps its mask.""" table = syn.make_session(tmp_path, [{"shape": (60, 48)}, {}]) session = AnnotatorSession.open(table, cache=False) @@ -645,18 +664,14 @@ def test_wider_trial_roi_cannot_silently_clip(tmp_path): visible = polygon_mask(pts, p.shape) & np.isfinite(p.trial_image(1)[0]) assert visible.sum() == 36 with pytest.raises(ValueError, match="crosses the anchor frame"): - store.set_state( - {"paths": [{"rois": [dict(roi, points=pts.tolist())]}]} - ) + store.set_state({"paths": [{"rois": [dict(roi, points=pts.tolist())]}]}) assert store.meta()["paths"][0]["edit_bounds"][2:] == [48, 60] entry = read_annotations(store.file)[0] assert entry.fn == p.stems[0] and store.file.read_bytes() == before - assert np.array_equal( - entry.rois[0].mask, polygon_mask(inside, p.frame_shape[0]) - ) + assert np.array_equal(entry.rois[0].mask, polygon_mask(inside, p.frame_shape[0])) -def test_edit_preserves_an_untouched_matlab_mask(session, tmp_path): +def test_edit_preserves_an_untouched_matlab_mask(session: AnnotatorSession, tmp_path: Path) -> None: """Editing a different ROI keeps the imported soma's hole and island.""" p = session.path(0) out = tmp_path / "annotations.h5" @@ -681,9 +696,7 @@ def test_edit_preserves_an_untouched_matlab_mask(session, tmp_path): assert changed.label == "soma2" and original.label == "soma1" assert np.array_equal( changed.mask, - polygon_mask( - p.canvas_to_trial(rois[0]["points"], p.anchor), mask.shape - ), + polygon_mask(p.canvas_to_trial(rois[0]["points"], p.anchor), mask.shape), ) assert np.array_equal(original.mask, mask) state = files.read_state(out, session) @@ -694,7 +707,7 @@ def test_edit_preserves_an_untouched_matlab_mask(session, tmp_path): assert np.array_equal(original.mask, mask) -def test_shifted_edges_survive_and_legacy_points_stay_in_the_trial(tmp_path): +def test_shifted_edges_survive_and_legacy_points_stay_in_the_trial(tmp_path: Path) -> None: """A shifted trial retains all pixels and old points keep their frame.""" table = syn.make_session(tmp_path, [{}, {}, {}]) session = AnnotatorSession.open(table, cache=False, max_shift=5) @@ -707,9 +720,7 @@ def test_shifted_edges_survive_and_legacy_points_stay_in_the_trial(tmp_path): r, c = -p.frame_offset[2] actual = p.trial_image(2) assert np.isfinite(actual[0]).sum() == 1200 - assert np.array_equal( - actual[:, r : r + 30, c : c + 40], np.moveaxis(moved, -1, 0) - ) + assert np.array_equal(actual[:, r : r + 30, c : c + 40], np.moveaxis(moved, -1, 0)) path = tmp_path / "legacy.h5" pts = [[5, 4], [10, 4], [10, 9], [5, 9]] @@ -729,7 +740,7 @@ def test_shifted_edges_survive_and_legacy_points_stay_in_the_trial(tmp_path): assert np.array_equal(p.canvas_to_trial(got["points"], 0), pts) -def test_unavailable_path_is_disabled_and_its_annotations_survive(tmp_path): +def test_unavailable_path_is_disabled_and_its_annotations_survive(tmp_path: Path) -> None: """A usable path can save while an unavailable MATLAB path is copied.""" table = syn.make_session(tmp_path, [{}, {}], n_paths=2) session = AnnotatorSession.open(table, cache=False) @@ -765,7 +776,7 @@ def test_unavailable_path_is_disabled_and_its_annotations_survive(tmp_path): assert f["Path1/alignment_ncc"][()].item() == 0.8 -def test_empty_trial_range_returns_no_other_trials(tmp_path): +def test_empty_trial_range_returns_no_other_trials(tmp_path: Path) -> None: """An empty selected range returns NaNs while the session still loads.""" table = syn.make_session(tmp_path, [{}, None, {}], failed=[0, 2]) store = AnnotatorStore(AnnotatorSession.open(table)) @@ -777,7 +788,7 @@ def test_empty_trial_range_returns_no_other_trials(tmp_path): assert np.isfinite(np.frombuffer(body, np.float32)).any() -def test_matlab_completion_is_separate_from_the_editor_anchor(session): +def test_matlab_completion_is_separate_from_the_editor_anchor(session: AnnotatorSession) -> None: """An editor anchor leaves an untouched path unannotated in MATLAB.""" store = AnnotatorStore(session) store.set_state(STATE) @@ -789,7 +800,7 @@ def test_matlab_completion_is_separate_from_the_editor_anchor(session): assert a.fn and not a.rois and not b.fn -def test_cli_overrides_require_a_table(): +def test_cli_overrides_require_a_table() -> None: """File overrides fail at launch instead of being ignored by the picker.""" parser = build_parser() for flag in ("--annotations", "--moco-dir"): @@ -798,7 +809,7 @@ def test_cli_overrides_require_a_table(): make_hub(args) -def _run_page_script(code): +def _run_page_script(code: str) -> None: """Run the shipped page's functions in Node with minimal DOM stubs.""" node = shutil.which("node") if node is None: @@ -817,7 +828,7 @@ def _run_page_script(code): ) -def test_autosave_serializes_edits_and_blocks_switch_on_failure(): +def test_autosave_serializes_edits_and_blocks_switch_on_failure() -> None: """A delayed save cannot relabel a survivor or let a failed edit switch.""" _run_page_script(""" const assert = require('node:assert/strict'); @@ -858,7 +869,7 @@ def test_autosave_serializes_edits_and_blocks_switch_on_failure(): """) -def test_autosave_repaints_an_roi_reclassified_as_soma(): +def test_autosave_repaints_an_roi_reclassified_as_soma() -> None: """The list and overlay use the kind the server saved for a renamed ROI.""" _run_page_script(""" const assert = require('node:assert/strict'); @@ -882,7 +893,7 @@ def test_autosave_repaints_an_roi_reclassified_as_soma(): """) -def test_prefetched_trial_repaints_when_it_becomes_visible(): +def test_prefetched_trial_repaints_when_it_becomes_visible() -> None: """A pending background request repaints when its trial is selected.""" _run_page_script(""" const assert = require('node:assert/strict'); @@ -907,7 +918,7 @@ def test_prefetched_trial_repaints_when_it_becomes_visible(): """) -def test_readme_scope_points_raster_roi_users_to_annotate_raster(): +def test_readme_scope_points_raster_roi_users_to_annotate_raster() -> None: """The README scope points raster ROI users to the Python command.""" readme = (PAGE.parents[3] / "README.md").read_text() scope = next(line for line in readme.splitlines() if "**Scope.**" in line) diff --git a/tests/export/test_f0_layout.py b/tests/export/test_f0_layout.py index 84d21b92..22f4c6ad 100644 --- a/tests/export/test_f0_layout.py +++ b/tests/export/test_f0_layout.py @@ -19,7 +19,11 @@ slot_statistics, ) from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + read_raster_samples, +) from giant_python.registration import multiroi from giant_python.registration.stats.gain import next_slots @@ -286,7 +290,7 @@ def test_version_3_files_are_read(patched: Registered, tmp_path: Path) -> None: Version 3 has no slot positions (registrations without online compensation); such a file gives the same frames. """ - layout, table, root = patched + layout, table, _root = patched export_layouts(table, tmp_path) out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" new = read_layout(out) diff --git a/tests/export/test_f0_training.py b/tests/export/test_f0_training.py index 0db5ffc4..35878e89 100644 --- a/tests/export/test_f0_training.py +++ b/tests/export/test_f0_training.py @@ -36,7 +36,7 @@ def session( def _export( syn: dict[str, Any], out: Path, - **kw: Any, # noqa: ANN401 - forwarded to ExportOptions, whose fields differ in type + **kw: object, ) -> dict: """Export the synthetic run with the given options. @@ -434,7 +434,7 @@ def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path: Path) -> None: This is as slap2-f0 computes it at inference. """ syn = write_session(tmp_path / "syn", "rigid", n80=200) - alf = sorted(syn["moco"].glob("*_ALIGNMENTDATA.h5"))[0] + alf = min(syn["moco"].glob("*_ALIGNMENTDATA.h5")) with h5py.File(alf, "r+") as f: rne = f["recNegErr"][()] rne[100:110] = 1.0 # a motion spike: those frames are discarded @@ -840,7 +840,7 @@ def test_mask_fractions_count_finite_samples(tmp_path: Path) -> None: syn = write_session(tmp_path / "syn", "rigid", n80=300) _noisy_traces(syn) - mf = sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5"))[0] + mf = min(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")) with h5py.File(mf, "r+") as f: key = next(iter(f.keys())) a = f[key][()] # (frames, cols, rows) diff --git a/tests/raster/alignment_synthetic.py b/tests/raster/alignment_synthetic.py index e6632680..b9efd179 100644 --- a/tests/raster/alignment_synthetic.py +++ b/tests/raster/alignment_synthetic.py @@ -11,7 +11,7 @@ from collections.abc import Callable import numpy as np -import scipy.ndimage as ndimage +from scipy import ndimage from giant_python.extraction.raster.alignment import interp2_cubic diff --git a/tests/raster/data/compare_matlab_wmf.py b/tests/raster/data/compare_matlab_wmf.py index 6239b949..15e93197 100644 --- a/tests/raster/data/compare_matlab_wmf.py +++ b/tests/raster/data/compare_matlab_wmf.py @@ -1,10 +1,10 @@ """Audit the public WMF call against every checkpoint in the full MATLAB H5. -Generate the fixture with ``make_matlab_wmf.m`` and GIAnT-MATLAB e61873b. -The generator includes ``close_pair`` and ``close_pair_no_deblend`` by -default. For the two real-crop cases, copy the ``actT`` and ``excludeMask`` -datasets from ``real_crop/in`` in the checked-in fixture to the root of -``fixtures/real_crop_input.h5`` beside the MATLAB script. +Generate the fixture with make_matlab_wmf.m and GIAnT-MATLAB e61873b. +The generator includes close_pair and close_pair_no_deblend by +default. For the two real-crop cases, copy the actT and excludeMask +datasets from real_crop/in in the checked-in fixture to the root of +fixtures/real_crop_input.h5 beside the MATLAB script. Run from the repository root with the source tree on PYTHONPATH: python -m tests.raster.data.compare_matlab_wmf /path/to/matlab_wmf_full.h5 @@ -12,13 +12,15 @@ import argparse from contextlib import ExitStack +from pathlib import Path +from typing import Any from unittest.mock import patch import h5py import numpy as np +from tests.raster.wmf_reference import load_case from giant_python.extraction.raster import wmf -from tests.raster.wmf_reference import load_case # Group columns by stage to keep the generated Markdown tables readable. _TABLES = ( @@ -30,19 +32,31 @@ ) -def _trace(act, mask, params): - """Observe the actual implementation, including paths that skip the fit.""" - with ExitStack() as stack: +def _trace(act: np.ndarray, mask: np.ndarray, params: dict[str, float]) -> dict[str, Any]: + """Observe the actual implementation, including paths that skip the fit. + Returns + ------- + dict[str, Any] + The implementation's diagnostics, extended with its seeds and the intermediate + results of each stage, keyed by the MATLAB fixture's checkpoint names. + """ + with ExitStack() as stack: outputs = {} - def record(name): + def record(name: str) -> None: """Capture this helper's results in the order the port calls it.""" results = outputs[name] = [] original = getattr(wmf, name) - def run(*args, **kwargs): - """Observe the unmodified stage result.""" + def run(*args: object, **kwargs: object) -> object: + """Observe the unmodified stage result. + + Returns + ------- + object + The wrapped helper's result, unchanged. + """ result = original(*args, **kwargs) results.append(result) return result @@ -60,8 +74,20 @@ def run(*args, **kwargs): record(name) before_final = {} - def finish(seeds, values, added, anchors, *rest): - """Capture fit results before anchor repair and activity checks.""" + def finish( + seeds: np.ndarray, + values: np.ndarray, + added: np.ndarray, + anchors: np.ndarray, + *rest: object, + ) -> object: + """Capture fit results before anchor repair and activity checks. + + Returns + ------- + object + The result of the wrapped `_finish_seeds`, unchanged. + """ before_final.update( seeds_deblend=seeds.copy(), v_deblend=values.copy(), @@ -92,8 +118,15 @@ def finish(seeds, values, added, anchors, *rest): return got -def _compare(key, got, ref): - """Check shape, non-finite locations, discrete fields and tolerances.""" +def _compare(key: str, got: np.ndarray, ref: np.ndarray) -> tuple[float, float]: + """Check shape, non-finite locations, discrete fields and tolerances. + + Returns + ------- + tuple[float, float] + The maximum absolute error and the maximum pointwise relative error over the finite + reference values. + """ assert got.shape == ref.shape, key for flag in (np.isnan, np.isposinf, np.isneginf): np.testing.assert_array_equal(flag(got), flag(ref), err_msg=key) @@ -114,8 +147,22 @@ def _compare(key, got, ref): return diff.max(initial=0), (diff[nonzero] / mag[nonzero]).max(initial=0) -def compare_case(group): - """Compare every supplied field and return the errors and seed counts.""" +def compare_case( + group: h5py.Group, +) -> tuple[dict[str, tuple[float, float]], tuple[int, int, float]]: + """Compare every supplied field and return the errors and seed counts. + + Returns + ------- + tuple[dict[str, tuple[float, float]], tuple[int, int, float]] + The maximum absolute and relative errors by checkpoint name, then the number of seeds, + the number of added seeds and the maximum seed displacement in pixels. + + Raises + ------ + ValueError + If the group lacks the `dbg/added` checkpoint. + """ act, mask, params, out, dbg = load_case(group) if "added" not in dbg: raise ValueError( @@ -136,7 +183,7 @@ def compare_case(group): ) -def print_tables(path): +def print_tables(path: str | Path) -> None: """Print per-case absolute and pointwise relative maxima as Markdown.""" with h5py.File(path, "r") as f: cases = {name: compare_case(group) for name, group in f.items()} diff --git a/tests/raster/data/make_matlab_wmf_h5.py b/tests/raster/data/make_matlab_wmf_h5.py index e492c7fe..81889ca7 100644 --- a/tests/raster/data/make_matlab_wmf_h5.py +++ b/tests/raster/data/make_matlab_wmf_h5.py @@ -15,7 +15,7 @@ CASES = ("fallback_kernel", "islands_nan", "three_trials", "real_crop") -def main(src, dst): +def main(src: str, dst: str) -> None: """Keep each case's inputs, final seed results and selected images.""" with h5py.File(src, "r") as full, h5py.File(dst, "w") as small: small.attrs["source"] = "make_matlab_wmf.m (GIAnT-MATLAB e61873b)" diff --git a/tests/raster/test_raster_alignment.py b/tests/raster/test_raster_alignment.py index 04db23e8..866698dd 100644 --- a/tests/raster/test_raster_alignment.py +++ b/tests/raster/test_raster_alignment.py @@ -144,7 +144,7 @@ def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: """ render = _scene((30, 40), 12, seed=3) template, frame = render(), render((1.0, -1.0)) - motion, r = xcorr2_nans(frame, template, (1, -1), 2) + motion, _r = xcorr2_nans(frame, template, (1, -1), 2) np.testing.assert_allclose(motion, (1.0, -1.0), atol=0.05) # a centre beyond the margin makes the valid pixels wrap around wrapped, _ = xcorr2_nans(frame, template, (9, 0), 2) diff --git a/tests/raster/test_raster_alignment_modes.py b/tests/raster/test_raster_alignment_modes.py index 13ae8311..451f7bfe 100644 --- a/tests/raster/test_raster_alignment_modes.py +++ b/tests/raster/test_raster_alignment_modes.py @@ -1,10 +1,15 @@ -"""Tests of the affine and patchwise across-trial alignments (ports of -GIAnT-MATLAB's ``TestTrialAlignment.m``) and of their helpers.""" +"""Tests of the affine and patchwise across-trial alignments and of their helpers. + +The tests are ports of GIAnT-MATLAB's TestTrialAlignment.m. +""" import multiprocessing import os import warnings +from collections.abc import Callable, Iterable, Iterator from dataclasses import fields +from pathlib import Path +from typing import NoReturn import numpy as np import pytest @@ -29,19 +34,28 @@ from .alignment_synthetic import field_error, neuron, trials +# the neuron's labeled image, its scanned pixels and the random generator that made them +SyntheticNeuron = tuple[np.ndarray, np.ndarray, np.random.Generator] + -def test_cubic_reproduces_quadratics_and_grid_values(): - """Keys' convolution with MATLAB's boundary rows is exact for - quadratics, also next to the edges, and returns the image on the - grid; NaN outside the image.""" +def test_cubic_reproduces_quadratics_and_grid_values() -> None: + """Keys' convolution with MATLAB's boundary rows is exact for quadratics. + + This holds also next to the edges, and the image is returned on the grid; + NaN outside the image. + """ rng = np.random.default_rng(0) rr, cc = np.mgrid[0:9, 0:11].astype(float) - def f(r, c): - """A quadratic surface.""" - return ( - 1 + 0.3 * r - 0.2 * c + 0.05 * r * r - 0.04 * r * c + 0.02 * c**2 - ) + def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: + """Return a quadratic surface. + + Returns + ------- + np.ndarray + The surface at rows r and columns c. + """ + return 1 + 0.3 * r - 0.2 * c + 0.05 * r * r - 0.04 * r * c + 0.02 * c**2 im = f(rr, cc) r = rng.uniform(0, 8, 500) @@ -52,10 +66,12 @@ def f(r, c): assert np.isnan(out).all() -def test_cubic_nan_reaches_its_whole_stencil(): - """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN, also - a grid point next to it (MATLAB's interp2), unlike linear - interpolation; the cubic warp falls back to linear there.""" +def test_cubic_nan_reaches_its_whole_stencil() -> None: + """A NaN pixel makes every point whose 4 x 4 stencil holds it NaN. + + This includes a grid point next to it (MATLAB's interp2), unlike linear + interpolation; the cubic warp falls back to linear there. + """ im = np.arange(80, dtype=float).reshape(8, 10) im[4, 5] = np.nan assert np.isnan(interp2_cubic(im, 4.0, 4.0)) # on the grid, next to it @@ -68,7 +84,7 @@ def test_cubic_nan_reaches_its_whole_stencil(): np.testing.assert_array_equal(np.isnan(cub), np.isnan(lin)) -def test_gradient_is_matlabs(): +def test_gradient_is_matlabs() -> None: """Central differences inside, one-sided differences at the edges.""" im = np.array([[0.0, 1, 4, 9], [1, 3, 5, 7], [2, 2, 2, 2]]) g_r, g_c = matlab_gradient(im) @@ -77,13 +93,13 @@ def test_gradient_is_matlabs(): np.testing.assert_array_equal(g_r[1], [1, 0.5, -1, -3.5]) -def test_field_reproduces_affine_map(): - """Displacements at the centres that follow an affine map give that - map everywhere, also far outside the centres.""" +def test_field_reproduces_affine_map() -> None: + """Displacements at the centres that follow an affine map give that map everywhere. + + This holds also far outside the centres. + """ rng = np.random.default_rng(1) - nodes = np.column_stack( - [rng.random(12) * 200 + 50, rng.random(12) * 400 + 50] - ) + nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T cc, rr = np.meshgrid(np.linspace(-50, 550, 61), np.linspace(-50, 350, 41)) @@ -99,13 +115,13 @@ def test_field_reproduces_affine_map(): assert np.nanmax(np.abs(out - ref)) < 1e-9 -def test_field_apply_matches_field_matrix(): - """Evaluating a bent field without the field matrix gives the same - displacements, also with fewer than 3 centres (their mean).""" +def test_field_apply_matches_field_matrix() -> None: + """Evaluating a bent field without the field matrix gives the same displacements. + + This holds also with fewer than 3 centres (their mean). + """ rng = np.random.default_rng(2) - nodes = np.column_stack( - [rng.random(40) * 200 + 50, rng.random(40) * 400 + 50] - ) + nodes = np.column_stack([rng.random(40) * 200 + 50, rng.random(40) * 400 + 50]) a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T d = d + 0.4 * rng.standard_normal(d.shape) @@ -122,12 +138,10 @@ def test_field_apply_matches_field_matrix(): ) -def test_inverse_undoes_bent_field(): +def test_inverse_undoes_bent_field() -> None: """trialWarpInverse: back to the consensus points to 1e-5 px.""" rng = np.random.default_rng(3) - nodes = np.column_stack( - [rng.random(12) * 200 + 50, rng.random(12) * 400 + 50] - ) + nodes = np.column_stack([rng.random(12) * 200 + 50, rng.random(12) * 400 + 50]) a = np.array([[1.004, 0.002, 0.7], [-0.003, 0.997, -1.2]]) d = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T d = d + 0.4 * rng.standard_normal(d.shape) @@ -141,13 +155,13 @@ def test_inverse_undoes_bent_field(): assert (r2[0], c2[0]) == (2.75, 5.5) -def test_matlab_conversion_of_a_field(): - """MATLAB's one-based centres and affine maps convert to zero-based; - displacements stay; the map of a point moves with the base.""" +def test_matlab_conversion_of_a_field() -> None: + """MATLAB's one-based centres and affine maps convert to zero-based. + + Displacements stay; the map of a point moves with the base. + """ rng = np.random.default_rng(4) - nodes1 = np.column_stack( - [rng.random(8) * 50 + 10, rng.random(8) * 80 + 10] - ) + nodes1 = np.column_stack([rng.random(8) * 50 + 10, rng.random(8) * 80 + 10]) a1 = np.array([[[1.002, 0.001, 0.4], [0.0, 0.999, -0.3]]]) d = 0.3 * rng.standard_normal((1, 8, 2)) warp = TrialWarp.from_matlab(a1, nodes1, 12.0, d) @@ -162,9 +176,11 @@ def test_matlab_conversion_of_a_field(): np.testing.assert_allclose(warp.to_matlab(), a1) -def test_kmeans_finds_separated_clusters(): - """Three well separated clusters are found from k-means++ starts; an - empty cluster restarts at the farthest point.""" +def test_kmeans_finds_separated_clusters() -> None: + """Three well separated clusters are found from k-means++ starts. + + An empty cluster restarts at the farthest point. + """ rng = np.random.default_rng(5) centres = np.array([[0.0, 0], [50, 0], [0, 50]]) x = np.vstack([c + rng.standard_normal((200, 2)) for c in centres]) @@ -177,14 +193,12 @@ def test_kmeans_finds_separated_clusters(): assert np.bincount(labels, minlength=3).min() > 0 # the farthest point of a singleton is not moved (that would empty it) pts = np.array([[0.0, 0], [10, 0], [11, 0]]) - labels, cen = kmeans( - pts, 3, start=np.array([[5.0, 0], [10.5, 0], [1e3, 0]]) - ) + labels, cen = kmeans(pts, 3, start=np.array([[5.0, 0], [10.5, 0], [1e3, 0]])) assert np.isfinite(cen).all() assert sorted(np.bincount(labels, minlength=3)) == [1, 1, 1] -def test_patch_size_is_bounded(): +def test_patch_size_is_bounded() -> None: """A patch needs at least one pixel; one pixel per patch at most.""" valid = np.zeros((6, 8), bool) valid[1:4, 2:6] = True @@ -197,9 +211,11 @@ def test_patch_size_is_bounded(): PlanParams(align_patch_px=0.5) -def test_patches_have_their_size(): - """About patch_px pixels each, none under half of it, centred on their - pixels.""" +def test_patches_have_their_size() -> None: + """About patch_px pixels each, none under half of it. + + The patches are centred on their pixels. + """ valid = np.zeros((120, 160), bool) valid[10:100, 20:150] = True valid[40:60, 60:90] = False @@ -210,22 +226,29 @@ def test_patches_have_their_size(): rows, cols = np.nonzero(valid) for k in range(nodes.shape[0]): sel = patch[rows, cols] == k + 1 - np.testing.assert_allclose( - nodes[k], [rows[sel].mean(), cols[sel].mean()], atol=1e-9 - ) + np.testing.assert_allclose(nodes[k], [rows[sel].mean(), cols[sel].mean()], atol=1e-9) @pytest.fixture(scope="module") -def synthetic_neuron(): - """The labeled neuron of MATLAB's test and its scanned pixels.""" +def synthetic_neuron() -> SyntheticNeuron: + """Build the labeled neuron of MATLAB's test and its scanned pixels. + + Returns + ------- + tuple[np.ndarray, np.ndarray, np.random.Generator] + The labeled neuron, its scanned pixels and the random generator that + made them (shared by the tests). + """ rng = np.random.default_rng(1) truth, scan = neuron(rng) return truth, scan, rng -def test_affine_recovers_known_maps(synthetic_neuron): - """The relative maps between trials are recovered to 0.05 px, much - better than the rigid start.""" +def test_affine_recovers_known_maps(synthetic_neuron: SyntheticNeuron) -> None: + """The relative maps between trials are recovered to 0.05 px. + + This is much better than the rigid start. + """ truth, scan, rng = synthetic_neuron m, _, u, a0 = trials(truth, scan, False, rng) a, info = align_trials_affine(m, a0) @@ -235,10 +258,12 @@ def test_affine_recovers_known_maps(synthetic_neuron): assert np.all(info.corr > 0.9) -def test_patchwise_recovers_bends(synthetic_neuron): - """Smooth bends (over ~40 px) on top of affine maps: recovered to 0.08 - px, much better than the rigid start and beyond an affine fit; no - patch under half the target size.""" +def test_patchwise_recovers_bends(synthetic_neuron: SyntheticNeuron) -> None: + """Smooth bends (over ~40 px) on top of affine maps are recovered to 0.08 px. + + This is much better than the rigid start and beyond an affine fit; no + patch under half the target size. + """ truth, scan, rng = synthetic_neuron m, mh, u, a0 = trials(truth, scan, True, rng) fit, info = align_trials_patchwise(m, a0, mh, 1500) @@ -251,15 +276,12 @@ def test_patchwise_recovers_bends(synthetic_neuron): assert err < 0.7 * err_a # the plane is the field's affine part: equal at the plane's points plane = TrialWarp(fit.affine) - np.testing.assert_allclose( - np.mean(fit.affine[:, :, :2], axis=0), np.eye(2), atol=1e-3 - ) + np.testing.assert_allclose(np.mean(fit.affine[:, :, :2], axis=0), np.eye(2), atol=1e-3) assert np.isfinite(plane.coords(0, 1.0, 1.0)[0]) -def test_patchwise_adds_nothing_without_bends(synthetic_neuron): - """Affine maps only: the patchwise field is as good as the affine - fit.""" +def test_patchwise_adds_nothing_without_bends(synthetic_neuron: SyntheticNeuron) -> None: + """Affine maps only: the patchwise field is as good as the affine fit.""" truth, scan, rng = synthetic_neuron m, mh, u, a0 = trials(truth, scan, False, rng) fit, _ = align_trials_patchwise(m, a0, mh, 1500) @@ -268,16 +290,17 @@ def test_patchwise_adds_nothing_without_bends(synthetic_neuron): assert err < 0.05 -def test_patchwise_given_patches_and_without_halves(): - """Given its own patches back, the fit is the same; without halves the - departures are kept as fitted (weight 1) and the fit still runs.""" +def test_patchwise_given_patches_and_without_halves() -> None: + """Given its own patches back, the fit is the same. + + Without halves the departures are kept as fitted (weight 1) and the fit + still runs. + """ rng = np.random.default_rng(7) truth, scan = neuron(rng, (70, 90)) m, mh, _, a0 = trials(truth, scan, True, rng, n_trials=3) fit, info = align_trials_patchwise(m, a0, mh, 600, n_rounds=1) - again, _ = align_trials_patchwise( - m, a0, mh, 600, n_rounds=1, patches=(fit.patch, fit.nodes) - ) + again, _ = align_trials_patchwise(m, a0, mh, 600, n_rounds=1, patches=(fit.patch, fit.nodes)) np.testing.assert_array_equal(again.disp, fit.disp) assert np.all((info.weight >= 0) & (info.weight <= 1)) plain, plain_info = align_trials_patchwise(m, a0, None, 600, n_rounds=1) @@ -286,11 +309,11 @@ def test_patchwise_given_patches_and_without_halves(): assert np.isfinite(plain.disp).all() -def test_too_few_trials_or_pixels_keep_the_start(): +def test_too_few_trials_or_pixels_keep_the_start() -> None: """With fewer than 2 trials to fit, the maps are the starting ones.""" m = np.random.default_rng(6).random((2, 30, 40)) a0 = np.array([np.eye(2, 3), np.full((2, 3), np.nan)]) - a, info = align_trials_affine(m, a0) + a, _info = align_trials_affine(m, a0) np.testing.assert_array_equal(a, a0) fit, _ = align_trials_patchwise(m, a0) assert fit.nodes.shape[0] == 0 @@ -299,14 +322,20 @@ def test_too_few_trials_or_pixels_keep_the_start(): @pytest.fixture -def refiners(monkeypatch): - """The trial refiners the alignments make, recorded.""" +def refiners(monkeypatch: pytest.MonkeyPatch) -> list[alignment_mod._TrialRefiner]: + """Record the trial refiners the alignments make. + + Returns + ------- + list + The refiners made, in order of creation (filled while the test runs). + """ made = [] class Recorded(alignment_mod._TrialRefiner): """A refiner that is recorded.""" - def __init__(self, *args, **kw): + def __init__(self, *args: object, **kw: object) -> None: """Record it.""" super().__init__(*args, **kw) made.append(self) @@ -315,8 +344,14 @@ def __init__(self, *args, **kw): return made -def _blas_count(): - """This process's BLAS thread count (skip where it cannot be read).""" +def _blas_count() -> int: + """Return the BLAS thread count of this process (skip where it cannot be read). + + Returns + ------- + int + The one BLAS thread count of this process. + """ from giant_python.parallel import blas_threads counts = blas_threads() @@ -326,27 +361,27 @@ def _blas_count(): def test_patchwise_refits_in_workers_are_the_same( - synthetic_neuron, refiners, monkeypatch -): - """The trials refit by worker processes (each round's and the halves') - give every field of the fit and of its diagnostics made here, bit for - bit. The workers have this process's BLAS thread count, not the one - its environment names, and OpenBLAS's idle timeout, which this - process's environment keeps (starts 2 processes).""" + synthetic_neuron: SyntheticNeuron, + refiners: list[alignment_mod._TrialRefiner], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The trials refit by worker processes give every field of the fit, bit for bit. + + This holds for each round's and the halves' refits, and for the fit's + diagnostics made here. The workers have this process's BLAS thread count, + not the one its environment names, and OpenBLAS's idle timeout, which + this process's environment keeps (starts 2 processes). + """ from giant_python.parallel import BLAS_IDLE - truth, scan, rng = synthetic_neuron - m, mh, _, a0 = trials( - truth, scan, True, np.random.default_rng(3), n_trials=8 - ) + truth, scan, _rng = synthetic_neuron + m, mh, _, a0 = trials(truth, scan, True, np.random.default_rng(3), n_trials=8) here, info = align_trials_patchwise(m, a0, mh, 1500, n_rounds=1) assert refiners[-1].started is None and refiners[-1].in_workers == 0 n = _blas_count() monkeypatch.setenv("OPENBLAS_NUM_THREADS", str(1 if n != 1 else 2)) monkeypatch.setenv(BLAS_IDLE[0], "28") - there, info2 = align_trials_patchwise( - m, a0, mh, 1500, n_rounds=1, workers=2 - ) + there, info2 = align_trials_patchwise(m, a0, mh, 1500, n_rounds=1, workers=2) r = refiners[-1] fitted = np.isfinite(info.corr).sum() assert fitted == 8 @@ -364,26 +399,34 @@ def test_patchwise_refits_in_workers_are_the_same( assert np.asarray(x).tobytes() == np.asarray(y).tobytes(), f.name -def test_no_refit_workers_without_refits(synthetic_neuron, monkeypatch): +def test_no_refit_workers_without_refits( + synthetic_neuron: SyntheticNeuron, monkeypatch: pytest.MonkeyPatch +) -> None: """Without rounds and halves nothing is refit, and no worker starts.""" - def no_pool(*args, **kw): - """A pool must not start.""" + def no_pool(*args: object, **kw: object) -> NoReturn: + """Fail because a pool must not start. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("a pool was started") monkeypatch.setattr(alignment_mod, "spawn_pool", no_pool) - truth, scan, rng = synthetic_neuron - m, _, _, a0 = trials( - truth, scan, True, np.random.default_rng(3), n_trials=8 - ) + truth, scan, _rng = synthetic_neuron + m, _, _, a0 = trials(truth, scan, True, np.random.default_rng(3), n_trials=8) fit, _ = align_trials_patchwise(m, a0, None, 1500, n_rounds=0, workers=2) assert fit.nodes.shape[0] > 0 @pytest.mark.parametrize("bad", [0, -1, 2.5, True, "2", None]) -def test_workers_must_be_a_positive_integer(bad): - """The patchwise alignment, the refinement and the plan refuse a - number of workers that is not a positive integer.""" +def test_workers_must_be_a_positive_integer(bad: object) -> None: + """The patchwise alignment, the refinement and the plan refuse a bad worker count. + + A number of workers that is not a positive integer is refused. + """ from giant_python.extraction.raster.plan import ( plan_path, refine_alignment, @@ -400,35 +443,41 @@ def test_workers_must_be_a_positive_integer(bad): align_trials_patchwise(m, np.zeros((2, 2, 3)), workers=np.int64(3)) -def test_bend_variance_is_reduced_once(synthetic_neuron): - """The bends' variance across trials gives the reliability weight and - ``bend_sd``: one reduction, one overflow warning for huge maps.""" - truth, scan, rng = synthetic_neuron - m, _, _, a0 = trials( - truth, scan, True, np.random.default_rng(3), n_trials=8 - ) +def test_bend_variance_is_reduced_once(synthetic_neuron: SyntheticNeuron) -> None: + """The bends' variance across trials gives the reliability weight and bend_sd. + + One reduction, one overflow warning for huge maps. + """ + truth, scan, _rng = synthetic_neuron + m, _, _, a0 = trials(truth, scan, True, np.random.default_rng(3), n_trials=8) fit, _ = align_trials_patchwise(m, a0, None, 1500, n_rounds=0) a1 = a0.copy() a1[:, :, 2] += 1e200 with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") - align_trials_patchwise( - m, a1, None, 1500, n_rounds=0, patches=(fit.patch, fit.nodes) - ) + align_trials_patchwise(m, a1, None, 1500, n_rounds=0, patches=(fit.patch, fit.nodes)) overflow = [w for w in caught if "overflow" in str(w.message)] assert len(overflow) == 1 -def test_trial_refiner_without_workers_refits_here(): - """With one worker the refiner refits in this process, in the order of - the trials, as the layout's own refit.""" +def test_trial_refiner_without_workers_refits_here() -> None: + """With one worker the refiner refits in this process. + + The trials are refit in their order, as the layout's own refit. + """ from giant_python.extraction.raster.alignment import _TrialRefiner class Layout: """A layout whose refit adds the trial's image mean.""" - def refine(self, s_t, template, d): - """A refit.""" + def refine(self, s_t: np.ndarray, template: np.ndarray, d: np.ndarray) -> np.ndarray: + """Return a refit. + + Returns + ------- + np.ndarray + The displacements d plus the trial's image mean and the template's sum. + """ return d + s_t.mean() + template.sum() s = np.arange(12.0).reshape(3, 2, 2) @@ -440,17 +489,38 @@ def refine(self, s_t, template, d): class _SqrtLayout: - """A layout whose refit takes square roots of the trial's image (an - invalid value and a warning for a negative pixel) and a product.""" + """A layout whose refit takes square roots of the trial's image and a product. + + The square roots give an invalid value and a warning for a negative pixel. + """ - def refine(self, s_t, template, d): - """A refit.""" + def refine(self, s_t: np.ndarray, template: np.ndarray, d: np.ndarray) -> np.ndarray: + """Return a refit. + + Returns + ------- + np.ndarray + The displacements d plus the sum of the square roots of the trial's + image and the product term. + """ return d + np.sqrt(s_t).sum() + (s_t @ s_t.T).sum() * template.sum() -def _refit(workers, s, errors="warn", layout=None): - """Refits of the trials ``s`` with :class:`_SqrtLayout` (or - ``layout``) and the refiner.""" +def _refit( + workers: int, + s: np.ndarray, + errors: str = "warn", + layout: "_SqrtLayout | _WarnThenRaiseLayout | None" = None, +) -> tuple[np.ndarray, alignment_mod._TrialRefiner]: + """Refit the trials s with :class:`_SqrtLayout` (or layout) and the refiner. + + Returns + ------- + out : np.ndarray + The refit displacements. + r : alignment_mod._TrialRefiner + The refiner that made them. + """ disp = np.zeros((s.shape[0], 2, 3)) lay = _SqrtLayout() if layout is None else layout with np.errstate(invalid=errors): @@ -462,16 +532,24 @@ def _refit(workers, s, errors="warn", layout=None): class _WarnThenRaiseLayout: """A layout whose refit warns and then fails.""" - def refine(self, s_t, template, d): - """A refit that fails.""" + def refine(self, s_t: np.ndarray, template: np.ndarray, d: np.ndarray) -> NoReturn: + """Warn and then fail, as a refit that fails. + + Raises + ------ + FloatingPointError + Always. + """ warnings.warn("first", RuntimeWarning) raise FloatingPointError("later") -def test_refit_workers_give_their_warnings_before_their_exception(): - """A refit that warns and then raises gives the warning and then the - exception, in a worker as here: with warnings as errors the warning is - what is raised (starts 2 processes, twice).""" +def test_refit_workers_give_their_warnings_before_their_exception() -> None: + """A refit that warns and then raises gives the warning and then the exception. + + This holds in a worker as here: with warnings as errors the warning is + what is raised (starts 2 processes, twice). + """ _blas_count() s = np.ones((3, 2, 4)) lay = _WarnThenRaiseLayout() @@ -489,24 +567,45 @@ def test_refit_workers_give_their_warnings_before_their_exception(): @pytest.mark.parametrize("where", ["probe", "start", "daemon"]) -def test_refits_stay_here_when_workers_cannot_start(monkeypatch, where): - """When this process's BLAS threads cannot be read (the probe fails), - the workers cannot be started (a broken pool, as from a script read - from standard input) or this process is daemonic (it may not have - children: no start is tried), the trials are refit here; a failed - start warns.""" +def test_refits_stay_here_when_workers_cannot_start( + monkeypatch: pytest.MonkeyPatch, where: str +) -> None: + """The trials are refit here when no worker can be used. + + This is so when this process's BLAS threads cannot be read (the probe + fails), the workers cannot be started (a broken pool, as from a script + read from standard input) or this process is daemonic (it may not have + children: no start is tried); a failed start warns. + """ from concurrent.futures.process import BrokenProcessPool starts = [] - def probe(): - """A probe that fails, or a readable thread count.""" + def probe() -> dict[str, int]: + """Return a readable thread count, or fail as a probe that fails. + + Returns + ------- + dict + The BLAS thread counts by library. + + Raises + ------ + OSError + If where is "probe". + """ if where == "probe": raise OSError("no") return {"lib": 2} - def start(*args, **kw): - """A start that fails.""" + def start(*args: object, **kw: object) -> NoReturn: + """Fail as a start that fails. + + Raises + ------ + BrokenProcessPool + Always. + """ starts.append(args) raise BrokenProcessPool("no") @@ -524,13 +623,15 @@ def start(*args, **kw): assert out.tobytes() == _refit(1, s)[0].tobytes() -def test_unguarded_script_runs_once(tmp_path): - """A script that refits with workers at its top level, outside - ``if __name__ == "__main__":``, runs once: its workers, which import - the script again, end at their own attempt to start workers instead - of refitting here and running the rest of the script (starts a Python - process, which starts 2 more). The script's process is told that its - workers could not be started and refits in itself.""" +def test_unguarded_script_runs_once(tmp_path: Path) -> None: + """A script that refits with workers at its top level runs once. + + The script refits outside if __name__ == "__main__":. Its workers, + which import the script again, end at their own attempt to start workers + instead of refitting here and running the rest of the script (starts a + Python process, which starts 2 more). The script's process is told that + its workers could not be started and refits in itself. + """ import subprocess import sys @@ -569,19 +670,32 @@ def test_unguarded_script_runs_once(tmp_path): assert done.read_text().splitlines() == ["(8, 2, 3) 1"] -def test_a_failed_refit_cancels_those_still_waiting(): - """When a refit fails in a worker, the refiner closes the iterator of - the round's refits (which cancels those still waiting) before the - error is raised.""" +def test_a_failed_refit_cancels_those_still_waiting() -> None: + """When a refit fails in a worker, the refiner closes the iterator of the round's refits. + + That cancels those still waiting, before the error is raised. + """ class Pool: - """A pool whose first refit fails; whether its iterator was - closed, and how many results were taken.""" + """A pool whose first refit fails. + + It records whether its iterator was closed, and how many results were + taken. + """ closed, taken = False, 0 - def map(self, func, tasks): - """The first result with an error, then results for ever.""" + def map( + self, func: Callable[..., object], tasks: Iterable[object] + ) -> Iterator[tuple[None, list, FloatingPointError | None]]: + """Yield the first result with an error, then results for ever. + + Yields + ------ + tuple + A result of a refit: nothing, no warnings and the error, which is + set only for the first. + """ try: yield None, [], FloatingPointError("first") while True: @@ -590,7 +704,7 @@ def map(self, func, tasks): finally: Pool.closed = True - def shutdown(self, *args, **kw): + def shutdown(self, *args: object, **kw: object) -> None: """Nothing to stop.""" r = alignment_mod._TrialRefiner(_SqrtLayout(), 2) @@ -601,12 +715,20 @@ def shutdown(self, *args, **kw): assert Pool.closed and Pool.taken == 0 -def test_refits_stay_here_when_numpy_calls_a_function(monkeypatch): - """Under ``np.errstate(invalid='call')`` no worker starts and the - function is called here; nor does one start under ``'print'``.""" +def test_refits_stay_here_when_numpy_calls_a_function(monkeypatch: pytest.MonkeyPatch) -> None: + """Under np.errstate(invalid='call') no worker starts and the function is called here. - def no_pool(*args, **kw): - """A pool must not start.""" + Nor does one start under 'print'. + """ + + def no_pool(*args: object, **kw: object) -> NoReturn: + """Fail because a pool must not start. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("a pool was started") monkeypatch.setattr(alignment_mod, "spawn_pool", no_pool) @@ -624,11 +746,12 @@ def no_pool(*args, **kw): assert r.pool is None and r.in_workers == 0 -def test_refit_workers_keep_numpy_errors_and_warnings(): - """Refits in workers raise under ``np.errstate(invalid='raise')`` as - here (and the workers end), and give their warnings here, at the same - places, through this process's filters (starts 2 processes, 3 - times).""" +def test_refit_workers_keep_numpy_errors_and_warnings() -> None: + """Refits in workers raise under np.errstate(invalid='raise') as here. + + The workers end, and give their warnings here, at the same places, + through this process's filters (starts 2 processes, 3 times). + """ _blas_count() s = np.arange(24.0).reshape(3, 2, 4) s[1, 0, 0] = -1.0 @@ -637,10 +760,7 @@ def test_refit_workers_keep_numpy_errors_and_warnings(): with warnings.catch_warnings(record=True) as got: warnings.simplefilter("always") out, r = _refit(workers, s) - caught[workers] = [ - (type(w.message), str(w.message), w.filename, w.lineno) - for w in got - ] + caught[workers] = [(type(w.message), str(w.message), w.filename, w.lineno) for w in got] if workers == 1: here = out assert r.in_workers == 3 @@ -658,8 +778,15 @@ def test_refit_workers_keep_numpy_errors_and_warnings(): def _no_children(seconds: float = 30.0) -> bool: - """Whether this process's children end within ``seconds`` (a stopped - pool's workers end by themselves once their refits have).""" + """Whether this process's children end within seconds. + + A stopped pool's workers end by themselves once their refits have. + + Returns + ------- + bool + True if this process has no child left within seconds. + """ import time deadline = time.monotonic() + seconds @@ -670,10 +797,12 @@ def _no_children(seconds: float = 30.0) -> bool: return False -def test_refit_workers_have_this_process_blas_threads(monkeypatch): - """The workers' BLAS has this process's thread count, whatever the - environment says; OpenBLAS's idle timeout is set in the workers only, - also when it was unset here (starts 2 processes).""" +def test_refit_workers_have_this_process_blas_threads(monkeypatch: pytest.MonkeyPatch) -> None: + """The workers' BLAS has this process's thread count, whatever the environment says. + + OpenBLAS's idle timeout is set in the workers only, also when it was + unset here (starts 2 processes). + """ from giant_python.parallel import BLAS_IDLE n = _blas_count() @@ -689,18 +818,26 @@ def test_refit_workers_have_this_process_blas_threads(monkeypatch): assert os.environ["OPENBLAS_NUM_THREADS"] == str(1 if n != 1 else 2) -@pytest.mark.parametrize( - "counts", [None, {"a": 2, "b": 3}, {"a": 999}], ids=str -) -def test_refits_stay_here_when_workers_cannot_match(monkeypatch, counts): - """No worker starts when this process's BLAS thread count cannot be - read or is not one number; workers whose count differs (999: more - than OpenBLAS takes) are stopped. The trials are then refit here - (999 starts 2 processes).""" +@pytest.mark.parametrize("counts", [None, {"a": 2, "b": 3}, {"a": 999}], ids=str) +def test_refits_stay_here_when_workers_cannot_match( + monkeypatch: pytest.MonkeyPatch, counts: dict[str, int] | None +) -> None: + """No worker starts when this process's BLAS thread count cannot be matched. + + It cannot be read or is not one number; workers whose count differs (999: + more than OpenBLAS takes) are stopped. The trials are then refit here + (999 starts 2 processes). + """ if counts is None or len(set(counts.values())) > 1: - def no_pool(*args, **kw): - """A pool must not start.""" + def no_pool(*args: object, **kw: object) -> NoReturn: + """Fail because a pool must not start. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("a pool was started") monkeypatch.setattr(alignment_mod, "spawn_pool", no_pool) diff --git a/tests/raster/test_raster_container.py b/tests/raster/test_raster_container.py index 52f49df1..f8ad707d 100644 --- a/tests/raster/test_raster_container.py +++ b/tests/raster/test_raster_container.py @@ -1,5 +1,8 @@ """Tests of the container: one trial-path's inputs of source extraction.""" +from pathlib import Path +from typing import NoReturn + import h5py import numpy as np import pytest @@ -20,11 +23,24 @@ SHAPE = (12, 15) # consensus frame -def make_trial(n_frames=40, seed=0): - """A small trial with two blobs of selected pixels and three sources. +def make_trial( + n_frames: int = 40, seed: int = 0 +) -> tuple[TrialData, np.ndarray, list[np.ndarray], list[np.ndarray], np.ndarray]: + """Build a small trial with two blobs of selected pixels and three sources. - Returns the trial, the sources and each subproblem's pixels and - sources: the two blobs' subproblems share the pixels of column 7. + Returns + ------- + trial : TrialData + The trial. + sources_rc : np.ndarray + The sources' [row, col] positions. + pixels : list of np.ndarray + The pixels (indices into the trial's selected pixels) of each subproblem. + sources : list of np.ndarray + The sources (indices into sources_rc) of each subproblem; the two + blobs' subproblems share the pixels of column 7. + sel : np.ndarray + The selected-pixel map of the consensus frame. """ rng = np.random.default_rng(seed) sel = np.zeros(SHAPE, dtype=bool) @@ -56,7 +72,7 @@ def make_trial(n_frames=40, seed=0): @pytest.mark.parametrize("compression", ["lzf", "gzip", None]) -def test_round_trip_is_exact(tmp_path, compression): +def test_round_trip_is_exact(tmp_path: Path, compression: str | None) -> None: """Everything written is read back unchanged, whole or by subproblem.""" trial, sources_rc, pixels, sources, sel = make_trial() params = {"loader": TrialLoadParams(), "lambda": 0.9, "k": np.arange(3.0)} @@ -120,9 +136,7 @@ def test_round_trip_is_exact(tmp_path, compression): ] assert not (sp.sel & ~box).any() # within the selected map cols, rows = np.nonzero(sp.sel.T) - np.testing.assert_array_equal( - np.stack([rows + sp.row0, cols + sp.col0], 1), rc - ) + np.testing.assert_array_equal(np.stack([rows + sp.row0, cols + sp.col0], 1), rc) np.testing.assert_array_equal( sp.sources_rc, sources_rc[sources[k]] - [sp.row0, sp.col0] ) @@ -136,12 +150,10 @@ def test_round_trip_is_exact(tmp_path, compression): assert f.attrs["format_version"] == FORMAT_VERSION -def test_baseline_is_reserved_and_can_be_filled(tmp_path): +def test_baseline_is_reserved_and_can_be_filled(tmp_path: Path) -> None: """The F0 network's baseline has empty, resizable datasets.""" trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container( - tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE - ) + path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) n_px = trial.y.shape[1] with h5py.File(path, "r+") as f: g = f["baseline"] @@ -162,7 +174,7 @@ def test_baseline_is_reserved_and_can_be_filled(tmp_path): ) -def test_settings_hash_ignores_key_order_only(): +def test_settings_hash_ignores_key_order_only() -> None: """The same settings hash alike however they are ordered or typed.""" a = {"lambda": 0.9, "loader": TrialLoadParams(), "k": np.array([1.0, 2.0])} b = { @@ -184,7 +196,7 @@ def test_settings_hash_ignores_key_order_only(): assert settings_hash({}) != settings_hash({"lambda": 0.9}) -def test_subproblem_lists_are_checked(tmp_path): +def test_subproblem_lists_are_checked(tmp_path: Path) -> None: """Index lists must match, increase and stay inside their lists.""" trial, sources_rc, pixels, sources, _ = make_trial() path = tmp_path / "trial.h5" @@ -207,9 +219,7 @@ def test_subproblem_lists_are_checked(tmp_path): # whole numbers held as floating point are indices as_float = [v.astype(np.float64) for v in pixels] write_container(path, trial, sources_rc, as_float, sources, SHAPE) - np.testing.assert_array_equal( - read_container(path, data=False).subproblem_pixels[1], pixels[1] - ) + np.testing.assert_array_equal(read_container(path, data=False).subproblem_pixels[1], pixels[1]) write_container(path, trial, sources_rc, pixels, sources, SHAPE) # the same indices are refused in memory and from the file whole = read_container(path) @@ -219,27 +229,23 @@ def test_subproblem_lists_are_checked(tmp_path): read_subproblem(source, k) -def test_empty_grouping_and_foreign_files(tmp_path): - """A container may hold no subproblems, or an empty one; other HDF5 - files and newer formats are refused.""" - trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container( - tmp_path / "none.h5", trial, sources_rc[:0], [], [], SHAPE - ) +def test_empty_grouping_and_foreign_files(tmp_path: Path) -> None: + """A container may hold no subproblems, or an empty one. + + Other HDF5 files and newer formats are refused. + """ + trial, sources_rc, pixels, _sources, _ = make_trial() + path = write_container(tmp_path / "none.h5", trial, sources_rc[:0], [], [], SHAPE) c = read_container(path) assert c.n_subproblems == 0 and c.crops.shape == (0, 4) assert c.sources_rc.shape == (0, 2) empty = [np.zeros(0, int), pixels[1]] - path = write_container( - tmp_path / "empty.h5", trial, sources_rc, empty, [[], [1, 2]], SHAPE - ) + path = write_container(tmp_path / "empty.h5", trial, sources_rc, empty, [[], [1, 2]], SHAPE) sp = read_subproblem(path, 0) assert sp.y.shape == (2, 0, trial.y.shape[2]) and sp.sel.shape == (0, 0) assert sp.sources_rc.shape == (0, 2) np.testing.assert_array_equal(crop_of(trial.pixel_rc[:0]), [0, 0, 0, 0]) - np.testing.assert_array_equal( - read_subproblem(path, 1).y, trial.y[:, pixels[1]] - ) + np.testing.assert_array_equal(read_subproblem(path, 1).y, trial.y[:, pixels[1]]) other = tmp_path / "other.h5" with h5py.File(other, "w") as f: f["data"] = np.arange(3) @@ -252,9 +258,11 @@ def test_empty_grouping_and_foreign_files(tmp_path): @pytest.mark.parametrize("compression", ["lzf", None]) -def test_trial_without_selected_pixels_round_trips(tmp_path, compression): - """A path without sources has no selected pixels: its container holds - the frames and traces, and empty data.""" +def test_trial_without_selected_pixels_round_trips(tmp_path: Path, compression: str | None) -> None: + """A path without sources has no selected pixels. + + Its container holds the frames and traces, and empty data. + """ full, *_ = make_trial() n_f = full.frame_lines.size trial = TrialData( @@ -292,18 +300,23 @@ def test_trial_without_selected_pixels_round_trips(tmp_path, compression): read_subproblem(path, 0) -def test_interrupted_write_leaves_the_old_container(tmp_path, monkeypatch): - """A failed write keeps an existing container and no partial file under - its name.""" +def test_interrupted_write_leaves_the_old_container( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed write keeps an existing container and no partial file under its name.""" trial, sources_rc, pixels, sources, _ = make_trial() - path = write_container( - tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE - ) + path = write_container(tmp_path / "trial.h5", trial, sources_rc, pixels, sources, SHAPE) before = path.read_bytes() from giant_python.extraction.raster import container - def fail(*args, **kwargs): - """Stand in for a failure late in the write.""" + def fail(*args: object, **kwargs: object) -> NoReturn: + """Stand in for a failure late in the write. + + Raises + ------ + OSError + Always. + """ raise OSError("disk full") monkeypatch.setattr(container, "_reserve_baseline", fail) diff --git a/tests/raster/test_raster_core_f0.py b/tests/raster/test_raster_core_f0.py index 152eabb5..2998e23c 100644 --- a/tests/raster/test_raster_core_f0.py +++ b/tests/raster/test_raster_core_f0.py @@ -1,14 +1,19 @@ -"""Tests of each source's core baseline (``f0_core``, GIAnT-Python#50): the -core and its baseline, their independence of the footprint's support, the -solver's output, results files, assembly and the summaries.""" +"""Test each source's core baseline (f0_core, GIAnT-Python#50). +The tests cover the core and its baseline, their independence of the footprint's support, the +solver's output, results files, assembly and the summaries. +""" + +from collections.abc import Callable from dataclasses import replace +from pathlib import Path import h5py import numpy as np import pytest from giant_python.extraction.raster.results import ( + TrialOutcome, TrialRecord, _same, read_results, @@ -18,6 +23,7 @@ ) from giant_python.extraction.raster.solver import ( SolverOptions, + SubproblemResult, assemble_results, solve_subproblem, ) @@ -31,26 +37,49 @@ from giant_python.io.experiment_summary import read_summary, write_summary from giant_python.models.params import SiloParams -from .test_raster_solver import PARAMS, _placed, _result -from .test_raster_solver import fixture # noqa: F401 (a pytest fixture) -from .test_raster_summary import C, FRAMES, N_TRIALS, alignment, make_plan +from .test_raster_solver import ( + PARAMS, + SubproblemFixture, + _placed, + _result, + fixture, # noqa: F401 (a pytest fixture) +) +from .test_raster_summary import FRAMES, N_TRIALS, C, alignment, make_plan from .test_raster_summary import outcome as summary_outcome -def _grid(n=9): - """Rows and columns of an n x n crop, in column-major order.""" +def _grid(n: int = 9) -> tuple[np.ndarray, np.ndarray]: + """Return the rows and columns of an n x n crop, in column-major order. + + Returns + ------- + rows : np.ndarray + Row index of each pixel. + cols : np.ndarray + Column index of each pixel. + """ return sel_coords(np.ones((n, n), bool)) -def _gaussian(rows, cols, centre, sigma): - """A Gaussian profile (peak 1) at the pixels.""" +def _gaussian( + rows: np.ndarray, cols: np.ndarray, centre: tuple[float, float], sigma: float +) -> np.ndarray: + """Return a Gaussian profile (peak 1) at the pixels. + + Returns + ------- + np.ndarray + The profile's value at each pixel. + """ d2 = (rows - centre[0]) ** 2 + (cols - centre[1]) ** 2 return np.exp(-d2 / (2 * sigma**2)) -def test_core_is_the_3x3_around_the_peak(): - """The core is the 3 x 3 around each footprint's peak pixel, cut by the - crop's edge; half 0 is the peak alone; a footprint of zeros has none.""" +def test_core_is_the_3x3_around_the_peak() -> None: + """The core is the 3 x 3 around each footprint's peak pixel. + + It is cut by the crop's edge; half 0 is the peak alone; a footprint of zeros has none. + """ rows, cols = _grid(5) h = np.zeros((25, 3)) h[:, 0] = _gaussian(rows, cols, (2, 2), 1.0) @@ -68,10 +97,12 @@ def test_core_is_the_3x3_around_the_peak(): core_mask(h, rows, cols, half=-1) -def test_core_baseline_values(): - """The baseline summed over the core over the footprint's share in it, - per frame; at half 0 the peak pixel's baseline over its weight; NaN for - a source without a footprint.""" +def test_core_baseline_values() -> None: + """The baseline summed over the core over the footprint's share in it. + + It is per frame; at half 0 the peak pixel's baseline over its weight; NaN for + a source without a footprint. + """ rows, cols = _grid(5) rng = np.random.default_rng(0) h = np.zeros((25, 2)) @@ -83,16 +114,16 @@ def test_core_baseline_values(): np.testing.assert_allclose(got[0], b[m].sum(0) / h[m, 0].sum()) assert np.isnan(got[1]).all() pk = (rows == 2) & (cols == 1) - np.testing.assert_allclose( - source_core_f0(h, b, rows, cols, half=0)[0], b[pk][0] / h[pk, 0] - ) + np.testing.assert_allclose(source_core_f0(h, b, rows, cols, half=0)[0], b[pk][0] / h[pk, 0]) -def test_core_dff_does_not_depend_on_the_support(): - """A source whose activity has a known profile, fitted with footprints - of that profile cut to supports of different size: the least-squares dF +def test_core_dff_does_not_depend_on_the_support() -> None: + """A source whose activity has a known profile is fitted with footprints of that profile. + + The footprints are cut to supports of different size: the least-squares dF over the core baseline is the same for every support (the core's dF/F), - while dF over the footprint-weighted F0 falls as the footprint widens.""" + while dF over the footprint-weighted F0 falls as the footprint widens. + """ n = 15 rows, cols = _grid(n) p = _gaussian(rows, cols, (7, 7), 1.6) # the activity's profile @@ -114,9 +145,8 @@ def test_core_dff_does_not_depend_on_the_support(): assert np.all(np.diff(weighted[:, 2]) < 0) # wider: lower -def test_solver_returns_the_core_baseline(fixture): # noqa: F811 - """The solver's core baseline is that of its final footprints and - baseline, per channel.""" +def test_solver_returns_the_core_baseline(fixture: SubproblemFixture) -> None: # noqa: F811 + """The solver's core baseline is that of its final footprints and baseline, per channel.""" sub, _ = fixture r = solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) n_ch, n_src, n_t = r.f0.shape @@ -132,13 +162,25 @@ def test_solver_returns_the_core_baseline(fixture): # noqa: F811 assert (np.nanmedian(r.f0_core[0], 1) < np.nanmedian(r.f0[0], 1)).all() -def _with_core(result, value): - """``result`` with a core baseline filled with ``value``.""" +def _with_core(result: SubproblemResult, value: float) -> SubproblemResult: + """Return result with a core baseline filled with value. + + Returns + ------- + SubproblemResult + A copy of the result with the core baseline set. + """ return replace(result, f0_core=np.full(result.f0.shape, float(value))) -def _record(n_t=6): - """A trial record of ``n_t`` frames.""" +def _record(n_t: int = 6) -> TrialRecord: + """Return a trial record of n_t frames. + + Returns + ------- + TrialRecord + The record. + """ return TrialRecord( frame_lines=np.arange(n_t) + 1, discard=np.zeros(n_t, bool), @@ -148,9 +190,11 @@ def _record(n_t=6): ) -def test_assembly_places_the_core_baseline(): - """Core baselines go to their sources in movie units; without one in - every subproblem the trial has none; a wrong shape is refused.""" +def test_assembly_places_the_core_baseline() -> None: + """Core baselines go to their sources in movie units. + + Without one in every subproblem the trial has none; a wrong shape is refused. + """ subs = [_placed([0, 1, 4], [2], 6), _placed([2, 3], [0, 3], 6)] a = _with_core(_result(3, 1, 6, 1.0), 7.0) b = _with_core(_result(2, 2, 6, 2.0), 9.0) @@ -159,35 +203,39 @@ def test_assembly_places_the_core_baseline(): np.testing.assert_allclose(t.f0_core[:, 2], 25.0 * 7.0) np.testing.assert_allclose(t.f0_core[:, [0, 3]], 25.0 * 9.0) assert np.isnan(t.f0_core[:, [1, 4]]).all() - t2 = assemble_results( - subs, [a, _result(2, 2, 6, 2.0)], 5, 5, photon_scale=25.0 - ) + t2 = assemble_results(subs, [a, _result(2, 2, 6, 2.0)], 5, 5, photon_scale=25.0) assert t2.f0_core is None bad = replace(b, f0_core=np.ones((2, 2, 5))) with pytest.raises(ValueError, match="f0_core"): assemble_results(subs, [a, bad], 5, 5, photon_scale=25.0) -def test_results_files_keep_the_core_baseline(tmp_path): - """The core baseline goes into the results file and back, reaches the - trial's activity, and the trial's sizes say whether it is there; a - result without one (older files) reads back without one.""" +def test_results_files_keep_the_core_baseline(tmp_path: Path) -> None: + """The core baseline goes into the results file and back, reaches the trial's activity. + + The trial's sizes say whether it is there; a + result without one (older files) reads back without one. + """ a = _with_core(_result(3, 1, 6, 1.0), 4.0) b = _result(3, 1, 6, 1.0) - attrs = dict( - n_subproblems=1, - n_pixels=3, - n_sources=1, - photon_scale=2.0, - container="c", - container_hash="h", - ) + attrs = { + "n_subproblems": 1, + "n_pixels": 3, + "n_sources": 1, + "photon_scale": 2.0, + "container": "c", + "container_hash": "h", + } pa = write_results( - tmp_path / "a.h5", _record(), {0: (np.arange(3), np.array([0]), a)}, + tmp_path / "a.h5", + _record(), + {0: (np.arange(3), np.array([0]), a)}, attrs, ) pb = write_results( - tmp_path / "b.h5", _record(), {0: (np.arange(3), np.array([0]), b)}, + tmp_path / "b.h5", + _record(), + {0: (np.arange(3), np.array([0]), b)}, attrs, ) back = read_results(pa).results[0] @@ -205,15 +253,27 @@ def test_results_files_keep_the_core_baseline(tmp_path): assert trial_outcome([read_results(pb)], PARAMS).activity.f0_core is None -def _core_outcome(t, n_px): - """The summary tests' trial outcome with a core baseline: F0 + 0.5.""" +def _core_outcome(t: int, n_px: int) -> TrialOutcome: + """Return the summary tests' trial outcome with a core baseline: F0 + 0.5. + + Returns + ------- + TrialOutcome + The trial outcome, with its activity's core baseline set. + """ out = summary_outcome(t, n_px) out.activity.f0_core = out.activity.f0 + 0.5 return out -def _path(trials): - """A path result of the summary tests' plan with the given trials.""" +def _path(trials: list[tuple[int, Callable[[int, int], TrialOutcome]]]) -> PathResult: + """Return a path result of the summary tests' plan with the given trials. + + Returns + ------- + PathResult + The path result. + """ plan = make_plan() return PathResult( plan=plan, @@ -222,10 +282,12 @@ def _path(trials): ) -def test_summaries_hold_the_core_baseline(tmp_path): - """``sources/temporal/F0_core`` beside ``F0``, in the same layout; NaN in - a trial whose results have none; read and written by the summary - codec; absent when no trial has one.""" +def test_summaries_hold_the_core_baseline(tmp_path: Path) -> None: + """``sources/temporal/F0_core`` is beside F0, in the same layout. + + It is NaN in a trial whose results have none; read and written by the summary + codec; absent when no trial has one. + """ params = SiloParams().to_matlab(C, 80.0) exp, per = tmp_path / "e.h5", tmp_path / "p.h5" result = _path([(1, _core_outcome), (2, summary_outcome)]) diff --git a/tests/raster/test_raster_f0_images.py b/tests/raster/test_raster_f0_images.py index a32c9397..0e0ae0ea 100644 --- a/tests/raster/test_raster_f0_images.py +++ b/tests/raster/test_raster_f0_images.py @@ -268,14 +268,14 @@ def __init__(self, results: dict, attrs: dict) -> None: self.attrs = attrs a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - attrs = dict( - n_subproblems=1, - n_pixels=3, - n_sources=1, - photon_scale=2.0, - container="c", - container_hash="h", - ) + attrs = { + "n_subproblems": 1, + "n_pixels": 3, + "n_sources": 1, + "photon_scale": 2.0, + "container": "c", + "container_hash": "h", + } out = trial_outcome( [File({0: (np.arange(3), np.array([0]), a)}, attrs)], replace(PARAMS), diff --git a/tests/raster/test_raster_kinetics.py b/tests/raster/test_raster_kinetics.py index 115a2cb4..46d5d711 100644 --- a/tests/raster/test_raster_kinetics.py +++ b/tests/raster/test_raster_kinetics.py @@ -1,9 +1,9 @@ """Tests of the kinetics test (sourceKinetics, rejectFastSources). -``data/matlab_kinetics.h5`` holds GIAnT-MATLAB's results (main 5a0673b, -MATLAB R2024b) on the inputs of ``data/make_matlab_kinetics.m`` (converted -by ``data/make_matlab_kinetics_h5.py``): rows with -and without runs of equal values for ``islocalmax``, and three trials of +data/matlab_kinetics.h5 holds GIAnT-MATLAB's results (main 5a0673b, +MATLAB R2024b) on the inputs of data/make_matlab_kinetics.m (converted +by data/make_matlab_kinetics_h5.py): rows with +and without runs of equal values for islocalmax, and three trials of ten sources (four with the sensor's kinetics, three with one-frame transients, three in between; discarded frames; a source without data in one trial; a trial without traces). @@ -26,22 +26,30 @@ @pytest.fixture(scope="module") -def ref(): - """MATLAB's inputs and results.""" +def ref() -> dict[str, np.ndarray]: + """Load MATLAB's inputs and results. + + Returns + ------- + dict + Each dataset of the reference file as an array, by name. + """ with h5py.File(DATA, "r") as f: return {k: f[k][()] for k in f} -def test_islocalmax_matches_matlab(ref): +def test_islocalmax_matches_matlab(ref: dict[str, np.ndarray]) -> None: """Maxima, runs of equal values and MinSeparation as MATLAB's.""" for i, sep in enumerate(ref["seps"]): got = islocalmax(ref["Y"], sep) np.testing.assert_array_equal(got, ref["M"][i].astype(bool)) -def test_islocalmax_rules(): - """Ends are never maxima; a run's centre is marked; a closer, more - prominent maximum replaces the last one kept.""" +def test_islocalmax_rules() -> None: + """Ends are never maxima; a run's centre is marked. + + A closer, more prominent maximum replaces the last one kept. + """ y = np.array([5.0, 1, 3, 3, 3, 3, 1, 0, 4, 0, 2, 9]) assert np.flatnonzero(islocalmax(y)).tolist() == [3, 8] # 3 (run 2..5) and 8 are 3 apart from the run's end; 8 is more prominent @@ -52,7 +60,7 @@ def test_islocalmax_rules(): np.testing.assert_array_equal(islocalmax(two)[1], islocalmax(y[::-1])) -def test_kinetics_scores_match_matlab(ref): +def test_kinetics_scores_match_matlab(ref: dict[str, np.ndarray]) -> None: """Scores and event counts of sourceKinetics; the sources kept.""" traces = list(ref["LS"]) + [None] score, n_events = source_kinetics(traces, 0.024, 200.0) @@ -64,30 +72,26 @@ def test_kinetics_scores_match_matlab(ref): np.testing.assert_array_equal(test.rejected, np.flatnonzero(~test.keep)) -def test_movmean_omitnan(): +def test_movmean_omitnan() -> None: """Window placement of MATLAB's movmean (even and odd), NaN left out.""" x = np.array([[1.0, np.nan, 3, 4, 5, 6]]) - np.testing.assert_allclose( - movmean_omitnan(x, 3)[0], [1, 2, 3.5, 4, 5, 5.5] - ) + np.testing.assert_allclose(movmean_omitnan(x, 3)[0], [1, 2, 3.5, 4, 5, 5.5]) # even window: two before, one after - np.testing.assert_allclose( - movmean_omitnan(x, 4)[0], [1, 2, 8 / 3, 4, 4.5, 5] - ) + np.testing.assert_allclose(movmean_omitnan(x, 4)[0], [1, 2, 8 / 3, 4, 4.5, 5]) assert np.isnan(movmean_omitnan(np.full((1, 4), np.nan), 3)).all() -def test_source_minutes(ref): - """Minutes of each source's frames that were not discarded, over the - trials with traces; the rate the evidence test compares.""" +def test_source_minutes(ref: dict[str, np.ndarray]) -> None: + """Minutes of each source's frames that were not discarded. + + Over the trials with traces; the rate the evidence test compares. + """ from giant_python.extraction.raster.kinetics import ( source_minutes, weak_sources, ) - np.testing.assert_allclose( - source_minutes([np.zeros((2, 1200)), None], 2, 200.0), [0.1, 0.1] - ) + np.testing.assert_allclose(source_minutes([np.zeros((2, 1200)), None], 2, 200.0), [0.1, 0.1]) traces = [np.array(t, dtype=np.float64) for t in ref["LS"]] n = traces[0].shape[0] expect = source_minutes(traces, n, 200.0) @@ -99,15 +103,13 @@ def test_source_minutes(ref): _, n_events = source_kinetics(traces, 0.024, 200.0) rate = n_events / minutes cut = float(np.median(rate)) - np.testing.assert_array_equal( - weak_sources(np.ones(n), rate, min_event_rate=cut), rate < cut - ) + np.testing.assert_array_equal(weak_sources(np.ones(n), rate, min_event_rate=cut), rate < cut) # a recording twice as long with the same events has half the rate twice = source_minutes(traces + traces, n, 200.0) np.testing.assert_allclose(twice, 2 * minutes) -def test_kinetics_edge_cases(): +def test_kinetics_edge_cases() -> None: """No traces, a short time constant and threshold 0 keep everything.""" score, n = source_kinetics([None], 0.024, 200.0) assert score.size == 0 and n.size == 0 @@ -121,29 +123,21 @@ def test_kinetics_edge_cases(): assert test.keep.all() -def test_weak_sources_and_mean_snr(): +def test_weak_sources_and_mean_snr() -> None: """The evidence test's criteria, each off at 0.""" from giant_python.extraction.raster.kinetics import ( mean_snr, weak_sources, ) - snr = mean_snr( - [np.array([1.0, np.nan, 3.0]), None, np.array([3.0, np.nan, 5.0])], 3 - ) + snr = mean_snr([np.array([1.0, np.nan, 3.0]), None, np.array([3.0, np.nan, 5.0])], 3) np.testing.assert_allclose(snr, [2.0, np.nan, 4.0]) # only NaN is left out, as the summary's mean SNR assert mean_snr([np.array([1.0]), np.array([np.inf])], 1)[0] == np.inf rates = np.array([0.0, 9.0, 2.0]) - np.testing.assert_array_equal( - weak_sources(snr, rates), [False, False, False] - ) - np.testing.assert_array_equal( - weak_sources(snr, rates, min_snr=3.0), [True, False, False] - ) - np.testing.assert_array_equal( - weak_sources(snr, rates, min_event_rate=3.0), [True, False, True] - ) + np.testing.assert_array_equal(weak_sources(snr, rates), [False, False, False]) + np.testing.assert_array_equal(weak_sources(snr, rates, min_snr=3.0), [True, False, False]) + np.testing.assert_array_equal(weak_sources(snr, rates, min_event_rate=3.0), [True, False, True]) # a source without a rate (no valid frame) is not judged by it np.testing.assert_array_equal( weak_sources(snr, [np.nan, 9.0, 2.0], min_event_rate=3.0), @@ -155,13 +149,27 @@ def test_weak_sources_and_mean_snr(): weak_sources(snr, rates, min_snr=-1.0) -def test_plateaus_are_the_loop(): - """The maxima's runs (vectorized) are those of the loop over runs, on - rows with many runs of equal values.""" +def test_plateaus_are_the_loop() -> None: + """The maxima's runs (vectorized) are those of the loop over runs. + + On rows with many runs of equal values. + """ from giant_python.extraction.raster.kinetics import _plateaus - def loop(y): - """The loop over runs of equal values.""" + def loop(y: np.ndarray) -> list[tuple[int, int, int]]: + """Run the loop over runs of equal values. + + Parameters + ---------- + y : np.ndarray + One row of values. + + Returns + ------- + list + (start, end, centre) of each run of equal values that is higher than both + neighbours. + """ n = y.size if n < 3: return [] diff --git a/tests/raster/test_raster_localization.py b/tests/raster/test_raster_localization.py index bf7e9415..fe3bf23f 100644 --- a/tests/raster/test_raster_localization.py +++ b/tests/raster/test_raster_localization.py @@ -19,10 +19,22 @@ FIXTURE = Path(__file__).parent / "data" / "matlab_localization.h5" -def _fixture(): - """The synthetic trial and GIAnT-MATLAB's results on it. +def _fixture() -> tuple[np.ndarray, np.ndarray, np.ndarray, dict]: + """Return the synthetic trial and GIAnT-MATLAB's results on it. HDF5 holds MATLAB's (rows, cols, frames) arrays as (frames, cols, rows). + + Returns + ------- + movie : np.ndarray + The synthetic movie, (frames, cols, rows). + vf : np.ndarray + Its variance factor, same shape. + base : np.ndarray + Its baseline, same shape. + ref : dict + MATLAB's results, by kind (movmedian or external): the + activity image, the summary and the seeds at each threshold. """ with h5py.File(FIXTURE, "r") as f: movie = f["movie"][()].transpose(0, 2, 1) @@ -31,29 +43,30 @@ def _fixture(): ref = {} for kind in ("movmedian", "external"): g = f["matlab"][kind] - ref[kind] = dict( - act_im=g["act_im"][()].T, - summary=g["summary"][()].T, - peaks={ - th: np.atleast_2d(g[f"peaks_{th}"][()].T) - for th in (3, 5, 8) - }, - ) + ref[kind] = { + "act_im": g["act_im"][()].T, + "summary": g["summary"][()].T, + "peaks": {th: np.atleast_2d(g[f"peaks_{th}"][()].T) for th in (3, 5, 8)}, + } return movie, vf, base, ref -def _seed_offsets(py, ml): - """Distance from each MATLAB seed (1-based) to the nearest Python seed.""" +def _seed_offsets(py: np.ndarray, ml: np.ndarray) -> np.ndarray: + """Return the distance from each MATLAB seed (1-based) to the nearest Python seed. + + Returns + ------- + np.ndarray + The distances, one per MATLAB seed (empty if either set is empty). + """ if ml.size == 0 or py.size == 0: return np.array([]) - d = np.hypot( - ml[:, 1:2] - 1 - py[None, :, 1], ml[:, 2:3] - 1 - py[None, :, 2] - ) + d = np.hypot(ml[:, 1:2] - 1 - py[None, :, 1], ml[:, 2:3] - 1 - py[None, :, 2]) return d.min(1) @pytest.mark.parametrize("kind", ["movmedian", "external"]) -def test_matches_matlab(kind): +def test_matches_matlab(kind: str) -> None: """Activity image, summary and seeds agree with GIAnT-MATLAB.""" movie, vf, base, ref = _fixture() r = localize_sources( @@ -79,7 +92,7 @@ def test_matches_matlab(kind): assert np.mean(_seed_offsets(py, ml) < 0.1) >= 0.9 -def test_peak_port_on_matlab_summary(): +def test_peak_port_on_matlab_summary() -> None: """Seeds from MATLAB's own summary image agree with MATLAB's seeds.""" from giant_python.extraction.raster.peaks import get_act_im_peaks @@ -92,21 +105,17 @@ def test_peak_port_on_matlab_summary(): assert np.mean(_seed_offsets(py, ml) < 0.25) >= near -def test_moving_windows_match_matlab(): - """smoothdata movmean/movmedian with 'omitnan' and an even window.""" +def test_moving_windows_match_matlab() -> None: + """``smoothdata`` movmean/movmedian with 'omitnan' and an even window.""" x = np.array([1, np.nan, 3, 4, np.nan, 6, 7, 8, 9, 10], np.float32) mean = movmean_nan(x[:, None], 4).ravel() med = movmedian_nan(x[:, None], 4).ravel() - np.testing.assert_allclose( - mean, [1, 2, 8 / 3, 3.5, 13 / 3, 17 / 3, 7, 7.5, 8.5, 9], rtol=1e-6 - ) + np.testing.assert_allclose(mean, [1, 2, 8 / 3, 3.5, 13 / 3, 17 / 3, 7, 7.5, 8.5, 9], rtol=1e-6) np.testing.assert_allclose(med, [1, 2, 3, 3.5, 4, 6, 7, 7.5, 8.5, 9]) - assert matlab_prctile(np.array([3, 1, 4, 1, 5, 9, 2, 6.0]), 90) == ( - pytest.approx(8.1) - ) + assert matlab_prctile(np.array([3, 1, 4, 1, 5, 9, 2, 6.0]), 90) == (pytest.approx(8.1)) -def test_no_surround_is_the_gaussian_alone(): +def test_no_surround_is_the_gaussian_alone() -> None: """surround=False: the spatial filter is the Gaussian, without the DoG.""" rng = np.random.default_rng(0) z = rng.standard_normal((40, 30, 32)).astype(np.float32) @@ -132,7 +141,7 @@ def test_no_surround_is_the_gaussian_alone(): np.testing.assert_allclose(sk, want, rtol=1e-5, atol=1e-9) -def test_soft_threshold_ignores_noise_maxima(): +def test_soft_threshold_ignores_noise_maxima() -> None: """Maxima below soft_th add nothing; a strong event still scores.""" rng = np.random.default_rng(1) z = rng.standard_normal((300, 24, 24)).astype(np.float32) @@ -147,7 +156,7 @@ def test_soft_threshold_ignores_noise_maxima(): assert np.unravel_index(np.argmax(sk_ev), sk_ev.shape) == (12, 12) -def test_params_validation(): +def test_params_validation() -> None: """Unknown option values are rejected.""" with pytest.raises(ValueError): RasterLocalizationParams(null="signflip") @@ -163,41 +172,49 @@ def test_params_validation(): RasterLocalizationParams(soft_th=-1) -def test_external_baseline_shape_checked(): +def test_external_baseline_shape_checked() -> None: """An external baseline must have the movie's shape.""" movie = np.ones((50, 10, 10), np.float32) with pytest.raises(ValueError): localize_sources(movie, None, baseline=np.ones((50, 10, 9))) -def test_var_factor_shape_checked(): - """The variance factor must have the movie's shape: a transposed one - of the same size, or a single frame, is rejected rather than reshaped.""" +def test_var_factor_shape_checked() -> None: + """The variance factor must have the movie's shape. + + A transposed one of the same size, or a single frame, is rejected rather + than reshaped. + """ movie = np.ones((50, 10, 12), np.float32) for vf in (np.ones((50, 12, 10)), np.ones((10, 12))): with pytest.raises(ValueError, match="var_factor"): localize_sources(movie, vf) -def test_no_variance_floor_needs_an_external_baseline(): - """Without the floor, the moving median's low bias at low counts would - blow up dim pixels' Z-scores, so an external baseline is required.""" +def test_no_variance_floor_needs_an_external_baseline() -> None: + """Without the floor, an external baseline is required. + + The moving median's low bias at low counts would blow up dim pixels' + Z-scores. + """ movie = np.ones((50, 10, 10), np.float32) p = RasterLocalizationParams(variance_floor=False) with pytest.raises(ValueError, match="external baseline"): localize_sources(movie, None, p) -def test_moving_mean_keeps_precision_on_long_recordings(): +def test_moving_mean_keeps_precision_on_long_recordings() -> None: """Prefix sums in float64: no drift over a long float32 recording.""" x = np.full((24000, 2), 1.1, np.float32) out = movmean_nan(x, 8) np.testing.assert_allclose(out[-50:], np.float32(1.1), rtol=1e-6) -def test_no_floor_with_a_uniform_external_baseline(): - """A spatially uniform baseline (no pixel above the 90th percentile of - brightness) still gives a finite activity image without the floor.""" +def test_no_floor_with_a_uniform_external_baseline() -> None: + """A spatially uniform baseline still gives a finite activity image without the floor. + + That is, no pixel is above the 90th percentile of brightness. + """ rng = np.random.default_rng(3) base = np.full((600, 20, 20), 9.0, np.float32) movie = (base + 3 * rng.standard_normal(base.shape)).astype(np.float32) @@ -207,9 +224,11 @@ def test_no_floor_with_a_uniform_external_baseline(): assert loc.info["Vk"] > 0 -def test_no_valid_pixels_keeps_find_peaks_false(): - """The early return for a trial without valid pixels honours - ``find_peaks``: peaks are None when seeding was not requested.""" +def test_no_valid_pixels_keeps_find_peaks_false() -> None: + """The early return for a trial without valid pixels honours find_peaks. + + Peaks are None when seeding was not requested. + """ movie = np.full((50, 10, 10), np.nan, np.float32) with pytest.warns(UserWarning): loc = localize_sources(movie, find_peaks=False) @@ -218,9 +237,11 @@ def test_no_valid_pixels_keeps_find_peaks_false(): assert localize_sources(movie).peaks.shape == (0, 4) -def test_pixels_mostly_missing_leave_the_variance_model(): - """As MATLAB (``varIM(nanFrac > 0.4) = nan``): valid pixels missing - more than 40% of frames do not change Vb.""" +def test_pixels_mostly_missing_leave_the_variance_model() -> None: + """As MATLAB (varIM(nanFrac > 0.4) = nan). + + Valid pixels missing more than 40% of frames do not change Vb. + """ rng = np.random.default_rng(5) t = 600 movie = (20 + 3 * rng.standard_normal((t, 20, 20))).astype(np.float32) @@ -238,9 +259,12 @@ def test_pixels_mostly_missing_leave_the_variance_model(): assert vb[0] == vb[1] -def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): - """Network baseline_sd whitens heteroscedastic noise and modulates by - sqrt(vf_t / mean_t(vf)), with or without the floor and bootstrap null.""" +def test_localize_sources_uses_network_sd_and_scales_by_var_factor() -> None: + """Network baseline_sd whitens heteroscedastic noise. + + It modulates by sqrt(vf_t / mean_t(vf)), with or without the floor and + bootstrap null. + """ rng = np.random.default_rng(11) n_t, h, w = 600, 20, 24 base = np.full((n_t, h, w), 30.0, np.float32) @@ -252,9 +276,7 @@ def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): movie[300:304, 10, 18] += 25.0 p_sd = RasterLocalizationParams(surround=False, variance_floor=False) - p_mod = RasterLocalizationParams( - surround=False, variance_floor=False, use_baseline_sd=False - ) + p_mod = RasterLocalizationParams(surround=False, variance_floor=False, use_baseline_sd=False) loc_sd = localize_sources(movie, None, p_sd, base, sd, find_peaks=False) loc_mod = localize_sources(movie, None, p_mod, base, sd, find_peaks=False) assert loc_sd.info["sd_source"] == "network" @@ -269,32 +291,24 @@ def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): # temporal burst of var_factor downweights noisy frames. vf_spatial = np.ones_like(movie) vf_spatial[:, :10, :] = 3.0 - loc_sp = localize_sources( - movie, vf_spatial, p_sd, base, sd, find_peaks=False - ) + loc_sp = localize_sources(movie, vf_spatial, p_sd, base, sd, find_peaks=False) np.testing.assert_allclose(loc_sp.act_im, loc_sd.act_im, rtol=1e-5) # Single-frame sampling spike on an isolated 1-frame artifact: unsmoothed # vf_raw suppresses that frame immediately, unlike smoothed vf. one_frame = movie.copy() one_frame[100, 4:7, 4:7] += 35.0 - loc_spike_plain = localize_sources( - one_frame, None, p_sd, base, sd, find_peaks=False - ) + loc_spike_plain = localize_sources(one_frame, None, p_sd, base, sd, find_peaks=False) vf_burst = np.ones_like(movie) vf_burst[100] = 25.0 # single-frame sampling spike (unsmoothed vf_raw) - loc_burst = localize_sources( - one_frame, vf_burst, p_sd, base, sd, find_peaks=False - ) + loc_burst = localize_sources(one_frame, vf_burst, p_sd, base, sd, find_peaks=False) assert loc_burst.act_im[5, 5] < 0.25 * loc_spike_plain.act_im[5, 5] # Bootstrap null uses spatially varying net_var (no 25x null distortion), # including zero-baseline regions with positive network uncertainty. base_z = base.copy() base_z[:, :4, :6] = 0.0 - movie_z = (base_z + sd * rng.standard_normal(base.shape)).astype( - np.float32 - ) + movie_z = (base_z + sd * rng.standard_normal(base.shape)).astype(np.float32) movie_z[200:204, 10, 5] += 18.0 movie_z[300:304, 10, 18] += 25.0 p_boot_nf = RasterLocalizationParams( @@ -304,9 +318,7 @@ def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): null_draws=2, null_seed=0, ) - loc_boot_nf = localize_sources( - movie_z, None, p_boot_nf, base_z, sd, find_peaks=False - ) + loc_boot_nf = localize_sources(movie_z, None, p_boot_nf, base_z, sd, find_peaks=False) assert loc_boot_nf.act_im[10, 5] > loc_boot_nf.act_im[10, 18] assert np.isfinite(loc_boot_nf.act_im[loc_boot_nf.valid]).all() @@ -318,9 +330,7 @@ def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): null_draws=1, null_seed=0, ) - loc_boot = localize_sources( - movie, None, p_boot, base, sd, find_peaks=False - ) + loc_boot = localize_sources(movie, None, p_boot, base, sd, find_peaks=False) assert loc_boot.info["Vb_sd"] > 0 assert np.isfinite(loc_boot.act_im[loc_boot.valid]).all() @@ -330,9 +340,12 @@ def test_localize_sources_uses_network_sd_and_scales_by_var_factor(): localize_sources(movie, None, p_sd, base, sd[:10]) -def test_zero_baseline_additive_null_calibration(): - """Zero-baseline regions with positive network SD draw additive Gaussian - noise in null_movie and calibrate to median ~0, 99.5% tail ~2.576.""" +def test_zero_baseline_additive_null_calibration() -> None: + """Zero-baseline regions with positive network SD draw additive Gaussian noise. + + The noise is drawn in null_movie and calibrates to median ~0, 99.5% tail + ~2.576. + """ from giant_python.extraction.raster.null import ( null_movie, spatial_kernel, @@ -342,14 +355,14 @@ def test_zero_baseline_additive_null_calibration(): # 1. Exact null_movie check on Copilot's scenario: SD=2, gain=4/30, b=0 n_t, h, w = 600, 6, 8 n_px = h * w - noise = dict( - gain=4.0 / 30.0, - kt=temporal_kernel(0.0, 0.0), - kr=spatial_kernel(0.0), - kc=spatial_kernel(0.0), - W2=1.0, - q=1.0, - ) + noise = { + "gain": 4.0 / 30.0, + "kt": temporal_kernel(0.0, 0.0), + "kr": spatial_kernel(0.0), + "kc": spatial_kernel(0.0), + "W2": 1.0, + "q": 1.0, + } z0 = null_movie( np.zeros((n_t, n_px), np.float32), np.ones((n_t, n_px), np.float32), @@ -366,13 +379,13 @@ def test_zero_baseline_additive_null_calibration(): # 2. Calibration inside a zero-baseline region next to dim shot noise n_t2, rows, cols, gain = 1500, 44, 72, 8.0 - corr_noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + corr_noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } corr_noise["W2"] = float( (corr_noise["kt"] ** 2).sum() * (corr_noise["kr"] ** 2).sum() @@ -380,9 +393,7 @@ def test_zero_baseline_additive_null_calibration(): ) base = np.full((n_t2, rows, cols), 0.2 * gain, dtype=np.float32) base[:, :, :30] = 0.0 # nonpositive-baseline region - sd = np.where(base > 0, np.sqrt(gain * base), np.float32(2.0)).astype( - np.float32 - ) + sd = np.where(base > 0, np.sqrt(gain * base), np.float32(2.0)).astype(np.float32) flat_b = base.reshape(n_t2, -1) ones = np.ones_like(flat_b) movie = base + null_movie( @@ -432,9 +443,7 @@ def test_zero_baseline_additive_null_calibration(): null_draws=2, null_seed=23, ) - loc_f = localize_sources( - movie_f, None, p_floor, base_f, sd_f, find_peaks=False - ) + loc_f = localize_sources(movie_f, None, p_floor, base_f, sd_f, find_peaks=False) for sl in (slice(3, 33), slice(39, cols - 3)): reg = loc_f.act_im[3:-3, sl].ravel() med_r = float(np.median(reg)) @@ -447,9 +456,7 @@ def test_zero_baseline_additive_null_calibration(): al_imb = np.concatenate([np.full(9000, 0.4), np.full(1000, 0.7)]) b_imb, n_imb = _alpha_bands(al_imb, draws=1) - assert ( - n_imb == 2 and (b_imb[:9000] == 0).all() and (b_imb[9000:] == 1).all() - ) + assert n_imb == 2 and (b_imb[:9000] == 0).all() and (b_imb[9000:] == 1).all() p_soft = RasterLocalizationParams( surround=False, variance_floor=True, @@ -462,9 +469,7 @@ def test_zero_baseline_additive_null_calibration(): rows_s, cols_s = 104, 108 # ~90% low-SD plateau, ~10% high-SD plateau base_s = np.full((600, rows_s, cols_s), 30.0, dtype=np.float32) sd_s = np.full((600, rows_s, cols_s), 2.0, dtype=np.float32) - sd_s[:, :, 92:] = ( - 4.5 # ~15% columns -> ~12% interior pixels (> 500 null vals) - ) + sd_s[:, :, 92:] = 4.5 # ~15% columns -> ~12% interior pixels (> 500 null vals) ones_s = np.ones((600, rows_s * cols_s), dtype=np.float32) movie_s = base_s + null_movie( base_s.reshape(600, -1), @@ -476,9 +481,7 @@ def test_zero_baseline_additive_null_calibration(): seed=31, noise_var=(sd_s.reshape(600, -1) ** 2), ) - loc_s = localize_sources( - movie_s, None, p_soft, base_s, sd_s, find_peaks=False - ) + loc_s = localize_sources(movie_s, None, p_soft, base_s, sd_s, find_peaks=False) for sl in (slice(3, 88), slice(95, cols_s - 3)): reg = loc_s.act_im[3:-3, sl].ravel() med_r = float(np.median(reg)) @@ -487,9 +490,23 @@ def test_zero_baseline_additive_null_calibration(): assert 0.65 * 2.576 < tail_r < 1.35 * 2.576 -def _sparse_scene(seed, rows=150, cols=170, n=120): - """A Z-scored movie on a few thin ROIs far apart (one at the frame's - border), with samples and whole frames missing: (dense, nans, valid).""" +def _sparse_scene( + seed: int, rows: int = 150, cols: int = 170, n: int = 120 +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return a Z-scored movie on a few thin ROIs far apart. + + One of them is at the frame's border, with samples and whole frames + missing. + + Returns + ------- + dense : np.ndarray + The movie, (frames, rows, cols), NaN where missing. + nans : np.ndarray + Boolean mask of the missing samples, same shape. + valid : np.ndarray + Boolean mask of the ROI pixels, (rows, cols). + """ rng = np.random.default_rng(seed) valid = np.zeros((rows, cols), bool) valid[0:6, 0:40] = True # at the border @@ -505,9 +522,11 @@ def _sparse_scene(seed, rows=150, cols=170, n=120): @pytest.mark.parametrize("surround", [True, False]) -def test_tiled_score_equals_the_whole_frame_score(surround): - """The score on rectangles around the valid pixels is the score on the - whole frame, bit for bit, whatever the tiling.""" +def test_tiled_score_equals_the_whole_frame_score(surround: bool) -> None: + """The score on rectangles around the valid pixels is the score on the whole frame. + + It is so bit for bit, whatever the tiling. + """ from giant_python.extraction.raster import localization as loc p = RasterLocalizationParams(surround=surround) @@ -538,13 +557,15 @@ def test_tiled_score_equals_the_whole_frame_score(surround): @pytest.mark.parametrize("size", [3, 5]) -def test_nanmedfilt2_is_the_median_of_every_window(size): - """Sorting only the windows that hold a value gives, bit for bit, the - NaN-median of every window (the form it replaces): on mostly-NaN +def test_nanmedfilt2_is_the_median_of_every_window(size: int) -> None: + """Sorting only the windows that hold a value gives the NaN-median of every window. + + It does so bit for bit (the form it replaces): on mostly-NaN images with imaged islands, values at the border, infinite values (also +inf next to -inf, whose median is NaN), NaN of other bit patterns, an image without values and one without NaN, and images - smaller than the window. Neither form warns.""" + smaller than the window. Neither form warns. + """ import struct import warnings @@ -552,13 +573,17 @@ def test_nanmedfilt2_is_the_median_of_every_window(size): from giant_python.extraction.raster.localization import nanmedfilt2 - def every_window(a): - """The NaN-median of each pixel's window, all of them.""" + def every_window(a: np.ndarray) -> np.ndarray: + """Return the NaN-median of each pixel's window, all of them. + + Returns + ------- + np.ndarray + The medians, the shape of a. + """ m = (size - 1) // 2 padded = np.pad(np.asarray(a, np.float64), m, constant_values=np.nan) - win = sliding_window_view(padded, (size, size)).reshape( - a.shape + (size * size,) - ) + win = sliding_window_view(padded, (size, size)).reshape(a.shape + (size * size,)) with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) return np.nanmedian(win, axis=-1) @@ -574,9 +599,7 @@ def every_window(a): with_inf[8, 15], with_inf[53, 4] = np.inf, -np.inf other_nan = islands.copy() # NaN as 0/0 gives it, and one with a payload other_nan[30, 60] = struct.unpack("d", struct.pack("Q", 0xFFF8 << 48))[0] - other_nan[6, 12] = struct.unpack( - "d", struct.pack("Q", (0x7FF8 << 48) + 1) - )[0] + other_nan[6, 12] = struct.unpack("d", struct.pack("Q", (0x7FF8 << 48) + 1))[0] other_nan[45:48, 70:75] = other_nan[30, 60] cases = [ islands, @@ -603,9 +626,11 @@ def every_window(a): "size", [0, 2, 4, -3, 5.0, True, np.True_, "5", None, np.timedelta64(5, "D")], ) -def test_nanmedfilt2_wants_an_odd_window(size): - """A window that has no centre pixel is refused whatever the image - holds (the form it replaces raised ValueError for even sizes too).""" +def test_nanmedfilt2_wants_an_odd_window(size: object) -> None: + """A window that has no centre pixel is refused whatever the image holds. + + The form it replaces raised ValueError for even sizes too. + """ from giant_python.extraction.raster.localization import nanmedfilt2 for a in (np.full((3, 3), np.nan), np.eye(3)): @@ -613,11 +638,13 @@ def test_nanmedfilt2_wants_an_odd_window(size): nanmedfilt2(a, size) -def test_nanmedfilt2_checks_its_arguments_before_the_image(): - """A window side given as a numpy integer of any width or as a 0-d - integer array is used as a Python int (13 * 13 does not fit an int8), +def test_nanmedfilt2_checks_its_arguments_before_the_image() -> None: + """A window side given as a numpy integer of any width is used as a Python int. + + The same holds for a 0-d integer array (13 * 13 does not fit an int8), and an array that is not an image is refused whether or not it holds - a value.""" + a value. + """ from giant_python.extraction.raster.localization import nanmedfilt2 a = np.arange(6.0).reshape(2, 3) diff --git a/tests/raster/test_raster_null.py b/tests/raster/test_raster_null.py index 7d3aad3b..b47c5e60 100644 --- a/tests/raster/test_raster_null.py +++ b/tests/raster/test_raster_null.py @@ -1,5 +1,7 @@ """Tests of the bootstrap null of the raster SiLo activity image.""" +from collections.abc import Callable + import numpy as np import pytest @@ -18,27 +20,44 @@ def _gradient_movie( - rng, t=1500, rows=40, cols=90, gain=8.0, margin=0, photons=None -): - """Pure photon noise with brightness 0.03-30 photons across the columns - (or the given photons per column), filtered as image formation does - (correlations in time and space); with a margin of unimaged (NaN) pixels - around it, as SLAP2 frames have.""" + rng: np.random.Generator, + t: int = 1500, + rows: int = 40, + cols: int = 90, + gain: float = 8.0, + margin: int = 0, + photons: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray, dict, np.ndarray]: + """Build pure photon noise with brightness 0.03-30 photons across the columns. + + The brightness is that, or the given photons per column. The noise is + filtered as image formation does (correlations in time and space); with a + margin of unimaged (NaN) pixels around it, as SLAP2 frames have. + + Returns + ------- + movie : np.ndarray + The movie (float32), (t, rows, cols) plus the margin. + base : np.ndarray + The baseline the movie was drawn with, shaped like movie. + noise : dict + The noise model it was drawn with. + photons : np.ndarray + The photons per column. + """ if photons is None: photons = np.exp(np.linspace(np.log(0.03), np.log(30), cols)) b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } noise["W2"] = float( - (noise["kt"] ** 2).sum() - * (noise["kr"] ** 2).sum() - * (noise["kc"] ** 2).sum() + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() ) vidx = np.arange(rows * cols) nans = np.zeros((t, rows, cols), bool) @@ -53,7 +72,7 @@ def _gradient_movie( return movie.astype(np.float32), base, noise, photons -def test_kernels_give_the_correlations(): +def test_kernels_give_the_correlations() -> None: """The fitted kernels' autocorrelations are the requested ones.""" k = temporal_kernel(0.6, 0.25) ac = np.correlate(k, k, "full")[k.size - 1 :] / (k**2).sum() @@ -63,7 +82,7 @@ def test_kernels_give_the_correlations(): assert np.isclose(k.sum(), 1) and np.isclose(s.sum(), 1) -def test_noise_model_recovers_gain_and_correlations(): +def test_noise_model_recovers_gain_and_correlations() -> None: """A null movie's measured model is the model it was drawn with.""" rng = np.random.default_rng(0) movie, base, noise, _ = _gradient_movie(rng) @@ -81,7 +100,7 @@ def test_noise_model_recovers_gain_and_correlations(): assert 1.0 <= m["q"] < 1.3 -def test_null_mean_is_the_baseline_and_skew_is_poisson(): +def test_null_mean_is_the_baseline_and_skew_is_poisson() -> None: """Null noise has the baseline's mean, gain x b variance, Poisson skew.""" rng = np.random.default_rng(1) movie, base, noise, photons = _gradient_movie(rng, t=3000, cols=6) @@ -92,26 +111,32 @@ def test_null_mean_is_the_baseline_and_skew_is_poisson(): np.testing.assert_allclose(var / (noise["gain"] * base[0, 0]), 1, rtol=0.1) skew = (r**3).mean((0, 1)) / var**1.5 w2 = noise["W2"] - w3 = ( - (noise["kt"] ** 3).sum() - * (noise["kr"] ** 3).sum() - * (noise["kc"] ** 3).sum() - ) + w3 = (noise["kt"] ** 3).sum() * (noise["kr"] ** 3).sum() * (noise["kc"] ** 3).sum() want = w3 / w2**1.5 / np.sqrt(photons * w2) np.testing.assert_allclose(skew[:3], want[:3], rtol=0.25) -def _tail(x): - """Median and (99.5th percentile - median) of an image's pixels.""" +def _tail(x: np.ndarray) -> tuple[float, float]: + """Return the median and (99.5th percentile - median) of an image's pixels. + + Returns + ------- + m : float + The median. + tail : float + The 99.5th percentile minus the median. + """ x = x[np.isfinite(x)] m = np.median(x) return m, np.quantile(x, 0.995) - m -def test_bootstrap_calibrates_dim_and_bright_pixels(): - """On a trial of pure photon noise, the calibrated image has the same - centre and upper tail at every brightness; uncalibrated, dim pixels' - tail is heavier.""" +def test_bootstrap_calibrates_dim_and_bright_pixels() -> None: + """On a trial of pure photon noise, the calibrated image is the same at every brightness. + + It has the same centre and upper tail at every brightness; uncalibrated, + dim pixels' tail is heavier. + """ rng = np.random.default_rng(2) movie, base, _, photons = _gradient_movie(rng, rows=80, margin=6) p_raw = RasterLocalizationParams(variance_floor=False) @@ -133,8 +158,14 @@ def test_bootstrap_calibrates_dim_and_bright_pixels(): assert info["s0"][0] > 1.3 * info["s0"][-1] -def _ar1(rng, t, n, rho=0.6): - """Independent AR(1) series (one per column) with lag-1 correlation.""" +def _ar1(rng: np.random.Generator, t: int, n: int, rho: float = 0.6) -> np.ndarray: + """Return independent AR(1) series (one per column) with lag-1 correlation. + + Returns + ------- + np.ndarray + The series, (t, n). + """ e = rng.standard_normal((t, n)) r = np.empty((t, n)) r[0] = e[0] @@ -150,10 +181,14 @@ def _ar1(rng, t, n, rho=0.6): lambda t: t % 3 != 2, # 0, 1, 3, 4, 6, 7...: lag 2 spans a gap ], ) -def test_lag_correlations_use_recorded_frame_indices(kept): - """Lags are counted in recorded frames: pairs are matched by their - original indices, also across a discarded frame between them, and - never across a gap that changes the lag.""" +def test_lag_correlations_use_recorded_frame_indices( + kept: Callable[[np.ndarray], np.ndarray], +) -> None: + """Lags are counted in recorded frames. + + Pairs are matched by their original indices, also across a discarded + frame between them, and never across a gap that changes the lag. + """ rng = np.random.default_rng(4) t, n = 3000, 400 r = _ar1(rng, t, n) @@ -163,21 +198,21 @@ def test_lag_correlations_use_recorded_frame_indices(kept): np.testing.assert_allclose(m["rho"][:2], [0.6, 0.36], atol=0.03) -def test_null_variance_around_discarded_frames(): - """Discarded frames (NaN baseline, as an external baseline gives) keep - their latent noise: the frames next to them get the full variance.""" +def test_null_variance_around_discarded_frames() -> None: + """Discarded frames (NaN baseline, as an external baseline gives) keep their latent noise. + + The frames next to them get the full variance. + """ t, rows, cols, gain = 4000, 20, 20, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } noise["W2"] = float( - (noise["kt"] ** 2).sum() - * (noise["kr"] ** 2).sum() - * (noise["kc"] ** 2).sum() + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() ) disc = np.arange(t) % 8 == 0 base = np.full((t, rows * cols), 2.0 * gain, np.float32) @@ -185,9 +220,7 @@ def test_null_variance_around_discarded_frames(): ones = np.ones_like(base) nans = np.zeros((t, rows, cols), bool) nans[disc] = True - z = null_movie( - base, ones, ones, nans, np.arange(rows * cols), noise, seed=7 - ) + z = null_movie(base, ones, ones, nans, np.arange(rows * cols), noise, seed=7) assert np.isnan(z[disc]).all() inner = z[:, 2:-2, 2:-2] phase = np.arange(t) % 8 @@ -197,43 +230,37 @@ def test_null_variance_around_discarded_frames(): assert abs(var_far / (gain * 2.0 * gain) - 1) < 0.05 # gain x b -def test_null_variance_next_to_bright_structures(): - """Where brightness changes across the spatial kernel, every pixel keeps - the variance gain x b, and the measured model is still the drawn one.""" +def test_null_variance_next_to_bright_structures() -> None: + """Where brightness changes across the spatial kernel, every pixel keeps the variance. + + The variance is gain x b, and the measured model is still the drawn one. + """ t, rows, cols, gain = 3000, 30, 30, 8.0 photons = np.where((np.arange(cols) // 3) % 2 == 0, 30.0, 0.3) b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) base = np.broadcast_to(b[None], (t, rows, cols)).astype(np.float32) - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } noise["W2"] = float( - (noise["kt"] ** 2).sum() - * (noise["kr"] ** 2).sum() - * (noise["kc"] ** 2).sum() + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() ) flat = base.reshape(t, -1) ones = np.ones_like(flat) vidx = np.arange(rows * cols) - z = null_movie( - flat, ones, ones, np.zeros(base.shape, bool), vidx, noise, seed=5 - ) + z = null_movie(flat, ones, ones, np.zeros(base.shape, bool), vidx, noise, seed=5) inner = (slice(None), slice(2, -2), slice(2, -2)) var = z[inner].var(0) - np.testing.assert_allclose( - (var / (gain * b[2:-2, 2:-2])).mean(0), 1, rtol=0.1 - ) - m = noise_model( - z.reshape(t, -1), flat, ones, vidx, (rows, cols), np.arange(1000) - ) + np.testing.assert_allclose((var / (gain * b[2:-2, 2:-2])).mean(0), 1, rtol=0.1) + m = noise_model(z.reshape(t, -1), flat, ones, vidx, (rows, cols), np.arange(1000)) np.testing.assert_allclose(m["rho"][:3], [0.6, 0.25, 0.23], atol=0.03) -def test_bootstrap_on_a_uniform_baseline(): +def test_bootstrap_on_a_uniform_baseline() -> None: """A trial of one brightness is calibrated with a single bin.""" rng = np.random.default_rng(6) t, rows, cols = 1200, 30, 30 @@ -245,9 +272,11 @@ def test_bootstrap_on_a_uniform_baseline(): assert loc.info["null"]["m0"].size == 1 -def test_temporal_kernel_stays_finite_for_negative_lag2(): - """A negative lag-2 correlation whose best unconstrained taps sum to 0 - (``[-0.4, -0.1, 0, 1, 0, -0.1, -0.4]``) gives a finite kernel.""" +def test_temporal_kernel_stays_finite_for_negative_lag2() -> None: + """A negative lag-2 correlation gives a finite kernel. + + The best unconstrained taps sum to 0 ([-0.4, -0.1, 0, 1, 0, -0.1, -0.4]). + """ k = temporal_kernel(0.08 / 1.34, -0.2 / 1.34) assert np.isfinite(k).all() and np.isclose(k.sum(), 1) assert np.abs(k).max() < 2.0 @@ -259,21 +288,22 @@ def test_temporal_kernel_stays_finite_for_negative_lag2(): assert abs(ac[1] - t1) < 0.02 and abs(ac[2] - t2) < 0.02 -def test_null_variance_follows_a_fast_changing_baseline(): - """Where the baseline changes within the temporal kernel (here every - 2 frames, 30 or 0.3 photons), each frame keeps the variance gain x b.""" +def test_null_variance_follows_a_fast_changing_baseline() -> None: + """Where the baseline changes within the temporal kernel, each frame keeps the variance. + + The baseline here changes every 2 frames, 30 or 0.3 photons; the variance + is gain x b. + """ t, rows, cols, gain = 4000, 12, 12, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } noise["W2"] = float( - (noise["kt"] ** 2).sum() - * (noise["kr"] ** 2).sum() - * (noise["kc"] ** 2).sum() + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() ) bright = (np.arange(t) // 2) % 2 == 0 b_t = np.where(bright, 30.0, 0.3) * gain @@ -294,9 +324,11 @@ def test_null_variance_follows_a_fast_changing_baseline(): assert abs(ratio - 1) < 0.1 -def test_calibration_of_zero_brightness_is_the_dimmest_bin(): - """Pixels with zero or negative baseline take the dimmest bin's centre - and scale (not the middle bin's); NaN brightness takes the middle.""" +def test_calibration_of_zero_brightness_is_the_dimmest_bin() -> None: + """Pixels with zero or negative baseline take the dimmest bin's centre and scale. + + Not the middle bin's; NaN brightness takes the middle. + """ centre = np.log([0.1, 1.0, 10.0]) m0, s0 = np.array([1.0, 2.0, 3.0]), np.array([10.0, 20.0, 30.0]) photons = np.array([0.0, -1.0, np.nan, 0.01, 1.0, 100.0]) @@ -305,21 +337,21 @@ def test_calibration_of_zero_brightness_is_the_dimmest_bin(): np.testing.assert_array_equal(s, [10, 10, 20, 10, 20, 30]) -def test_null_has_no_noise_at_zero_baselines(): - """A zero-baseline pixel next to bright ones gets no null noise (its - variance gain x b is 0), not its neighbours' mixed in.""" +def test_null_has_no_noise_at_zero_baselines() -> None: + """A zero-baseline pixel next to bright ones gets no null noise. + + Its variance gain x b is 0, not its neighbours' mixed in. + """ t, rows, cols, gain = 2000, 16, 16, 8.0 - noise = dict( - gain=gain, - kt=temporal_kernel(0.6, 0.25), - kr=spatial_kernel(0.23), - kc=spatial_kernel(0.37), - q=1.0, - ) + noise = { + "gain": gain, + "kt": temporal_kernel(0.6, 0.25), + "kr": spatial_kernel(0.23), + "kc": spatial_kernel(0.37), + "q": 1.0, + } noise["W2"] = float( - (noise["kt"] ** 2).sum() - * (noise["kr"] ** 2).sum() - * (noise["kc"] ** 2).sum() + (noise["kt"] ** 2).sum() * (noise["kr"] ** 2).sum() * (noise["kc"] ** 2).sum() ) photons = np.where((np.arange(cols) // 2) % 2 == 0, 20.0, 0.0) b = np.broadcast_to(photons[None, :] * gain, (rows, cols)) @@ -341,10 +373,12 @@ def test_null_has_no_noise_at_zero_baselines(): np.testing.assert_allclose(bright.mean(), 1, rtol=0.1) -def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch): - """The data's variance follows the per-frame variance factor, so the - noise model and the null movies get it unsmoothed (the Z-score keeps - MATLAB's smoothed one).""" +def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch: pytest.MonkeyPatch) -> None: + """The data's variance follows the per-frame variance factor. + + So the noise model and the null movies get it unsmoothed (the Z-score + keeps MATLAB's smoothed one). + """ import giant_python.extraction.raster.null as null_mod rng = np.random.default_rng(10) @@ -356,13 +390,33 @@ def test_bootstrap_uses_the_per_frame_variance_factor(monkeypatch): seen = {} real_model, real_movie = null_mod.noise_model, null_mod.null_movie_valid - def spy_model(resid, baseline, var_factor, *a, **k): - """Record the variance factor given to the noise model.""" + def spy_model( + resid: np.ndarray, + baseline: np.ndarray, + var_factor: np.ndarray, + *a: object, + **k: object, + ) -> dict: + """Record the variance factor given to the noise model. + + Returns + ------- + dict + The real noise model's result. + """ seen["model"] = np.array(var_factor) return real_model(resid, baseline, var_factor, *a, **k) - def spy_movie(baseline, var_factor, *a, **k): - """Record the variance factor given to the null movie.""" + def spy_movie( + baseline: np.ndarray, var_factor: np.ndarray, *a: object, **k: object + ) -> np.ndarray: + """Record the variance factor given to the null movie. + + Returns + ------- + np.ndarray + The real null movie. + """ seen["movie"] = np.array(var_factor) return real_movie(baseline, var_factor, *a, **k) @@ -376,56 +430,52 @@ def spy_movie(baseline, var_factor, *a, **k): assert set(np.unique(got[np.isfinite(got)])) == {1.0, 3.0} -def test_bins_hold_enough_null_values(): - """A small field of view gets fewer brightness bins, so no bin's 99.5th - percentile rests on a few dozen values.""" +def test_bins_hold_enough_null_values() -> None: + """A small field of view gets fewer brightness bins. + + So no bin's 99.5th percentile rests on a few dozen values. + """ rng = np.random.default_rng(11) movie, base, _, _ = _gradient_movie(rng, t=1200, rows=12, cols=30) - p = RasterLocalizationParams( - variance_floor=False, null="bootstrap", null_draws=1 - ) + p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) loc = localize_sources(movie, None, p, base, find_peaks=False) n_ok = 8 * 26 # pixels away from the edges, at most assert loc.info["null"]["m0"].size <= max(1, n_ok // 500) -def test_bins_keep_the_minimum_with_tied_brightness(): - """Ties collapse equal-count edges; a few pixels below a tied block - would form a bin of their own. Bins merge until each holds 500 null - values, and tied pixels are never split.""" +def test_bins_keep_the_minimum_with_tied_brightness() -> None: + """Ties collapse equal-count edges. + + A few pixels below a tied block would form a bin of their own. Bins merge + until each holds 500 null values, and tied pixels are never split. + """ rng = np.random.default_rng(12) - lp = np.concatenate( - [ - np.full(3, -3.0), # a few darker pixels - np.zeros(2000), # half the pixels at one brightness - rng.uniform(0.1, 3.0, 2000), - ] - ) + lp = np.concatenate([ + np.full(3, -3.0), # a few darker pixels + np.zeros(2000), # half the pixels at one brightness + rng.uniform(0.1, 3.0, 2000), + ]) bins, counts = _brightness_bins(lp, draws=1) assert counts.size > 1 and counts.min() >= 500 np.testing.assert_array_equal(counts, np.bincount(bins)) for k in range(counts.size - 1): # contiguous in brightness, no split assert lp[bins == k].max() < lp[bins == k + 1].min() assert bins[0] == bins[3] # the darker pixels joined the tied block - bins2, counts2 = _brightness_bins(lp, draws=2) # counts are values + _bins2, counts2 = _brightness_bins(lp, draws=2) # counts are values assert counts2.min() >= 500 and counts2.size >= counts.size -def test_tied_brightness_end_to_end(): - """Half the columns at one brightness and two darker ones: every bin of - the calibration has at least 500 null values, so the dimmest bin's 99.5th - percentile is not set by a single maximum.""" +def test_tied_brightness_end_to_end() -> None: + """Half the columns at one brightness and two darker ones. + + Every bin of the calibration has at least 500 null values, so the dimmest + bin's 99.5th percentile is not set by a single maximum. + """ rng = np.random.default_rng(13) cols = 60 - photons = np.r_[ - [0.05, 0.05], np.full(30, 0.5), np.linspace(1, 30, cols - 32) - ] - movie, base, _, _ = _gradient_movie( - rng, t=1200, rows=40, cols=cols, photons=photons - ) - p = RasterLocalizationParams( - variance_floor=False, null="bootstrap", null_draws=1 - ) + photons = np.r_[[0.05, 0.05], np.full(30, 0.5), np.linspace(1, 30, cols - 32)] + movie, base, _, _ = _gradient_movie(rng, t=1200, rows=40, cols=cols, photons=photons) + p = RasterLocalizationParams(variance_floor=False, null="bootstrap", null_draws=1) info = localize_sources(movie, None, p, base, find_peaks=False).info counts = info["null"]["counts"] assert counts.size >= 2 and counts.min() >= 500 @@ -433,10 +483,12 @@ def test_tied_brightness_end_to_end(): @pytest.mark.parametrize("t", [1, 5]) -def test_trial_too_short_for_the_null_is_left_out(t): - """A trial of a few frames (no pixel has enough frames for the noise - model) is left out of localization with a warning, as a trial without - valid pixels, instead of failing SILo.""" +def test_trial_too_short_for_the_null_is_left_out(t: int) -> None: + """A trial of a few frames is left out of localization with a warning. + + No pixel has enough frames for the noise model, so it is treated as a + trial without valid pixels, instead of failing SILo. + """ rng = np.random.default_rng(9) base = np.full((t, 30, 30), 16.0, np.float32) movie = (base + 4 * rng.standard_normal(base.shape)).astype(np.float32) @@ -448,7 +500,7 @@ def test_trial_too_short_for_the_null_is_left_out(t): assert loc.peaks.shape == (0, 4) -def test_noise_model_raises_null_unavailable(): +def test_noise_model_raises_null_unavailable() -> None: """The noise model's refusal is a NullUnavailable (a ValueError).""" from giant_python.extraction.raster.null import NullUnavailable @@ -460,11 +512,13 @@ def test_noise_model_raises_null_unavailable(): assert issubclass(NullUnavailable, ValueError) -def test_trial_without_calibration_pixels_is_left_out(): - """A trial whose noise model can be measured but whose null calibration - has no eligible pixel (a 2-pixel-wide imaged stripe: no pixel has a full - 3 x 3 neighbourhood) is left out of localization, as a trial without - valid pixels.""" +def test_trial_without_calibration_pixels_is_left_out() -> None: + """A trial whose noise model can be measured is left out of localization. + + Its null calibration has no eligible pixel (a 2-pixel-wide imaged stripe: + no pixel has a full 3 x 3 neighbourhood), so it is treated as a trial + without valid pixels. + """ from giant_python.extraction.raster.null import noise_model rng = np.random.default_rng(4) @@ -475,9 +529,7 @@ def test_trial_without_calibration_pixels_is_left_out(): vidx = np.flatnonzero(np.isfinite(base[0]).ravel()) flat_m = movie.reshape(t, -1)[:, vidx] flat_b = base.reshape(t, -1)[:, vidx] - noise_model( - flat_m - flat_b, flat_b, np.ones_like(flat_b), vidx, (rows, cols) - ) + noise_model(flat_m - flat_b, flat_b, np.ones_like(flat_b), vidx, (rows, cols)) p = RasterLocalizationParams(null="bootstrap") with pytest.warns(UserWarning, match="null calibration"): loc = localize_sources(movie, None, p, base, find_peaks=True) @@ -487,11 +539,13 @@ def test_trial_without_calibration_pixels_is_left_out(): @pytest.mark.parametrize("with_sd", [False, True]) -def test_null_at_the_valid_pixels_equals_the_whole_frame_null(with_sd): - """The null movie, its score and the calibrated activity image made at - the valid pixels are those made on whole frames, bit for bit: with the +def test_null_at_the_valid_pixels_equals_the_whole_frame_null(with_sd: bool) -> None: + """The null movie, its score and the calibrated activity image are the same. + + Those made at the valid pixels are those made on whole frames, bit for bit: with the model's noise SD and with the network's (shot and additive noise, and - the extra cropped draws for pixels of nonpositive baseline).""" + the extra cropped draws for pixels of nonpositive baseline). + """ from giant_python.extraction.raster import localization as loc from giant_python.extraction.raster import null as null_mod @@ -514,14 +568,19 @@ def test_null_at_the_valid_pixels_equals_the_whole_frame_null(with_sd): if with_sd: bl[:, 72:80, 100:108] = 0.0 # no baseline there, but noise sd = np.sqrt(np.maximum(bl, 0.3) * 1.5).astype(np.float32) - p = RasterLocalizationParams( - null="bootstrap", surround=False, null_draws=2 - ) + p = RasterLocalizationParams(null="bootstrap", surround=False, null_draws=2) ref_cal = null_mod.null_calibration seen = {} - def whole_frames(*a, **k): - """The calibration as before this path existed: on whole frames.""" + def whole_frames(*a: object, **k: object) -> tuple[np.ndarray, dict]: + """Return the calibration as before this path existed: on whole frames. + + Returns + ------- + tuple + The calibrated activity image and the info, from the reference + calibration. + """ nan_v = k.pop("nan_v") seen["dark"] = k.get("noise_var") is not None a = list(a) @@ -540,7 +599,5 @@ def whole_frames(*a, **k): np.testing.assert_array_equal(got.act_im, want.act_im) np.testing.assert_array_equal(got.summary, want.summary) for k in ("photons", "m0", "s0", "counts", "null_im"): - np.testing.assert_array_equal( - got.info["null"][k], want.info["null"][k] - ) + np.testing.assert_array_equal(got.info["null"][k], want.info["null"][k]) assert np.isfinite(got.info["null"]["null_im"]).any() diff --git a/tests/raster/test_raster_peaks.py b/tests/raster/test_raster_peaks.py index 31759ff3..8054893b 100644 --- a/tests/raster/test_raster_peaks.py +++ b/tests/raster/test_raster_peaks.py @@ -1,7 +1,5 @@ """Tests of the getActImPeaks port (raster SiLo seeds).""" -from typing import Any - import numpy as np import pytest from scipy.optimize import OptimizeResult @@ -61,12 +59,12 @@ def test_finds_separated_gaussians() -> None: def test_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: """A LAPACK SVD failure in the default solver retries with lsmr.""" - import giant_python.extraction.raster.peaks as peaks + from giant_python.extraction.raster import peaks calls = [] real = peaks.least_squares - def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy + def flaky(*args: object, **kwargs: object) -> OptimizeResult: """least_squares whose default (SVD) solver always fails. Returns @@ -219,7 +217,7 @@ def test_local_fit_finds_separated_gaussians( With the dense (SVD) solver of small fits and with the sparse (lsmr) one of large fits. """ - import giant_python.extraction.raster.peaks as peaks + from giant_python.extraction.raster import peaks monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) rng = np.random.default_rng(0) @@ -258,12 +256,12 @@ def test_local_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> And the seeds are found. """ - import giant_python.extraction.raster.peaks as peaks + from giant_python.extraction.raster import peaks calls = [] real = peaks.least_squares - def flaky(*args: Any, **kwargs: Any) -> OptimizeResult: # noqa: ANN401 - forwards to scipy + def flaky(*args: object, **kwargs: object) -> OptimizeResult: """least_squares whose dense (SVD) solver always fails. Returns diff --git a/tests/raster/test_raster_plan.py b/tests/raster/test_raster_plan.py index 09977eb6..47de419d 100644 --- a/tests/raster/test_raster_plan.py +++ b/tests/raster/test_raster_plan.py @@ -1,5 +1,6 @@ """Tests of SiLo's path-level plan (alignment, sources, pixels, groups).""" +import itertools import json from dataclasses import replace from pathlib import Path @@ -32,45 +33,118 @@ # sources of the synthetic path (scene coordinates): four apart, and a pair # four pixels from each other -SOURCES = np.array( - [[14, 16], [14, 60], [40, 30], [52, 70], [30, 50], [30, 54]], dtype=float -) +SOURCES = np.array([[14, 16], [14, 60], [40, 30], [52, 70], [30, 50], [30, 54]], dtype=float) SHIFTS = np.array([[0, 0], [1, -1], [-1, 2], [2, 1], [0, -2]], dtype=float) -def _blobs(shape, centres, amps, sigma, shift): - """Gaussian blobs at ``centres + shift``.""" +def _blobs( + shape: tuple[int, int], + centres: np.ndarray, + amps: np.ndarray, + sigma: float, + shift: np.ndarray, +) -> np.ndarray: + """Return Gaussian blobs at centres + shift. + + Parameters + ---------- + shape : tuple of int + Image shape. + centres : np.ndarray + Blob centres (n, 2). + amps : np.ndarray + Blob amplitudes. + sigma : float + Blob width. + shift : np.ndarray + Shift of the centres (2,). + + Returns + ------- + np.ndarray + The image of the blobs. + """ rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) im = np.zeros(shape) for (r0, c0), a in zip(centres, amps): - im += a * np.exp( - -((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) - / (2 * sigma**2) - ) + im += a * np.exp(-((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * sigma**2)) return im -def _peaks(shape, centres, amp, sigma, shift): - """Narrow peaks at ``centres + shift``: Gaussians integrated over each +def _peaks( + shape: tuple[int, int], + centres: np.ndarray, + amp: float, + sigma: float, + shift: np.ndarray, +) -> np.ndarray: + """Return narrow peaks at centres + shift. + + The peaks are Gaussians integrated over each pixel, the model that seeding fits (activity images are sharper than - the PSF, and a sampled Gaussian would leave residual peaks).""" + the PSF, and a sampled Gaussian would leave residual peaks). + + Parameters + ---------- + shape : tuple of int + Image shape. + centres : np.ndarray + Peak centres (n, 2). + amp : float + Peak amplitude. + sigma : float + Peak width. + shift : np.ndarray + Shift of the centres (2,). + + Returns + ------- + np.ndarray + The image of the peaks. + """ - def axis(n, mu): - """Integral of the Gaussian over each of n pixels.""" + def axis(n: int, mu: float) -> np.ndarray: + """Return the integral of the Gaussian over each of n pixels. + + Parameters + ---------- + n : int + Number of pixels. + mu : float + Centre of the Gaussian. + + Returns + ------- + np.ndarray + The integral over each pixel. + """ edges = (np.arange(n + 1) - 0.5 - mu) / (np.sqrt(2) * sigma) return np.sqrt(np.pi / 2) * sigma * np.diff(erf(edges)) im = np.zeros(shape) for r0, c0 in centres: - im += amp * np.outer( - axis(shape[0], r0 + shift[0]), axis(shape[1], c0 + shift[1]) - ) + im += amp * np.outer(axis(shape[0], r0 + shift[0]), axis(shape[1], c0 + shift[1])) return im -def _synthetic_trials(shape=(64, 84), seed=0): - """Five trials of one scene at SHIFTS, with an imaged region, two - channels, and activity images that peak at SOURCES.""" +def _synthetic_trials(shape: tuple[int, int] = (64, 84), seed: int = 0) -> list[TrialImages]: + """Return five trials of one scene at SHIFTS. + + The trials have an imaged region, two + channels, and activity images that peak at SOURCES. + + Parameters + ---------- + shape : tuple of int + Image shape. + seed : int + Seed of the random generator. + + Returns + ------- + list of TrialImages + The five trials. + """ rng = np.random.default_rng(seed) scene_c = rng.uniform([6, 6], [shape[0] - 6, shape[1] - 6], (40, 2)) scene_a = rng.uniform(50, 150, 40) @@ -95,20 +169,27 @@ def _synthetic_trials(shape=(64, 84), seed=0): @pytest.fixture(scope="module") -def synthetic_plan(): - """The plan of the synthetic path, and its intermediates.""" +def synthetic_plan() -> tuple[ExtractionPlan, dict]: + """Return the plan of the synthetic path, and its intermediates. + + Returns + ------- + tuple + The plan and the details dict filled by :func:`plan_path`. + """ details = {} - plan = plan_path( - _synthetic_trials(), params=PlanParams(peak_th=12.0), details=details - ) + plan = plan_path(_synthetic_trials(), params=PlanParams(peak_th=12.0), details=details) return plan, details -def test_plan_params(): - """Radii follow MATLAB (selRadius = ceil(2 dXY); zones of +def test_plan_params() -> None: + """Radii follow MATLAB and options are validated. + + Radii follow MATLAB (selRadius = ceil(2 dXY); zones of ceil(1.5 sigma + (validKernel - 1) / 2): MATLAB's 3 x 3 gives ceil(1.5 sigma + 1), the default 5 x 5 one more); options are - validated.""" + validated. + """ p = PlanParams() assert p.valid_kernel == 5 assert p.sel_radius == 6 and p.zone_radius == 4 @@ -123,10 +204,13 @@ def test_plan_params(): PlanParams(d_xy=0) -def test_group_sources_zones_and_order(): - """Sources whose zones (5 x 5 squares for radius 3) touch form a group; +def test_group_sources_zones_and_order() -> None: + """Sources whose zones touch form a group, and groups come in MATLAB's order. + + Sources whose zones (5 x 5 squares for radius 3) touch form a group; groups come in MATLAB's order, by the first pixel of their zone column - by column; pixels are the group's disks within the selected pixels.""" + by column; pixels are the group's disks within the selected pixels. + """ sel = np.ones((40, 60), bool) sel[:, 30] = False # (row, col): b and c touch through adjacent zones (5 columns apart); @@ -157,9 +241,12 @@ def test_group_sources_zones_and_order(): group_sources(rows, cols, np.zeros_like(sel), 3, 6) -def test_combined_activity_image(): - """The trials' mean (NaN where any trial is NaN), scaled to a maximum - of 10 to 100, minus its 5 x 5 NaN-median.""" +def test_combined_activity_image() -> None: + """Check the trials' mean, scaled and minus its NaN-median. + + The trials' mean (NaN where any trial is NaN), scaled to a maximum + of 10 to 100, minus its 5 x 5 NaN-median. + """ rng = np.random.default_rng(1) act = rng.uniform(0.001, 0.002, (3, 12, 14)) act[:, 6, 7] = 0.04 @@ -168,25 +255,24 @@ def test_combined_activity_image(): assert np.isnan(im[0, 0]) and nan_frac[0, 0] == pytest.approx(1 / 3) scaled = act.mean(axis=0) / 1e-3 np.testing.assert_allclose(im[6, 7] + med[6, 7], 40.0) - np.testing.assert_allclose( - med[3, 3], np.median(scaled[1:6, 1:6]), rtol=1e-12 - ) + np.testing.assert_allclose(med[3, 3], np.median(scaled[1:6, 1:6]), rtol=1e-12) empty = combined_activity_image(act[:0], 0.33) assert all(np.isnan(x).all() for x in empty) -def test_plan_of_a_synthetic_path(synthetic_plan): - """Shifts, valid trials, sources, selected pixels and groups of a path - with known sources.""" +def test_plan_of_a_synthetic_path(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """Check a path with known sources. + + Shifts, valid trials, sources, selected pixels and groups of a path + with known sources. + """ plan, details = synthetic_plan assert plan.shape == (64, 84) and plan.n_trials == 5 np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) np.testing.assert_array_equal(plan.aligned_trials, np.arange(5)) assert (plan.corr > 0.99).all() and plan.corr_thresh <= 0.9 # shifts are relative to the template's reference trial - np.testing.assert_allclose( - plan.shifts - plan.shifts[0], SHIFTS - SHIFTS[0], atol=0.1 - ) + np.testing.assert_allclose(plan.shifts - plan.shifts[0], SHIFTS - SHIFTS[0], atol=0.1) assert plan.n_sources == 6 # each source is where it was put, in every trial's own frame for t in range(5): @@ -219,19 +305,15 @@ def test_plan_of_a_synthetic_path(synthetic_plan): members = np.zeros(plan.shape, bool) for k in g.sources: members |= plan.source_mask(k) - crop = members[ - g.row0 : g.row0 + g.sel.shape[0], g.col0 : g.col0 + g.sel.shape[1] - ] + crop = members[g.row0 : g.row0 + g.sel.shape[0], g.col0 : g.col0 + g.sel.shape[1]] np.testing.assert_array_equal(crop, g.sel) assert members.sum() == g.sel.sum() == g.pixels.size np.testing.assert_array_equal( g.sources_rc, - np.column_stack( - [ - plan.source_rows[g.sources] - g.row0, - plan.source_cols[g.sources] - g.col0, - ] - ), + np.column_stack([ + plan.source_rows[g.sources] - g.row0, + plan.source_cols[g.sources] - g.col0, + ]), ) # images: the mean of the aligned trials, NaN ignored assert plan.mean_im.shape == (64, 84, 2) @@ -242,10 +324,13 @@ def test_plan_of_a_synthetic_path(synthetic_plan): assert details["med_im"].shape == plan.shape -def test_plan_leaves_out_bad_and_missing_trials(): - """A trial that was not localized, one that is not kept, one without an +def test_plan_leaves_out_bad_and_missing_trials() -> None: + """Trials that are bad or missing are not valid. + + A trial that was not localized, one that is not kept, one without an activity image and one that does not match the others are not valid; - sources are seeded from the rest.""" + sources are seeded from the rest. + """ trials = _synthetic_trials() shape = trials[0].act_im.shape noise = np.random.default_rng(7).uniform(10, 30, shape) @@ -255,9 +340,7 @@ def test_plan_leaves_out_bad_and_missing_trials(): everything = trials + [None, odd, blank, trials[2]] keep = np.ones(len(everything), bool) keep[8] = False - plan = plan_path( - everything, params=PlanParams(peak_th=12.0), keep_trials=keep - ) + plan = plan_path(everything, params=PlanParams(peak_th=12.0), keep_trials=keep) np.testing.assert_array_equal(plan.keep_trials, keep & (np.arange(9) != 5)) np.testing.assert_array_equal(plan.valid_trials, np.arange(5)) np.testing.assert_array_equal(plan.aligned_trials, [0, 1, 2, 3, 4, 6]) @@ -270,9 +353,12 @@ def test_plan_leaves_out_bad_and_missing_trials(): plan_path([None, None]) -def test_plan_soma_mask_and_given_seeds(): - """No source is seeded in the soma mask (smaller masks sit top left); - given seeds replace the seeding.""" +def test_plan_soma_mask_and_given_seeds() -> None: + """No source is seeded in the soma mask; given seeds replace the seeding. + + No source is seeded in the soma mask (smaller masks sit top left); + given seeds replace the seeding. + """ trials = _synthetic_trials() soma = np.zeros((40, 45), bool) soma[:25, :30] = True # covers the source at (14, 16) @@ -280,9 +366,7 @@ def test_plan_soma_mask_and_given_seeds(): assert plan.n_sources == 5 assert plan.soma_mask.shape == plan.shape and plan.soma_mask.sum() == 750 assert not plan.soma_mask[plan.source_rows, plan.source_cols].any() - seeds = np.array( - [[3.0, 20.2, 30.6, 0.5], [2.0, 20.4, 31.4, 0.5], [1.0, 2.0, 2.0, 0.5]] - ) + seeds = np.array([[3.0, 20.2, 30.6, 0.5], [2.0, 20.4, 31.4, 0.5], [1.0, 2.0, 2.0, 0.5]]) given = plan_path(trials, seeds=seeds) # the first two round to one pixel; the last is outside the imaged area np.testing.assert_array_equal(given.source_rows, [20]) @@ -294,27 +378,22 @@ def test_plan_soma_mask_and_given_seeds(): rr, cc = np.nonzero(plan.soma_mask) move = np.round(plan.shifts[3]).astype(int) drawn[rr + move[0], cc + move[1]] = True - moved = plan_path( - trials, drawn, PlanParams(peak_th=12.0), soma_mask_trial=3 - ) + moved = plan_path(trials, drawn, PlanParams(peak_th=12.0), soma_mask_trial=3) np.testing.assert_array_equal(moved.soma_mask, plan.soma_mask) np.testing.assert_array_equal(moved.source_rows, plan.source_rows) with pytest.warns(UserWarning, match="not aligned"): - loose = plan_path( - trials + [None], drawn, PlanParams(peak_th=12.0), soma_mask_trial=5 - ) + loose = plan_path(trials + [None], drawn, PlanParams(peak_th=12.0), soma_mask_trial=5) np.testing.assert_array_equal(loose.soma_mask, drawn) with pytest.raises(ValueError, match="soma_mask"): plan_path(trials, np.zeros((100, 100), bool)) -def test_wmf_seeds_without_complete_overlap_and_prunes_by_mean(): +def test_wmf_seeds_without_complete_overlap_and_prunes_by_mean() -> None: """WMF seeds partially covered pixels; mean-image coverage prunes them.""" rng = np.random.default_rng(21) y, x = np.mgrid[:40, :48] signal = 8 * ( - np.exp(-((y - 25) ** 2 + (x - 32) ** 2) / 2) - + np.exp(-((y - 10) ** 2 + (x - 12) ** 2) / 2) + np.exp(-((y - 25) ** 2 + (x - 32) ** 2) / 2) + np.exp(-((y - 10) ** 2 + (x - 12) ** 2) / 2) ) mean = rng.uniform(10, 60, signal.shape) mean[8:13, 10:15] = np.nan # second seed has no measured centre @@ -353,10 +432,8 @@ def test_wmf_seeds_without_complete_overlap_and_prunes_by_mean(): np.testing.assert_array_equal(plan.source_cols, [32]) -@pytest.mark.parametrize( - "method,n_trials", [("getactimpeaks", 5), ("wmf", 5), ("wmf", 3)] -) -def test_plan_source_values_follow_seeding_method(method, n_trials): +@pytest.mark.parametrize("method,n_trials", [("getactimpeaks", 5), ("wmf", 5), ("wmf", 3)]) +def test_plan_source_values_follow_seeding_method(method: str, n_trials: int) -> None: """Retained sources carry WMF scores or Gaussian amplitudes on fallback.""" details = {} plan = plan_path( @@ -366,9 +443,7 @@ def test_plan_source_values_follow_seeding_method(method, n_trials): ) assert plan.n_sources == len(SOURCES) if method == "wmf" and n_trials >= 4: - np.testing.assert_array_equal( - plan.source_values, details["seed_info"]["value"] - ) + np.testing.assert_array_equal(plan.source_values, details["seed_info"]["value"]) assert np.isnan(plan.seeds[:, 3]).all() else: assert np.isfinite(plan.seeds[:, 3]).all() @@ -376,13 +451,11 @@ def test_plan_source_values_follow_seeding_method(method, n_trials): @pytest.mark.parametrize("with_blank", [False, True]) -def test_wmf_falls_back_to_existing_gaussian_seeds(with_blank): +def test_wmf_falls_back_to_existing_gaussian_seeds(with_blank: bool) -> None: """Three imaged trials give the original seeds even with a fourth blank.""" trials = _synthetic_trials()[:3] if with_blank: - trials.append( - TrialImages(trials[0].mean_im, np.full_like(trials[0].act_im, NAN)) - ) + trials.append(TrialImages(trials[0].mean_im, np.full_like(trials[0].act_im, NAN))) p = PlanParams(peak_th=12.0, inter_trial_alignment="rigid") default = plan_path(trials, params=p) details = {} @@ -396,22 +469,33 @@ def test_wmf_falls_back_to_existing_gaussian_seeds(with_blank): np.testing.assert_array_equal(plan.seeds, default.seeds) np.testing.assert_array_equal(plan.sel, default.sel) # Ordered source pixels from the default seeding at 98faf75. - np.testing.assert_array_equal( - default.source_rows, [15, 41, 31, 31, 15, 53] - ) - np.testing.assert_array_equal( - default.source_cols, [15, 29, 49, 53, 59, 69] - ) + np.testing.assert_array_equal(default.source_rows, [15, 41, 31, 31, 15, 53]) + np.testing.assert_array_equal(default.source_cols, [15, 29, 49, 53, 59, 69]) -def test_wmf_plan_rechecks_rounded_fitted_positions_in_soma(monkeypatch): +def test_wmf_plan_rechecks_rounded_fitted_positions_in_soma( + monkeypatch: pytest.MonkeyPatch, +) -> None: """The plan passes the soma mask and rechecks rounded fitted positions.""" trials = _synthetic_trials() soma = np.zeros(trials[0].act_im.shape, bool) soma[13, 16] = True - def fitted(*args, exclude_mask): - """Return a half-pixel boundary point and a second, unmasked seed.""" + def fitted(*args: object, exclude_mask: np.ndarray) -> tuple[np.ndarray, dict[str, np.ndarray]]: + """Return a half-pixel boundary point and a second, unmasked seed. + + Parameters + ---------- + *args : object + Ignored. + exclude_mask : np.ndarray + The soma mask the plan passes. + + Returns + ------- + tuple + The seeds' (row, column) positions and the info dict. + """ np.testing.assert_array_equal(exclude_mask, soma) return np.array([[12.5, 15.5], [20.0, 22.0]]), { "value": np.array([9.0, 7.0]), @@ -419,9 +503,7 @@ def fitted(*args, exclude_mask): "added": np.array([True, False]), } - monkeypatch.setattr( - "giant_python.extraction.raster.plan.find_sources_wmf", fitted - ) + monkeypatch.setattr("giant_python.extraction.raster.plan.find_sources_wmf", fitted) details = {} p = PlanParams(peak_method="wmf", inter_trial_alignment="rigid") plan = plan_path(trials, soma, p, details=details) @@ -430,15 +512,16 @@ def fitted(*args, exclude_mask): np.testing.assert_array_equal(details["seed_info"]["added"], [False]) -def test_plan_of_trials_of_different_sizes(synthetic_plan): - """Trials of different sizes share one canvas (top left, NaN beyond), - as in MATLAB; their mean images must have the same channels.""" +def test_plan_of_trials_of_different_sizes(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """Trials of different sizes share one canvas. + + Trials of different sizes share one canvas (top left, NaN beyond), + as in MATLAB; their mean images must have the same channels. + """ plan, _ = synthetic_plan trials = _synthetic_trials() # nothing is imaged in the rows and columns cut off here - trials[4] = TrialImages( - trials[4].mean_im[:60, :80], trials[4].act_im[:60, :80] - ) + trials[4] = TrialImages(trials[4].mean_im[:60, :80], trials[4].act_im[:60, :80]) small = plan_path(trials, params=PlanParams(peak_th=12.0)) assert small.shape == plan.shape np.testing.assert_array_equal(small.shifts, plan.shifts) @@ -450,17 +533,18 @@ def test_plan_of_trials_of_different_sizes(synthetic_plan): plan_path(trials) -def test_plan_with_a_trial_without_images(synthetic_plan): - """A kept trial whose images are all NaN (nothing was imaged often +def test_plan_with_a_trial_without_images(synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """A kept trial whose images are all NaN does not enter the template. + + A kept trial whose images are all NaN (nothing was imaged often enough) does not enter the template, so the other trials are planned - as without it; in MATLAB it would leave the path without sources.""" + as without it; in MATLAB it would leave the path without sources. + """ plan, _ = synthetic_plan trials = _synthetic_trials() shape = trials[0].act_im.shape blank = TrialImages(np.full(shape + (2,), NAN), np.full(shape, NAN)) - with_blank = plan_path( - trials[:2] + [blank] + trials[2:], params=PlanParams(peak_th=12.0) - ) + with_blank = plan_path(trials[:2] + [blank] + trials[2:], params=PlanParams(peak_th=12.0)) rest = [0, 1, 3, 4, 5] assert with_blank.keep_trials.all() np.testing.assert_array_equal(with_blank.template_trials, rest) @@ -474,28 +558,59 @@ def test_plan_with_a_trial_without_images(synthetic_plan): plan_path([blank, blank]) -def test_plan_without_sources(): - """A path whose activity images hold nothing above threshold has no - sources, pixels or groups, and still writes and reads.""" +def test_plan_without_sources() -> None: + """A path whose activity images hold nothing above threshold has no sources. + + A path whose activity images hold nothing above threshold has no + sources, pixels or groups, and still writes and reads. + """ trials = _synthetic_trials() plan = plan_path(trials, params=PlanParams(peak_th=1e6)) assert plan.n_sources == 0 and plan.n_pixels == 0 and plan.groups == [] assert plan.seeds.shape == (0, 4) -def test_gaussian_fit_releases_valid_activity_copy(monkeypatch): +def test_gaussian_fit_releases_valid_activity_copy(monkeypatch: pytest.MonkeyPatch) -> None: """Gaussian fitting begins after the valid-trial copy is released.""" act_valid = None original_seeder = raster_plan.seed_sources - def capture_stack(stack, nan_thresh): - """Observe the combined image's input without retaining it.""" + def capture_stack( + stack: np.ndarray, nan_thresh: float + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Observe the combined image's input without retaining it. + + Parameters + ---------- + stack : np.ndarray + The aligned activity images. + nan_thresh : float + The NaN threshold of :func:`combined_activity_image`. + + Returns + ------- + tuple of np.ndarray + What :func:`combined_activity_image` returns. + """ nonlocal act_valid act_valid = ref(stack) return combined_activity_image(stack, nan_thresh) - def check_stack_released(*args, **kwargs): - """Check the copy's lifetime at entry to the real seeder.""" + def check_stack_released(*args: object, **kwargs: object) -> np.ndarray: + """Check the copy's lifetime at entry to the real seeder. + + Parameters + ---------- + *args : object + Forwarded to the real seeder. + **kwargs : object + Forwarded to the real seeder. + + Returns + ------- + np.ndarray + What the real seeder returns. + """ assert act_valid is not None and act_valid() is None return original_seeder(*args, **kwargs) @@ -544,17 +659,18 @@ def _assert_plans_equal(a: ExtractionPlan, b: ExtractionPlan) -> None: assert (x.row0, x.col0) == (y.row0, y.col0) for name in ("sources", "pixels", "sel", "sources_rc"): np.testing.assert_array_equal(getattr(x, name), getattr(y, name)) - for x, y in zip( - a.trial_peaks + a.trial_discard, b.trial_peaks + b.trial_discard - ): + for x, y in zip(a.trial_peaks + a.trial_discard, b.trial_peaks + b.trial_discard): assert (x is None) == (y is None) if x is not None: np.testing.assert_array_equal(x, y) -def test_write_and_read_plan(tmp_path, synthetic_plan): - """A plan survives the file; several paths share a file by group; a - file that is not a plan, or a newer version, is refused.""" +def test_write_and_read_plan(tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict]) -> None: + """A plan survives the file, and a file that is not a plan is refused. + + A plan survives the file; several paths share a file by group; a + file that is not a plan, or a newer version, is refused. + """ plan, _ = synthetic_plan fn = tmp_path / "extraction_plan.h5" write_plan(fn, plan) @@ -562,9 +678,7 @@ def test_write_and_read_plan(tmp_path, synthetic_plan): _assert_plans_equal(plan, back) assert back.trial_discard[0].dtype == bool # an empty plan, written next to it as a second imaging path - empty = plan_path( - _synthetic_trials()[:2] + [None], params=PlanParams(peak_th=1e6) - ) + empty = plan_path(_synthetic_trials()[:2] + [None], params=PlanParams(peak_th=1e6)) write_plan(fn, plan, group="DMD1") write_plan(fn, empty, group="DMD2") write_plan(fn, empty, group="DMD2") # replaces the group @@ -580,17 +694,15 @@ def test_write_and_read_plan(tmp_path, synthetic_plan): @pytest.mark.parametrize("method", ["getactimpeaks", "wmf"]) -def test_plan_saves_numpy_wmf_thresholds(tmp_path, method): +def test_plan_saves_numpy_wmf_thresholds(tmp_path: Path, method: str) -> None: """Accepted NumPy thresholds become built-in floats before saving.""" - thresholds = dict( - wmf_peak_th=np.float32(4), - wmf_dip=np.float32(2), - wmf_deblend_th=np.float32(np.inf), - ) + thresholds = { + "wmf_peak_th": np.float32(4), + "wmf_dip": np.float32(2), + "wmf_deblend_th": np.float32(np.inf), + } p = SiloParams(peak_method=method, **thresholds) - plan = plan_path( - _synthetic_trials(), params=replace(p.plan_params(), **thresholds) - ) + plan = plan_path(_synthetic_trials(), params=replace(p.plan_params(), **thresholds)) for name in thresholds: assert type(getattr(p, name)) is float assert type(getattr(plan.params, name)) is float @@ -602,7 +714,9 @@ def test_plan_saves_numpy_wmf_thresholds(tmp_path, method): _assert_plans_equal(saved, plan) -def test_gaussian_plan_omits_inactive_wmf_settings(tmp_path, synthetic_plan): +def test_gaussian_plan_omits_inactive_wmf_settings( + tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict] +) -> None: """Version-1 Gaussian payloads keep the original parameter fields.""" plan, _ = synthetic_plan inactive = replace(plan.params, wmf_peak_th=4, wmf_dip=2, wmf_deblend_th=9) @@ -615,12 +729,23 @@ def test_gaussian_plan_omits_inactive_wmf_settings(tmp_path, synthetic_plan): _assert_plans_equal(read_plan(fn), plan) -def _matlab_case(case): - """The inputs of one fixture case and MATLAB's results on them. +def _matlab_case(case: str) -> tuple[list[TrialImages | None], PlanParams, dict]: + """Return the inputs of one fixture case and MATLAB's results on them. The fixture holds a 72 x 96 window of five trials of one imaging path - (780125) and what ``SILo.m`` and ``extractTrial.m`` (GIAnT-MATLAB main + (780125) and what SILo.m and extractTrial.m (GIAnT-MATLAB main 5a0673b) compute from it, in Python's orientation and zero-based. + + Parameters + ---------- + case : str + The fixture case, e.g. all_trials. + + Returns + ------- + tuple + The trials (None for those not kept), the plan parameters of the + case, and MATLAB's results on them. """ with h5py.File(FIXTURE, "r") as f: mean = f["inputs/mean_ims"][()].astype(np.float64) @@ -643,60 +768,61 @@ def _matlab_case(case): inter_trial_alignment="rigid", ) keep = ref["keep_trials"].astype(bool) - trials = [ - TrialImages(mean[t], act[t]) if keep[t] else None - for t in range(keep.size) - ] + trials = [TrialImages(mean[t], act[t]) if keep[t] else None for t in range(keep.size)] return trials, params, ref -def _lists(ref, name): - """Index lists of the fixture (``_index`` and ``_ptr``).""" +def _lists(ref: dict, name: str) -> list[np.ndarray]: + """Return the index lists of the fixture (_index and _ptr). + + Parameters + ---------- + ref : dict + MATLAB's results, as :func:`_matlab_case` returns them. + name : str + The prefix of the index and pointer arrays. + + Returns + ------- + list of np.ndarray + The index list between each pair of consecutive pointers. + """ index, ptr = ref[f"{name}_index"], ref[f"{name}_ptr"] - return [index[a:b] for a, b in zip(ptr[:-1], ptr[1:])] + return [index[a:b] for a, b in itertools.pairwise(ptr)] @pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_plan_matches_matlab(case): - """Every step but the Gaussian fit of the seeds reproduces MATLAB: the +def test_plan_matches_matlab(case: str) -> None: + """Every step but the Gaussian fit of the seeds reproduces MATLAB. + + Every step but the Gaussian fit of the seeds reproduces MATLAB: the template, shifts, valid trials, aligned and combined images to rounding error; given MATLAB's seeds, the sources, their pixels and the - subproblems exactly.""" + subproblems exactly. + """ trials, params, ref = _matlab_case(case) details = {} - plan = plan_path( - trials, params=params, seeds=ref["seeds"], details=details - ) - close = dict(rtol=0, atol=1e-9) + plan = plan_path(trials, params=params, seeds=ref["seeds"], details=details) + close = {"rtol": 0, "atol": 1e-9} np.testing.assert_allclose(plan.template, ref["template"], **close) np.testing.assert_array_equal(plan.template_trials, ref["template_trials"]) np.testing.assert_allclose(plan.shifts, ref["shifts"], **close) np.testing.assert_allclose(plan.corr, ref["corr"], **close) assert plan.corr_thresh == pytest.approx(ref["corr_thresh"], abs=1e-12) - np.testing.assert_allclose( - plan.act_valid_pix, ref["act_valid_pix"], **close - ) + np.testing.assert_allclose(plan.act_valid_pix, ref["act_valid_pix"], **close) np.testing.assert_array_equal(plan.valid_trials, ref["valid_trials"]) np.testing.assert_allclose(plan.act_aligned, ref["act_aligned"], **close) np.testing.assert_allclose(plan.act_im, ref["act_im"], **close) if "mean_aligned" in ref: - np.testing.assert_allclose( - plan.mean_aligned, ref["mean_aligned"], rtol=1e-12, atol=1e-9 - ) - np.testing.assert_allclose( - plan.mean_im, ref["mean_im"], rtol=1e-12, atol=1e-9 - ) + np.testing.assert_allclose(plan.mean_aligned, ref["mean_aligned"], rtol=1e-12, atol=1e-9) + np.testing.assert_allclose(plan.mean_im, ref["mean_im"], rtol=1e-12, atol=1e-9) np.testing.assert_allclose(details["med_im"], ref["med_im"], **close) # from MATLAB's seeds on: exact - np.testing.assert_array_equal( - details["keep_sources"], ref["keep_sources"].astype(bool) - ) + np.testing.assert_array_equal(details["keep_sources"], ref["keep_sources"].astype(bool)) np.testing.assert_array_equal(plan.source_rows, ref["source_rows"]) np.testing.assert_array_equal(plan.source_cols, ref["source_cols"]) np.testing.assert_array_equal(plan.source_values, ref["source_values"]) - np.testing.assert_array_equal( - plan.px_always_valid, ref["px_always_valid"].astype(bool) - ) + np.testing.assert_array_equal(plan.px_always_valid, ref["px_always_valid"].astype(bool)) np.testing.assert_array_equal(plan.sel, ref["sel"].astype(bool)) for mine, matlab in zip(plan.source_pixels, _lists(ref, "source_pixel")): np.testing.assert_array_equal(mine, matlab) @@ -714,16 +840,17 @@ def test_plan_matches_matlab(case): assert (g.col0, g.col0 + g.sel.shape[1] - 1) == tuple(cols) -@pytest.mark.parametrize( - "case, same_pixel", [("all_trials", 0.85), ("one_trial_out", 1.0)] -) -def test_own_seeds_are_close_to_matlabs(case, same_pixel): - """Seeding MATLAB's combined activity image with this package's fit +@pytest.mark.parametrize("case, same_pixel", [("all_trials", 0.85), ("one_trial_out", 1.0)]) +def test_own_seeds_are_close_to_matlabs(case: str, same_pixel: float) -> None: + """Seeding MATLAB's combined activity image gives nearly MATLAB's sources. + + Seeding MATLAB's combined activity image with this package's fit gives nearly MATLAB's sources. They are not identical: the Gaussian fit is ill-conditioned for peaks narrower than a pixel and MATLAB's lsqcurvefit stops on a tolerance or on its evaluation limit, so where it ends depends on the optimizer (at a threshold of 3 SDs MATLAB finds - 21 sources in this window and this package 20).""" + 21 sources in this window and this package 20). + """ trials, params, ref = _matlab_case(case) plan = plan_path(trials, params=params) matlab = np.column_stack([ref["source_rows"], ref["source_cols"]]) @@ -735,12 +862,15 @@ def test_own_seeds_are_close_to_matlabs(case, same_pixel): @pytest.mark.parametrize("case", ["all_trials", "one_trial_out"]) -def test_default_seeding_on_matlabs_window(case): - """The default seeding (local fits, merging residual peaks within +def test_default_seeding_on_matlabs_window(case: str) -> None: + """The default seeding stays within 1 px of MATLAB's sources. + + The default seeding (local fits, merging residual peaks within 1.5 px) on MATLAB's combined activity image: every MATLAB source is within 1 px of a source here, and every source here within 1 px of a MATLAB source; only sources next to another are merged (all trials: 16 - of MATLAB's 21). Without merging the local fit gives MATLAB's count.""" + of MATLAB's 21). Without merging the local fit gives MATLAB's count. + """ import dataclasses trials, params, ref = _matlab_case(case) @@ -765,11 +895,14 @@ def test_default_seeding_on_matlabs_window(case): def test_plans_written_before_the_seed_options_read_as_matlabs( - tmp_path, synthetic_plan -): - """A plan file without the seed fields (written before they existed) + tmp_path: Path, synthetic_plan: tuple[ExtractionPlan, dict] +) -> None: + """A plan file without the seed fields reads back with MATLAB's seed fit. + + A plan file without the seed fields (written before they existed) reads back with MATLAB's seed fit and no merging, the settings it was - made with; a current plan keeps its own.""" + made with; a current plan keeps its own. + """ import json import h5py @@ -786,22 +919,35 @@ def test_plans_written_before_the_seed_options_read_as_matlabs( assert (old.seed_fit, old.seed_merge_px) == ("matlab", 0.0) -def _cropped(trial, c0): - """A trial whose registered image starts ``c0`` columns later (the - leftmost ROIs were deleted before it).""" - return TrialImages( - trial.mean_im[:, c0:], trial.act_im[:, c0:], trial.peaks, trial.discard - ) +def _cropped(trial: TrialImages, c0: int) -> TrialImages: + """Return a trial whose registered image starts c0 columns later. + + The leftmost ROIs were deleted before it. + + Parameters + ---------- + trial : TrialImages + The trial to crop. + c0 : int + Number of columns cut off on the left. + Returns + ------- + TrialImages + The cropped trial. + """ + return TrialImages(trial.mean_im[:, c0:], trial.act_im[:, c0:], trial.peaks, trial.discard) + + +def test_frame_offsets_and_origins(tmp_path: Path) -> None: + """Offsets are relative to the earliest start; origins come from the alignment files. -def test_frame_offsets_and_origins(tmp_path): - """Offsets are relative to the earliest start; unknown starts and a + Offsets are relative to the earliest start; unknown starts and a session without any give zero. Origins come from the alignment files' - ``slap2/cropRow`` and ``cropCol``; NaN without the file or the fields.""" + slap2/cropRow and cropCol; NaN without the file or the fields. + """ o = np.array([[115, 147], [115, 196], [NAN, NAN], [117, 285]]) - np.testing.assert_array_equal( - frame_offsets(o, 4), [[0, 0], [0, 49], [0, 0], [2, 138]] - ) + np.testing.assert_array_equal(frame_offsets(o, 4), [[0, 0], [0, 49], [0, 0], [2, 138]]) assert not frame_offsets(None, 3).any() assert not frame_offsets(np.full((2, 2), NAN), 2).any() files = [] @@ -819,18 +965,19 @@ def test_frame_offsets_and_origins(tmp_path): assert np.isnan(got[2:]).all() -def test_plan_places_trials_by_frame_origin(tmp_path): - """Trials whose registered images start elsewhere on the raster (the +def test_plan_places_trials_by_frame_origin(tmp_path: Path) -> None: + """Trials whose registered images start elsewhere on the raster are placed by their start. + + Trials whose registered images start elsewhere on the raster (the ROIs changed) are placed by their start: their maps include the offset, the consensus images agree with those of the uncropped session, and the sources are found where every trial imaged them. The - same origin in every trial changes nothing.""" + same origin in every trial changes nothing. + """ full = _synthetic_trials() p = PlanParams(peak_th=12.0) ref = plan_path(full, params=p) - same = plan_path( - full, params=p, frame_origins=np.tile([100.0, 200.0], (5, 1)) - ) + same = plan_path(full, params=p, frame_origins=np.tile([100.0, 200.0], (5, 1))) np.testing.assert_array_equal(same.shifts, ref.shifts) np.testing.assert_array_equal(same.act_im, ref.act_im) assert not same.frame_offset.any() @@ -862,10 +1009,7 @@ def test_plan_places_trials_by_frame_origin(tmp_path): assert right.sum() == 4 found = np.column_stack([plan.source_rows, plan.source_cols]) for r, c in zip(ref.source_rows[right], ref.source_cols[right]): - assert ( - np.hypot(found[:, 0] - (r - g[0]), found[:, 1] - (c - g[1])).min() - <= 1.0 - ) + assert np.hypot(found[:, 0] - (r - g[0]), found[:, 1] - (c - g[1])).min() <= 1.0 assert (plan.source_cols > c0 - 3).all() # the plan file keeps the offsets f = tmp_path / "plan.h5" @@ -885,6 +1029,4 @@ def test_plan_places_trials_by_frame_origin(tmp_path): frame_origins=origins, ) moved = np.round(b.shifts[3] + b.frame_offset[3]).astype(int) - np.testing.assert_array_equal( - b.soma_mask, np.roll(a.soma_mask, tuple(-moved), axis=(0, 1)) - ) + np.testing.assert_array_equal(b.soma_mask, np.roll(a.soma_mask, tuple(-moved), axis=(0, 1))) diff --git a/tests/raster/test_raster_results.py b/tests/raster/test_raster_results.py index f0585351..c4c4ceb9 100644 --- a/tests/raster/test_raster_results.py +++ b/tests/raster/test_raster_results.py @@ -1,10 +1,17 @@ -"""Tests of results files: solved subproblems of a trial-path, written by -the solve stage and assembled by the collect stage.""" +"""Tests of results files: solved subproblems of a trial-path. +The results files are written by the solve stage and assembled by the collect stage. +""" + +from pathlib import Path + +import h5py import numpy as np +import numpy.typing as npt import pytest from giant_python.extraction.raster.results import ( + TrialOutcome, TrialRecord, read_results, subproblem_results, @@ -21,8 +28,19 @@ N_PX, N_SRC, N_T = 9, 4, 50 -def record(seed=0): - """A trial's record.""" +def record(seed: int = 0) -> TrialRecord: + """Return a trial's record. + + Parameters + ---------- + seed : int, default 0 + Seed of the random generator that fills the record. + + Returns + ------- + TrialRecord + A record of N_T frames of random traces, with a random discard mask. + """ rng = np.random.default_rng(seed) return TrialRecord( frame_lines=np.arange(1, N_T + 1) * 40, @@ -33,8 +51,19 @@ def record(seed=0): ) -def solved(seed=1): - """Three subproblems' placements and results.""" +def solved(seed: int = 1) -> dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]]: + """Return three subproblems' placements and results. + + Parameters + ---------- + seed : int, default 1 + Seed of the random generator that fills the results. + + Returns + ------- + dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + For each subproblem index, its pixels, its sources and its result. + """ rng = np.random.default_rng(seed) placements = [ (np.array([0, 1, 2, 3]), np.array([0])), @@ -59,33 +88,43 @@ def solved(seed=1): return out -def attrs(**kw): - """A results file's attributes.""" - a = dict( - settings_hash="h", - container="path1_trial0001.h5", - container_hash="c", - path=1, - trial=1, - n_subproblems=3, - n_pixels=N_PX, - n_sources=N_SRC, - photon_scale=25.0, - extracted=1, - ) +def attrs(**kw: object) -> dict[str, object]: + """Return a results file's attributes. + + Parameters + ---------- + **kw : object + Attributes that replace or add to the defaults. + + Returns + ------- + dict[str, object] + The attributes of a consistent results file of the three subproblems of :func:`solved`, + updated with kw. + """ + a = { + "settings_hash": "h", + "container": "path1_trial0001.h5", + "container_hash": "c", + "path": 1, + "trial": 1, + "n_subproblems": 3, + "n_pixels": N_PX, + "n_sources": N_SRC, + "photon_scale": 25.0, + "extracted": 1, + } a.update(kw) return a -def test_round_trip(tmp_path): +def test_round_trip(tmp_path: Path) -> None: """The record, every result and the attributes come back.""" rec, res = record(), solved() write_results(tmp_path / "r.h5", rec, res, attrs()) back = read_results(tmp_path / "r.h5") for name in ("frame_lines", "discard", "global_f", "roi_f", "roi_fsvd"): - np.testing.assert_array_equal( - getattr(back.record, name), getattr(rec, name) - ) + np.testing.assert_array_equal(getattr(back.record, name), getattr(rec, name)) assert sorted(back.results) == [0, 1, 2] for k, (pix, src, r) in res.items(): bp, bs, br = back.results[k] @@ -101,9 +140,11 @@ def test_round_trip(tmp_path): assert not list(tmp_path.glob("*.partial")) -def test_assembly_does_not_depend_on_the_split(tmp_path): - """One file or one per subproblem: the same trial, equal to - assembleResults and processResult of the results.""" +def test_assembly_does_not_depend_on_the_split(tmp_path: Path) -> None: + """One file or one per subproblem: the same trial. + + The trial is equal to assembleResults and processResult of the results. + """ rec, res = record(), solved() p = SolverParams() write_results(tmp_path / "all.h5", rec, res, attrs()) @@ -118,7 +159,7 @@ def test_assembly_does_not_depend_on_the_split(tmp_path): class Place: """What assemble_results reads of a subproblem.""" - def __init__(self, pix, src): + def __init__(self, pix: np.ndarray, src: np.ndarray) -> None: """Placement only.""" self.pixels, self.sources = pix, src @@ -135,15 +176,15 @@ def __init__(self, pix, src): ) for got in (whole, split): for name in ("footprints", "events", "denoised", "ls", "f0", "snr"): - np.testing.assert_array_equal( - getattr(got.activity, name), getattr(direct, name) - ) + np.testing.assert_array_equal(getattr(got.activity, name), getattr(direct, name)) np.testing.assert_array_equal(got.record.global_f, rec.global_f) -def test_incomplete_or_conflicting_results_raise(tmp_path): - """A missing subproblem, two different results of one, and files of - two containers are errors.""" +def test_incomplete_or_conflicting_results_raise(tmp_path: Path) -> None: + """A missing subproblem, two different results of one, and files of two containers are errors. + + All three are errors of the assembly. + """ rec, res = record(), solved() p = SolverParams() write_results(tmp_path / "a.h5", rec, {0: res[0], 1: res[1]}, attrs()) @@ -156,9 +197,7 @@ def test_incomplete_or_conflicting_results_raise(tmp_path): [read_results(tmp_path / "a.h5"), read_results(tmp_path / "b.h5")], p, ) - write_results( - tmp_path / "c.h5", rec, {2: res[2]}, attrs(container_hash="other") - ) + write_results(tmp_path / "c.h5", rec, {2: res[2]}, attrs(container_hash="other")) with pytest.raises(ValueError, match="different containers"): trial_outcome( [read_results(tmp_path / "a.h5"), read_results(tmp_path / "c.h5")], @@ -173,13 +212,9 @@ def test_incomplete_or_conflicting_results_raise(tmp_path): write_results(tmp_path / "e.h5", rec, {2: moved[2]}, attrs()) write_results(tmp_path / "f.h5", rec, {0: res[0], 1: res[1]}, attrs()) with pytest.raises(ValueError, match="two different results"): - trial_outcome( - [read_results(tmp_path / n) for n in ("f.h5", "d.h5", "e.h5")], p - ) + trial_outcome([read_results(tmp_path / n) for n in ("f.h5", "d.h5", "e.h5")], p) # parts solved with different settings - write_results( - tmp_path / "g.h5", rec, {2: res[2]}, attrs(solve_settings="lam 0.5") - ) + write_results(tmp_path / "g.h5", rec, {2: res[2]}, attrs(solve_settings="lam 0.5")) write_results( tmp_path / "h.h5", rec, @@ -187,12 +222,10 @@ def test_incomplete_or_conflicting_results_raise(tmp_path): attrs(solve_settings="lam 0.9"), ) with pytest.raises(ValueError, match="different settings"): - trial_outcome( - [read_results(tmp_path / n) for n in ("g.h5", "h.h5")], p - ) + trial_outcome([read_results(tmp_path / n) for n in ("g.h5", "h.h5")], p) -def test_trial_not_extracted(tmp_path): +def test_trial_not_extracted(tmp_path: Path) -> None: """A trial too short to extract has its record and no sources.""" rec = record() write_results(tmp_path / "s.h5", rec, {}, attrs(extracted=0)) @@ -201,14 +234,14 @@ def test_trial_not_extracted(tmp_path): assert out.record.n_frames == N_T -def test_subproblem_results(): +def test_subproblem_results() -> None: """Placements of solved subproblems, with their container indices.""" class Sub: """A subproblem's placement.""" - def __init__(self, k): - """Pixels and sources of subproblem ``k``.""" + def __init__(self, k: int) -> None: + """Pixels and sources of subproblem k.""" self.pixels, self.sources = np.array([k]), np.array([k]) res = subproblem_results([Sub(4), Sub(7)], ["a", "b"], [4, 7]) @@ -218,10 +251,12 @@ def __init__(self, k): subproblem_results([Sub(0)], ["a", "b"]) -def test_sizes_and_activity_traces_without_the_outcome(tmp_path): - """trial_shape and trial_ls give, bit for bit, what the assembled - outcome gives (one file or one per subproblem), and None where it has - no activity.""" +def test_sizes_and_activity_traces_without_the_outcome(tmp_path: Path) -> None: + """trial_shape and trial_ls give, bit for bit, what the assembled outcome gives. + + That holds for one file or one per subproblem, and they give None where the outcome has no + activity. + """ from giant_python.extraction.raster.results import trial_ls, trial_shape rec, res = record(), solved() @@ -246,26 +281,74 @@ def test_sizes_and_activity_traces_without_the_outcome(tmp_path): assert size.trace_shape is None and size.n_frames == N_T -def _with(r, **kw): - """A SubproblemResult with some fields replaced.""" +def _with(r: SubproblemResult, **kw: object) -> SubproblemResult: + """Return a SubproblemResult with some fields replaced. + + Parameters + ---------- + r : SubproblemResult + The result to copy. + **kw : object + The fields to replace, by name. + + Returns + ------- + SubproblemResult + A copy of r with the fields in kw replaced. + """ from dataclasses import replace return replace(r, **kw) -def _image(res): - """Results with F0 images, that of subproblem 1 of the wrong size.""" - out = { - k: (p, s, _with(x, f0_image=np.zeros((2, p.size)))) - for k, (p, s, x) in res.items() - } +def _image( + res: dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]], +) -> dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]]: + """Return results with F0 images, that of subproblem 1 of the wrong size. + + Parameters + ---------- + res : dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + For each subproblem index, its pixels, its sources and its result. + + Returns + ------- + dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + res with an F0 image on each result, that of subproblem 1 with one pixel. + """ + out = {k: (p, s, _with(x, f0_image=np.zeros((2, p.size)))) for k, (p, s, x) in res.items()} p, s, x = out[1] out[1] = (p, s, _with(x, f0_image=np.zeros((2, 1)))) return out -def _sub(res, k, pix=None, src=None, **kw): - """Results with subproblem ``k``'s placement or fields replaced.""" +def _sub( + res: dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]], + k: int, + pix: npt.ArrayLike | None = None, + src: npt.ArrayLike | None = None, + **kw: object, +) -> dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]]: + """Return results with subproblem k's placement or fields replaced. + + Parameters + ---------- + res : dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + For each subproblem index, its pixels, its sources and its result. + k : int + The subproblem to change. + pix : array_like, optional + New pixels of subproblem k (default: unchanged). + src : array_like, optional + New sources of subproblem k (default: unchanged). + **kw : object + Fields of the result of subproblem k to replace, by name. + + Returns + ------- + dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + A copy of res with subproblem k changed. + """ out = dict(res) p, s, r = res[k] out[k] = ( @@ -291,10 +374,32 @@ def _sub(res, k, pix=None, src=None, **kw): _BAD_DISCARD = {"empty discard": 0, "discard of other frames": 3} -def _reshaped(n_ch=2, n_t=N_T, n_src=None, fp3=False): - """Results of every subproblem with ``n_ch`` channels, ``n_t`` - frames, ``n_src`` sources each (default: as solved), footprints with - a third axis if ``fp3``; and the matching record.""" +def _reshaped( + n_ch: int = 2, n_t: int = N_T, n_src: int | None = None, fp3: bool = False +) -> tuple[dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]], TrialRecord]: + """Return results of every subproblem with n_ch channels, and the matching record. + + The results have n_t frames, n_src sources each (default: as solved), footprints with + a third axis if fp3. + + Parameters + ---------- + n_ch : int, default 2 + Number of channels. + n_t : int, default N_T + Number of frames. + n_src : int, optional + Number of sources of each subproblem (default: as solved). + fp3 : bool, default False + Whether the footprints have a third axis. + + Returns + ------- + dict[int, tuple[np.ndarray, np.ndarray, SubproblemResult]] + For each subproblem index, its pixels, its sources and its result. + TrialRecord + The record that matches the results. + """ res, rec = solved(), record() out = {} for k, (pix, src, r) in res.items(): @@ -338,9 +443,14 @@ def _reshaped(n_ch=2, n_t=N_T, n_src=None, fp3=False): } -def _float_sources(h): - """Store subproblem 1's sources as floats (write_results writes - integers).""" +def _float_sources(h: h5py.File) -> None: + """Store subproblem 1's sources as floats (write_results writes integers). + + Parameters + ---------- + h : h5py.File + The results file to change. + """ del h["subproblems/1/sources"] h["subproblems/1/sources"] = np.array([1.0, 2.0]) @@ -393,28 +503,62 @@ def _float_sources(h): } -def _shards(tmp_path, case): - """The results files of one of the cases of - :func:`test_shortcuts_accept_and_reject_what_the_assembly_does`.""" +def _shards(tmp_path: Path, case: str) -> list[Path]: + """Return the results files of one of the cases of the shortcuts test. + + The cases are those of :func:`test_shortcuts_accept_and_reject_what_the_assembly_does`. + + Parameters + ---------- + tmp_path : Path + Directory in which to write the files. + case : str + Name of the case. + + Returns + ------- + list[Path] + The results files of the case, in the order in which they are given to the assembly. + """ import h5py rec, res = record(), solved() res["other"] = (1, solved(seed=5)[1]) res["moved"] = (2, (res[2][0], np.array([2]), res[2][2])) - def put(name, keys, rec=rec, results=res, **kw): - """A results file of the subproblems ``keys``.""" - sub = dict( - results[k] if isinstance(k, str) else (k, results[k]) for k in keys - ) + def put( + name: str, + keys: tuple, + rec: TrialRecord = rec, + results: dict = res, + **kw: object, + ) -> Path: + """Return a results file of the subproblems keys, written. + + Parameters + ---------- + name : str + File name, in tmp_path. + keys : tuple + Keys of results of the subproblems in the file. + rec : TrialRecord, default the record of the case + The trial record to write. + results : dict, default the solved subproblems + The subproblems to choose from. + **kw : object + Attributes of the file that replace the defaults of :func:`attrs`. + + Returns + ------- + Path + The file written. + """ + sub = dict(results[k] if isinstance(k, str) else (k, results[k]) for k in keys) write_results(tmp_path / name, rec, sub, attrs(**kw)) return tmp_path / name if case in _SPLITS: - return [ - put(f"s{i}.h5", keys, **kw) - for i, (keys, kw) in enumerate(_SPLITS[case]) - ] + return [put(f"s{i}.h5", keys, **kw) for i, (keys, kw) in enumerate(_SPLITS[case])] if case in _EDITS: keys, edit = _EDITS[case] f = put("edited.h5", keys) @@ -474,13 +618,15 @@ def put(name, keys, rec=rec, results=res, **kw): "negative sources", ], ) -def test_shortcuts_accept_and_reject_what_the_assembly_does(tmp_path, case): - """trial_shape and trial_ls give what the assembled trial gives, for - any split of the subproblems over the files (an empty shard first, +def test_shortcuts_accept_and_reject_what_the_assembly_does(tmp_path: Path, case: str) -> None: + """trial_shape and trial_ls give what the assembled trial gives. + + That holds for any split of the subproblems over the files (an empty shard first, any order, equal duplicates), and where trial_outcome raises they raise the same exception with the same message (interrupted dispatch, file version, containers, settings, conflicting duplicates, - placements, shapes, discard mask).""" + placements, shapes, discard mask). + """ from giant_python.extraction.raster.results import ( TrialShape, trial_ls, @@ -490,8 +636,14 @@ def test_shortcuts_accept_and_reject_what_the_assembly_does(tmp_path, case): files = _shards(tmp_path, case) p = SolverParams() - def outcome(): - """What the full assembly gives or raises.""" + def outcome() -> tuple[TrialOutcome | None, Exception | None]: + """Return what the full assembly gives or raises. + + Returns + ------- + tuple[TrialOutcome | None, Exception | None] + The assembled outcome and None, or None and the exception the assembly raised. + """ try: return trial_outcome([read_results(f) for f in files], p), None except Exception as exc: # noqa: BLE001 (compared below) @@ -515,11 +667,13 @@ def outcome(): assert trial_ls(files, 1)[0].tobytes() == ref.activity.ls[1].tobytes() -def test_shortcuts_read_no_traces(tmp_path, monkeypatch): - """trial_shape reads none of the record's data and no traces or - footprints (only indices, placements and shapes); trial_ls reads, of +def test_shortcuts_read_no_traces(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """trial_shape reads none of the record's data and no traces or footprints. + + It reads only indices, placements and shapes; trial_ls reads, of the data, only the discard mask and each subproblem's ls of the one - channel and snr. Neither assembles the trial.""" + channel and snr. Neither assembles the trial. + """ import h5py from giant_python.extraction.raster import results @@ -531,16 +685,42 @@ def test_shortcuts_read_no_traces(tmp_path, monkeypatch): write_results(tmp_path / f"s{k}.h5", rec, {k: res[k]}, attrs()) files.append(tmp_path / f"s{k}.h5") - def no_assembly(*args, **kw): - """The full assembly must not be needed.""" + def no_assembly(*args: object, **kw: object) -> None: + """Fail: the full assembly must not be needed. + + Parameters + ---------- + *args : object + Ignored. + **kw : object + Ignored. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("assembled") monkeypatch.setattr(results, "trial_outcome", no_assembly) read = [] get = h5py.Dataset.__getitem__ - def spy(self, key): - """Record which datasets' data are read, and the selection.""" + def spy(self: h5py.Dataset, key: object) -> object: + """Return the data of a dataset, and record which dataset and selection were read. + + Parameters + ---------- + self : h5py.Dataset + The dataset read. + key : object + The selection. + + Returns + ------- + object + What ``h5py.Dataset.__getitem__`` gives for key. + """ read.append((self.name.split("/")[-1], key)) return get(self, key) @@ -562,12 +742,17 @@ def spy(self, key): assert [key for name, key in read if name == "ls"] == [channel] * 3 -def test_traces_come_from_the_files_checked(tmp_path, monkeypatch): - """A shard replaced (as silo-solve publishes one, by renaming) after - trial_ls has checked the files and before it reads their traces does - not mix in: the traces are trial_outcome's of the file versions that +def test_traces_come_from_the_files_checked( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A shard replaced after trial_ls has checked the files does not mix in. + + The shard is replaced (as silo-solve publishes one, by renaming) after + trial_ls has checked the files and before it reads their traces. The traces + are trial_outcome's of the file versions that were checked, while the pair with the new version is one that - trial_outcome rejects.""" + trial_outcome rejects. + """ import os from giant_python.extraction.raster import results @@ -584,8 +769,19 @@ def test_traces_come_from_the_files_checked(tmp_path, monkeypatch): trial_outcome([read_results(a), read_results(new)], p) checked = results._check_entries - def replace_after(*args): - """Check, then publish the new version of shard b.""" + def replace_after(*args: object) -> tuple[int, int] | None: + """Check, then publish the new version of shard b. + + Parameters + ---------- + *args : object + Passed to _check_entries. + + Returns + ------- + tuple[int, int] | None + What _check_entries gives for args, from the version checked. + """ got = checked(*args) os.replace(new, b) return got diff --git a/tests/raster/test_raster_seed_acceptance.py b/tests/raster/test_raster_seed_acceptance.py index 02fd87bc..60a12f52 100644 --- a/tests/raster/test_raster_seed_acceptance.py +++ b/tests/raster/test_raster_seed_acceptance.py @@ -259,14 +259,14 @@ def test_silo_params_null_acceptance() -> None: keep = SiloParams(baseline_source="network", localization_keep_null=True) assert keep.seed_acceptance == "image" and keep.localization_keep_null for bad in ( - dict(seed_acceptance="null"), # no bootstrap null - dict( - baseline_source="network", - seed_acceptance="null", - localization_keep_null=False, - ), - dict(baseline_source="network", seed_false_per_field=-1.0), - dict(baseline_source="network", seed_acceptance="robust"), + {"seed_acceptance": "null"}, # no bootstrap null + { + "baseline_source": "network", + "seed_acceptance": "null", + "localization_keep_null": False, + }, + {"baseline_source": "network", "seed_false_per_field": -1.0}, + {"baseline_source": "network", "seed_acceptance": "robust"}, ): with pytest.raises(ValueError): SiloParams(**bad) @@ -290,7 +290,7 @@ def test_silo_params_evidence_test() -> None: assert on.stage_settings("collect")["min_source_snr"] == 2.0 assert on.to_matlab(2, 80.0)["minSourceSNR"] == 2.0 assert on.to_matlab(2, 80.0)["minSourceEventRate"] == 1.5 - for bad in (dict(min_source_snr=-1.0), dict(min_source_event_rate=-1)): + for bad in ({"min_source_snr": -1.0}, {"min_source_event_rate": -1}): with pytest.raises(ValueError): SiloParams(**bad) diff --git a/tests/raster/test_raster_seeding.py b/tests/raster/test_raster_seeding.py index 0807c378..df32da36 100644 --- a/tests/raster/test_raster_seeding.py +++ b/tests/raster/test_raster_seeding.py @@ -16,7 +16,7 @@ FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" -def test_disk_strel_matches_matlab(): +def test_disk_strel_matches_matlab() -> None: """strel('disk', r).Neighborhood of MATLAB R2024b for r = 0 .. 39.""" with h5py.File(FIXTURE, "r") as f: g = f["strel_disk"] @@ -26,13 +26,14 @@ def test_disk_strel_matches_matlab(): ) -def test_disk_strel_shapes(): - """MATLAB's disk is smaller than its radius says: radius 3 is a full - 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's selRadius).""" +def test_disk_strel_shapes() -> None: + """MATLAB's disk is smaller than its radius says. + + Radius 3 is a full + 5 x 5 square, radius 6 an 11 x 11 octagon (SiLo's selRadius). + """ assert disk_strel(0).shape == (1, 1) - np.testing.assert_array_equal( - disk_strel(1), [[0, 1, 0], [1, 1, 1], [0, 1, 0]] - ) + np.testing.assert_array_equal(disk_strel(1), [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) np.testing.assert_array_equal(disk_strel(3), np.ones((5, 5), bool)) d6 = disk_strel(6) assert d6.shape == (11, 11) and d6.sum() == 109 @@ -49,19 +50,20 @@ def test_disk_strel_shapes(): disk_strel(5, 5) -def test_sources_from_seeds_rounds_and_prunes(): - """Positions round as MATLAB's (halves up in its one-based +def test_sources_from_seeds_rounds_and_prunes() -> None: + """Positions round as MATLAB's, the first seed of a pixel wins. + + Positions round as MATLAB's (halves up in its one-based coordinates), the first seed of a pixel wins, order is kept, and - positions are clamped to the image.""" - seeds = np.array( - [ - [5.0, 3.5, 7.49, 0.4], # MATLAB 4.5, 8.49 -> pixel (5, 8) - [2.0, 9.2, 1.0, 0.4], - [9.0, 3.6, 7.2, 0.4], # same pixel as the first: dropped - [1.0, -0.5, 19.5, 0.4], # MATLAB 0.5, 20.5 -> (1, 21): clamped - [4.0, 2.5 - 1e-12, 0.0, 0.4], - ] - ) + positions are clamped to the image. + """ + seeds = np.array([ + [5.0, 3.5, 7.49, 0.4], # MATLAB 4.5, 8.49 -> pixel (5, 8) + [2.0, 9.2, 1.0, 0.4], + [9.0, 3.6, 7.2, 0.4], # same pixel as the first: dropped + [1.0, -0.5, 19.5, 0.4], # MATLAB 0.5, 20.5 -> (1, 21): clamped + [4.0, 2.5 - 1e-12, 0.0, 0.4], + ]) rows, cols, values = sources_from_seeds(seeds, (12, 20)) np.testing.assert_array_equal(rows, [4, 9, 0, 2]) np.testing.assert_array_equal(cols, [7, 1, 19, 0]) @@ -70,10 +72,12 @@ def test_sources_from_seeds_rounds_and_prunes(): assert all(x.size == 0 for x in empty) -def test_select_source_pixels(): - """A source's pixels are MATLAB's disk within the image and the valid - pixels, in column-major order; sources that lose their own pixel or - nearly all pixels are pruned.""" +def test_select_source_pixels() -> None: + """A source's pixels are MATLAB's disk within the image and the valid pixels. + + They are in column-major order; sources that lose their own pixel or + nearly all pixels are pruned. + """ valid = np.ones((30, 40), bool) valid[:, 25:] = False valid[12, 10] = False @@ -104,10 +108,13 @@ def test_select_source_pixels(): assert more.pixels[0].size == 6 and more.keep[0] -def test_seed_sources(): - """The default method seeds blobs; the soma mask excludes them; unknown +def test_seed_sources() -> None: + """The default method seeds blobs; the soma mask excludes them. + + Unknown and unported methods are refused; an image without usable pixels gives - no seeds.""" + no seeds. + """ rng = np.random.default_rng(0) im = rng.normal(0, 0.3, (40, 50)) rr, cc = np.mgrid[:40, :50] @@ -115,17 +122,13 @@ def test_seed_sources(): im += 20 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) seeds = seed_sources(im, 8.0) assert seeds.shape == (2, 4) - np.testing.assert_allclose( - seeds[np.argsort(seeds[:, 1]), 1:3], [(10, 12), (28, 35)], atol=0.3 - ) + np.testing.assert_allclose(seeds[np.argsort(seeds[:, 1]), 1:3], [(10, 12), (28, 35)], atol=0.3) soma = np.zeros(im.shape, bool) soma[20:, 25:] = True masked = seed_sources(im, 8.0, soma) assert masked.shape == (1, 4) and abs(masked[0, 1] - 10) < 0.3 # an all-false mask is no mask - np.testing.assert_array_equal( - seed_sources(im, 8.0, np.zeros(im.shape, bool)), seeds - ) + np.testing.assert_array_equal(seed_sources(im, 8.0, np.zeros(im.shape, bool)), seeds) assert seed_sources(np.full((5, 5), np.nan), 3.0).shape == (0, 4) assert seed_sources(im, 8.0, np.ones(im.shape, bool)).shape == (0, 4) with pytest.raises(ValueError, match="WMF needs aligned per-trial"): diff --git a/tests/raster/test_raster_silo_load_ahead.py b/tests/raster/test_raster_silo_load_ahead.py index 1b689f0b..a6899cd6 100644 --- a/tests/raster/test_raster_silo_load_ahead.py +++ b/tests/raster/test_raster_silo_load_ahead.py @@ -1,15 +1,18 @@ -"""Loading trials ahead of the solver in the streamed run -(``SiloExecution.load_workers``, ``load_memory_gb``).""" +"""Loading trials ahead of the solver in the streamed run. + +The options are SiloExecution.load_workers and load_memory_gb. +""" import threading import time +from collections.abc import Iterable, Iterator from dataclasses import replace from pathlib import Path import numpy as np import pytest -from giant_python.models.params import SiloExecution +from giant_python.models.params import SiloExecution, SiloParams from giant_python.pipeline import silo from giant_python.pipeline.silo_session import SiloSession @@ -24,23 +27,34 @@ ) -def _units(n, lines=100.0): - """``n`` units of a path, each of ``lines`` lines.""" - return [ - silo._Unit(0, t, None, "", "", Path(f"r{t}.h5"), Path(""), lines) - for t in range(n) - ] +def _units(n: int, lines: float = 100.0) -> list[silo._Unit]: + """Build n units of a path, each of lines lines. + + Returns + ------- + list[silo._Unit] + The units, one per trial 0 to n - 1. + """ + return [silo._Unit(0, t, None, "", "", Path(f"r{t}.h5"), Path(""), lines) for t in range(n)] + +def test_loaded_keeps_order_and_limits(monkeypatch: pytest.MonkeyPatch) -> None: + """Units come back in order whatever finishes first. -def test_loaded_keeps_order_and_limits(monkeypatch): - """Units come back in order whatever finishes first; at most - ``load_workers`` load at once; with a memory limit only one loads until - a load has measured the bytes per line, then as many as fit.""" + At most load_workers load at once; with a memory limit only one loads until + a load has measured the bytes per line, then as many as fit. + """ active, most, started = [0], [0], [] lock = threading.Lock() - def load(u): - """A load that takes longer for earlier units.""" + def load(u: silo._Unit) -> dict[str, int]: + """Load slowly for earlier units, so that they finish last. + + Returns + ------- + dict[str, int] + The unit's trial and a measured size of 1000 bytes. + """ with lock: active[0] += 1 most[0] = max(most[0], active[0]) @@ -67,16 +81,25 @@ def load(u): assert started == [0] -def test_loaded_waits_for_a_measured_load_and_takes_units_lazily(): - """A load without ``nbytes`` (a trial too short to extract) gives no +def test_loaded_waits_for_a_measured_load_and_takes_units_lazily() -> None: + """Check that a load without nbytes gives no estimate. + + A load without nbytes (a trial too short to extract) gives no estimate: with a memory limit the loads stay one at a time until a load reports its bytes. Units are taken from the iterable only when they are - about to be loaded.""" + about to be loaded. + """ active, most, taken = [0], [0], [] lock = threading.Lock() - def load(u): - """The first unit is short (no subproblems, no bytes).""" + def load(u: silo._Unit) -> dict[str, int]: + """Load units, the first of which is short (no subproblems, no bytes). + + Returns + ------- + dict[str, int] + An empty dict for the first unit, else a measured size of 1000 bytes. + """ with lock: active[0] += 1 most[0] = max(most[0], active[0]) @@ -87,8 +110,14 @@ def load(u): return {} return {"nbytes": 1000} - def lazy(units): - """The units, noting when each is taken.""" + def lazy(units: Iterable[silo._Unit]) -> Iterator[silo._Unit]: + """Yield the units, noting when each is taken. + + Yields + ------ + silo._Unit + Each unit, as it is taken. + """ for u in units: taken.append(u.t) yield u @@ -108,18 +137,30 @@ def lazy(units): assert taken == [0] -def test_loaded_hands_on_earlier_units_before_a_failed_check(): - """With several loaders, an error raised while taking a unit (its - check) reaches the caller after the units taken before it.""" +def test_loaded_hands_on_earlier_units_before_a_failed_check() -> None: + """Check that a failed check reaches the caller after the earlier units. + + With several loaders, an error raised while taking a unit (its + check) reaches the caller after the units taken before it. + """ + + def units() -> Iterator[silo._Unit]: + """Yield two units, then a failing check. + + Yields + ------ + silo._Unit + Each of the two units. - def units(): - """Two units, then a failing check.""" + Raises + ------ + FileNotFoundError + After the two units, as the failing check. + """ yield from _units(2) raise FileNotFoundError("no baseline") - gen = silo._loaded( - units(), lambda u: {"t": u.t}, SiloExecution(load_workers=3) - ) + gen = silo._loaded(units(), lambda u: {"t": u.t}, SiloExecution(load_workers=3)) got = [] with pytest.raises(FileNotFoundError, match="no baseline"): for u, item in gen: @@ -129,18 +170,41 @@ def units(): @pytest.mark.parametrize("load_workers", [1, 3]) def test_streamed_run_checks_later_trials_when_it_reaches_them( - tmp_path, fake, monkeypatch, load_workers # noqa: F811 -): - """A later trial whose check fails (here its baseline) does not stop + tmp_path: Path, + fake: None, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, + load_workers: int, +) -> None: + """Check that a later trial's failed check does not stop the earlier trials. + + A later trial whose check fails (here its baseline) does not stop the earlier trials from being extracted and written, with one loader or several (the trial waiting for its results is written before the - error is raised).""" + error is raised). + """ s = make_session(tmp_path / "s") real = silo._extraction_baseline calls = [] - def failing(session, params, d, t, baseline_dir): - """Fails for the last trial of the first path.""" + def failing( + session: SiloSession, + params: SiloParams, + d: int, + t: int, + baseline_dir: str | Path | None, + ) -> Path | None: + """Fail for the last trial of the first path. + + Returns + ------- + Path or None + The baseline file the real function returns for other trials. + + Raises + ------ + FileNotFoundError + For the last trial of the first path. + """ calls.append((d, t)) if (d, t) == (0, session.n_trials - 1): raise FileNotFoundError("no baseline for this trial") @@ -150,20 +214,30 @@ def failing(session, params, d, t, baseline_dir): with pytest.raises(FileNotFoundError, match="no baseline"): silo.run_silo(s, PARAMS, replace(EX, load_workers=load_workers)) session = SiloSession.open(s) - written = [ - t - for t in range(session.n_trials) - if session.results_file(0, t).exists() - ] + written = [t for t in range(session.n_trials) if session.results_file(0, t).exists()] assert written == list(range(session.n_trials - 1)) -def test_loaded_passes_on_errors(): - """A load's error reaches the caller at its unit; later loads are not - waited for beyond the running ones.""" +def test_loaded_passes_on_errors() -> None: + """Check that a load's error reaches the caller at its unit. + + A load's error reaches the caller at its unit; later loads are not + waited for beyond the running ones. + """ + + def load(u: silo._Unit) -> dict[str, int]: + """Fail on the second unit. - def load(u): - """Fails on the second unit.""" + Returns + ------- + dict[str, int] + A measured size of 10 bytes for the other units. + + Raises + ------ + RuntimeError + For the second unit. + """ if u.t == 1: raise RuntimeError("bad trial") return {"nbytes": 10} @@ -174,9 +248,12 @@ def load(u): next(gen) -def test_options_are_checked(): - """Worker counts are positive integers, the limit positive; the loader - options come after the earlier fields, which keep their positions.""" +def test_options_are_checked() -> None: + """Check that worker counts are positive integers and the limit positive. + + Worker counts are positive integers, the limit positive; the loader + options come after the earlier fields, which keep their positions. + """ with pytest.raises(ValueError): SiloExecution(load_workers=0) with pytest.raises(ValueError): @@ -192,18 +269,29 @@ def test_options_are_checked(): @pytest.mark.parametrize("memory", [None, 1e-9]) def test_streamed_run_loading_ahead_is_the_same( - tmp_path, fake, memory # noqa: F811 -): - """Loading three trials ahead gives the results files and summaries of - loading one at a time.""" + tmp_path: Path, + fake: None, # noqa: F811 + memory: float | None, +) -> None: + """Check that loading ahead gives the same results as loading one at a time. + + Loading three trials ahead gives the results files and summaries of + loading one at a time. + """ one = make_session(tmp_path / "one") r1 = silo.run_silo(one, PARAMS, replace(EX, load_workers=1)) ahead = make_session(tmp_path / "ahead") ex = replace(EX, load_workers=3, load_memory_gb=memory) r2 = silo.run_silo(ahead, PARAMS, ex) - def loaded(report): - """The units the run loaded.""" + def loaded(report: dict) -> list[tuple]: + """Return the units the run loaded. + + Returns + ------- + list[tuple] + The unit of each trial entry in the report that was loaded. + """ return [tuple(e["unit"]) for e in report["trials"] if "load" in e] assert loaded(r1) == loaded(r2) and loaded(r1) @@ -221,19 +309,18 @@ def loaded(report): ) -def test_held_bytes_count_what_a_loaded_trial_keeps(): - """The memory of a loaded trial waiting for the solver: its +def test_held_bytes_count_what_a_loaded_trial_keeps() -> None: + """Check that held bytes count what a loaded trial keeps. + + The memory of a loaded trial waiting for the solver: its subproblems' data, variance multipliers and baselines, and its - traces.""" + traces. + """ from types import SimpleNamespace y = np.zeros((2, 10, 50), np.float32) - sub = SimpleNamespace( - y=y, finv=np.zeros((10, 50), np.float32), baseline=None - ) - with_base = SimpleNamespace( - y=y, finv=sub.finv, baseline=np.zeros((10, 50), np.float32) - ) + sub = SimpleNamespace(y=y, finv=np.zeros((10, 50), np.float32), baseline=None) + with_base = SimpleNamespace(y=y, finv=sub.finv, baseline=np.zeros((10, 50), np.float32)) rec = SimpleNamespace( global_f=np.zeros((2, 50)), roi_f=np.zeros((1, 2, 50)), diff --git a/tests/raster/test_raster_silo_local.py b/tests/raster/test_raster_silo_local.py index 35111e1a..1413344e 100644 --- a/tests/raster/test_raster_silo_local.py +++ b/tests/raster/test_raster_silo_local.py @@ -1,10 +1,10 @@ """SILo's prepare and solve stages in several processes of one machine. -``prepare_workers`` (trials prepared at once), ``trial_workers`` (trials -solved at once, each whole in its own process) and ``giant silo`` with +prepare_workers (trials prepared at once), trial_workers (trials +solved at once, each whole in its own process) and giant silo with either (:func:`~giant_python.pipeline.silo.stream_local`) must give the files the one-process stages and the streamed run give. The synthetic -session of ``test_raster_silo_stages`` stands in for a recording; its +session of test_raster_silo_stages stands in for a recording; its loader runs in this process only, so the prepare pool is replaced by threads here, while the solver pools are real spawned processes. """ @@ -16,6 +16,8 @@ import sys from concurrent.futures.process import BrokenProcessPool from dataclasses import replace +from pathlib import Path +from typing import NoReturn from unittest.mock import Mock, mock_open import h5py @@ -39,20 +41,34 @@ @pytest.fixture -def fake(monkeypatch): +def fake(monkeypatch: pytest.MonkeyPatch) -> None: """Synthetic localization and loading, in this process.""" monkeypatch.setattr(trial_mod, "localize_trial", stages.fake_localize) monkeypatch.setattr(trial_data_mod, "load_trial", stages.fake_load) @pytest.fixture -def prepare_in_threads(monkeypatch): - """The prepare pool as threads of this process (where the synthetic - loader is); gives the sizes of the pools asked for.""" +def prepare_in_threads(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, int]]: + """Replace the prepare pool by threads of this process. + + The threads run where the synthetic loader is. + + Returns + ------- + list[tuple[int, int]] + The (workers, threads) sizes of the pools asked for, filled as the + stages ask for pools. + """ asked = [] - def pool(workers, threads): - """A thread pool in place of :func:`make_pool`.""" + def pool(workers: int, threads: int) -> cf.ThreadPoolExecutor: + """Return a thread pool in place of :func:`make_pool`. + + Returns + ------- + cf.ThreadPoolExecutor + A thread pool of workers threads. + """ asked.append((workers, threads)) return cf.ThreadPoolExecutor(workers) @@ -60,29 +76,39 @@ def pool(workers, threads): return asked -def _planned(root): - """A session localized and planned (the stages' seeds).""" +def _planned(root: Path) -> SiloSession: + """Return a session localized and planned (the stages' seeds). + + Returns + ------- + SiloSession + The localized and planned session. + """ session = SiloSession.open(stages.make_session(root)) silo.localize(session, PARAMS, EX) silo.plan(session, PARAMS, EX, seeds=stages._seeds(session, root.parent)) return session -def _datasets(path): - """Every dataset of an HDF5 file, by name.""" +def _datasets(path: Path) -> dict: + """Every dataset of an HDF5 file, by name. + + Returns + ------- + dict + The value of each dataset, keyed by its name. + """ out = {} with h5py.File(path, "r") as f: f.visititems( lambda name, obj: ( - out.__setitem__(name, obj[()]) - if isinstance(obj, h5py.Dataset) - else None + out.__setitem__(name, obj[()]) if isinstance(obj, h5py.Dataset) else None ) ) return out -def _same_files(a, b): +def _same_files(a: Path, b: Path) -> None: """Two HDF5 files hold the same datasets (NaN equal).""" da, db = _datasets(a), _datasets(b) assert da.keys() == db.keys() and da @@ -90,7 +116,7 @@ def _same_files(a, b): np.testing.assert_array_equal(da[name], db[name], err_msg=name) -def _same_results(a: SiloSession, b: SiloSession): +def _same_results(a: SiloSession, b: SiloSession) -> None: """Two sessions' results files hold the same solved arrays.""" ra, rb = stages._all_results(a), stages._all_results(b) assert ra.keys() == rb.keys() and ra @@ -99,9 +125,12 @@ def _same_results(a: SiloSession, b: SiloSession): np.testing.assert_array_equal(value, rb[key][name]) -def test_options(): - """The two options: validated, off by default, each standing in for - the other in ``giant silo``; the commands that take them.""" +def test_options() -> None: + """The two options: validated, off by default. + + Each one stands in for the other in giant silo; the commands that take + them. + """ ex = SiloExecution() assert (ex.prepare_workers, ex.trial_workers) == (0, 0) assert not ex.local_stages @@ -116,19 +145,13 @@ def test_options(): SiloExecution(trial_workers=bad) parse = build_parser().parse_args run = execution_from_args( - parse( - ["silo", "t.h5", "--prepare-workers", "3", "--trial-workers", "4"] - ) + parse(["silo", "t.h5", "--prepare-workers", "3", "--trial-workers", "4"]) ) assert (run.prepare_workers, run.trial_workers) == (3, 4) assert not execution_from_args(parse(["silo", "t.h5"])).local_stages - prep = execution_from_args( - parse(["silo-prepare", "t.h5", "--prepare-workers", "2"]) - ) + prep = execution_from_args(parse(["silo-prepare", "t.h5", "--prepare-workers", "2"])) assert prep.prepare_workers == 2 - solve = execution_from_args( - parse(["silo-solve", "job.json", "--trial-workers", "2"]) - ) + solve = execution_from_args(parse(["silo-solve", "job.json", "--trial-workers", "2"])) assert solve.trial_workers == 2 for cmd, opt in ( ("silo-prepare", "--trial-workers"), @@ -142,10 +165,12 @@ def test_options(): def test_prepare_workers_give_the_same_containers( - tmp_path, fake, prepare_in_threads -): - """Trials prepared several at once are the containers prepared one - after another; a rerun starts no pool.""" + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: + """Trials prepared several at once are the containers prepared one after another. + + A rerun starts no pool. + """ one = _planned(tmp_path / "one") made_one = silo.prepare(one, PARAMS, EX) assert prepare_in_threads == [] @@ -174,14 +199,14 @@ def test_prepare_workers_give_the_same_containers( @pytest.mark.parametrize("check", ["localizations", "valid_kernel"]) def test_parallel_prepare_checks_plans_with_current_containers( - tmp_path, fake, prepare_in_threads, check -): - """A selected path still needs a current, compatible plan when all - its containers match the plan on disk.""" + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]], check: str +) -> None: + """A selected path still needs a current, compatible plan. + + This holds when all its containers match the plan on disk. + """ session = _planned(tmp_path / "s") - silo.prepare( - session, PARAMS, EX, units=[(0, t) for t in range(session.n_trials)] - ) + silo.prepare(session, PARAMS, EX, units=[(0, t) for t in range(session.n_trials)]) params = PARAMS if check == "localizations": changed = replace(PARAMS, peak_th=PARAMS.peak_th + 1) @@ -197,8 +222,8 @@ def test_parallel_prepare_checks_plans_with_current_containers( def test_prepare_accepts_a_single_unit_iterator( - tmp_path, fake, prepare_in_threads -): + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: """A one-shot selection reaches the serial fallback as prepared.""" session = _planned(tmp_path / "s") ex = replace(EX, prepare_workers=2) @@ -209,13 +234,29 @@ def test_prepare_accepts_a_single_unit_iterator( def test_prepare_worker_marks_a_trial_without_data( - tmp_path, fake, prepare_in_threads, monkeypatch -): - """A trial without data is marked as skipped by its prepare process, - and counted as done on the next run.""" - - def load(dat_path, *args, **kwargs): - """No data in path 2's second trial.""" + tmp_path: Path, + fake: None, + prepare_in_threads: list[tuple[int, int]], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A trial without data is marked as skipped by its prepare process. + + It is counted as done on the next run. + """ + + def load(dat_path: str | Path, *args: object, **kwargs: object) -> trial_data_mod.TrialData: + """No data in path 2's second trial. + + Returns + ------- + trial_data_mod.TrialData + The synthetic trial of :func:`stages.fake_load`. + + Raises + ------ + ValueError + If the data path is the second trial of path 2. + """ if "DMD2-TRIAL000002" in str(dat_path): raise ValueError(silo.NO_DATA + " in this trial") return stages.fake_load(dat_path, *args, **kwargs) @@ -230,10 +271,12 @@ def load(dat_path, *args, **kwargs): assert silo.prepare(session, PARAMS, ex) == [] -def test_prepare_process_failure_is_raised(tmp_path, fake): - """A prepare process that fails stops the stage with its error (real - processes: their loader is the real one, and the raw files are - empty).""" +def test_prepare_process_failure_is_raised(tmp_path: Path, fake: None) -> None: + """A prepare process that fails stops the stage with its error. + + The processes are real: their loader is the real one, and the raw files are + empty. + """ session = _planned(tmp_path / "s") with pytest.raises(Exception) as err: silo.prepare(session, PARAMS, replace(EX, prepare_workers=2)) @@ -241,25 +284,27 @@ def test_prepare_process_failure_is_raised(tmp_path, fake): assert not list(session.container_file(0, 0).parent.glob("*.h5")) -def _kill_prepare_worker(job): +def _kill_prepare_worker(job: dict) -> NoReturn: """Exit a prepare worker before it can return a result.""" os._exit(1) -def test_a_killed_worker_is_reported(monkeypatch): - """A worker that dies without a result (as when it is killed for - memory) is reported with what it was doing.""" +def test_a_killed_worker_is_reported(monkeypatch: pytest.MonkeyPatch) -> None: + """A worker that dies without a result is reported with what it was doing. + + This is the case when it is killed for memory. + """ monkeypatch.setattr(silo, "_prepare_job", _kill_prepare_worker) with pytest.raises(RuntimeError, match="preparing trial-paths:.*trial 7"): - silo._prepare_parallel( - None, PARAMS, replace(EX, prepare_workers=2), [(0, 6)], None - ) + silo._prepare_parallel(None, PARAMS, replace(EX, prepare_workers=2), [(0, 6)], None) @pytest.mark.parametrize("when", ["submit", "result"]) -def test_broken_prepare_pool_reports_the_batch(monkeypatch, when): - """A broken pool reports the affected batch on submit or result - failure, where the dead worker's assignment is unknown.""" +def test_broken_prepare_pool_reports_the_batch(monkeypatch: pytest.MonkeyPatch, when: str) -> None: + """A broken pool reports the affected batch on submit or result failure. + + The dead worker's assignment is unknown. + """ failure = BrokenProcessPool("worker exited") pool = Mock() if when == "submit": @@ -283,10 +328,12 @@ def test_broken_prepare_pool_reports_the_batch(monkeypatch, when): pool.shutdown.assert_called_once_with(cancel_futures=True) -def test_trial_workers_give_the_same_results(tmp_path, fake): - """Trials solved several at once, each whole in a process, give the - results files of the shared pool: by job (also with a container split - over jobs) and for a session's containers.""" +def test_trial_workers_give_the_same_results(tmp_path: Path, fake: None) -> None: + """Trials solved several at once, each whole in a process, give the shared pool's results. + + They give the results files of the shared pool: by job (also with a container split + over jobs) and for a session's containers. + """ ref = _planned(tmp_path / "ref") silo.prepare(ref, PARAMS, EX) assert silo.plan_subproblems(ref.plan_file(0)) > 1 @@ -321,9 +368,8 @@ def test_trial_workers_give_the_same_results(tmp_path, fake): silo_solve.solve_job(job, execution=ex) -def test_shared_pool_solves_multiple_subproblems_for_one_trial(tmp_path, fake): - """The reference solver uses two processes for a trial with several - subproblems.""" +def test_shared_pool_solves_multiple_subproblems_for_one_trial(tmp_path: Path, fake: None) -> None: + """The reference solver uses two processes for a trial with several subproblems.""" session = _planned(tmp_path / "s") silo.prepare(session, PARAMS, EX, units=[(0, 0)]) options = SHARED_EX.solver_options() @@ -342,12 +388,14 @@ def test_shared_pool_solves_multiple_subproblems_for_one_trial(tmp_path, fake): def test_local_stages_agree_with_the_streamed_run( - tmp_path, fake, prepare_in_threads -): - """``giant silo`` with prepare and trial workers gives the streamed - run's results and summaries; its containers are removed once solved, - or kept where ``save_subproblems`` says; a rerun keeps what is - done.""" + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: + """``giant silo`` with prepare and trial workers gives the streamed run's results. + + It gives the streamed run's results and summaries; its containers are removed once solved, + or kept where save_subproblems says; a rerun keeps what is + done. + """ seeds = stages.seeds_file(tmp_path) t1 = stages.make_session(tmp_path / "streamed") silo.run_silo(t1, PARAMS, EX, seeds_file=seeds) @@ -401,11 +449,13 @@ def test_local_stages_agree_with_the_streamed_run( def test_local_stages_finish_an_interrupted_run( - tmp_path, fake, prepare_in_threads -): - """Containers left by a run that stopped are solved without being - prepared again; a trial without data is skipped; an error in a solver - process stops the run.""" + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: + """Containers left by a run that stopped are solved without being prepared again. + + A trial without data is skipped; an error in a solver + process stops the run. + """ seeds = stages.seeds_file(tmp_path) ref = stages.make_session(tmp_path / "ref") silo.run_silo(ref, PARAMS, EX, seeds_file=seeds) @@ -418,14 +468,20 @@ def test_local_stages_finish_an_interrupted_run( seen = {} real = silo._prepare_job - def watch(job): - """Record whether the unit's container was there already.""" + def watch(job: dict) -> dict | None: + """Record whether the unit's container was there already. + + Returns + ------- + dict or None + The result of the real prepare job. + """ d, t = job["unit"] f = job["session"].container_file(d, t) seen[(d, t)] = f.stat().st_mtime_ns if f.exists() else None return real(job) - import unittest.mock as mock + from unittest import mock ex = replace(EX, prepare_workers=2, trial_workers=2) with mock.patch.object(silo, "_prepare_job", watch): @@ -449,10 +505,12 @@ def watch(job): def test_local_stages_reject_the_results_directory_as_an_archive( - tmp_path, fake, prepare_in_threads -): - """An archive alias of the results directory is rejected before - either trial pool can write files.""" + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: + """An archive alias of the results directory is rejected. + + It is rejected before either trial pool can write files. + """ session = _planned(tmp_path / "s") alias = session.results_dir / ".." / "results" ex = replace(EX, trial_workers=2) @@ -471,8 +529,11 @@ def test_local_stages_reject_the_results_directory_as_an_archive( def test_local_stages_reject_stage_directories_as_archives( - tmp_path, fake, prepare_in_threads, monkeypatch -): + tmp_path: Path, + fake: None, + prepare_in_threads: list[tuple[int, int]], + monkeypatch: pytest.MonkeyPatch, +) -> None: """Aliases of stage directories are rejected before either pool starts.""" session = _planned(tmp_path / "s") trial_pool = Mock(side_effect=AssertionError("solver pool started")) @@ -492,8 +553,8 @@ def test_local_stages_reject_stage_directories_as_archives( def test_local_resume_preserves_standalone_containers( - tmp_path, fake, prepare_in_threads -): + tmp_path: Path, fake: None, prepare_in_threads: list[tuple[int, int]] +) -> None: """A local rerun keeps prepared containers referenced by a solved job.""" session = _planned(tmp_path / "s") prepared = silo.prepare(session, PARAMS, EX) @@ -515,22 +576,25 @@ def test_local_resume_preserves_standalone_containers( def test_local_stages_archive_to_a_directory_named_remove( - tmp_path, fake, prepare_in_threads, monkeypatch -): + tmp_path: Path, + fake: None, + prepare_in_threads: list[tuple[int, int]], + monkeypatch: pytest.MonkeyPatch, +) -> None: """A relative --save-subproblems directory named remove keeps files.""" session = _planned(tmp_path / "s") monkeypatch.chdir(tmp_path) ex = replace(EX, trial_workers=1) - silo.stream_local( - session, PARAMS, ex, paths=[0], save_subproblems="remove" - ) + silo.stream_local(session, PARAMS, ex, paths=[0], save_subproblems="remove") for t in range(session.n_trials): container = session.container_file(0, t) assert (tmp_path / "remove" / container.name).is_file() assert not container.exists() -def test_openblas_fallback_accepts_spaces_in_mapped_paths(monkeypatch): +def test_openblas_fallback_accepts_spaces_in_mapped_paths( + monkeypatch: pytest.MonkeyPatch, +) -> None: """Without threadpoolctl, both BLAS fallbacks use the whole pathname.""" path = "/opt/Science Tools/lib/libscipy_openblas.so" maps = mock_open(read_data=f"7f000-7ffff r-xp 0 08:01 42 {path}\n") @@ -550,10 +614,12 @@ def test_openblas_fallback_accepts_spaces_in_mapped_paths(monkeypatch): assert [call.args for call in load.call_args_list] == [(path,), (path,)] -def test_thread_limit_holds_after_the_libraries_are_loaded(): - """``thread_env`` limits a process whose numerical libraries are - already loaded with one thread per core: the solver process that - solves in itself (``--solver-workers 1``) keeps to its threads.""" +def test_thread_limit_holds_after_the_libraries_are_loaded() -> None: + """``thread_env`` limits a process whose numerical libraries are already loaded. + + The libraries are loaded with one thread per core: the solver process that + solves in itself (--solver-workers 1) keeps to its threads. + """ if not sys.platform.startswith("linux"): pytest.skip("reads the loaded libraries from /proc") code = """ @@ -583,11 +649,7 @@ def counts(): "torch": torch.get_num_threads(), "env": os.environ["OPENBLAS_NUM_THREADS"]})) """ - env = { - k: v - for k, v in os.environ.items() - if k not in silo_session._THREAD_VARS - } + env = {k: v for k, v in os.environ.items() if k not in silo_session._THREAD_VARS} out = subprocess.run( [sys.executable, "-c", code], env=env, @@ -604,13 +666,13 @@ def counts(): assert got["after"] == [2] * len(got["before"]) -def test_solver_processes_start_with_their_threads(): - """The processes that solve whole trials start with the thread - variables in their environment, so their libraries load with the - solver's threads.""" - pool = silo_solve.trial_pool( - SiloExecution(trial_workers=2, solver_threads=3), tasks=1 - ) +def test_solver_processes_start_with_their_threads() -> None: + """The processes that solve whole trials start with the thread variables set. + + The variables are in their environment, so their libraries load with the + solver's threads. + """ + pool = silo_solve.trial_pool(SiloExecution(trial_workers=2, solver_threads=3), tasks=1) try: assert pool._max_workers == 1 # no more processes than trials for name in silo_session._THREAD_VARS: @@ -619,10 +681,12 @@ def test_solver_processes_start_with_their_threads(): pool.shutdown() -def test_plan_without_trial_images(tmp_path, fake): - """A plan read without its per-trial image stacks gives each trial's - aligned mean image from the file, equal to the whole stack's, and - everything else the prepare stage uses.""" +def test_plan_without_trial_images(tmp_path: Path, fake: None) -> None: + """A plan read without its per-trial image stacks gives each trial's mean image. + + That is each trial's aligned mean image from the file, equal to the whole + stack's, and everything else the prepare stage uses. + """ from giant_python.extraction.raster.plan import TrialStack, read_plan session = _planned(tmp_path / "s") diff --git a/tests/raster/test_raster_silo_network.py b/tests/raster/test_raster_silo_network.py index 61ed31ce..eece5b9e 100644 --- a/tests/raster/test_raster_silo_network.py +++ b/tests/raster/test_raster_silo_network.py @@ -1,18 +1,20 @@ -"""SILo with the F0 network's baseline (``baseline_source='network'``). +"""SILo with the F0 network's baseline (baseline_source='network'). The synthetic session of :mod:`test_raster_silo_stages`, with baseline -files as ``slap2-f0 predict-registered`` writes them: the network's +files as slap2-f0 predict-registered writes them: the network's baseline is mapped into the containers and the streamed run's subproblems alike, so that streamed, staged and sharded runs agree; each stage refuses files made with another baseline; the prediction step calls slap2-f0 for the missing files only. """ +import argparse import json import os import subprocess from dataclasses import asdict, replace from pathlib import Path +from typing import NoReturn import h5py import numpy as np @@ -62,7 +64,7 @@ @pytest.fixture -def fake(monkeypatch): +def fake(monkeypatch: pytest.MonkeyPatch) -> None: """Synthetic localization and loading (as in the stages' tests).""" monkeypatch.setattr(trial_mod, "localize_trial", stages.fake_localize) monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) @@ -73,9 +75,16 @@ def fake(monkeypatch): MEDIAN = SiloParams(min_kinetic_score=0.0) -def _baseline_stack(d, t, n_frames, level=50.0): - """A smooth baseline in movie counts, (frames, rows, cols), with a - corner without values (NaN, as outside the valid pixels).""" +def _baseline_stack(d: int, t: int, n_frames: int, level: float = 50.0) -> np.ndarray: + """Build a smooth baseline in movie counts, (frames, rows, cols). + + The baseline has a corner without values (NaN, as outside the valid pixels). + + Returns + ------- + np.ndarray + The float32 baseline stack (frames, rows, cols) of trial-path d and trial t. + """ r, c = np.mgrid[:H, :W] img = level * (1 + 0.2 * np.sin(r / 5.0 + d) * np.cos(c / 7.0 + t)) ramp = 1 + 0.05 * np.linspace(-1, 1, n_frames) @@ -84,9 +93,16 @@ def _baseline_stack(d, t, n_frames, level=50.0): return stack.astype(np.float32) -def write_baselines(root: Path, folder: Path, level=50.0) -> Path: - """Baseline files of every trial-path, laid out as slap2-f0 writes - them: ``/baseline`` (frame, col, row) float16, with its attributes.""" +def write_baselines(root: Path, folder: Path, level: float = 50.0) -> Path: + """Baseline files of every trial-path, laid out as slap2-f0 writes them. + + The datasets are /baseline (frame, col, row) float16, with its attributes. + + Returns + ------- + Path + The folder holding the baseline files. + """ folder.mkdir(parents=True, exist_ok=True) moco = root / "motion_correction" for d in range(N_PATHS): @@ -105,9 +121,11 @@ def write_baselines(root: Path, folder: Path, level=50.0) -> Path: return folder -def test_params_baseline_source(): - """'network' sets the localization settings and N1; each can still be - set; MATLAB's algorithm keeps its settings, hashes and params struct.""" +def test_params_baseline_source() -> None: + """'network' sets the localization settings and N1; each can still be set. + + MATLAB's algorithm keeps its settings, hashes and params struct. + """ m = SiloParams() assert (m.peak_th, m.localization_baseline, m.baseline_mode) == ( 3.0, @@ -127,9 +145,7 @@ def test_params_baseline_source(): o = SiloParams(baseline_source="network", peak_th=8, baseline_mode="fixed") assert o.peak_th == 8 and o.baseline_mode == "fixed" # the network's defaults before 2026-11-28 (GIAnT-Python#51) - old = SiloParams( - baseline_source="network", peak_th=8, min_source_event_rate=0 - ) + old = SiloParams(baseline_source="network", peak_th=8, min_source_event_rate=0) assert old.min_source_event_rate == 0 assert "min_source_event_rate" not in old.stage_settings("collect") assert n.stage_settings("collect")["min_source_event_rate"] == 2.0 @@ -153,9 +169,11 @@ def test_params_baseline_source(): SiloParams(baseline_mode="guess") -def test_trial_baseline_is_map_baseline(tmp_path): - """The pipeline's two steps (space and units at the registration's - frames, then time and the fallback) give map_baseline's values.""" +def test_trial_baseline_is_map_baseline(tmp_path: Path) -> None: + """The pipeline's two steps give map_baseline's values. + + The steps are space and units at the registration's frames, then time and the fallback. + """ rng = np.random.default_rng(3) n_t, n_r, n_c = 9, 20, 16 stack = (40 + 10 * rng.random((n_t, n_r, n_c))).astype(np.float32) @@ -166,16 +184,12 @@ def test_trial_baseline_is_map_baseline(tmp_path): f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) f.attrs["checkpoint"] = "x.pt" full, _ = read_network_baseline(path) - rc = np.column_stack( - [rng.uniform(-0.8, n_r - 0.2, 60), rng.uniform(2, 9, 60)] - ) + rc = np.column_stack([rng.uniform(-0.8, n_r - 0.2, 60), rng.uniform(2, 9, 60)]) rc[:5, 0] = rng.uniform(0, 2, 5) # no network value: fallback ds_lines = np.linspace(1, 400, n_t) frame_lines = np.arange(1, 401, 3) data = 1.5 + rng.random((rc.shape[0], frame_lines.size)) - ref = map_baseline( - full, rc, ds_lines, frame_lines, 25.0, fallback_data=data - ) + ref = map_baseline(full, rc, ds_lines, frame_lines, 25.0, fallback_data=data) tb = read_trial_baseline(path, rc, ds_lines, 25.0) assert tb.values.dtype == np.float32 assert tb.identity["missing_pixels"] == int(ref.missing.sum()) > 0 @@ -186,16 +200,16 @@ def test_trial_baseline_is_map_baseline(tmp_path): # any subset of pixels: the same rows (the fallback is per pixel) rows = np.array([1, 4, 7, 30, 59]) np.testing.assert_array_equal( - subproblem_baseline( - tb.values[rows], tb.lines, frame_lines, data[rows] - ), + subproblem_baseline(tb.values[rows], tb.lines, frame_lines, data[rows]), got[rows], ) -def test_container_holds_the_baseline(tmp_path): - """A container stores the baseline at the registration's frames; its - subproblems get it for a mode that uses it, from memory or the file.""" +def test_container_holds_the_baseline(tmp_path: Path) -> None: + """A container stores the baseline at the registration's frames. + + Its subproblems get it for a mode that uses it, from memory or the file. + """ trial = fake_load( "x_DMD1-TRIAL000001.dat", 1, @@ -255,10 +269,12 @@ def test_container_holds_the_baseline(tmp_path): read_container(bare).subproblem(0, sp) -def test_network_streamed_and_staged_runs_agree(tmp_path, fake): - """With the network's baseline (N1), the streamed run, one job and - three jobs give the same results and summaries; the summaries record - the baseline; the baseline changes the results.""" +def test_network_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: + """With the network's baseline (N1), the streamed run, one job and three jobs agree. + + They give the same results and summaries; the summaries record the baseline; the baseline + changes the results. + """ root = tmp_path / "streamed" table = make_session(root) bdir = write_baselines(root, tmp_path / "baselines") @@ -311,14 +327,14 @@ def test_network_streamed_and_staged_runs_agree(tmp_path, fake): assert "baseline_source" not in f.attrs # as MATLAB writes it -def test_baseline_file_change_redoes_its_containers(tmp_path, fake): - """The settings hash of a container covers its baseline file; MATLAB's - algorithm keeps the hash it had before the network was wired in.""" +def test_baseline_file_change_redoes_its_containers(tmp_path: Path, fake: None) -> None: + """The settings hash of a container covers its baseline file. + + MATLAB's algorithm keeps the hash it had before the network was wired in. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) - bdir = write_baselines( - root, root / "source_extraction" / "silo" / "baselines" - ) + bdir = write_baselines(root, root / "source_extraction" / "silo" / "baselines") # localized with the moving median, extracted with the network: a new # baseline file redoes its container only (with network localization it # redoes the localization, hence the plan, first) @@ -339,25 +355,23 @@ def test_baseline_file_change_redoes_its_containers(tmp_path, fake): assert [r["unit"] for r in redone] == [(0, 1)] # MATLAB's algorithm: the hash of the stage files before this change ph = "abc" - old = stage_hash( - { - "stage": "prepare", - "settings": MEDIAN.stage_settings("prepare"), - "plan": ph, - "unit": [0, 0], - "raw": recording_ids(s.raw(0, 0)), - "lines": [ - float(s.first_line[0, 0]), - float(s.last_line[0, 0]), - ], - "alignment": file_id(s.alignment(0, 0)), - } - ) + old = stage_hash({ + "stage": "prepare", + "settings": MEDIAN.stage_settings("prepare"), + "plan": ph, + "unit": [0, 0], + "raw": recording_ids(s.raw(0, 0)), + "lines": [ + float(s.first_line[0, 0]), + float(s.last_line[0, 0]), + ], + "alignment": file_id(s.alignment(0, 0)), + }) assert silo._prepare_hash(s, MEDIAN, ph, 0, 0) == old assert silo._prepare_hash(s, NET, ph, 0, 0, f) != old -def test_stages_refuse_another_baseline(tmp_path, fake): +def test_stages_refuse_another_baseline(tmp_path: Path, fake: None) -> None: """Each stage checks that the stage before it used the same baseline.""" root = tmp_path / "s" s = SiloSession.open(make_session(root)) @@ -371,9 +385,7 @@ def test_stages_refuse_another_baseline(tmp_path, fake): # network localization and plan, MATLAB's baseline fit: no baseline fit = replace(NET, baseline_mode="fit") silo.prepare(s, fit, EX, baseline_dir=bdir) - assert not read_container( - s.container_file(0, 0), data=False - ).baseline_filled + assert not read_container(s.container_file(0, 0), data=False).baseline_filled with pytest.raises(ValueError, match="has no network baseline"): silo_solve.dispatch(s, NET, 2, EX) with pytest.raises(ValueError, match="baseline_source='network'"): @@ -386,14 +398,22 @@ def test_stages_refuse_another_baseline(tmp_path, fake): silo.prepare(s, NET, EX, baseline_dir=bdir) -def _args(*argv): - """Parsed arguments of a ``giant`` command line.""" +def _args(*argv: str) -> argparse.Namespace: + """Parse the arguments of a giant command line. + + Returns + ------- + argparse.Namespace + The parsed arguments. + """ return build_parser().parse_args(list(argv)) -def test_cli_baseline_default(): - """--baseline-dir or --f0-ckpt make the network the default; --baseline - chooses; otherwise MATLAB's moving median.""" +def test_cli_baseline_default() -> None: + """--baseline-dir or --f0-ckpt make the network the default; --baseline chooses. + + Otherwise MATLAB's moving median. + """ p = params_from_args(_args("silo", "t.h5")) assert p.baseline_source == "median" and p.peak_th == 3.0 p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b")) @@ -414,15 +434,11 @@ def test_cli_baseline_default(): assert (p.peak_th, p.min_source_event_rate) == (8.0, 0.0) p = params_from_args(_args("silo", "t.h5", "--f0-ckpt", "x.pt")) assert p.baseline_source == "network" - p = params_from_args( - _args("silo", "t.h5", "--baseline-dir", "b", "--baseline", "median") - ) + p = params_from_args(_args("silo", "t.h5", "--baseline-dir", "b", "--baseline", "median")) assert p.baseline_source == "median" p = params_from_args(_args("silo-plan", "t.h5", "--baseline", "network")) assert p.baseline_source == "network" and p.baseline_mode == "gain" - p = params_from_args( - _args("silo-prepare", "t.h5", "--baseline-dir", "b", "--peak-th", "6") - ) + p = params_from_args(_args("silo-prepare", "t.h5", "--baseline-dir", "b", "--peak-th", "6")) assert p.baseline_source == "network" and p.peak_th == 6.0 p = params_from_args( _args( @@ -439,16 +455,28 @@ def test_cli_baseline_default(): assert a.f0_device == "cpu" and a.f0_command is None -def test_run_silo_default_source(tmp_path, fake, monkeypatch): - """run_silo: a dict or no params take the network with its baselines; - a SiloParams is used as it is (with a warning that they are unused).""" +def test_run_silo_default_source( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """run_silo: a dict or no params take the network with its baselines. + + A SiloParams is used as it is (with a warning that they are unused). + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") seen = [] - def stop(session, params, *args, **kw): - """Record the params and stop the run.""" + def stop( + session: SiloSession, params: SiloParams | dict | None, *args: object, **kw: object + ) -> NoReturn: + """Record the params and stop the run. + + Raises + ------ + RuntimeError + Always, to stop the run. + """ seen.append(params) raise RuntimeError("stop") @@ -464,9 +492,12 @@ def stop(session, params, *args, **kw): assert silo.default_baseline_source(None, False) is None -def test_predict_baselines(tmp_path, monkeypatch): - """--f0-ckpt runs slap2-f0 predict-registered once, for the trial-paths - without a baseline file, with the run's trial preparation settings.""" +def test_predict_baselines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """--f0-ckpt runs slap2-f0 predict-registered once. + + It runs for the trial-paths without a baseline file, with the run's trial preparation + settings. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = tmp_path / "b" @@ -476,12 +507,16 @@ def test_predict_baselines(tmp_path, monkeypatch): ckpt = tmp_path / "s6_test.pt" ckpt.write_bytes(b"weights") calls = [] - monkeypatch.setattr( - silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}" - ) + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + """Stand in for slap2-f0 and write the files asked for. - def fake_run(args, **kw): - """slap2-f0 stood in for: write the files asked for.""" + Returns + ------- + subprocess.CompletedProcess[str] + A completed process with exit code 0. + """ calls.append(args) keys = args[args.index("--files") + 1].split(",") for k in keys: @@ -503,9 +538,7 @@ def fake_run(args, **kw): assert args[:2] == ["/bin/slap2-f0", "predict-registered"] assert args[args.index("--ckpt") + 1] == str(ckpt) assert args[args.index("--out") + 1] == str(bdir) - assert args[args.index("--files") + 1] == ( - "E1T2DMD2_REGISTERED,E1T3DMD2_REGISTERED" - ) + assert args[args.index("--files") + 1] == ("E1T2DMD2_REGISTERED,E1T3DMD2_REGISTERED") assert args[args.index("--motion_thresh") + 1] == "1.5" assert args[args.index("--channel") + 1] == "1" assert args[args.index("--device") + 1] == "cpu" @@ -513,10 +546,7 @@ def fake_run(args, **kw): assert "--fast" in args # nothing missing: nothing run calls.clear() - assert ( - silo_baseline.predict_baselines(s, params, bdir, ckpt)["predicted"] - == [] - ) + assert silo_baseline.predict_baselines(s, params, bdir, ckpt)["predicted"] == [] assert not calls # the predicted files have records: the prediction's settings, the @@ -581,8 +611,14 @@ def fake_run(args, **kw): # a run that writes a file and then fails: the file has its record, so # a retry with other settings does not reuse it unchecked - def fail_after_one(args, **kw): - """Write the files, then fail.""" + def fail_after_one(args: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + """Write the files, then fail. + + Returns + ------- + subprocess.CompletedProcess[str] + A completed process with exit code 1. + """ fake_run(args, **kw) return subprocess.CompletedProcess(args, 1) @@ -616,10 +652,12 @@ def fail_after_one(args, **kw): silo_baseline.predict_baselines(s, params, bdir, tmp_path / "x.pt") -def test_source_alone_redoes_plan_and_containers(tmp_path, fake): - """baseline_source enters the plan and prepare hashes (when it is not - MATLAB's): changing it alone redoes those stages rather than reusing - files that the next stage would refuse.""" +def test_source_alone_redoes_plan_and_containers(tmp_path: Path, fake: None) -> None: + """baseline_source enters the plan and prepare hashes (when it is not MATLAB's). + + Changing it alone redoes those stages rather than reusing files that the next stage would + refuse. + """ alt = SiloParams( baseline_source="median", localization_baseline="network", @@ -649,12 +687,14 @@ def test_source_alone_redoes_plan_and_containers(tmp_path, fake): silo.prepare(s, NET, EX, baseline_dir=bdir) -def test_earlier_network_defaults_are_localized_again(tmp_path, fake): - """Files made with the network's defaults before 2026-11-28 (peak_th 8, - no evidence test) are localized again with the current ones (peak_th - is also the per-trial peaks' threshold, and every later stage checks - the hash of the one before), so a run never mixes the two; the earlier - defaults given as options keep the files.""" +def test_earlier_network_defaults_are_localized_again(tmp_path: Path, fake: None) -> None: + """Files made with the network's defaults before 2026-11-28 are localized again. + + Those defaults are peak_th 8 and no evidence test. The files are localized again with the + current ones (peak_th is also the per-trial peaks' threshold, and every later stage checks + the hash of the one before), so a run never mixes the two; the earlier defaults given as + options keep the files. + """ old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) s = SiloSession.open(make_session(tmp_path / "s")) bdir = write_baselines(tmp_path / "s", tmp_path / "b") @@ -666,11 +706,12 @@ def test_earlier_network_defaults_are_localized_again(tmp_path, fake): assert old.stage_settings("solve") == NET.stage_settings("solve") -def test_collect_refuses_another_seed_threshold(tmp_path, fake): - """A standalone collect of a folder seeded with the network's earlier - default (peak_th 8) is refused under today's (3), which would record - peakth 3 and judge the sources' evidence against it; the earlier - settings collect it.""" +def test_collect_refuses_another_seed_threshold(tmp_path: Path, fake: None) -> None: + """A standalone collect of a folder seeded with the network's earlier default is refused. + + The earlier default is peak_th 8; the collect is refused under today's (3), which would + record peakth 3 and judge the sources' evidence against it; the earlier settings collect it. + """ old = replace(NET, peak_th=8.0, min_source_event_rate=0.0) s = SiloSession.open(make_session(tmp_path / "s")) bdir = write_baselines(tmp_path / "s", tmp_path / "b") @@ -687,11 +728,12 @@ def test_collect_refuses_another_seed_threshold(tmp_path, fake): assert float(np.ravel(f["params/peakth"][()])[0]) == 8.0 -def test_collect_refuses_another_seed_acceptance(tmp_path, fake): - """A standalone collect of a plan seeded with the null threshold is - refused under the image threshold (whose evidence test would exempt - strong seeds that the null mode judges); its own settings collect - it.""" +def test_collect_refuses_another_seed_acceptance(tmp_path: Path, fake: None) -> None: + """A standalone collect of a plan seeded with the null threshold is refused. + + It is refused under the image threshold (whose evidence test would exempt strong seeds that + the null mode judges); its own settings collect it. + """ null = replace(NET, seed_acceptance="null_sd", localization_keep_null=True) assert null.evidence_judge_below is None s = SiloSession.open(make_session(tmp_path / "s")) @@ -706,10 +748,12 @@ def test_collect_refuses_another_seed_acceptance(tmp_path, fake): assert silo_collect.collect(s, null, EX, baseline_dir=bdir) is not None -def test_unrecorded_network_localization_is_redone(tmp_path, fake): - """A localization file without the record of its baseline (made before - it was recorded) counts as the moving median's: with the network's - settings it is localized again, with MATLAB's it is kept.""" +def test_unrecorded_network_localization_is_redone(tmp_path: Path, fake: None) -> None: + """A localization file without the record of its baseline counts as the moving median's. + + It was made before the baseline was recorded; with the network's settings it is localized + again, with MATLAB's it is kept. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -726,9 +770,11 @@ def test_unrecorded_network_localization_is_redone(tmp_path, fake): assert silo.localize_jobs(m, MEDIAN) == [] -def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake): - """The summary's network_baseline comes from the results files that - are assembled, not from earlier runs' files left in the folder.""" +def test_summary_records_the_baseline_of_the_results_used(tmp_path: Path, fake: None) -> None: + """The summary's network_baseline comes from the results files that are assembled. + + It does not come from earlier runs' files left in the folder. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -737,7 +783,7 @@ def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake): silo.prepare(s, NET, EX, baseline_dir=bdir) for job in silo_solve.dispatch(s, NET, 3, EX): silo_solve.solve_job(job, execution=EX) - shard = sorted(s.results_dir.glob("*_s*.h5"))[0] + shard = min(s.results_dir.glob("*_s*.h5")) stem = shard.name.split("_s")[0] stale = s.results_dir / f"{stem}.h5" # sorts before the shards assert not stale.exists() @@ -753,9 +799,8 @@ def test_summary_records_the_baseline_of_the_results_used(tmp_path, fake): assert json.loads(f.attrs["network_baseline"])[stem] == used -def test_baseline_from_another_movie_is_refused(tmp_path, fake): - """A baseline file predicted from another movie than SILo reads (its - 'source') is refused.""" +def test_baseline_from_another_movie_is_refused(tmp_path: Path, fake: None) -> None: + """A baseline file predicted from another movie than SILo reads (its 'source') is refused.""" root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -765,16 +810,16 @@ def test_baseline_from_another_movie_is_refused(tmp_path, fake): silo.localize(s, NET, EX, baseline_dir=bdir) -def test_collect_checks_baselines_without_movies(tmp_path, fake): - """A collect machine without the registered movies still checks the - results against the baseline files (named after the trial table's - movies): a replaced baseline leaves the results stale.""" +def test_collect_checks_baselines_without_movies(tmp_path: Path, fake: None) -> None: + """A collect machine without the registered movies still checks the results. + + They are checked against the baseline files (named after the trial table's movies): a + replaced baseline leaves the results stale. + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") - silo.run_silo( - table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir - ) + silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) for movie in (root / "motion_correction").glob("*_REGISTERED_*"): movie.unlink() s = SiloSession.open(table, inputs="collect") @@ -787,9 +832,13 @@ def test_collect_checks_baselines_without_movies(tmp_path, fake): silo_collect.collect(s, NET, EX, baseline_dir=bdir) -def test_localize_predicts_for_extraction_too(tmp_path, fake, monkeypatch): - """silo-localize --f0-ckpt predicts whenever a stage uses the network's - baselines, also when localization alone uses the moving median.""" +def test_localize_predicts_for_extraction_too( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """silo-localize --f0-ckpt predicts whenever a stage uses the network's baselines. + + It predicts also when localization alone uses the moving median. + """ table = make_session(tmp_path / "s") calls = [] monkeypatch.setattr( @@ -805,9 +854,11 @@ def test_localize_predicts_for_extraction_too(tmp_path, fake, monkeypatch): assert len(calls) == 1 -def test_extraction_uses_the_localization_baseline(tmp_path, fake): - """Extraction refuses another baseline file than the trial was - localized with (stages given different folders).""" +def test_extraction_uses_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """Extraction refuses another baseline file than the trial was localized with. + + Here the stages are given different folders. + """ import shutil root = tmp_path / "s" @@ -823,7 +874,7 @@ def test_extraction_uses_the_localization_baseline(tmp_path, fake): assert len(silo.prepare(s, NET, EX, baseline_dir=a)) == 6 -def test_predict_units_may_be_a_generator(tmp_path, monkeypatch): +def test_predict_units_may_be_a_generator(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """The trial-paths to predict may be given as a generator.""" root = tmp_path / "s" s = SiloSession.open(make_session(root)) @@ -831,14 +882,18 @@ def test_predict_units_may_be_a_generator(tmp_path, monkeypatch): (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() ckpt = tmp_path / "s6_test.pt" ckpt.write_bytes(b"weights") - monkeypatch.setattr( - silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}" - ) + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") rec_args = [] - def fake_run(args, **kw): - """Write the one file asked for.""" + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + """Write the one file asked for. + + Returns + ------- + subprocess.CompletedProcess[str] + A completed process with exit code 0. + """ rec_args.append(args) src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" @@ -849,9 +904,7 @@ def fake_run(args, **kw): monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) units = (u for u in [(0, 0), (1, 1)]) - rec = silo_baseline.predict_baselines( - s, NET, bdir, ckpt, units, out_frames=512 - ) + rec = silo_baseline.predict_baselines(s, NET, bdir, ckpt, units, out_frames=512) assert rec["predicted"] == [[2, 2]] args = rec_args[-1] assert args[args.index("--out_frames") + 1] == "512" @@ -859,16 +912,16 @@ def fake_run(args, **kw): assert _args("silo", "t.h5", "--f0-out-frames", "256").f0_out_frames == 256 -def test_summary_records_the_localization_baseline(tmp_path, fake): - """Localized with the network's baseline and extracted with MATLAB's - fit: the summary records the baseline that decided the seeds.""" +def test_summary_records_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """Localized with the network's baseline and extracted with MATLAB's fit. + + The summary records the baseline that decided the seeds. + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") loc_only = replace(NET, baseline_mode="fit") - silo.run_silo( - table, loc_only, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir - ) + silo.run_silo(table, loc_only, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) s = SiloSession.open(table) with h5py.File(s.out_dir / "experiment_summary.h5", "r") as f: assert f.attrs["baseline_mode"] == "fit" @@ -880,10 +933,12 @@ def test_summary_records_the_localization_baseline(tmp_path, fake): assert first["network"] == {"checkpoint": "ckpt/s6_test.pt", "step": 1700} -def test_localized_again_after_the_plan(tmp_path, fake): - """Trials localized again (here with other baseline files) after their - plan was made: prepare and collect refuse the stale plan and results - instead of reading the new localization's peaks and baselines.""" +def test_localized_again_after_the_plan(tmp_path: Path, fake: None) -> None: + """Trials localized again after their plan was made (here with other baseline files). + + Prepare and collect refuse the stale plan and results instead of reading the new + localization's peaks and baselines. + """ import shutil root = tmp_path / "s" @@ -906,11 +961,12 @@ def test_localized_again_after_the_plan(tmp_path, fake): assert len(silo.prepare(s, NET, EX, baseline_dir=b)) == 6 -def test_one_baseline_mode_per_run(tmp_path, fake): - """Containers prepared with the network's baseline are not solved with - MATLAB's fit (their hash covers a baseline the fit does not use, so - collect would take the results for stale); results name the baseline - only when the solver used it.""" +def test_one_baseline_mode_per_run(tmp_path: Path, fake: None) -> None: + """Containers prepared with the network's baseline are not solved with MATLAB's fit. + + Their hash covers a baseline the fit does not use, so collect would take the results for + stale; results name the baseline only when the solver used it. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") @@ -932,21 +988,20 @@ def test_one_baseline_mode_per_run(tmp_path, fake): with h5py.File(s.results_file(0, 0), "r") as h: assert "network_baseline" in h.attrs c = read_container(s.container_file(0, 0), data=False) - attrs = silo_solve.results_attrs( - c, "c.h5", "h", (0, 1), 1, True, "r", fit, EX.solver_options() - ) + attrs = silo_solve.results_attrs(c, "c.h5", "h", (0, 1), 1, True, "r", fit, EX.solver_options()) assert "network_baseline" not in attrs -def test_collect_checks_the_localization_baseline(tmp_path, fake): - """collect refuses settings whose localization baseline is not the one - the trials were localized with (the summary would mislabel them).""" +def test_collect_checks_the_localization_baseline(tmp_path: Path, fake: None) -> None: + """``collect`` refuses settings with another localization baseline. + + The baseline is not the one the trials were localized with (the summary would mislabel + them). + """ root = tmp_path / "s" table = make_session(root) bdir = write_baselines(root, tmp_path / "b") - silo.run_silo( - table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir - ) + silo.run_silo(table, NET, EX, seeds_file=seeds_file(tmp_path), baseline_dir=bdir) s = SiloSession.open(table) median_loc = replace( NET, @@ -959,21 +1014,27 @@ def test_collect_checks_the_localization_baseline(tmp_path, fake): silo_collect.collect(s, median_loc, EX, baseline_dir=bdir) -def test_one_checkpoint_per_run(tmp_path, monkeypatch): - """Baselines kept from an earlier prediction must have been made with - the given checkpoint (its SHA-256, not only its name).""" +def test_one_checkpoint_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Baselines kept from an earlier prediction must have been made with the given checkpoint. + + The checkpoint is identified by its SHA-256, not only its name. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) bdir = write_baselines(root, tmp_path / "b") (bdir / "E1T2DMD2_BASELINE-80Hz.h5").unlink() ckpt = tmp_path / "s6_test.pt" ckpt.write_bytes(b"weights") - monkeypatch.setattr( - silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}" - ) + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") - def fake_run(args, **kw): - """Write the one file asked for.""" + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + """Write the one file asked for. + + Returns + ------- + subprocess.CompletedProcess[str] + A completed process with exit code 0. + """ src = bdir / "E1T1DMD1_BASELINE-80Hz.h5" dest = bdir / "E1T2DMD2_BASELINE-80Hz.h5" dest.write_bytes(src.read_bytes()) @@ -983,17 +1044,22 @@ def fake_run(args, **kw): monkeypatch.setattr(silo_baseline.subprocess, "run", fake_run) silo_baseline.predict_baselines(s, NET, bdir, ckpt) - assert ( - silo_baseline.predict_baselines(s, NET, bdir, ckpt)["predicted"] == [] - ) + assert silo_baseline.predict_baselines(s, NET, bdir, ckpt)["predicted"] == [] ckpt.write_bytes(b"retrained weights") # same name, other model with pytest.raises(ValueError, match="another checkpoint"): silo_baseline.predict_baselines(s, NET, bdir, ckpt) def _copy_tree(src: Path, dest: Path) -> Path: - """A copy whose files have new modification times (as a data asset's - files carry their upload times).""" + """Copy a tree so that its files have new modification times. + + A data asset's files carry their upload times. + + Returns + ------- + Path + The copy, dest. + """ import shutil shutil.copytree(src, dest, copy_function=shutil.copyfile) @@ -1004,11 +1070,14 @@ def _copy_tree(src: Path, dest: Path) -> Path: return dest -def test_records_with_digests_identify_copied_files(tmp_path, monkeypatch): - """Records written with digests=True still identify the baseline, - movie and alignment files after they are copied elsewhere (another - modification time), and refuse a copy whose content changed; records - without digests refuse any copy, as before.""" +def test_records_with_digests_identify_copied_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Records written with digests=True still identify the baseline, movie and alignment files. + + They do so after the files are copied elsewhere (another modification time), and refuse a + copy whose content changed; records without digests refuse any copy, as before. + """ root = tmp_path / "s" s = SiloSession.open(make_session(root)) for d in range(N_PATHS): # movies with content, so that digests differ @@ -1020,12 +1089,16 @@ def test_records_with_digests_identify_copied_files(tmp_path, monkeypatch): (bdir / f"{stem}_BASELINE-80Hz.h5").unlink() ckpt = tmp_path / "s6_test.pt" ckpt.write_bytes(b"weights") - monkeypatch.setattr( - silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}" - ) + monkeypatch.setattr(silo_baseline.shutil, "which", lambda c: f"/bin/{Path(c).name}") + + def fake_run(args: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + """Write the file asked for. - def fake_run(args, **kw): - """Write the file asked for.""" + Returns + ------- + subprocess.CompletedProcess[str] + A completed process with exit code 0. + """ dest = bdir / f"{stem}_BASELINE-80Hz.h5" dest.write_bytes((bdir / "E1T1DMD1_BASELINE-80Hz.h5").read_bytes()) with h5py.File(dest, "a") as f: @@ -1076,15 +1149,15 @@ def fake_run(args, **kw): old[k].pop("sha256") rec3.write_text(json.dumps(old)) with pytest.raises(ValueError, match="does not describe"): - silo_baseline.check_baseline_record( - bdir3 / base.name, None, s.alignment(1, 1), NET - ) + silo_baseline.check_baseline_record(bdir3 / base.name, None, s.alignment(1, 1), NET) assert not silo_baseline.same_file(None, base) -def test_localize_trial_reads_network_sd_when_present(tmp_path): - """localize_trial uses /sd from *_BASELINE-80Hz.h5 when present and - localization_sd=True, falls back when absent, and honours False.""" +def test_localize_trial_reads_network_sd_when_present(tmp_path: Path) -> None: + """localize_trial uses /sd from *_BASELINE-80Hz.h5 when present and localization_sd=True. + + It falls back when absent, and honours False. + """ moco = tmp_path / "moco" moco.mkdir() bdir = tmp_path / "b" @@ -1108,9 +1181,7 @@ def test_localize_trial_reads_network_sd_when_present(tmp_path): assert read_network_sd(bfile) is None lp_on = SiloParams(baseline_source="network").localization_params(80.0) - lp_off = SiloParams( - baseline_source="network", localization_sd=False - ).localization_params(80.0) + lp_off = SiloParams(baseline_source="network", localization_sd=False).localization_params(80.0) loc_no_sd, _ = trial_mod.localize_trial( moco, fn, 1, replace(lp_on, null="none"), baseline_dir=bdir ) @@ -1138,11 +1209,12 @@ def test_localize_trial_reads_network_sd_when_present(tmp_path): assert p_off.to_matlab(2, 80.0)["localizationSd"] == np.bool_(False) -def test_solver_sd_is_off_by_default(): - """The solver keeps its own variance model unless solver_sd is set: - the default leaves the prepare stage's settings and the saved params - as they were before the option existed, and switching it on is - recorded in both.""" +def test_solver_sd_is_off_by_default() -> None: + """The solver keeps its own variance model unless solver_sd is set. + + The default leaves the prepare stage's settings and the saved params as they were before the + option existed, and switching it on is recorded in both. + """ p = SiloParams(baseline_source="network") assert p.solver_sd is False assert "solver_sd" not in p.stage_settings("prepare") @@ -1155,6 +1227,4 @@ def test_solver_sd_is_off_by_default(): assert settings["discard_initial_s"] == on.discard_initial_s assert on.to_matlab(2, 80.0)["solverSd"] == np.bool_(True) # with MATLAB's baseline fit the option changes nothing - assert "solver_sd" not in SiloParams(solver_sd=True).stage_settings( - "prepare" - ) + assert "solver_sd" not in SiloParams(solver_sd=True).stage_settings("prepare") diff --git a/tests/raster/test_raster_silo_params.py b/tests/raster/test_raster_silo_params.py index 1959db32..ebe78c33 100644 --- a/tests/raster/test_raster_silo_params.py +++ b/tests/raster/test_raster_silo_params.py @@ -2,6 +2,7 @@ from argparse import Namespace from dataclasses import replace +from pathlib import Path from types import SimpleNamespace import h5py @@ -45,16 +46,16 @@ # size and class. Values of the scalars are checked below. # the settings that make SiloParams MATLAB's algorithm (the defaults differ # from it in the footprint fit and the seed fit) -MATLAB_ALGORITHM = dict( - footprint_variance="model", - seed_fit="matlab", - seed_merge_px=0.0, - valid_kernel=3, - f0_im_trim_s=None, - variance_mode="freshness", - snr_mode="diagonal", - warp_interp="linear", -) +MATLAB_ALGORITHM = { + "footprint_variance": "model", + "seed_fit": "matlab", + "seed_merge_px": 0.0, + "valid_kernel": 3, + "f0_im_trim_s": None, + "variance_mode": "freshness", + "snr_mode": "diagonal", + "warp_interp": "linear", +} MATLAB_FIELDS = { "Bfilter": ((25, 25, 3), np.float64), @@ -132,16 +133,16 @@ } -def test_defaults_are_matlabs_slap2_silo(): - """The derived stage parameters keep each stage's MATLAB defaults aside - from SiloParams' explicit SLAP2 Python defaults.""" +def test_defaults_are_matlabs_slap2_silo() -> None: + """Check that derived stage parameters keep each stage's MATLAB defaults. + + The defaults hold aside from SiloParams' explicit SLAP2 Python defaults. + """ from dataclasses import replace p = SiloParams() assert replace(p.plan_params(), warp_interp="linear") == PlanParams() - assert replace(p.load_params(), variance_mode="freshness") == ( - TrialLoadParams() - ) + assert replace(p.load_params(), variance_mode="freshness") == (TrialLoadParams()) assert replace(p.solver_params(), snr_mode="diagonal") == SolverParams() loc = p.localization_params(80.0) # peakth is 3 for SLAP2 in every stage (RasterLocalizationParams' own @@ -151,7 +152,7 @@ def test_defaults_are_matlabs_slap2_silo(): assert p.sel_radius == 6 -def test_footprint_default_is_the_solvers(monkeypatch): +def test_footprint_default_is_the_solvers(monkeypatch: pytest.MonkeyPatch) -> None: """The footprint fit's default comes from the solver, not from here.""" from dataclasses import fields @@ -159,21 +160,15 @@ def test_footprint_default_is_the_solvers(monkeypatch): assert SiloParams().footprint_variance == SolverParams.footprint_variance default = next( - f.default - for f in fields(solver_setup.SolverParams) - if f.name == "footprint_variance" + f.default for f in fields(solver_setup.SolverParams) if f.name == "footprint_variance" ) assert SiloParams().solver_params().footprint_variance == default - monkeypatch.setattr( - solver_setup.SolverParams, "footprint_variance", "model" - ) + monkeypatch.setattr(solver_setup.SolverParams, "footprint_variance", "model") assert SiloParams().footprint_variance == "model" - assert SiloParams(footprint_variance="fixed").footprint_variance == ( - "fixed" - ) + assert SiloParams(footprint_variance="fixed").footprint_variance == ("fixed") -def test_one_setting_reaches_every_stage(): +def test_one_setting_reaches_every_stage() -> None: """A shared setting is passed to each stage that uses it.""" p = SiloParams(sigma_px=1.5, nan_thresh=0.2, peak_th=4.0) assert p.plan_params().sigma_px == 1.5 @@ -183,20 +178,17 @@ def test_one_setting_reaches_every_stage(): assert p.load_params().nan_thresh == 0.2 assert p.localization_params(80).nan_thresh == 0.2 assert p.localization_params(80).peak_th == 4.0 - assert ( - SiloParams(localization_peak_th=8.0).localization_params(80).peak_th - == 8.0 - ) + assert SiloParams(localization_peak_th=8.0).localization_params(80).peak_th == 8.0 assert p.localization_params(123.0).align_hz == 123.0 - net = SiloParams( - localization_baseline="network", localization_variance_floor=False - ) + net = SiloParams(localization_baseline="network", localization_variance_floor=False) assert net.localization_params(80).variance_floor is False -def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path): - """Written as saveStructToH5 would, the struct of MATLAB's algorithm - has MATLAB's schema.""" +def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path: Path) -> None: + """Check that the struct of MATLAB's algorithm has MATLAB's schema. + + The struct is written as saveStructToH5 would. + """ m = SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0, 12, "a", "b") assert set(m) == set(MATLAB_FIELDS) path = tmp_path / "p.h5" @@ -223,13 +215,14 @@ def test_to_matlab_has_matlabs_fields_types_and_values(tmp_path): np.testing.assert_array_equal(m["Bfilter"][:, :, 2], sp.bfilter[2]) -def test_python_only_settings_are_recorded_when_not_matlabs(): - """MATLAB's algorithm has MATLAB's fields only; other settings add one +def test_python_only_settings_are_recorded_when_not_matlabs() -> None: + """MATLAB's algorithm has MATLAB's fields only. + + Other settings add one each, the defaults (fixed-variance footprint fit, local seed fit with - merging, F0 images) too.""" - assert set(SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0)) == set( - MATLAB_FIELDS - ) + merging, F0 images) too. + """ + assert set(SiloParams(**MATLAB_ALGORITHM).to_matlab(2, 80.0)) == set(MATLAB_FIELDS) assert set(SiloParams().to_matlab(2, 80.0)) - set(MATLAB_FIELDS) == { "footprintVariance", "seedFit", @@ -297,13 +290,13 @@ def test_python_only_settings_are_recorded_when_not_matlabs(): {"valid_kernel": True}, ], ) -def test_invalid_values_are_rejected(kwargs): +def test_invalid_values_are_rejected(kwargs: dict) -> None: """Values no stage can run with raise ValueError.""" with pytest.raises(ValueError): SiloParams(**kwargs) -def test_wmf_thresholds_and_evidence(): +def test_wmf_thresholds_and_evidence() -> None: """WMF thresholds reach the plan and evidence judges every WMF seed.""" p = SiloParams( peak_method="wmf", @@ -319,14 +312,25 @@ def test_wmf_thresholds_and_evidence(): assert replace(p, peak_method="getactimpeaks").evidence_judge_below == 5 -def test_wmf_hash_only_depends_on_active_seed_settings(): +def test_wmf_hash_only_depends_on_active_seed_settings() -> None: """The original plan hash survives and every WMF threshold affects WMF.""" session = SimpleNamespace(n_trials=0) default = SiloParams() wmf = replace(default, peak_method="wmf") - def plan_hash(params): - """Hash a plan without any input file identities.""" + def plan_hash(params: SiloParams) -> str: + """Hash a plan without any input file identities. + + Parameters + ---------- + params : SiloParams + The settings to hash. + + Returns + ------- + str + The plan's settings hash. + """ return _plan_hash(session, params, 0, None, None) old = "c8097bb03c1ece9987cd0a5904b474785926cde36403f8b886cb65e862939996" @@ -338,7 +342,7 @@ def plan_hash(params): assert plan_hash(replace(wmf, **changed)) != plan_hash(wmf) -def test_collect_checks_wmf_settings_against_the_saved_plan(): +def test_collect_checks_wmf_settings_against_the_saved_plan() -> None: """Collection uses the same method and active thresholds as the plan.""" p = SiloParams(peak_method="wmf") plan = SimpleNamespace(params=p.plan_params()) @@ -350,7 +354,7 @@ def test_collect_checks_wmf_settings_against_the_saved_plan(): check_plan_seeding("plan", plan, replace(p, **{name: 10.0})) -def test_collect_suggests_parseable_infinite_wmf_threshold(): +def test_collect_suggests_parseable_infinite_wmf_threshold() -> None: """The collection recovery setting parses when deblending was off.""" p = SiloParams(peak_method="wmf", wmf_deblend_th=np.inf) plan = SimpleNamespace(params=p.plan_params()) @@ -361,11 +365,13 @@ def test_collect_suggests_parseable_infinite_wmf_threshold(): check_plan_seeding("plan", plan, recovered) -def test_alignment_modes(): - """The three across-trial alignments are accepted and reach the plan - stage; others are rejected. The patch size counts in the plan's +def test_alignment_modes() -> None: + """The three across-trial alignments are accepted and reach the plan stage. + + Others are rejected. The patch size counts in the plan's settings only when it is not the default (plans made before it was a - field stay current).""" + field stay current). + """ for mode in ("rigid", "affine", "patchwise"): p = SiloParams(inter_trial_alignment=mode, align_patch_px=1200) assert p.plan_params().inter_trial_alignment == mode @@ -373,46 +379,39 @@ def test_alignment_modes(): with pytest.raises(ValueError, match="inter_trial_alignment"): SiloParams(inter_trial_alignment="elastic") assert "align_patch_px" not in SiloParams().stage_settings("plan") - assert ( - SiloParams(align_patch_px=1000).stage_settings("plan")[ - "align_patch_px" - ] - == 1000 - ) + assert SiloParams(align_patch_px=1000).stage_settings("plan")["align_patch_px"] == 1000 assert SiloParams().stage_settings("localize") == SiloParams( inter_trial_alignment="patchwise" ).stage_settings("localize") -def test_stage_settings_change_only_with_their_fields(): +def test_stage_settings_change_only_with_their_fields() -> None: """A solver setting changes the solve stage's settings only.""" a, b = SiloParams(), SiloParams(lam=0.5) for stage in ("localize", "plan", "prepare", "collect"): assert a.stage_settings(stage) == b.stage_settings(stage) assert a.stage_settings("solve") != b.stage_settings("solve") - assert a.stage_settings("plan") != SiloParams(peak_th=4.0).stage_settings( - "plan" - ) + assert a.stage_settings("plan") != SiloParams(peak_th=4.0).stage_settings("plan") # the frames a trial keeps reach the prepare stage through solver_sd # alone (its average of the network's variance over the kept frames) for sd in (False, True): p_net = SiloParams(baseline_mode="fit_from", solver_sd=sd) for change in ({"motion_thresh": 3.0}, {"discard_initial_s": 0.5}): other = replace(p_net, **change) - same = p_net.stage_settings("prepare") == other.stage_settings( - "prepare" - ) + same = p_net.stage_settings("prepare") == other.stage_settings("prepare") assert same is not sd with pytest.raises(ValueError): a.stage_settings("other") -def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes(): - """The seed fit's defaults (local fits, merging within 1.5 px) are the - plan stage's; they reach the plan and the per-trial peaks' stage and +def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes() -> None: + """The seed fit's defaults (local fits, merging within 1.5 px) are the plan stage's. + + They reach the plan and the per-trial peaks' stage and are in those stages' settings, so outputs made with MATLAB's fit (the behaviour before the options existed) are not current. Asking for - MATLAB's fit leaves those stages' settings as they were then.""" + MATLAB's fit leaves those stages' settings as they were then. + """ a = SiloParams() assert ( (a.seed_fit, a.seed_merge_px) @@ -439,13 +438,15 @@ def test_seed_fit_settings_reach_the_plan_and_keep_old_hashes(): assert "seedFit" not in matlab.to_matlab(2, 80.0) -def test_valid_kernel_is_one_setting_for_plan_and_solver(): - """The footprint support reaches the plan's zones and the solver - together (default 5 x 5, one default for the three types); 3 (MATLAB's) +def test_valid_kernel_is_one_setting_for_plan_and_solver() -> None: + """The footprint support reaches the plan's zones and the solver together. + + The default is 5 x 5, one default for the three types; 3 (MATLAB's) leaves every stage's settings as before the setting existed, so outputs made then stay current with it; another value changes the plan's and the solve's only; the saved params struct records validKernel at its - size.""" + size. + """ a, b = SiloParams(valid_kernel=3), SiloParams() assert b.valid_kernel == PlanParams.valid_kernel == 5 assert b.valid_kernel == SolverParams.valid_kernel @@ -468,12 +469,10 @@ def test_valid_kernel_is_one_setting_for_plan_and_solver(): np.testing.assert_array_equal(mb["validKernel"], np.ones((5, 5), bool)) -def test_execution_options(): +def test_execution_options() -> None: """Execution options validate and give the solver's options.""" e = SiloExecution(device="cuda", dtype="float32", batch_bytes=1e8) - assert e.solver_options() == SolverOptions( - device="cuda", dtype="float32", batch_bytes=1e8 - ) + assert e.solver_options() == SolverOptions(device="cuda", dtype="float32", batch_bytes=1e8) for bad in ( {"solver_threads": 0}, {"device": "gpu"}, @@ -494,8 +493,23 @@ def test_execution_options(): resolve_silo_options({"nWorkers": 2}) -def _trial(sel, n_frames=30, seed=0): - """A trial with random data at the selected pixels of ``sel``.""" +def _trial(sel: np.ndarray, n_frames: int = 30, seed: int = 0) -> TrialData: + """Build a trial with random data at the selected pixels of sel. + + Parameters + ---------- + sel : np.ndarray + Boolean mask of the selected pixels, (rows, cols). + n_frames : int + Number of frames. + seed : int + Seed of the random generator. + + Returns + ------- + TrialData + The trial, with random data at the selected pixels. + """ rng = np.random.default_rng(seed) cols, rows = np.nonzero(sel.T) rc = np.stack([rows, cols], 1) @@ -515,7 +529,7 @@ def _trial(sel, n_frames=30, seed=0): ) -def test_plan_groups_container_and_solver_share_one_type(tmp_path): +def test_plan_groups_container_and_solver_share_one_type(tmp_path: Path) -> None: """A plan group's subproblem equals the container's: the solver's type.""" shape = (20, 24) rows, cols = np.array([5, 6, 14]), np.array([5, 8, 17]) @@ -541,16 +555,17 @@ def test_plan_groups_container_and_solver_share_one_type(tmp_path): for got in (container.subproblem(k), read_subproblem(path, k)): assert isinstance(got, Subproblem) for name in ("y", "finv", "sel", "sources_rc", "pixels"): - np.testing.assert_array_equal( - getattr(got, name), getattr(sub, name) - ) + np.testing.assert_array_equal(getattr(got, name), getattr(sub, name)) np.testing.assert_array_equal(got.sources, sub.sources) assert (got.row0, got.col0) == (sub.row0, sub.col0) -def test_loader_warp(): - """A shift reaches the loader as a RigidShift, an affine map as a - function of zero-based coordinates; an unaligned trial raises.""" +def test_loader_warp() -> None: + """A shift reaches the loader as a RigidShift. + + An affine map reaches it as a + function of zero-based coordinates; an unaligned trial raises. + """ warp = TrialWarp.from_shifts(np.array([[1.5, -2.0], [np.nan, np.nan]])) w = loader_warp(warp, 0) assert w == RigidShift(1.5, -2.0) diff --git a/tests/raster/test_raster_silo_stages.py b/tests/raster/test_raster_silo_stages.py index 54618ed5..ef02d634 100644 --- a/tests/raster/test_raster_silo_stages.py +++ b/tests/raster/test_raster_silo_stages.py @@ -8,10 +8,15 @@ """ import os +from collections.abc import Callable, Sequence +from concurrent.futures import Future +from multiprocessing.synchronize import Lock from pathlib import Path +from typing import NoReturn import h5py import numpy as np +import numpy.typing as npt import pytest from giant_python.cli import build_parser, main @@ -22,7 +27,7 @@ from giant_python.extraction.raster.plan import read_plan from giant_python.extraction.raster.results import read_results from giant_python.extraction.raster.trial import RegisteredTrial -from giant_python.extraction.raster.trial_data import TrialData +from giant_python.extraction.raster.trial_data import TrialAlignment, TrialData from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 from giant_python.models.params import SiloExecution, SiloParams from giant_python.pipeline import silo, silo_collect, silo_solve @@ -35,27 +40,42 @@ SHIFTS = {0: (0, 0), 1: (1, -1), 2: (0, 1)} -def _blobs(amplitude, sigma=1.3, shift=(0, 0)): - """Gaussian blobs at the sources (moved into a trial's frame).""" +def _blobs( + amplitude: Sequence[float], sigma: float = 1.3, shift: tuple[int, int] = (0, 0) +) -> np.ndarray: + """Build Gaussian blobs at the sources (moved into a trial's frame). + + Returns + ------- + np.ndarray + The image (H, W) with one blob per source, of the given amplitudes. + """ r, c = np.mgrid[:H, :W] img = np.zeros((H, W)) for (sr, sc), a in zip(SOURCES, amplitude): - img += a * np.exp( - -((r - sr - shift[0]) ** 2 + (c - sc - shift[1]) ** 2) - / (2 * sigma**2) - ) + img += a * np.exp(-((r - sr - shift[0]) ** 2 + (c - sc - shift[1]) ** 2) / (2 * sigma**2)) return img -def fake_localize(moco_dir, fn, num_channels, params=None, **kw): - """Images of a localized trial (instead of reading its movie).""" +def fake_localize( + moco_dir: str | Path, + fn: str, + num_channels: int, + params: object = None, + **kw: object, +) -> tuple[RasterLocalization, RegisteredTrial]: + """Build the images of a localized trial (instead of reading its movie). + + Returns + ------- + tuple of (RasterLocalization, RegisteredTrial) + The trial's localization and its registered data, synthetic. + """ t = int(fn.split("T")[1][0]) - 1 rng = np.random.default_rng(t) shift = SHIFTS[t] act = _blobs([30, 25, 40, 20], shift=shift) + rng.random((H, W)) - mean = np.stack( - [_blobs([5, 5, 5, 5], 3, shift) + 10, np.full((H, W), 4.0)], 2 - ) + mean = np.stack([_blobs([5, 5, 5, 5], 3, shift) + 10, np.full((H, W), 4.0)], 2) loc = RasterLocalization( act_im=act, summary=act, @@ -78,20 +98,26 @@ def fake_localize(moco_dir, fn, num_channels, params=None, **kw): def fake_load( - dat_path, - first_line, - last_line, - alignment, - sel_pix, - warp, - discard_frames, - mean_image, - roi_masks=(), - params=None, - device="cpu", - dtype=np.float32, -): - """A trial at the selected pixels: baseline plus sources with events.""" + dat_path: str | Path, + first_line: float, + last_line: float, + alignment: TrialAlignment | str | Path, + sel_pix: np.ndarray, + warp: Callable, + discard_frames: np.ndarray, + mean_image: np.ndarray, + roi_masks: Sequence[np.ndarray] = (), + params: object = None, + device: str = "cpu", + dtype: npt.DTypeLike = np.float32, +) -> TrialData: + """Build a trial at the selected pixels: baseline plus sources with events. + + Returns + ------- + TrialData + The synthetic trial at the pixels selected by sel_pix. + """ name = Path(dat_path).name t = int(name.split("TRIAL")[1][:6]) - 1 d = int(name.split("DMD")[1][0]) - 1 @@ -123,7 +149,13 @@ def fake_load( def make_session(root: Path) -> Path: - """Trial table, alignment files and empty movies and raw files.""" + """Build the trial table, alignment files and empty movies and raw files. + + Returns + ------- + Path + The session's trial_table.h5. + """ moco, raw = root / "motion_correction", root / "raw" moco.mkdir(parents=True) raw.mkdir() @@ -176,8 +208,8 @@ def make_session(root: Path) -> Path: @pytest.fixture -def fake(monkeypatch): - """Synthetic localization and loading, in this process.""" +def fake(monkeypatch: pytest.MonkeyPatch) -> None: + """Patch in synthetic localization and loading, in this process.""" monkeypatch.setattr(trial_mod, "localize_trial", fake_localize) monkeypatch.setattr(trial_data_mod, "load_trial", fake_load) @@ -187,39 +219,64 @@ def fake(monkeypatch): def seeds_file(root: Path) -> Path: - """The sources as seeds of both paths (zero-based); the plan's own - seeding is tested with the plan stage.""" + """Write the sources as seeds of both paths (zero-based). + + The plan's own seeding is tested with the plan stage. + + Returns + ------- + Path + The seeds file in root. + """ from giant_python.extraction.raster.stage_files import write_seeds - seeds = np.column_stack( - [np.full(len(SOURCES), 10.0), SOURCES, np.full(len(SOURCES), 1.3)] - ).astype(float) + seeds = np.column_stack([ + np.full(len(SOURCES), 10.0), + SOURCES, + np.full(len(SOURCES), 1.3), + ]).astype(float) path = root / "seeds.h5" write_seeds(path, {1: seeds, 2: seeds}, index_base=0) return path -def _seeds(session, root): - """The seeds of :func:`seeds_file` per path.""" +def _seeds(session: SiloSession, root: Path) -> list: + """Read the seeds of :func:`seeds_file` per path. + + Returns + ------- + list + Each path's seeds, zero-based. + """ from giant_python.extraction.raster.stage_files import read_seeds return read_seeds(seeds_file(root), session.n_paths) -def _data(path): - """The solved arrays of a results file, by subproblem.""" +def _data(path: Path) -> dict: + """Read the solved arrays of a results file, by subproblem. + + Returns + ------- + dict + For each subproblem key, a dict of its footprints, events, ls, + f0, snr and f0_image arrays. + """ r = read_results(path) return { - k: { - n: getattr(v[2], n) - for n in ("footprints", "events", "ls", "f0", "snr", "f0_image") - } + k: {n: getattr(v[2], n) for n in ("footprints", "events", "ls", "f0", "snr", "f0_image")} for k, v in r.results.items() } -def _all_results(session): - """Every subproblem's arrays, keyed by (path, trial, subproblem).""" +def _all_results(session: SiloSession) -> dict: + """Collect every subproblem's arrays, keyed by (path, trial, subproblem). + + Returns + ------- + dict + The arrays of each subproblem, as from :func:`_data`. + """ out = {} for f in sorted(session.results_dir.glob("*.h5")): r = read_results(f) @@ -228,15 +285,21 @@ def _all_results(session): return out -def _summary(path): - """A summary file's datasets (params' times left out).""" +def _summary(path: Path) -> dict: + """Read a summary file's datasets (params' times left out). + + Returns + ------- + dict + The file's datasets without params. + """ s = load_struct_h5(path) s.pop("params", None) return s -def _equal(a, b): - """Nested dicts of arrays are equal (NaN equal).""" +def _equal(a: dict, b: dict) -> None: + """Check that nested dicts of arrays are equal (NaN equal).""" assert a.keys() == b.keys() for k in a: if isinstance(a[k], dict): @@ -245,9 +308,12 @@ def _equal(a, b): np.testing.assert_array_equal(a[k], b[k]) -def test_streamed_and_staged_runs_agree(tmp_path, fake): - """The streaming driver, one job and three jobs give the same results - and summaries; reruns keep finished units.""" +def test_streamed_and_staged_runs_agree(tmp_path: Path, fake: None) -> None: + """The streaming driver, one job and three jobs give the same results. + + They also give the same + summaries; reruns keep finished units. + """ table = make_session(tmp_path / "streamed") seeds = seeds_file(tmp_path) report = silo.run_silo(table, PARAMS, EX, seeds_file=seeds) @@ -260,9 +326,7 @@ def test_streamed_and_staged_runs_agree(tmp_path, fake): assert len(report["localize_trials"]) == N_PATHS * N_TRIALS assert all(r["seconds"] > 0 for r in report["localize_trials"]) loaded = [r for r in report["trials"] if "load" in r] - assert loaded and all( - 0 <= r["submitted"] <= r["solved"] <= report["total"] for r in loaded - ) + assert loaded and all(0 <= r["submitted"] <= r["solved"] <= report["total"] for r in loaded) streamed = _all_results(s1) # every subproblem has its F0 image, and the summaries the trials' F0 # images on the selected pixels of the extracted trials (not trial 3) @@ -270,9 +334,7 @@ def test_streamed_and_staged_runs_agree(tmp_path, fake): per = load_struct_h5(s1.out_dir / "per_trial_summary.h5") plan = read_plan(s1.plan_file(0)) f0 = np.asarray(per["Path1"]["visualizations"]["per_trial_F0_im"]) - assert f0.shape == np.shape( - per["Path1"]["visualizations"]["per_trial_mean_im"] - ) + assert f0.shape == np.shape(per["Path1"]["visualizations"]["per_trial_mean_im"]) act = f0[:, 0, 0] # trials, rows, cols (activity channel 1) for t in range(N_TRIALS): if t == 2: @@ -318,18 +380,16 @@ def test_streamed_and_staged_runs_agree(tmp_path, fake): _summary(s2.out_dir / "per_trial_summary.h5"), _summary(s1.out_dir / "per_trial_summary.h5"), ) - many = list( - (tmp_path / "staged3" / "source_extraction" / "silo" / "results").glob( - "*_s*.h5" - ) - ) + many = list((tmp_path / "staged3" / "source_extraction" / "silo" / "results").glob("*_s*.h5")) assert many, "three jobs split a container into ranges" -def test_valid_kernel_through_the_run(tmp_path, fake): - """One footprint support for the whole run: streamed and staged runs - at 5 agree, differ from 3, and record it; a changed support redoes the - plan; the stages after the plan refuse files made with another one.""" +def test_valid_kernel_through_the_run(tmp_path: Path, fake: None) -> None: + """One footprint support for the whole run: streamed and staged runs at 5 agree. + + They differ from 3, and record it; a changed support redoes the + plan; the stages after the plan refuse files made with another one. + """ import json from dataclasses import replace @@ -379,13 +439,10 @@ def test_valid_kernel_through_the_run(tmp_path, fake): silo_solve.solve_containers(s, p3, EX) three = _all_results(s) assert three.keys() == staged.keys() - assert any( - not np.array_equal(three[k]["footprints"], staged[k]["footprints"]) - for k in staged - ) + assert any(not np.array_equal(three[k]["footprints"], staged[k]["footprints"]) for k in staged) -def test_settings_change_redoes_units(tmp_path, fake): +def test_settings_change_redoes_units(tmp_path: Path, fake: None) -> None: """A changed solver setting redoes the solve stage only.""" s = SiloSession.open(make_session(tmp_path)) silo.localize(s, PARAMS, EX) @@ -402,10 +459,15 @@ def test_settings_change_redoes_units(tmp_path, fake): assert all(v is not None for v in done.values()) -def test_inputs_and_stale_results(tmp_path, fake, monkeypatch): - """A changed raw file redoes prepare; collect uses only results of the +def test_inputs_and_stale_results( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """A changed raw file redoes prepare. + + Collect uses only results of the current plan and solve settings; a trial found without data loses its - earlier container and results.""" + earlier container and results. + """ import os from giant_python.pipeline.silo_session import NO_DATA @@ -435,16 +497,25 @@ def test_inputs_and_stale_results(tmp_path, fake, monkeypatch): silo_collect.collect(s, third, EX) # the trial has no data any more: its container and results go - def no_data(dat_path, *args, **kw): - """Path 1, trial 1 has no data now.""" + def no_data(dat_path: str | Path, *args: object, **kw: object) -> TrialData: + """Load a trial, except that path 1, trial 1 has no data now. + + Returns + ------- + TrialData + The trial, as from :func:`fake_load`. + + Raises + ------ + ValueError + For path 1, trial 1. + """ if "DMD1-TRIAL000001" in str(dat_path): raise ValueError(NO_DATA) return fake_load(dat_path, *args, **kw) monkeypatch.setattr(trial_data_mod, "load_trial", no_data) - ex = SiloExecution( - workers=1, solver_workers=1, solver_threads=1, overwrite=True - ) + ex = SiloExecution(workers=1, solver_workers=1, solver_threads=1, overwrite=True) silo.prepare(s, other, ex, units=[(0, 0)]) assert s.skip_file(0, 0).exists() assert not s.container_file(0, 0).exists() @@ -463,9 +534,12 @@ def no_data(dat_path, *args, **kw): silo_collect.collect(s, other, EX) -def test_collect_and_dispatch_without_raw_data(tmp_path, fake): - """Dispatch and collect need neither the raw data nor the movies; a - short trial is one item of no work.""" +def test_collect_and_dispatch_without_raw_data(tmp_path: Path, fake: None) -> None: + """Dispatch and collect need neither the raw data nor the movies. + + A + short trial is one item of no work. + """ import json import shutil @@ -481,11 +555,7 @@ def test_collect_and_dispatch_without_raw_data(tmp_path, fake): SiloSession.open(table) c = SiloSession.open(table, inputs="collect") jobs = silo_solve.dispatch(c, PARAMS, 3, EX) - items = [ - it - for j in jobs - for it in json.loads(j.read_text(encoding="utf-8"))["items"] - ] + items = [it for j in jobs for it in json.loads(j.read_text(encoding="utf-8"))["items"]] short = [it for it in items if it["container"] == "path1_trial0003.h5"] assert len(short) == 1 and short[0]["work"] == 0 for job in jobs: @@ -496,9 +566,12 @@ def test_collect_and_dispatch_without_raw_data(tmp_path, fake): assert frames.tolist() == [FRAMES[0], FRAMES[1], FRAMES[2]] -def test_localize_fits_missing_peaks(tmp_path, fake): - """Localization files without their peaks (a streaming run stopped - before its background fits) get them from silo-localize.""" +def test_localize_fits_missing_peaks(tmp_path: Path, fake: None) -> None: + """Localization files without their peaks get them from silo-localize. + + A streaming run stopped + before its background fits leaves such files. + """ from giant_python.extraction.raster.stage_files import localization_attrs s = SiloSession.open(make_session(tmp_path)) @@ -513,7 +586,7 @@ def test_localize_fits_missing_peaks(tmp_path, fake): assert silo.localize(s, PARAMS, EX) == [] -def test_job_needs_its_container(tmp_path, fake): +def test_job_needs_its_container(tmp_path: Path, fake: None) -> None: """A job refuses a container other than the one it was made for.""" s = SiloSession.open(make_session(tmp_path)) silo.localize(s, PARAMS, EX) @@ -526,10 +599,13 @@ def test_job_needs_its_container(tmp_path, fake): silo_solve.solve_job(job, execution=EX) -def test_job_without_valid_kernel_is_matlabs(tmp_path, fake): - """A job file written before valid_kernel existed (its params lack the - field) solves its containers at MATLAB's 3 x 3, which they were - prepared for, not at today's default.""" +def test_job_without_valid_kernel_is_matlabs(tmp_path: Path, fake: None) -> None: + """A job file written before valid_kernel existed solves its containers at 3 x 3. + + Its params lack the + field; it solves its containers at MATLAB's 3 x 3, which they were + prepared for, not at today's default. + """ import json from dataclasses import replace @@ -548,13 +624,29 @@ def test_job_without_valid_kernel_is_matlabs(tmp_path, fake): assert results.results -def test_trial_without_data_is_skipped(tmp_path, fake, monkeypatch): - """A trial whose selected pixels have no sample is marked and left out - of the summaries, streamed and staged alike.""" +def test_trial_without_data_is_skipped( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """A trial whose selected pixels have no sample is marked. + + It is also left out + of the summaries, streamed and staged alike. + """ from giant_python.pipeline.silo_session import NO_DATA - def no_data(dat_path, *args, **kw): - """Path 2, trial 2 has no data.""" + def no_data(dat_path: str | Path, *args: object, **kw: object) -> TrialData: + """Load a trial, except that path 2, trial 2 has no data. + + Returns + ------- + TrialData + The trial, as from :func:`fake_load`. + + Raises + ------ + ValueError + For path 2, trial 2. + """ if "DMD2-TRIAL000002" in str(dat_path): raise ValueError(NO_DATA) return fake_load(dat_path, *args, **kw) @@ -581,9 +673,8 @@ def no_data(dat_path, *args, **kw): assert silo.prepare(s, PARAMS, EX, units=[(1, 1)]) == [] -def test_seeds_file_replaces_seeding(tmp_path, fake): - """Seeds from a file (one-based, MATLAB's thetaf) give the plan's - sources.""" +def test_seeds_file_replaces_seeding(tmp_path: Path, fake: None) -> None: + """Seeds from a file (one-based, MATLAB's thetaf) give the plan's sources.""" from giant_python.extraction.raster.plan import read_plan from giant_python.extraction.raster.stage_files import ( read_seeds, @@ -603,28 +694,26 @@ def test_seeds_file_replaces_seeding(tmp_path, fake): np.testing.assert_array_equal(p.source_cols, [7, 20]) -def test_cli(tmp_path, fake, capsys): +def test_cli(tmp_path: Path, fake: None, capsys: pytest.CaptureFixture[str]) -> None: """The commands parse their options and run the stages.""" assert parse_numbers("1,3-4") == [1, 3, 4] assert parse_numbers(None) is None with pytest.raises(ValueError): parse_numbers("0") (tmp_path / "p.json").write_text('{"lam": 0.5}') - args = build_parser().parse_args( - [ - "silo", - "t.h5", - "--params", - str(tmp_path / "p.json"), - "--set", - "nmf_iter=3", - "--set", - "footprint_variance=fixed", - "--peak-th", - "4", - "--no-trial-peaks", - ] - ) + args = build_parser().parse_args([ + "silo", + "t.h5", + "--params", + str(tmp_path / "p.json"), + "--set", + "nmf_iter=3", + "--set", + "footprint_variance=fixed", + "--peak-th", + "4", + "--no-trial-peaks", + ]) p = params_from_args(args) assert p.valid_kernel == 5 # the default for cmd in ("silo", "silo-plan", "silo-prepare", "silo-collect"): @@ -642,9 +731,7 @@ def test_cli(tmp_path, fake, capsys): ) assert p.trial_peaks is False with pytest.raises(ValueError): - params_from_args( - build_parser().parse_args(["silo", "t", "--set", "x=1"]) - ) + params_from_args(build_parser().parse_args(["silo", "t", "--set", "x=1"])) table = make_session(tmp_path / "s") opts = ["--workers", "1", "--set", "min_kinetic_score=0"] assert main(["silo-localize", str(table), "--paths", "1", *opts]) == 0 @@ -653,41 +740,40 @@ def test_cli(tmp_path, fake, capsys): assert main(["silo-plan", str(table), "--seeds", seeds, *opts]) == 0 assert main(["silo-prepare", str(table), "--trials", "1-3", *opts]) == 0 assert ( - main( - [ - "silo-dispatch", - str(table), - "--machines", - "2", - "--solver-workers", - "1", - *opts, - ] - ) + main([ + "silo-dispatch", + str(table), + "--machines", + "2", + "--solver-workers", + "1", + *opts, + ]) == 0 ) - jobs = sorted( - (tmp_path / "s" / "source_extraction" / "silo" / "jobs").glob("*.json") - ) + jobs = sorted((tmp_path / "s" / "source_extraction" / "silo" / "jobs").glob("*.json")) for job in jobs: assert main(["silo-solve", str(job), "--solver-workers", "1"]) == 0 assert main(["silo-collect", str(table), *opts]) == 0 - assert ( - tmp_path / "s" / "source_extraction" / "experiment_summary.h5" - ).exists() + assert (tmp_path / "s" / "source_extraction" / "experiment_summary.h5").exists() capsys.readouterr() class _FakePool: """A pool whose tasks finish at a set time on a controlled clock.""" - def __init__(self, now, finish_at): + def __init__(self, now: list[float], finish_at: Sequence[float | None]) -> None: """Take the clock and each task's finish time.""" self.now, self.finish_at, self.futures = now, list(finish_at), [] - def submit(self, *args, **kwargs): - """A future; finished at once (before the next submit) when its - time is None.""" + def submit(self, *args: object, **kwargs: object) -> Future: + """Return a future; finished at once (before the next submit) when its time is None. + + Returns + ------- + Future + The task's future. + """ import concurrent.futures as cf f = cf.Future() @@ -698,26 +784,25 @@ def submit(self, *args, **kwargs): return f -def test_solve_span_is_the_last_subproblem_solved(monkeypatch): - """A trial's solve span ends when its last subproblem is done: a +def test_solve_span_is_the_last_subproblem_solved(monkeypatch: pytest.MonkeyPatch) -> None: + """A trial's solve span ends when its last subproblem is done. + + A subproblem solved while the rest are still submitted keeps its own time, a trial collected later still ends then, and a trial solved here - ends when that solve returns. Controlled clock, set completion order.""" + ends when that solve returns. Controlled clock, set completion order. + """ import types from giant_python.extraction.raster import solver as solver_mod now = [0.0] - monkeypatch.setattr( - silo, "time", types.SimpleNamespace(perf_counter=lambda: now[0]) - ) + monkeypatch.setattr(silo, "time", types.SimpleNamespace(perf_counter=lambda: now[0])) sub = types.SimpleNamespace(n_pixels=1, n_frames=1, n_sources=1) # the first task is done before the second is submitted pool = _FakePool(now, [None, 0.2]) done = silo._Done() - futures, _ = silo._submit( - [sub, sub], None, EX.solver_options(), pool, done - ) + futures, _ = silo._submit([sub, sub], None, EX.solver_options(), pool, done) assert done.times == [0.01] now[0] = 0.2 pool.futures[1].set_result(None) # the last subproblem @@ -738,9 +823,11 @@ def test_solve_span_is_the_last_subproblem_solved(monkeypatch): assert silo._solve_span(q, 0.0) == (0.7, 0.9) -def test_pool_workers_are_spawned_with_their_thread_counts(): - """Pool workers start a fresh interpreter (not a fork of this one), so - the thread variables are set before numpy loads its BLAS.""" +def test_pool_workers_are_spawned_with_their_thread_counts() -> None: + """Pool workers start a fresh interpreter (not a fork of this one). + + The thread variables are set before numpy loads its BLAS. + """ import os from giant_python.pipeline.silo_session import make_pool @@ -755,9 +842,11 @@ def test_pool_workers_are_spawned_with_their_thread_counts(): assert pool.submit(os.getenv, name).result() == "2" -def test_plan_pool_workers_let_idle_blas_threads_sleep(): - """A pool made with blas_idle sets OpenBLAS's thread timeout in its - workers (not in this process, nor in other pools).""" +def test_plan_pool_workers_let_idle_blas_threads_sleep() -> None: + """A pool made with blas_idle sets OpenBLAS's thread timeout in its workers. + + It is not set in this process, nor in other pools. + """ import os from giant_python.pipeline.silo_session import BLAS_IDLE, make_pool @@ -770,11 +859,13 @@ def test_plan_pool_workers_let_idle_blas_threads_sleep(): assert pool.submit(os.getenv, BLAS_IDLE[0]).result() == before -def test_pool_workers_report_their_blas_threads(monkeypatch): - """Every worker of a pool from make_pool starts under its thread - variables, with its BLAS at that many threads, and with blas_idle +def test_pool_workers_report_their_blas_threads(monkeypatch: pytest.MonkeyPatch) -> None: + """Every worker of a pool from make_pool starts under its thread variables. + + Its BLAS is at that many threads, and with blas_idle OpenBLAS's idle timeout; this process's environment is as before, - whether the timeout was set or not (starts 3 + 3 processes).""" + whether the timeout was set or not (starts 3 + 3 processes). + """ import os from giant_python.parallel import THREAD_VARS @@ -783,8 +874,14 @@ def test_pool_workers_report_their_blas_threads(monkeypatch): reports = [] real = silo_session.spawn_pool - def spawn(*args, **kw): - """spawn_pool, its workers' reports kept.""" + def spawn(*args: object, **kw: object) -> tuple: + """Call spawn_pool, keeping its workers' reports. + + Returns + ------- + tuple + The pool and its workers' start reports, as from spawn_pool. + """ pool, started = real(*args, **kw) reports.append(started) return pool, started @@ -808,22 +905,36 @@ def spawn(*args, **kw): assert os.environ.get(name) == before -def _env_report(name): - """This worker's value of the variable ``name``.""" +def _env_report(name: str) -> str | None: + """Return this worker's value of the variable name. + + Returns + ------- + str or None + The variable's value; None if it is not set. + """ import os return os.environ.get(name) -def _failing_init(): - """A worker initializer that fails.""" +def _failing_init() -> NoReturn: + """Fail as a worker initializer. + + Raises + ------ + RuntimeError + Always. + """ raise RuntimeError("no start") -def test_pools_started_at_once_restore_the_environment(): - """Two pools started from two threads at once each start with their - own value of a variable, and leave it unset here (starts 2 x 2 - processes).""" +def test_pools_started_at_once_restore_the_environment() -> None: + """Two pools started from two threads at once each start with their own value. + + The value is that of a variable; they leave it unset here (starts 2 x 2 + processes). + """ import os import threading @@ -833,7 +944,7 @@ def test_pools_started_at_once_restore_the_environment(): assert name not in os.environ out = {} - def start(value): + def start(value: str) -> None: """Start a pool and ask its workers for the variable.""" pool, started = spawn_pool(2, {name: value}) with pool: @@ -850,9 +961,17 @@ def start(value): assert name not in os.environ -def _all_ended(procs, seconds: float = 30.0) -> bool: - """Whether the processes end within ``seconds`` (a stopped pool's - workers end by themselves).""" +def _all_ended(procs: Sequence, seconds: float = 30.0) -> bool: + """Return whether the processes end within seconds. + + A stopped pool's + workers end by themselves. + + Returns + ------- + bool + True if no process is alive within seconds. + """ import time deadline = time.monotonic() + seconds @@ -863,23 +982,26 @@ def _all_ended(procs, seconds: float = 30.0) -> bool: return False -def _slow_init(): - """A worker initializer that takes far longer than the pool is given - (and than the test waits for the workers to end).""" +def _slow_init() -> None: + """Act as a worker initializer that takes far longer than the pool is given. + + This is also longer than the test waits for the workers to end. + """ import time time.sleep(600.0) -@pytest.mark.parametrize( - "failure", ["initializer", "interrupt", "late", "manager"] -) -def test_failed_pool_start_leaves_no_process(monkeypatch, failure): - """A pool whose start fails (a worker's initializer raises), is +@pytest.mark.parametrize("failure", ["initializer", "interrupt", "late", "manager"]) +def test_failed_pool_start_leaves_no_process(monkeypatch: pytest.MonkeyPatch, failure: str) -> None: + """A pool whose start fails leaves no worker process behind. + + The start fails when a worker's initializer raises, is interrupted, takes longer than it is given (its workers still in their - initializer) or cannot start the thread that manages it leaves no + initializer) or cannot start the thread that manages it; it leaves no worker process behind, raises the first error and leaves the - environment as it was (starts 3 processes; 1 for the thread).""" + environment as it was (starts 3 processes; 1 for the thread). + """ import concurrent.futures as cf import os @@ -889,8 +1011,19 @@ def test_failed_pool_start_leaves_no_process(monkeypatch, failure): procs = [] real_wait = cf.wait - def wait(futures, *args, **kw): - """wait; the pool's workers kept (and the start interrupted).""" + def wait(futures: Sequence[Future], *args: object, **kw: object) -> object: + """Wait; the pool's workers kept (and the start interrupted). + + Returns + ------- + object + The result of concurrent.futures.wait. + + Raises + ------ + KeyboardInterrupt + If the test interrupts the start. + """ if failure == "interrupt": real_wait(futures, timeout=60) procs.extend(mp.active_children()) @@ -900,9 +1033,16 @@ def wait(futures, *args, **kw): import multiprocessing as mp - def no_thread(self): - """The pool's managing thread cannot start (its first worker - process has been launched by then).""" + def no_thread(self: object) -> NoReturn: + """Fail to start the pool's managing thread. + + Its first worker process has been launched by then. + + Raises + ------ + RuntimeError + Always. + """ procs.extend(mp.active_children()) raise RuntimeError("can't start new thread") @@ -923,9 +1063,7 @@ def no_thread(self): with pytest.raises(want) as err: parallel.spawn_pool(3, {name: "x"}, init) if failure == "late": - assert "had not started" in str(err.value) or "did not all" in str( - err.value - ) + assert "had not started" in str(err.value) or "did not all" in str(err.value) if failure == "manager": assert "can't start new thread" in str(err.value) assert procs or failure == "initializer" @@ -933,11 +1071,19 @@ def no_thread(self): assert name not in os.environ -def _first_only_init(lock, how): - """A worker initializer that only the first worker passes (``wait``) - or stays in, deaf to SIGTERM (``deaf``); the others fail once the - first has had time to get there: they raise (``wait``) or end - abruptly (``deaf``).""" +def _first_only_init(lock: Lock, how: str) -> None: + """Act as a worker initializer that only the first worker passes. + + The first worker passes (wait) + or stays in, deaf to SIGTERM (deaf); the others fail once the + first has had time to get there: they raise (wait) or end + abruptly (deaf). + + Raises + ------ + RuntimeError + In every worker but the first, when how is wait. + """ import os import signal import time @@ -954,13 +1100,17 @@ def _first_only_init(lock, how): @pytest.mark.parametrize("how", ["wait", "deaf"]) -def test_failed_start_with_a_worker_still_there_ends(monkeypatch, how): - """One worker waits at the start barrier while another's initializer - fails, or stays in its initializer, ignoring SIGTERM, while another +def test_failed_start_with_a_worker_still_there_ends( + monkeypatch: pytest.MonkeyPatch, how: str +) -> None: + """One worker waits at the start barrier while another's initializer fails. + + Or one stays in its initializer, ignoring SIGTERM, while another ends abruptly: the start raises within its time (it waits neither for the worker at the barrier, which the pool has ended, nor for the pool to end the deaf one) and no process is left (starts 3 processes: - with a third worker the pool notices the one that ended).""" + with a third worker the pool notices the one that ended). + """ import multiprocessing as mp import os import time @@ -981,9 +1131,12 @@ def test_failed_start_with_a_worker_still_there_ends(monkeypatch, how): @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") -def test_forked_child_gets_a_free_start_lock(): - """A child forked while a pool is starting (the start lock held by - another thread) has a start lock of its own, not held.""" +def test_forked_child_gets_a_free_start_lock() -> None: + """A child forked while a pool is starting has a start lock of its own, not held. + + The start lock is held by + another thread in the parent. + """ from giant_python import parallel with parallel._START_LOCK: @@ -996,9 +1149,12 @@ def test_forked_child_gets_a_free_start_lock(): @pytest.mark.parametrize("bad", [0, -1, 2.5, True]) -def test_pool_size_must_be_a_positive_integer(bad): - """A pool of no, or not a whole number of, workers is refused before - anything starts.""" +def test_pool_size_must_be_a_positive_integer(bad: float) -> None: + """A pool of no, or not a whole number of, workers is refused. + + This happens before + anything starts. + """ from giant_python import parallel from giant_python.pipeline import silo_session @@ -1008,18 +1164,26 @@ def test_pool_size_must_be_a_positive_integer(bad): silo_session.make_pool(bad, 1) -def test_pool_starts_without_a_blas_report(monkeypatch): - """A worker whose BLAS thread counts cannot be read reports None and - the start goes on; a count threadpoolctl gives as None is "cannot be - told".""" +def test_pool_starts_without_a_blas_report(monkeypatch: pytest.MonkeyPatch) -> None: + """A worker whose BLAS thread counts cannot be read reports None. + + The start goes on; a count threadpoolctl gives as None is "cannot be + told". + """ import sys import threading import types from giant_python import parallel - def broken(): - """A probe that fails.""" + def broken() -> NoReturn: + """Fail as a probe. + + Raises + ------ + TypeError + Always. + """ raise TypeError("no count") monkeypatch.setattr(parallel, "_START_BARRIER", (threading.Barrier(1), 1)) @@ -1034,18 +1198,26 @@ def broken(): assert parallel.blas_threads() is None -def test_run_jobs_hands_its_pool_the_idle_setting(monkeypatch): - """run_jobs starts its pool with as many workers as there are jobs at - most, the threads and ``blas_idle`` it was given; one job or one - worker runs here, without a pool.""" +def test_run_jobs_hands_its_pool_the_idle_setting(monkeypatch: pytest.MonkeyPatch) -> None: + """run_jobs starts its pool with as many workers as there are jobs at most. + + It uses the threads and blas_idle it was given; one job or one + worker runs here, without a pool. + """ import concurrent.futures as cf from giant_python.pipeline import silo_session calls = [] - def make_pool(workers, threads, blas_idle=False): - """A pool of threads, what it was asked for recorded.""" + def make_pool(workers: int, threads: int, blas_idle: bool = False) -> cf.ThreadPoolExecutor: + """Make a pool of threads, what it was asked for recorded. + + Returns + ------- + cf.ThreadPoolExecutor + A thread pool of workers threads. + """ calls.append((workers, threads, blas_idle)) return cf.ThreadPoolExecutor(workers) @@ -1062,8 +1234,14 @@ def make_pool(workers, threads, blas_idle=False): class _Here: """An executor that runs each task here, at once.""" - def submit(self, fn, *args): - """Run ``fn`` now.""" + def submit(self, fn: Callable, *args: object) -> Future: + """Run fn now. + + Returns + ------- + Future + A finished future holding fn's result or its exception. + """ import concurrent.futures as cf f = cf.Future() @@ -1073,19 +1251,31 @@ def submit(self, fn, *args): f.set_exception(exc) return f - def shutdown(self, *args, **kw): - """Nothing to stop.""" + def shutdown(self, *args: object, **kw: object) -> None: + """Do nothing, as there is nothing to stop.""" -def _record_refits(monkeypatch): - """The workers each plan's patchwise alignment was given.""" +def _record_refits(monkeypatch: pytest.MonkeyPatch) -> list: + """Record the workers each plan's patchwise alignment was given. + + Returns + ------- + list + The workers argument of each patchwise alignment, appended as they run. + """ from giant_python.extraction.raster import plan as plan_mod refits = [] real = plan_mod.align_trials_patchwise - def align(*args, **kw): - """The alignment, its workers recorded.""" + def align(*args: object, **kw: object) -> object: + """Run the alignment, its workers recorded. + + Returns + ------- + object + The result of the patchwise alignment. + """ refits.append(kw.get("workers", 1)) return real(*args, **kw) @@ -1094,10 +1284,14 @@ def align(*args, **kw): @pytest.mark.parametrize("workers", [1, 3]) -def test_plan_stage_processes(tmp_path, fake, monkeypatch, workers): - """silo-plan: with one worker every path is planned and refit here; - with more, the plans' pool lets idle BLAS threads sleep and each - plan's patchwise alignment refits in up to 8 processes.""" +def test_plan_stage_processes( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch, workers: int +) -> None: + """silo-plan: with one worker every path is planned and refit here. + + With more, the plans' pool lets idle BLAS threads sleep and each + plan's patchwise alignment refits in up to 8 processes. + """ import os s = SiloSession.open(make_session(tmp_path)) @@ -1105,8 +1299,16 @@ def test_plan_stage_processes(tmp_path, fake, monkeypatch, workers): calls = [] real = silo.run_jobs - def run_jobs(func, jobs, n, threads, blas_idle=False): - """run_jobs, recorded and run here.""" + def run_jobs( + func: Callable, jobs: Sequence, n: int, threads: int, blas_idle: bool = False + ) -> list: + """Run run_jobs, recorded and run here. + + Returns + ------- + list + The results of the jobs, as from silo.run_jobs. + """ calls.append((n, blas_idle)) return real(func, jobs, 1, threads) @@ -1132,17 +1334,27 @@ def run_jobs(func, jobs, n, threads, blas_idle=False): @pytest.mark.parametrize("workers", [1, 2]) -def test_one_call_run_plan_processes(tmp_path, fake, monkeypatch, workers): - """giant silo: with one worker the paths are planned and refit here, - without pools; with more, the plans' pool lets idle BLAS threads sleep +def test_one_call_run_plan_processes( + tmp_path: Path, fake: None, monkeypatch: pytest.MonkeyPatch, workers: int +) -> None: + """``giant silo``: with one worker the paths are planned and refit here, without pools. + + With more, the plans' pool lets idle BLAS threads sleep (the localization pool does not) and each plan's patchwise alignment - refits in up to 8 processes.""" + refits in up to 8 processes. + """ import os pools = [] - def make_pool(n, threads, blas_idle=False): - """A pool that runs here, recorded.""" + def make_pool(n: int, threads: int, blas_idle: bool = False) -> _Here: + """Make a pool that runs here, recorded. + + Returns + ------- + _Here + An executor that runs each task here. + """ pools.append((n, threads, blas_idle)) return _Here() @@ -1151,9 +1363,7 @@ def make_pool(n, threads, blas_idle=False): s = SiloSession.open(make_session(tmp_path)) ex = SiloExecution(workers=workers, solver_workers=1, solver_threads=1) timer = {} - done = silo._ready_paths( - s, PARAMS, ex, _seeds(s, tmp_path), None, timer, None, [], [] - ) + done = silo._ready_paths(s, PARAMS, ex, _seeds(s, tmp_path), None, timer, None, [], []) assert sorted(done) == list(range(N_PATHS)) threads = max(1, (os.cpu_count() or 1) // N_PATHS) if workers == 1: diff --git a/tests/raster/test_raster_solver.py b/tests/raster/test_raster_solver.py index 0039c573..87ff52e3 100644 --- a/tests/raster/test_raster_solver.py +++ b/tests/raster/test_raster_solver.py @@ -193,7 +193,7 @@ def test_batches_count_the_footprint_filter( The filter arrays are dense, pixels x pixels. """ - import giant_python.extraction.raster.solver as solver + from giant_python.extraction.raster import solver sub, _ = fixture sizes = [] @@ -453,10 +453,10 @@ def test_assemble_results() -> None: assemble_results([replace(subs[0], pixels=None)], results[:1], 6, 5, 25.0) # indices that would put results in the wrong place are refused for bad, message in ( - (dict(pixels=np.array([0, 1, 6])), "pixels indices must lie"), - (dict(sources=np.array([5])), "sources indices must lie"), - (dict(pixels=np.array([0, 1])), "3 pixels and 2 indices for"), - (dict(pixels=np.array([0, 1, 1])), "pixels indices repeat"), + ({"pixels": np.array([0, 1, 6])}, "pixels indices must lie"), + ({"sources": np.array([5])}, "sources indices must lie"), + ({"pixels": np.array([0, 1])}, "3 pixels and 2 indices for"), + ({"pixels": np.array([0, 1, 1])}, "pixels indices repeat"), ): with pytest.raises(ValueError, match=message): assemble_results([replace(subs[0], **bad)], results[:1], 6, 5, 25.0) diff --git a/tests/raster/test_raster_solver_baseline_modes.py b/tests/raster/test_raster_solver_baseline_modes.py index 40a9d41a..883f6bec 100644 --- a/tests/raster/test_raster_solver_baseline_modes.py +++ b/tests/raster/test_raster_solver_baseline_modes.py @@ -288,7 +288,7 @@ def test_gain_shared_without_outside_pixels_is_gain() -> None: bb, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) assert info["n_outside"] == 0 np.testing.assert_array_equal(info["shared"], 1.0) - b1, info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) + b1, _info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) np.testing.assert_array_equal(bb, b1) assert rows.size == cols.size == sub.n_pixels @@ -451,7 +451,7 @@ def test_outside_halves_are_apart() -> None: sel = np.ones((5, 12), bool) outside = np.ones(60, bool) a, b = outside_halves(sel, outside) - rows, cols = np.nonzero(sel.T)[::-1] + _rows, cols = np.nonzero(sel.T)[::-1] assert cols[a].max() < cols[b].min() - 2 assert a.sum() > 15 and b.sum() > 15 @@ -483,7 +483,7 @@ def test_halves_do_not_shrink_noiseless_factors() -> None: y = q * np.array([0.8, 1.2])[None] halves = (np.arange(20) < 8, np.arange(20) >= 12) for finv in (np.ones_like(q), np.ones_like(q) * np.array([1.0, 4.0])): - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) + c, _rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) np.testing.assert_allclose(c, [0.8, 1.2]) diff --git a/tests/raster/test_raster_solver_fits.py b/tests/raster/test_raster_solver_fits.py index 4973f439..b43cb0f8 100644 --- a/tests/raster/test_raster_solver_fits.py +++ b/tests/raster/test_raster_solver_fits.py @@ -4,6 +4,7 @@ fits against GIAnT-MATLAB's from the same inputs. """ +import itertools from pathlib import Path from typing import Any @@ -225,7 +226,7 @@ def test_activity_fit_reaches_scipy_optimum() -> None: assert float(info.optimality[0]) < 1e-5 assert float((s == 0).double().mean()) > 0.4 and float(s.min()) == 0 losses = [float(f[0]) for f in info.history] - assert all(b2 <= a2 for a2, b2 in zip(losses, losses[1:])) + assert all(b2 <= a2 for a2, b2 in itertools.pairwise(losses)) problem = sf.ActivityProblem(z, h, b, k, w, 0.9) @@ -248,7 +249,7 @@ def fun(x: np.ndarray) -> tuple[float, np.ndarray]: jac=True, method="L-BFGS-B", bounds=[(0, None)] * s.numel(), - options=dict(maxiter=20000, maxfun=50000, ftol=1e-15, gtol=1e-9), + options={"maxiter": 20000, "maxfun": 50000, "ftol": 1e-15, "gtol": 1e-9}, ) assert float(info.loss[0]) <= ref.fun + 1e-9 * abs(ref.fun) np.testing.assert_allclose(s.numpy().ravel(), ref.x, atol=2e-2) @@ -300,10 +301,10 @@ def test_iteration_cap_and_free_entries() -> None: z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) start = torch.full_like(s_true, 5.0) problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) + _s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) assert not bool(info.converged[0]) and int(info.iterations[0]) == 1 assert float(info.loss[0]) < float(problem.value(start)[0]) - full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) + _full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) assert float(done.loss[0]) < float(info.loss[0]) free = s_true > 0 s2, info2 = sf.fit_activity(z, h, b, k, w, 0.0, start, free=free) @@ -341,7 +342,7 @@ def test_footprint_fit_stays_on_its_support() -> None: They reach a lower loss than the start. """ - z, h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) + z, _h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) x = sf.TimeKernel(k).conv(s) g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 valid = torch.zeros((1, 12, 2), dtype=torch.bool) @@ -427,7 +428,9 @@ def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] x_thr = _t(m["it1"]["X_thr"]) - hs, info = sf.fit_footprints(m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid) + _hs, info = sf.fit_footprints( + m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid + ) assert bool(info.converged[0]) assert float(info.loss[0]) < m["it1"]["loss_H"] * (1 - 1e-5) @@ -450,7 +453,7 @@ def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: x, x_matlab = kern.conv(s), kern.conv(_t(m["debias"]["S_out"])) assert float((x - x_matlab).norm() / x_matlab.norm()) < 0.02 - s2, info = sf.fit_activity( + _s2, info = sf.fit_activity( m["z2"], _t(m["out"]["H"]), m["b2"], diff --git a/tests/raster/test_raster_solver_fits_bitwise.py b/tests/raster/test_raster_solver_fits_bitwise.py index d6db2672..eaf34c9f 100644 --- a/tests/raster/test_raster_solver_fits_bitwise.py +++ b/tests/raster/test_raster_solver_fits_bitwise.py @@ -22,8 +22,15 @@ DT = torch.float64 -def _same(a, b) -> bool: - """Equal to the last bit (the sign of zeros and NaNs included).""" +def _same(a: torch.Tensor | None, b: torch.Tensor | None) -> bool: + """Equal to the last bit (the sign of zeros and NaNs included). + + Returns + ------- + bool + True if both are None, or both tensors have the same shape, dtype + and bytes. + """ if a is None or b is None: return a is None and b is None if a.shape != b.shape or a.dtype != b.dtype: @@ -33,11 +40,23 @@ def _same(a, b) -> bool: return bool(torch.equal(ai, bi)) -def _reference_geometric_sum(x, a, taps, back): - """``_geometric_sum`` as it was: a new tensor for every addition.""" +def _reference_geometric_sum(x: torch.Tensor, a: float, taps: int, back: bool) -> torch.Tensor: + """``_geometric_sum`` as it was: a new tensor for every addition. - def shifted_add(y, z, m, c): - """y + c * (z shifted by m frames, zero-filled).""" + Returns + ------- + torch.Tensor + The geometric sum of x. + """ + + 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, a new tensor (y itself if m reaches past it). + """ if m >= y.shape[-1]: return y out = torch.empty_like(y) @@ -59,8 +78,24 @@ def shifted_add(y, z, m, c): return y -def _reference_loss(z, t, w, s0=None, order=2): - """``variance_loss`` as the fits evaluated it, new arrays each time.""" +def _reference_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]: + """``variance_loss`` as the fits evaluated it, new arrays each time. + + Returns + ------- + f : torch.Tensor + The loss. + g : torch.Tensor or None + Its gradient (None for order 0). + h : torch.Tensor or None + Its Hessian diagonal (None for order below 2). + """ e = z - t if s0 is None: s = t + 1 @@ -80,8 +115,21 @@ def _reference_loss(z, t, w, s0=None, order=2): return f, g, (2 * ws if order == 2 else None) -def _data(seed, batch=1, n_px=37, n_src=3, n_t=1001, dtype=DT): - """Random data, model and weights, with negative zeros among them.""" +def _data( + seed: int, + batch: int = 1, + n_px: int = 37, + n_src: int = 3, + n_t: int = 1001, + dtype: torch.dtype = DT, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Random data, model and weights, with negative zeros among them. + + Returns + ------- + z, h, b, w, s : torch.Tensor + The data, footprints, baseline, weights and events. + """ rng = np.random.default_rng(seed) z = torch.as_tensor(rng.poisson(4.0, (batch, n_px, n_t)), dtype=dtype) h = torch.as_tensor(rng.random((batch, n_px, n_src)) ** 3, dtype=dtype) @@ -95,11 +143,13 @@ def _data(seed, batch=1, n_px=37, n_src=3, n_t=1001, dtype=DT): @pytest.mark.parametrize("taps", [1, 2, 3, 7, 8, 64, 85, 200]) @pytest.mark.parametrize("n_t", [1, 5, 64, 1003]) @pytest.mark.parametrize("back", [True, False]) -def test_shifted_additions_into_kept_tensors(taps, n_t, back): - """Two kept tensors give the sums that a new tensor per addition gave - (and _geometric_sum, still used with autograd, is unchanged), +def test_shifted_additions_into_kept_tensors(taps: int, n_t: int, back: bool) -> None: + """Two kept tensors give the sums that a new tensor per addition gave. + + (And _geometric_sum, still used with autograd, is unchanged), for kernels shorter and longer than the trial, and the second use of - the same tensors does not depend on the first.""" + the same tensors does not depend on the first. + """ rng = np.random.default_rng(taps * 7 + n_t) kept = None for _ in range(2): @@ -113,9 +163,12 @@ def test_shifted_additions_into_kept_tensors(taps, n_t, back): @pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) -def test_time_kernel_returns_new_tensors(tau): - """conv and conv_adj equal the reference to the last bit, and a result - is not changed by the next call (it is not one of the kept tensors).""" +def test_time_kernel_returns_new_tensors(tau: float) -> None: + """``conv`` and conv_adj equal the reference to the last bit. + + A result is not changed by the next call (it is not one of the kept + tensors). + """ k = torch.as_tensor(temporal_kernel(tau), dtype=DT) kern = sf.TimeKernel(k) assert kern.decay is not None @@ -132,7 +185,7 @@ def test_time_kernel_returns_new_tensors(tau): @pytest.mark.parametrize("back", [True, False]) -def test_overlapping_time_kernel_calls(monkeypatch, back): +def test_overlapping_time_kernel_calls(monkeypatch: pytest.MonkeyPatch, back: bool) -> None: """A second call cannot overwrite the first call's unscaled sum.""" k = torch.tensor([0, 0, 1, 0.5, 0.25], dtype=DT) kernel = sf.TimeKernel(k) @@ -143,16 +196,28 @@ def test_overlapping_time_kernel_calls(monkeypatch, back): ready, resume = Event(), Event() kept_call = sf._KeptSum.__call__ - def pause_before_scaling(kept, x): - """Pause the first call after it has written its shared scratch.""" + def pause_before_scaling(kept: sf._KeptSum, x: torch.Tensor) -> torch.Tensor: + """Pause the first call after it has written its shared scratch. + + Returns + ------- + torch.Tensor + The unscaled sum, as the kept sum returns it. + """ y = kept_call(kept, x) if x is x1: ready.set() assert resume.wait(5) return y - def call_second(): - """Run the second convolution while the first is paused.""" + def call_second() -> torch.Tensor: + """Run the second convolution while the first is paused. + + Returns + ------- + torch.Tensor + The second convolution's result. + """ assert ready.wait(5) try: return conv(x2) @@ -167,10 +232,12 @@ def call_second(): @pytest.mark.parametrize("fixed", [False, True]) -def test_loss_into_buffers_equals_new_arrays(fixed): - """_LossWork gives variance_loss's value and derivatives to the last - bit, evaluation after evaluation (its buffers reused).""" - z, h, b, w, s = _data(1) +def test_loss_into_buffers_equals_new_arrays(fixed: bool) -> None: + """_LossWork gives variance_loss's value and derivatives to the last bit. + + So it does evaluation after evaluation (its buffers reused). + """ + z, _h, b, w, _s = _data(1) rng = np.random.default_rng(2) s0 = (b + 1.5) if fixed else None work = sf._LossWork(w, s0) @@ -179,16 +246,25 @@ def test_loss_into_buffers_equals_new_arrays(fixed): t[0, 0, :5] = -0.0 for order in (0, 1, 2): ref = _reference_loss(z, t, w, s0, order) - assert all( - _same(a, r) - for a, r in zip(sf.variance_loss(z, t, w, s0, order), ref) - ) + assert all(_same(a, r) for a, r in zip(sf.variance_loss(z, t, w, s0, order), ref)) got = work.loss(z, t.clone(), order) assert all(_same(a, r) for a, r in zip(got, ref)), (step, order) -def _activity_pair(fixed, seed=4): - """The same activity problem twice: through _LossWork and as before.""" +def _activity_pair( + fixed: bool, seed: int = 4 +) -> tuple[sf.ActivityProblem, sf.ActivityProblem, torch.Tensor]: + """Return the same activity problem twice: through _LossWork and as before. + + Returns + ------- + new : sf.ActivityProblem + The problem evaluated through _LossWork. + old : sf.ActivityProblem + The same problem evaluated as before. + s : torch.Tensor + The true events the problem was made from. + """ z, h, b, w, s = _data(seed) k = torch.as_tensor(temporal_kernel(4.8), dtype=DT) s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None @@ -200,9 +276,11 @@ def _activity_pair(fixed, seed=4): @pytest.mark.parametrize("fixed", [False, True]) -def test_activity_problem_evaluations_unchanged(fixed): - """Loss, gradient, Hessian products and diagonal of the activity - problem, at successive points, equal the form before to the last bit.""" +def test_activity_problem_evaluations_unchanged(fixed: bool) -> None: + """Loss, gradient, Hessian products and diagonal of the activity problem are unchanged. + + At successive points, they equal the form before to the last bit. + """ new, old, s = _activity_pair(fixed) rng = np.random.default_rng(5) for step in range(3): @@ -217,9 +295,12 @@ def test_activity_problem_evaluations_unchanged(fixed): @pytest.mark.parametrize("fixed", [False, True]) -def test_footprint_problem_evaluations_unchanged(fixed): - """The same for the footprint problem; with the variance fixed its - curvature product is formed once and kept, with the same values.""" +def test_footprint_problem_evaluations_unchanged(fixed: bool) -> None: + """The same for the footprint problem. + + With the variance fixed its curvature product is formed once and kept, + with the same values. + """ z, h, b, w, s = _data(6) k = torch.as_tensor(temporal_kernel(4.8), dtype=DT) x = sf.TimeKernel(k).conv(s) @@ -250,8 +331,22 @@ def test_footprint_problem_evaluations_unchanged(fixed): assert _same(new.hess_mult(v), old.hess_mult(v)) -def _fits(fixed, dtype, batch): - """Run an activity fit and a footprint fit, keeping their histories.""" +def _fits( + fixed: bool, dtype: torch.dtype, batch: int +) -> tuple[torch.Tensor, torch.Tensor, sf.FitInfo, sf.FitInfo]: + """Run an activity fit and a footprint fit, keeping their histories. + + Returns + ------- + s : torch.Tensor + The fitted events. + hs : torch.Tensor + The fitted super-resolved footprints. + info_s : sf.FitInfo + How the activity fit ended. + info_h : sf.FitInfo + How the footprint fit ended. + """ z, h, b, w, s_true = _data(8, batch, n_px=21, n_t=400, dtype=dtype) k = torch.as_tensor(temporal_kernel(4.8), dtype=dtype) kern = sf.TimeKernel(k) @@ -261,26 +356,28 @@ def _fits(fixed, dtype, batch): x = kern.conv(s) valid = h > 0.05 g = torch.eye(h.shape[1], dtype=dtype)[None] * 0.7 + 0.3 / h.shape[1] - hs, info_h = sf.fit_footprints( - z, x, b, g, w, h * valid, valid, s0=s0, history=True - ) + hs, info_h = sf.fit_footprints(z, x, b, g, w, h * valid, valid, s0=s0, history=True) return s, hs, info_s, info_h -def _check_whole_fits(monkeypatch, fixed, dtype, batch): +def _check_whole_fits( + monkeypatch: pytest.MonkeyPatch, fixed: bool, dtype: torch.dtype, batch: int +) -> None: """Compare the fitted tensors and diagnostics with the allocating code.""" - def allocating_conv(kernel, x, back): - """The pre-PR convolution, with independent shifted additions.""" - return kernel.gain * _reference_geometric_sum( - x, kernel.decay, kernel.lag + 1, back - ) + def allocating_conv(kernel: sf.TimeKernel, x: torch.Tensor, back: bool) -> torch.Tensor: + """Return the pre-PR convolution, with independent shifted additions. + + Returns + ------- + torch.Tensor + gain times the geometric sum of x. + """ + return kernel.gain * _reference_geometric_sum(x, kernel.decay, kernel.lag + 1, back) s1, hs1, a1, b1 = _fits(fixed, dtype, batch) monkeypatch.setattr(sf, "_plain", lambda *a: False) - monkeypatch.setattr( - sf.TimeKernel, "_convolve_exponential", allocating_conv - ) + monkeypatch.setattr(sf.TimeKernel, "_convolve_exponential", allocating_conv) s0, hs0, a0, b0 = _fits(fixed, dtype, batch) assert _same(s1, s0) and _same(hs1, hs0) for i1, i0 in ((a1, a0), (b1, b0)): @@ -299,18 +396,18 @@ def allocating_conv(kernel, x, back): @pytest.mark.parametrize("fixed", [False, True]) -def test_whole_fits_unchanged(monkeypatch, fixed): +def test_whole_fits_unchanged(monkeypatch: pytest.MonkeyPatch, fixed: bool) -> None: """Double-precision fits and diagnostics match the allocating fits.""" _check_whole_fits(monkeypatch, fixed, torch.float64, 1) @pytest.mark.parametrize("fixed", [False, True]) -def test_batched_float32_fits_unchanged(monkeypatch, fixed): +def test_batched_float32_fits_unchanged(monkeypatch: pytest.MonkeyPatch, fixed: bool) -> None: """Batched single-precision fits and diagnostics match bit for bit.""" _check_whole_fits(monkeypatch, fixed, torch.float32, 2) -def test_autograd_still_follows_the_loss(): +def test_autograd_still_follows_the_loss() -> None: """Arrays that need gradients take the old path (no buffers).""" z, h, b, w, s = _data(9, n_px=6, n_t=30) k = torch.as_tensor(temporal_kernel(3.0), dtype=DT) @@ -322,10 +419,9 @@ def test_autograd_still_follows_the_loss(): @pytest.mark.filterwarnings( - "ignore:Converting a tensor with requires_grad=True to a scalar" - ":UserWarning" + "ignore:Converting a tensor with requires_grad=True to a scalar:UserWarning" ) -def test_activity_loss_differentiates_temporal_kernel(): +def test_activity_loss_differentiates_temporal_kernel() -> None: """The loss is differentiable in a non-exponential temporal kernel.""" z, h, b, w, s = _data(11, n_px=6, n_t=30) k = torch.tensor([0, 0, 0.6, 0.1, 0.3], dtype=DT, requires_grad=True) @@ -337,7 +433,7 @@ def test_activity_loss_differentiates_temporal_kernel(): @pytest.mark.parametrize("mixed", [True, False]) -def test_fit_losses_respect_promotion_and_autocast(mixed): +def test_fit_losses_respect_promotion_and_autocast(mixed: bool) -> None: """Both losses preserve promotion, and fixed curvature follows autocast.""" z, h, b, w, s = _data(12, n_px=6, n_t=32, dtype=torch.float32) if mixed: @@ -359,7 +455,7 @@ def test_fit_losses_respect_promotion_and_autocast(mixed): assert _same(footprint.p, c @ footprint.xx) -def test_fits_and_kernel_leave_inference_mode(): +def test_fits_and_kernel_leave_inference_mode() -> None: """Warming scratch in inference mode permits a subsequent ordinary call.""" z, h, b, w, s = _data(13, n_px=6, n_t=32) k = torch.tensor([0, 0, 1, 0.5, 0.25], dtype=DT) @@ -378,9 +474,11 @@ def test_fits_and_kernel_leave_inference_mode(): assert _same(run(arg), expected) -def test_wls_blocks_in_threads_unchanged(monkeypatch): - """The noise estimate's per-frame WLS blocks, run in threads, give the - very arrays that one block after another gives.""" +def test_wls_blocks_in_threads_unchanged(monkeypatch: pytest.MonkeyPatch) -> None: + """The noise estimate's per-frame WLS blocks, run in threads, give the same arrays. + + They are the very arrays that one block after another gives. + """ rng = np.random.default_rng(10) n_px, n_src, n_f = 40, 3, 1100 h = rng.random((n_px, n_src)) ** 3 @@ -399,7 +497,7 @@ def test_wls_blocks_in_threads_unchanged(monkeypatch): @pytest.mark.filterwarnings("error::RuntimeWarning") -def test_wls_workers_inherit_numpy_error_settings(monkeypatch): +def test_wls_workers_inherit_numpy_error_settings(monkeypatch: pytest.MonkeyPatch) -> None: """Projected noise suppresses the same divide warnings in either path.""" y = np.vstack((np.full(32, -1e-200), np.linspace(-1, -2, 32))) args = (y, np.ones_like(y), np.zeros_like(y), np.ones((2, 1))) diff --git a/tests/raster/test_raster_solver_setup.py b/tests/raster/test_raster_solver_setup.py index 4f2c5b2f..82305ef7 100644 --- a/tests/raster/test_raster_solver_setup.py +++ b/tests/raster/test_raster_solver_setup.py @@ -168,19 +168,19 @@ def test_subproblem_checks_its_arrays() -> None: def _write_matlab_params(g: h5py.Group, params: SolverParams, **extra: np.ndarray) -> None: """Write a MATLAB params struct as a v7.3 file holds it.""" - fields = dict( - analyzeHz=params.analyze_hz, - tau_s=params.tau_s, - tau_full=params.tau_frames, - tau2_s=params.tau2_s, - sigma_px=params.sigma_px, - selRadius=params.sel_radius, - baselineWindow_Glu_s=params.baseline_window_s, - denoiseWindow_s=params.denoise_window_s, - minBaseline=params.min_baseline, - nmfIter=params.nmf_iter, - phi=params.phi, - ) + fields = { + "analyzeHz": params.analyze_hz, + "tau_s": params.tau_s, + "tau_full": params.tau_frames, + "tau2_s": params.tau2_s, + "sigma_px": params.sigma_px, + "selRadius": params.sel_radius, + "baselineWindow_Glu_s": params.baseline_window_s, + "denoiseWindow_s": params.denoise_window_s, + "minBaseline": params.min_baseline, + "nmfIter": params.nmf_iter, + "phi": params.phi, + } fields["lambda"] = params.lam for name, v in fields.items(): g.create_dataset(name, data=np.array([[float(v)]])) diff --git a/tests/raster/test_raster_spots.py b/tests/raster/test_raster_spots.py index 2ef22609..591348f4 100644 --- a/tests/raster/test_raster_spots.py +++ b/tests/raster/test_raster_spots.py @@ -1,8 +1,12 @@ -"""The spot annotation (GIAnT-Python#51 follow-up): spots of linked -sources, their tests and labels, and the annotation collect writes.""" +"""The spot annotation (GIAnT-Python#51 follow-up). + +Spots of linked sources, their tests and labels, and the annotation collect writes. +""" import json import warnings +from collections.abc import Sequence +from pathlib import Path import h5py import numpy as np @@ -24,11 +28,9 @@ ) -def test_link_groups(): +def test_link_groups() -> None: """Single linkage within link_px; sources without a position alone.""" - rc = np.array( - [[0, 0], [0, 2], [0, 4.2], [10, 10], [np.nan, np.nan], [30, 30]] - ) + rc = np.array([[0, 0], [0, 2], [0, 4.2], [10, 10], [np.nan, np.nan], [30, 30]]) lab = sp.link_groups(rc, 2.5) assert lab[0] == lab[1] == lab[2] # a chain links assert len({lab[0], lab[3], lab[4], lab[5]}) == 4 @@ -36,7 +38,7 @@ def test_link_groups(): assert sp.link_groups(np.zeros((0, 2)), 2.5).size == 0 -def test_event_train_corr(): +def test_event_train_corr() -> None: """Shared events correlate; independent ones do not; one train: NaN.""" rng = np.random.default_rng(0) a = (rng.random(5000) < 0.01).astype(float) @@ -46,10 +48,42 @@ def test_event_train_corr(): assert np.isnan(sp.event_train_corr(a[None])) -def _movie(pos, n=600, rate=0.03, amp=40.0, noise=2.0, seed=1): - """A 15 x 15 window: Gaussian events (sigma 1.4) at positions ``pos`` - (one drawn per event), white noise; returns x (frames, pixels), rows, - cols and the event frames.""" +def _movie( + pos: Sequence[tuple[float, float]], + n: int = 600, + rate: float = 0.03, + amp: float = 40.0, + noise: float = 2.0, + seed: int = 1, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Build a 15 x 15 window of Gaussian events and white noise. + + The events (sigma 1.4) are at positions pos (one drawn per event). + + Parameters + ---------- + pos : sequence of (float, float) + Positions (row, col) the events are drawn from. + n : int + Number of frames. + rate : float + Chance of an event per frame. + amp : float + Amplitude of an event. + noise : float + Standard deviation of the white noise. + seed : int + Seed of the random generator. + + Returns + ------- + x : np.ndarray + (frames, pixels) movie. + rr, cc : np.ndarray + Row and column of each pixel. + frames : np.ndarray + The event frames. + """ rng = np.random.default_rng(seed) rr, cc = np.meshgrid(np.arange(15.0), np.arange(15.0), indexing="ij") rr, cc = rr.ravel(), cc.ravel() @@ -65,9 +99,11 @@ def _movie(pos, n=600, rate=0.03, amp=40.0, noise=2.0, seed=1): return x, rr, cc, frames -def test_localize_events_finds_and_places_events(): - """Strong events are found at their frames and placed within a fraction - of a pixel; weak noise yields none.""" +def test_localize_events_finds_and_places_events() -> None: + """Strong events are found at their frames and placed within a fraction of a pixel. + + Weak noise yields none. + """ x, rr, cc, frames = _movie([(7.3, 6.6)]) ev = sp.localize_events(x, rr, cc, (7.0, 7.0), 4.0, sp.SpotSettings()) assert ev["frame"].size >= 0.9 * frames.size @@ -79,7 +115,7 @@ def test_localize_events_finds_and_places_events(): assert none["frame"].size <= 2 -def test_mixture_fit_counts_clusters(): +def test_mixture_fit_counts_clusters() -> None: """Two clusters 3 px apart give K = 2; one cluster K = 1.""" rng = np.random.default_rng(2) n = 80 @@ -96,7 +132,7 @@ def test_mixture_fit_counts_clusters(): assert np.sort(best.means[:, 1]) == pytest.approx([3.5, 6.5], abs=0.4) -def test_separation_power(): +def test_separation_power() -> None: """Points far apart are always resolved; one point never is.""" n = 60 S = sp.error_cov(np.full(n, 0.2), np.full(n, 0.2)) @@ -106,18 +142,18 @@ def test_separation_power(): assert np.isnan(sp.separation_power([[5, 5]], S, 0.0, (5, 5))) -def test_event_test_and_labels(): +def test_event_test_and_labels() -> None: """The event test on canvas positions, and the labels' precedence.""" st = sp.SpotSettings(n_sim=6) rng = np.random.default_rng(3) n = 60 src = np.array([[10.0, 9.0], [10.0, 11.0]]) - ev = dict( - r=np.r_[rng.normal(10, 0.3, n), 50.0], # one event far away: left out - c=np.r_[rng.normal(9, 0.3, n // 2), rng.normal(11, 0.3, n // 2), 50.0], - se_r=np.full(n + 1, 0.15), - se_c=np.full(n + 1, 0.15), - ) + ev = { + "r": np.r_[rng.normal(10, 0.3, n), 50.0], # one event far away: left out + "c": np.r_[rng.normal(9, 0.3, n // 2), rng.normal(11, 0.3, n // 2), 50.0], + "se_r": np.full(n + 1, 0.15), + "se_c": np.full(n + 1, 0.15), + } t = sp.event_test(ev, src, st) assert t["n_events"] == n and t["K"] == 2 assert sp.spot_label(2, 0.05, t, st) == "close_pair" @@ -126,19 +162,20 @@ def test_event_test_and_labels(): assert sp.spot_label(2, 0.05, few, st) == "undecided" assert sp.spot_label(2, 0.5, few, st) == "merge" assert sp.spot_label(1, 0.9, t, st) == "single" - compact = dict(K=1, cloud_major=0.3, power=0.1) + compact = {"K": 1, "cloud_major": 0.3, "power": 0.1} assert sp.spot_label(2, 0.0, compact, st) == "merge" - wide = dict(K=1, cloud_major=0.8, power=0.9) + wide = {"K": 1, "cloud_major": 0.8, "power": 0.9} assert sp.spot_label(2, 0.0, wide, st) == "continuum" assert sp.spot_label(2, 0.0, dict(wide, power=0.5), st) == "undecided" -def test_summary_warp_matches_the_plan(): - """The maps a summary records give the plan's warp: rigid, affine and - patchwise (its displacement field sampled on the canvas).""" - a = np.array( - [[[1.0, 0, 0.5], [0, 1, -1.0]], [[1.0, 0.02, 0], [0, 0.98, 2]]] - ) +def test_summary_warp_matches_the_plan() -> None: + """The maps a summary records give the plan's warp. + + The warp is rigid, affine or patchwise (its displacement field sampled + on the canvas). + """ + a = np.array([[[1.0, 0, 0.5], [0, 1, -1.0]], [[1.0, 0.02, 0], [0, 0.98, 2]]]) w = TrialWarp(a) sw = SummaryWarp(a) r, c = np.array([3.2, 10.0]), np.array([4.5, 7.25]) @@ -152,10 +189,12 @@ def test_summary_warp_matches_the_plan(): np.testing.assert_allclose(got[1], [3.0 * 0.95, 12.25 * 0.95]) -def test_collect_writes_the_annotation(tmp_path, fake): # noqa: F811 - """Every run's summary gets each kept source's spot and each spot's - label; with empty movies the event test is skipped (a warning) and the - spots keep the correlation test; silo-spots writes it again.""" +def test_collect_writes_the_annotation(tmp_path: Path, fake: None) -> None: # noqa: F811 + """Every run's summary gets each kept source's spot and each spot's label. + + With empty movies the event test is skipped (a warning) and the spots + keep the correlation test; silo-spots writes it again. + """ table = make_session(tmp_path / "s") params = SiloParams(min_kinetic_score=0.0, spot_link_px=4.0) with warnings.catch_warnings(record=True) as w: @@ -191,7 +230,7 @@ def test_collect_writes_the_annotation(tmp_path, fake): # noqa: F811 assert tuple(labels) == sp.LABELS -def test_spot_params(): +def test_spot_params() -> None: """Defaults and checks of the spot settings.""" p = SiloParams() assert (p.spot_link_px, p.spot_split_corr, p.spot_min_power) == ( @@ -201,21 +240,23 @@ def test_spot_params(): ) assert p.spot_event_test and p.spot_compact_px == 0.45 for bad in ( - dict(spot_link_px=0), - dict(spot_split_corr=1.5), - dict(spot_min_events=2.5), - dict(spot_event_test="yes"), - dict(spot_min_power=-0.1), - dict(spot_min_events=4), # a cloud's fit takes 5 + {"spot_link_px": 0}, + {"spot_split_corr": 1.5}, + {"spot_min_events": 2.5}, + {"spot_event_test": "yes"}, + {"spot_min_power": -0.1}, + {"spot_min_events": 4}, # a cloud's fit takes 5 ): with pytest.raises(ValueError): SiloParams(**bad) assert PARAMS.spot_event_test -def test_event_tests_in_a_pool_agree(): - """Event tests in spawned workers give the serial results (one seed - per spot).""" +def test_event_tests_in_a_pool_agree() -> None: + """Event tests in spawned workers give the serial results. + + One seed per spot. + """ from giant_python.pipeline.silo_spots import _event_tests, _pool rng = np.random.default_rng(5) @@ -223,12 +264,12 @@ def test_event_tests_in_a_pool_agree(): jobs = [] for g in range(4): n = 40 - ev = dict( - r=rng.normal(10, 0.5, n), - c=rng.normal(10, 0.5, n), - se_r=np.full(n, 0.2), - se_c=np.full(n, 0.2), - ) + ev = { + "r": rng.normal(10, 0.5, n), + "c": rng.normal(10, 0.5, n), + "se_r": np.full(n, 0.2), + "se_c": np.full(n, 0.2), + } jobs.append((ev, np.array([[10.0, 9.0], [10.0, 11.0]]), st, g)) serial = _event_tests(jobs, None) pool = _pool(2) @@ -240,18 +281,22 @@ def test_event_tests_in_a_pool_agree(): assert _pool(1) is None -def test_few_events_are_not_fitted(): - """Fewer than MIN_FIT_EVENTS events give no cloud, whatever - min_events says.""" +def test_few_events_are_not_fitted() -> None: + """Fewer than MIN_FIT_EVENTS events give no cloud. + + That holds whatever min_events says. + """ st = sp.SpotSettings(min_events=1, n_sim=4) - one = dict(r=[10.0], c=[10.0], se_r=[0.2], se_c=[0.2]) + one = {"r": [10.0], "c": [10.0], "se_r": [0.2], "se_c": [0.2]} src = np.array([[10.0, 9.5], [10.0, 10.5]]) assert sp.event_test(one, src, st) == {"n_events": 1} -def test_tiff_and_hdf5_pixels_agree(tmp_path): - """A movie's pixels read from a TIFF (page by page) and from HDF5 are - the same, NaN outside the image.""" +def test_tiff_and_hdf5_pixels_agree(tmp_path: Path) -> None: + """A movie's pixels read from a TIFF (page by page) and from HDF5 are the same. + + They are NaN outside the image. + """ import tifffile from giant_python.pipeline.silo_spots import _read_pixels @@ -277,12 +322,17 @@ def test_tiff_and_hdf5_pixels_agree(tmp_path): "layout", ["gzip, a page per chunk", "gzip, 4 pages per chunk", "contiguous"], ) -def test_hdf5_pixels_over_several_blocks(tmp_path, monkeypatch, layout): - """Frames read over several blocks, from one page per frame or from - the activity channel's page of several, are the frames' pixels. Only - the frames' own pages are read where each page is its own chunk (as - the registered movies are stored deflated); contiguous movies and - chunks of several pages are read in blocks of every page.""" +def test_hdf5_pixels_over_several_blocks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, layout: str +) -> None: + """Frames read over several blocks are the frames' pixels. + + The frames are read from one page per frame or from the activity + channel's page of several. Only the frames' own pages are read where + each page is its own chunk (as the registered movies are stored + deflated); contiguous movies and chunks of several pages are read in + blocks of every page. + """ from giant_python.pipeline import silo_spots monkeypatch.setattr(silo_spots, "_BLOCK", 4) @@ -290,8 +340,8 @@ def test_hdf5_pixels_over_several_blocks(tmp_path, monkeypatch, layout): pages = rng.random((3 * 11, 5, 7)).astype(np.float32) h5 = tmp_path / "m.h5" opts = { - "gzip, a page per chunk": dict(chunks=(1, 5, 7), compression="gzip"), - "gzip, 4 pages per chunk": dict(chunks=(4, 5, 7), compression="gzip"), + "gzip, a page per chunk": {"chunks": (1, 5, 7), "compression": "gzip"}, + "gzip, 4 pages per chunk": {"chunks": (4, 5, 7), "compression": "gzip"}, "contiguous": {}, }[layout] with h5py.File(h5, "w") as f: @@ -299,14 +349,49 @@ def test_hdf5_pixels_over_several_blocks(tmp_path, monkeypatch, layout): single, blocks = [], [] read_direct, getitem = h5py.Dataset.read_direct, h5py.Dataset.__getitem__ - def spy_direct(self, dest, source_sel=None, dest_sel=None): - """Record the pages read one at a time.""" + def spy_direct( + self: h5py.Dataset, + dest: np.ndarray, + source_sel: slice | None = None, + dest_sel: slice | None = None, + ) -> None: + """Record the pages read one at a time. + + Parameters + ---------- + self : h5py.Dataset + The dataset read. + dest : np.ndarray + Array to read into. + source_sel : slice, optional + Pages to read; it must be a single page. + dest_sel : slice, optional + Where to put them in dest. + + Returns + ------- + None + The result of the original read_direct. + """ assert source_sel.stop == source_sel.start + 1 single.append(source_sel.start) return read_direct(self, dest, source_sel, dest_sel) - def spy_get(self, key): - """Record the blocks of pages read.""" + def spy_get(self: h5py.Dataset, key: slice) -> np.ndarray: + """Record the blocks of pages read. + + Parameters + ---------- + self : h5py.Dataset + The dataset read. + key : slice + Pages to read. + + Returns + ------- + np.ndarray + The pages, as the original ``__getitem__`` reads them. + """ blocks.append((key.start, key.stop)) return getitem(self, key) @@ -321,9 +406,7 @@ def spy_get(self, key): got = silo_spots._read_pixels(h5, ppf, page0, rows, cols, n) frames = pages[page0::ppf][: (n or pages.shape[0] // ppf)] assert got.shape == (frames.shape[0], 5) - np.testing.assert_array_equal( - got[:, inside], frames[:, cols[inside], rows[inside]] - ) + np.testing.assert_array_equal(got[:, inside], frames[:, cols[inside], rows[inside]]) assert np.isnan(got[:, ~inside]).all() n_f = frames.shape[0] if ppf > 1 and layout == "gzip, a page per chunk": @@ -332,13 +415,10 @@ def spy_get(self, key): else: step = 4 * ppf assert not single - assert blocks == [ - (a, min(a + step, n_f * ppf)) - for a in range(0, n_f * ppf, step) - ] + assert blocks == [(a, min(a + step, n_f * ppf)) for a in range(0, n_f * ppf, step)] -def test_missing_movies_warn(): +def test_missing_movies_warn() -> None: """Trials to test without a movie are named in a warning.""" from giant_python.pipeline.silo_spots import _spot_events @@ -348,21 +428,23 @@ class _Session: n_trials = 2 keep = np.ones((1, 2), bool) - def movie(self, d, t): + def movie(self, d: int, t: int) -> None: """No movie.""" - return None + return warp = SummaryWarp(np.tile(np.eye(2, 3), (2, 1, 1))) - spots = [dict(g=0, center=np.array([5.0, 5.0]), extent=1.0)] + spots = [{"g": 0, "center": np.array([5.0, 5.0]), "extent": 1.0}] st = sp.SpotSettings() with pytest.warns(UserWarning, match=r"trials \[1, 2\] have no"): ev = _spot_events(_Session(), PARAMS, st, 0, warp, spots, None, False) assert ev[0]["r"].size == 0 -def test_event_corr_uses_the_activity_channel(tmp_path): - """The summary keeps physical channels: the correlation is the - activity channel's.""" +def test_event_corr_uses_the_activity_channel(tmp_path: Path) -> None: + """The summary keeps physical channels. + + The correlation is the activity channel's. + """ from giant_python.pipeline.silo_spots import _annotate_path rng = np.random.default_rng(7) @@ -375,9 +457,7 @@ def test_event_corr_uses_the_activity_channel(tmp_path): ev[:, 1, 1] = shared summary = tmp_path / "experiment_summary.h5" with h5py.File(summary, "w") as f: - f["Path1/sources/spatial/coords"] = np.array( - [[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]] - ) + f["Path1/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) f["Path1/sources/temporal/events"] = ev st = sp.SpotSettings() for ch, label in ((2, "merge"), (1, "undecided")): @@ -386,9 +466,11 @@ def test_event_corr_uses_the_activity_channel(tmp_path): assert list(read_spots(summary, 1)["label"]) == [label] -def test_truncated_files_are_refused(tmp_path): - """A baseline (or movie) without every frame asked for is an error, - not frames left unfilled.""" +def test_truncated_files_are_refused(tmp_path: Path) -> None: + """A baseline (or movie) without every frame asked for is an error. + + The frames are not left unfilled. + """ import tifffile from giant_python.pipeline.silo_spots import _read_pixels @@ -405,9 +487,11 @@ def test_truncated_files_are_refused(tmp_path): _read_pixels(path, 1, 0, [1], [1], n_frames=7) -def test_reannotation_uses_the_recorded_run(tmp_path): - """silo-spots reads the run's own activity channel and annotates the - paths the summary has (here only Path2).""" +def test_reannotation_uses_the_recorded_run(tmp_path: Path) -> None: + """Silo-spots reads the run's own activity channel. + + It annotates the paths the summary has (here only Path2). + """ from giant_python.pipeline.silo_spots import annotate_spots rng = np.random.default_rng(8) @@ -419,9 +503,7 @@ def test_reannotation_uses_the_recorded_run(tmp_path): ev[:, 1, 1] = shared summary = tmp_path / "experiment_summary.h5" with h5py.File(summary, "w") as f: - f["Path2/sources/spatial/coords"] = np.array( - [[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]] - ) + f["Path2/sources/spatial/coords"] = np.array([[0.0, 0.0], [5.0, 5.0], [5.0, 6.5]]) f["Path2/sources/temporal/events"] = ev f["params/activityChannel"] = np.array([[2.0]]) f["params/baselineMode"] = np.array([b"fit"]) diff --git a/tests/raster/test_raster_summary.py b/tests/raster/test_raster_summary.py index c8b6da33..395f19a1 100644 --- a/tests/raster/test_raster_summary.py +++ b/tests/raster/test_raster_summary.py @@ -1,8 +1,14 @@ -"""Tests of SILo's summaries in GIAnT-MATLAB's schema -(saveExperimentSummaryH5, savePerTrialSummaryH5).""" +"""Tests of SILo's summaries in GIAnT-MATLAB's schema. + +The summaries are saveExperimentSummaryH5, savePerTrialSummaryH5. +""" + +from pathlib import Path +from typing import Any import h5py import numpy as np +import numpy.typing as npt import pytest from giant_python.extraction.raster.alignment import TrialWarp @@ -30,8 +36,14 @@ SHIFTS = np.array([[np.nan, np.nan], [0.0, 0.0], [1.0, -2.0]]) -def make_plan(): - """A plan of four sources on a 14 x 18 frame, three trials.""" +def make_plan() -> ExtractionPlan: + """Build a plan of four sources on a 14 x 18 frame, three trials. + + Returns + ------- + ExtractionPlan + The plan. + """ rng = np.random.default_rng(0) rows, cols = np.array([3, 4, 9, 10]), np.array([3, 5, 12, 15]) sel = np.zeros((H, W), bool) @@ -78,8 +90,14 @@ def make_plan(): ) -def outcome(t, n_px, extracted=True): - """A trial's outcome with distinct values per source and channel.""" +def outcome(t: int, n_px: int, extracted: bool = True) -> TrialOutcome: + """Build a trial's outcome with distinct values per source and channel. + + Returns + ------- + TrialOutcome + The outcome; without activity when extracted is False. + """ n = FRAMES[t] rng = np.random.default_rng(t) rec = TrialRecord( @@ -106,8 +124,14 @@ def outcome(t, n_px, extracted=True): return TrialOutcome(rec, act) -def alignment(t): - """A registration record with 5 registered frames over the trial.""" +def alignment(t: int) -> AlignmentRecord: + """Build a registration record with 5 registered frames over the trial. + + Returns + ------- + AlignmentRecord + The record. + """ ds = np.linspace(100 * t + 1, 100 * t + 1 + FRAMES[t] * 8, 5) return AlignmentRecord( ds_frames=ds, @@ -121,8 +145,14 @@ def alignment(t): @pytest.fixture -def written(tmp_path): - """Both summaries of one path (activity channel 2).""" +def written(tmp_path: Path) -> tuple[Path, Path, PathResult]: + """Write both summaries of one path (activity channel 2). + + Returns + ------- + tuple of (Path, Path, PathResult) + The experiment summary's file, the per-trial summary's file and the path's result. + """ plan = make_plan() n_px = plan.n_pixels result = PathResult( @@ -155,12 +185,18 @@ def written(tmp_path): return exp, per, result -def sizes(path): - """Every dataset's MATLAB size and class.""" +def sizes(path: Path) -> dict[str, tuple]: + """Return every dataset's MATLAB size and class. + + Returns + ------- + dict of str to tuple + For each dataset's name, its MATLAB size, dtype kind and item size. + """ out = {} with h5py.File(path, "r") as f: - def visit(name, obj): + def visit(name: str, obj: object) -> None: """Record a dataset.""" if isinstance(obj, h5py.Dataset): out[name] = ( @@ -173,7 +209,7 @@ def visit(name, obj): return out -def test_experiment_summary_schema(written): +def test_experiment_summary_schema(written: tuple[Path, Path, PathResult]) -> None: """Names, MATLAB sizes and classes of saveExperimentSummaryH5.""" exp, _, _ = written s = sizes(exp) @@ -216,9 +252,11 @@ def test_experiment_summary_schema(written): assert {k: v for k, v in s.items() if k not in params} == want -def test_experiment_summary_values(written): - """Traces at their trials' frames in file channel order; kept sources - only; frame records; ROI traces reordered; profiles averaged.""" +def test_experiment_summary_values(written: tuple[Path, Path, PathResult]) -> None: + """Check traces at their trials' frames in file channel order. + + Kept sources only; frame records; ROI traces reordered; profiles averaged. + """ exp, _, result = written e = load_struct_h5(exp)["Path1"] o1, o2 = result.trials[1], result.trials[2]() @@ -233,12 +271,8 @@ def test_experiment_summary_values(written): np.testing.assert_array_equal( e["sources"]["temporal"]["kinetic_score"].ravel(), [0.9, np.nan, 0.5] ) - np.testing.assert_array_equal( - e["sources"]["temporal"]["SNR"].ravel(), [1.5, np.nan, 6.0] - ) - np.testing.assert_array_equal( - e["sources"]["rejected"]["seed_coords"], [[0, 4, 5]] - ) + np.testing.assert_array_equal(e["sources"]["temporal"]["SNR"].ravel(), [1.5, np.nan, 6.0]) + np.testing.assert_array_equal(e["sources"]["rejected"]["seed_coords"], [[0, 4, 5]]) np.testing.assert_array_equal( e["visualizations"]["act_im_peaks"], [[0, 3, 3], [0, 9, 12], [0, 10, 15]], @@ -258,9 +292,7 @@ def test_experiment_summary_values(written): first = np.interp(o2.record.frame_lines[0], a.ds_frames, a.motion_c) assert fi["offlineXshifts"].ravel()[30] == pytest.approx(first - 2.0) assert "offlineZshifts" not in fi - np.testing.assert_array_equal( - fi["trial_alignment_affine"][2], [[1, 0, 1], [0, 1, -2]] - ) + np.testing.assert_array_equal(fi["trial_alignment_affine"][2], [[1, 0, 1], [0, 1, -2]]) np.testing.assert_array_equal(e["global"]["F"][:, :30], o1.record.global_f) roi_f = e["user_rois"]["F"] np.testing.assert_array_equal(roi_f[:, 1, :30], o1.record.roi_f[:, 0]) @@ -285,7 +317,7 @@ def test_experiment_summary_values(written): ) -def test_per_trial_summary(written): +def test_per_trial_summary(written: tuple[Path, Path, PathResult]) -> None: """Per-trial images, peaks in the consensus frame, footprints.""" _, per, result = written s = sizes(per) @@ -340,23 +372,30 @@ def test_per_trial_summary(written): assert (coords[:, :, 0] == 0).all() and np.isnan(coords[0, :, 1:]).all() -def test_compressed_dataset_splits_large_columns(tmp_path): +def test_compressed_dataset_splits_large_columns(tmp_path: Path) -> None: """A column of images above 1 GiB is split along the last axis.""" from giant_python.extraction.raster.summary import _Writer with h5py.File(tmp_path / "big.h5", "w") as f: - ds = _Writer(f).create( - "a/profiles", (3000, 400, 1, 800, 9), np.float32, compressed=True - ) + ds = _Writer(f).create("a/profiles", (3000, 400, 1, 800, 9), np.float32, compressed=True) assert ds.shape == (9, 800, 1, 400, 3000) assert ds.chunks == (1, 800, 1, 400, 750) plain = _Writer(f).create("a/plain", (2, 3), np.float32) assert plain.chunks is None and plain.compression is None -def _profile_data(dtype=np.float32, shape=(10, 6, 1, 4, 7)): - """A block of per-trial profiles, the file's orientation (cols, rows, - 1, sources, trials): mostly zeros, NaN for a trial.""" +def _profile_data( + dtype: npt.DTypeLike = np.float32, shape: tuple[int, ...] = (10, 6, 1, 4, 7) +) -> np.ndarray: + """Build a block of per-trial profiles, in the file's orientation. + + The orientation is (cols, rows, 1, sources, trials): mostly zeros, NaN for a trial. + + Returns + ------- + ndarray + The block of profiles. + """ rng = np.random.default_rng(5) data = rng.random(shape).astype(dtype) data[data < 0.6] = 0 @@ -364,8 +403,14 @@ def _profile_data(dtype=np.float32, shape=(10, 6, 1, 4, 7)): return data -def _stored(ds): - """Every chunk of a dataset as stored: ``{offset: (mask, bytes)}``.""" +def _stored(ds: h5py.Dataset) -> dict[tuple[int, ...], tuple[int, bytes]]: + """Return every chunk of a dataset as stored: {offset: (mask, bytes)}. + + Returns + ------- + dict of tuple to tuple + For each chunk's offset, its filter mask and its stored bytes. + """ out = {} for i in range(ds.id.get_num_chunks()): info = ds.id.get_chunk_info(i) @@ -376,20 +421,20 @@ def _stored(ds): @pytest.mark.parametrize("dtype", [np.float32, np.float64]) @pytest.mark.parametrize("depth", [None, 3, 7]) def test_deflated_columns_store_what_hdf5_stores( - tmp_path, monkeypatch, depth, dtype -): - """A shuffled and deflated dataset written chunk by chunk (deflated in - threads) stores, chunk for chunk, the bytes that writing the same data + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, depth: int | None, dtype: type[np.generic] +) -> None: + """A shuffled and deflated dataset written chunk by chunk (deflated in threads). + + It stores, chunk for chunk, the bytes that writing the same data through h5py's filters stores, and reads back the same values: whole chunks, chunks that split the last axis, and a last chunk that - overhangs it (completed with the zero fill value).""" + overhangs it (completed with the zero fill value). + """ from giant_python.extraction.raster import summary data = _profile_data(dtype) chunks = (1, 6, 1, 4, depth or 7) - opts = dict( - chunks=chunks, compression="gzip", compression_opts=1, shuffle=True - ) + opts = {"chunks": chunks, "compression": "gzip", "compression_opts": 1, "shuffle": True} direct = [] write = summary._write_deflated monkeypatch.setattr( @@ -419,9 +464,24 @@ def test_deflated_columns_store_what_hdf5_stores( assert summary._deflated_by_column(plain, data, 10) is None -def _filtered(f, name, shape, chunks, filters, dtype=np.float32, **kw): - """A chunked dataset with the filters in the given order (h5py's - ``create_dataset`` puts shuffle first).""" +def _filtered( + f: h5py.File, + name: str, + shape: tuple[int, ...], + chunks: tuple[int, ...], + filters: list[str], + dtype: npt.DTypeLike = np.float32, + **kw: Any, # noqa: ANN401 +) -> h5py.Dataset: + """Create a chunked dataset with the filters in the given order. + + (h5py's create_dataset puts shuffle first.) + + Returns + ------- + h5py.Dataset + The new dataset. + """ dcpl = h5py.h5p.create(h5py.h5p.DATASET_CREATE) dcpl.set_chunk(chunks) for name_ in filters: @@ -435,10 +495,7 @@ def _filtered(f, name, shape, chunks, filters, dtype=np.float32, **kw): dcpl.set_fill_value(np.array(kw["fillvalue"], dtype)) if "fill_time" in kw: dcpl.set_fill_time(kw["fill_time"]) - maxshape = tuple( - h5py.h5s.UNLIMITED if m is None else m - for m in kw.get("maxshape", shape) - ) + maxshape = tuple(h5py.h5s.UNLIMITED if m is None else m for m in kw.get("maxshape", shape)) space = h5py.h5s.create_simple(shape, maxshape) tid = h5py.h5t.py_create(np.dtype(dtype)) h5py.h5d.create(f.id, name.encode(), tid, space, dcpl=dcpl) @@ -449,34 +506,32 @@ def _filtered(f, name, shape, chunks, filters, dtype=np.float32, **kw): # type or shape, the filters, the chunks, the fill (the dataset's last # chunk overhangs its last axis, 7 by 3) _GUARDS = { - "block of another type": dict(block=lambda d: d.astype(np.float64)), - "block to broadcast": dict(block=lambda d: d[:, :, :, :1]), - "deflate then shuffle": dict(filters=["gzip", "shuffle"]), - "shuffle only": dict(filters=["shuffle"]), - "deflate only": dict(filters=["gzip"]), - "with a checksum": dict(filters=["shuffle", "gzip", "fletcher32"]), - "chunks of several columns": dict(chunks=(2, 6, 1, 4, 3)), - "chunks split in the middle": dict(chunks=(1, 3, 1, 4, 3)), - "nonzero fill, overhanging chunk": dict(kw=dict(fillvalue=5.0)), - "nonzero fill, resized": dict( - kw=dict(fillvalue=5.0, maxshape=(10, 6, 1, 4, None)) - ), - "fill never written, overhanging chunk": dict( - kw=dict(fill_time=h5py.h5d.FILL_TIME_NEVER) - ), + "block of another type": {"block": lambda d: d.astype(np.float64)}, + "block to broadcast": {"block": lambda d: d[:, :, :, :1]}, + "deflate then shuffle": {"filters": ["gzip", "shuffle"]}, + "shuffle only": {"filters": ["shuffle"]}, + "deflate only": {"filters": ["gzip"]}, + "with a checksum": {"filters": ["shuffle", "gzip", "fletcher32"]}, + "chunks of several columns": {"chunks": (2, 6, 1, 4, 3)}, + "chunks split in the middle": {"chunks": (1, 3, 1, 4, 3)}, + "nonzero fill, overhanging chunk": {"kw": {"fillvalue": 5.0}}, + "nonzero fill, resized": {"kw": {"fillvalue": 5.0, "maxshape": (10, 6, 1, 4, None)}}, + "fill never written, overhanging chunk": {"kw": {"fill_time": h5py.h5d.FILL_TIME_NEVER}}, } @pytest.mark.parametrize("case", list(_GUARDS)) def test_deflated_columns_only_where_the_bytes_are_hdf5s( - tmp_path, monkeypatch, case -): - """Blocks are written chunk by chunk only into a dataset stored as the - writer makes it (shuffle then deflate, chunks of one column, whole in - the middle axes), of its own type and shape, and, where the last chunk + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + """Blocks are written chunk by chunk only into a dataset stored as the writer makes it. + + That is shuffle then deflate, chunks of one column, whole in + the middle axes, of its own type and shape, and, where the last chunk overhangs the last axis, with a zero fill value that is written; any other is written through h5py and reads back (and extends) as h5py - writes it.""" + writes it. + """ from giant_python.extraction.raster import summary data = _profile_data() @@ -486,17 +541,13 @@ def test_deflated_columns_only_where_the_bytes_are_hdf5s( chunks = guard.get("chunks", (1, 6, 1, 4, 3)) kw = guard.get("kw", {}) direct = [] - monkeypatch.setattr( - summary, "_write_deflated", lambda *a: direct.append(a[1]) - ) + monkeypatch.setattr(summary, "_write_deflated", lambda *a: direct.append(a[1])) with h5py.File(tmp_path / "a.h5", "w") as f: ref = _filtered(f, "ref", data.shape, chunks, filters, **kw) ref[()] = block ds = _filtered(f, "x", data.shape, chunks, filters, **kw) assert summary._deflated_by_column(ds, block, 10) is None - summary._profile_blocks( - ds, lambda c0, c1: block[c0:c1], reversed_order=True - ) + summary._profile_blocks(ds, lambda c0, c1: block[c0:c1], reversed_order=True) assert not direct assert ds[()].tobytes() == ref[()].tobytes() if "maxshape" in kw: @@ -507,19 +558,19 @@ def test_deflated_columns_only_where_the_bytes_are_hdf5s( # the same fill with chunks that do not overhang is written directly if "kw" in guard: with h5py.File(tmp_path / "b.h5", "w") as f: - whole = _filtered( - f, "w", data.shape, (1, 6, 1, 4, 7), filters, **kw - ) + whole = _filtered(f, "w", data.shape, (1, 6, 1, 4, 7), filters, **kw) assert summary._deflated_by_column(whole, data, 10) == 1 @pytest.mark.parametrize("kind", ["one-dimensional", "strings"]) def test_deflated_columns_only_of_images_of_numbers( - tmp_path, monkeypatch, kind -): - """A one-dimensional dataset and one of variable-length strings, even - shuffled and deflated in chunks of one index, are written through h5py - (same values), not chunk by chunk.""" + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + """A one-dimensional dataset and one of variable-length strings are written through h5py. + + Even shuffled and deflated in chunks of one index, they are written through h5py + (same values), not chunk by chunk. + """ from giant_python.extraction.raster import summary if kind == "one-dimensional": @@ -529,9 +580,7 @@ def test_deflated_columns_only_of_images_of_numbers( dtype = h5py.string_dtype() block = np.array([f"s{i}" for i in range(10)], dtype=dtype) direct = [] - monkeypatch.setattr( - summary, "_write_deflated", lambda *a: direct.append(a[1]) - ) + monkeypatch.setattr(summary, "_write_deflated", lambda *a: direct.append(a[1])) with h5py.File(tmp_path / "a.h5", "w") as f: ds = f.create_dataset( "x", @@ -543,22 +592,22 @@ def test_deflated_columns_only_of_images_of_numbers( shuffle=True, ) assert summary._deflated_by_column(ds, block, 10) is None - summary._profile_blocks( - ds, lambda c0, c1: block[c0:c1], reversed_order=True - ) + summary._profile_blocks(ds, lambda c0, c1: block[c0:c1], reversed_order=True) assert not direct got = ds.asstr()[()] if kind == "strings" else ds[()] assert list(got) == list(block) def test_deflating_threads_sizing_rule_and_chunks_in_flight( - tmp_path, monkeypatch -): - """The sizing rule: the deflating threads are chosen from the chunk's - size so that the estimate of four chunk sizes per thread fits the 4 + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The sizing rule: the deflating threads are chosen from the chunk's size. + + They are chosen so that the estimate of four chunk sizes per thread fits the 4 GiB target (an estimate the scheduling aims at; buffers are not measured here). The chunks in flight: no more than 2 x threads chunks - are deflated ahead of a slow write.""" + are deflated ahead of a slow write. + """ import threading import time @@ -578,8 +627,14 @@ def test_deflating_threads_sizing_rule_and_chunks_in_flight( shuffled = summary._shuffled lock = threading.Lock() - def count(*a): - """Count the chunks given to zlib.""" + def count(*a: Any) -> np.ndarray: # noqa: ANN401 + """Count the chunks given to zlib. + + Returns + ------- + ndarray + What the original _shuffled returns for the same arguments. + """ with lock: deflated.append(1) return shuffled(*a) @@ -590,7 +645,7 @@ def count(*a): class SlowID: """Stands for a dataset's id: its first write is slow.""" - def write_direct_chunk(self, offset, stored): + def write_direct_chunk(self, offset: tuple[int, ...], stored: bytes) -> None: """Note the chunks deflated by the end of the write.""" if not seen: time.sleep(0.3) @@ -608,9 +663,12 @@ class Fake: assert len(seen) == 64 and len(deflated) == 64 -def test_short_trial_and_no_peaks(tmp_path): - """A trial loaded but not extracted adds frames, no sources; without - per-trial peaks the peak fields are left out.""" +def test_short_trial_and_no_peaks(tmp_path: Path) -> None: + """A trial loaded but not extracted adds frames, no sources. + + Without + per-trial peaks the peak fields are left out. + """ plan = make_plan() result = PathResult( plan=plan, @@ -635,9 +693,11 @@ def test_short_trial_and_no_peaks(tmp_path): assert "sources" not in p -def test_trial_without_sources_is_nan(tmp_path): - """Frames of a trial loaded but not extracted are NaN in the sources' - traces when other trials have sources.""" +def test_trial_without_sources_is_nan(tmp_path: Path) -> None: + """Frames of a trial loaded but not extracted are NaN in the sources' traces. + + That is when other trials have sources. + """ plan = make_plan() result = PathResult( plan=plan, @@ -659,20 +719,21 @@ def test_trial_without_sources_is_nan(tmp_path): assert np.isnan(snr[1]).all() -def test_nearest_interpolation(): +def test_nearest_interpolation() -> None: """MATLAB's interp1 'nearest' with 'extrap': ties go right.""" ds = np.array([1.0, 5.0, 9.0]) v = np.array([10.0, 20.0, 30.0]) - np.testing.assert_array_equal( - _nearest(ds, v, [0, 2, 3, 4, 7, 12]), [10, 10, 20, 20, 30, 30] - ) + np.testing.assert_array_equal(_nearest(ds, v, [0, 2, 3, 4, 7, 12]), [10, 10, 20, 20, 30, 30]) np.testing.assert_array_equal(_nearest(ds[:1], v[:1], [0, 4]), [10, 10]) -def test_evidence_test_removes_weak_sources(tmp_path): - """With min_snr the sources whose SNR averaged over trials is below it - are removed with the kinetics test's, and marked in the summary; the - SNR of a source without one (NaN) does not judge it.""" +def test_evidence_test_removes_weak_sources(tmp_path: Path) -> None: + """With min_snr the weak sources are removed with the kinetics test's. + + Those are the sources whose SNR averaged over trials is below it, + and they are marked in the summary; the + SNR of a source without one (NaN) does not judge it. + """ plan = make_plan() result = PathResult( plan=plan, @@ -693,10 +754,12 @@ def test_evidence_test_removes_weak_sources(tmp_path): assert off.weak is None and off.keep.all() -def test_evidence_test_event_rate(tmp_path): - """min_event_rate compares each source's kinetics events per minute of - its frames with the rate, and the summary records the rejected - sources' rates.""" +def test_evidence_test_event_rate(tmp_path: Path) -> None: + """The min_event_rate compares each source's kinetics events per minute with the rate. + + The events per minute are of its frames, and the summary records the rejected + sources' rates. + """ plan = make_plan() result = PathResult( plan=plan, @@ -716,9 +779,12 @@ def test_evidence_test_event_rate(tmp_path): np.testing.assert_array_equal(kin.weak, kin.n_events == 0) -def test_evidence_test_judges_weak_seeds_only(): - """With judge_below the evidence test judges only the sources whose - seed height in the plan's combined image is below it.""" +def test_evidence_test_judges_weak_seeds_only() -> None: + """With judge_below the evidence test judges only the weaker sources. + + Those are the sources whose + seed height in the plan's combined image is below it. + """ from giant_python.extraction.raster.seeding import seed_heights plan = make_plan() @@ -729,9 +795,7 @@ def test_evidence_test_judges_weak_seeds_only(): ) h = seed_heights(plan.act_im, plan.source_rows, plan.source_cols) cut = float(np.median(h)) - kin = kinetics_test( - result, 0.024, 200.0, 0.0, min_event_rate=1e6, judge_below=cut - ) + kin = kinetics_test(result, 0.024, 200.0, 0.0, min_event_rate=1e6, judge_below=cut) np.testing.assert_allclose(kin.seed_height, h) np.testing.assert_array_equal(kin.weak, ~(h >= cut)) assert kin.weak.any() and not kin.weak.all() @@ -740,9 +804,11 @@ def test_evidence_test_judges_weak_seeds_only(): assert every.weak.all() and every.seed_height is None -def test_evidence_events_skipped_without_counts(): - """The event criterion judges nothing when the kinetics test cannot - count events (decay under 3 frames); the SNR criterion still does.""" +def test_evidence_events_skipped_without_counts() -> None: + """The event criterion judges nothing when the kinetics test cannot count events. + + That is with a decay under 3 frames; the SNR criterion still does. + """ plan = make_plan() result = PathResult( plan=plan, @@ -756,16 +822,24 @@ def test_evidence_events_skipped_without_counts(): np.testing.assert_array_equal(kin.weak, [True, True, False, False]) -def test_frame_offset_is_written_and_added_to_the_offline_shifts(tmp_path): - """With trials that start at different raster positions (the ROIs - changed), the summary holds each trial's offset, the typed reader +def test_frame_offset_is_written_and_added_to_the_offline_shifts(tmp_path: Path) -> None: + """With trials that start at different raster positions, the summary holds their offsets. + + The ROIs changed, the summary holds each trial's offset, the typed reader returns it, and the offline motion of a trial is its registration's motion plus the plan's shift plus the offset; without an offset the - dataset is left out and the reader gives None.""" + dataset is left out and the reader gives None. + """ from giant_python.models.experiment_summary import ExperimentSummary - def write(offset, name): - """The summary of one path whose plan has this frame offset.""" + def write(offset: np.ndarray | None, name: str) -> tuple[Path, PathResult]: + """Write the summary of one path whose plan has this frame offset. + + Returns + ------- + tuple of (Path, PathResult) + The experiment summary's file and the path's result. + """ plan = make_plan() plan.frame_offset = offset result = PathResult( diff --git a/tests/raster/test_raster_summary_model.py b/tests/raster/test_raster_summary_model.py index 131e474a..142d1ea0 100644 --- a/tests/raster/test_raster_summary_model.py +++ b/tests/raster/test_raster_summary_model.py @@ -91,7 +91,7 @@ def test_from_h5_reads_a_raster_summary(written: tuple[Path, Path, PathResult]) It loads with its values, its kinetics and rejected sources, and no offlineZshifts. """ - exp, _, result = written + exp, _, _result = written s = ExperimentSummary.from_h5(exp) raw = load_struct_h5(exp)["Path1"] assert [p.path_index for p in s.paths] == [0] # Path2 was None diff --git a/tests/raster/test_raster_trial.py b/tests/raster/test_raster_trial.py index a8cce16e..b686e721 100644 --- a/tests/raster/test_raster_trial.py +++ b/tests/raster/test_raster_trial.py @@ -16,9 +16,12 @@ PLAN_FIXTURE = Path(__file__).parent / "data" / "matlab_plan.h5" -def test_discard_frames_around_a_motion_event(): - """A jump of recNegErr discards it and neighbours above half the - threshold (MATLAB: dilate by ~50 ms, keep above half, close).""" +def test_discard_frames_around_a_motion_event() -> None: + """Discard a motion event and its neighbours. + + A jump of recNegErr discards it and neighbours above half the + threshold (MATLAB: dilate by ~50 ms, keep above half, close). + """ rne = -0.5 + 0.01 * np.random.default_rng(0).standard_normal(800) rne[400:402] += 0.2 # registration error jumps for two frames d = discard_frames(rne, 80.0, motion_thresh=2.0) @@ -29,11 +32,14 @@ def test_discard_frames_around_a_motion_event(): @pytest.mark.parametrize("layout", ["one_series", "page_by_page"]) -def test_load_registered_trial(tmp_path, layout): - """Channels are deinterleaved, pages transposed to MATLAB's rows and +def test_load_registered_trial(tmp_path: Path, layout: str) -> None: + """Load a registered trial. + + Channels are deinterleaved, pages transposed to MATLAB's rows and columns, discards set to NaN, the variance factor read. The TIFF may hold one series of all pages (MATLAB's Fast_BigTiff_Write) or one per - page (GIAnT-Python's registration writes each page on its own).""" + page (GIAnT-Python's registration writes each page on its own). + """ tifffile = pytest.importorskip("tifffile") n, rows, cols = 400, 6, 9 # MATLAB rows x cols; n > the 4 s median rng = np.random.default_rng(0) @@ -59,9 +65,7 @@ def test_load_registered_trial(tmp_path, layout): f["alignHz"] = np.array([[80.0]]) f["recNegErr"] = rne[None, :] f["slap2/varFacDS"] = vf # MATLAB rows x cols x frames, reversed - tr = load_registered_trial( - tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2 - ) + tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) assert tr.movie.shape == (n, rows, cols) and tr.align_hz == 80.0 keep = ~tr.discard assert tr.discard[200] and keep.sum() > n - 8 @@ -72,9 +76,12 @@ def test_load_registered_trial(tmp_path, layout): @pytest.mark.parametrize("save_tif", [False, True]) -def test_load_registration_movie(tmp_path, save_tif): - """Movies written by GIAnT-Python's registration, HDF5 (the default) or - TIFF, load as the same frames in MATLAB's rows and columns.""" +def test_load_registration_movie(tmp_path: Path, save_tif: bool) -> None: + """Load movies written by GIAnT-Python's registration. + + Movies written by GIAnT-Python's registration, HDF5 (the default) or + TIFF, load as the same frames in MATLAB's rows and columns. + """ if save_tif: pytest.importorskip("tifffile") from giant_python.registration.outputs import MovieWriter @@ -85,9 +92,7 @@ def test_load_registration_movie(tmp_path, save_tif): act[3, 2, 4] = np.nan other = np.full((n, rows, cols), 100, np.float32) stem = "E1T1DMD1" - name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz" + ( - ".tif" if save_tif else ".h5" - ) + name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz" + (".tif" if save_tif else ".h5") movie = MovieWriter(tmp_path / name, (rows, cols), 2 * n, save_tif) for a, o in zip(act, other): movie.write(a) @@ -102,23 +107,35 @@ def test_load_registration_movie(tmp_path, save_tif): np.testing.assert_allclose(tr.mean_im[..., 1], 100) -def test_localize_trial_retries_numerical_failures(monkeypatch): - """Any failure of the localization itself is retried with the outer - rows and columns NaN (MATLAB's catch); invalid inputs are not.""" +def test_localize_trial_retries_numerical_failures(monkeypatch: pytest.MonkeyPatch) -> None: + """Retry any failure of the localization itself. + + Any failure of the localization itself is retried with the outer + rows and columns NaN (MATLAB's catch); invalid inputs are not. + """ import giant_python.extraction.raster.trial as trial_mod from giant_python.extraction.raster.localization import ( RasterLocalizationParams, ) movie = np.ones((20, 6, 7), np.float32) - fake = trial_mod.RegisteredTrial( - movie, None, np.ones((6, 7, 1)), np.zeros(20, bool), 80.0 - ) + fake = trial_mod.RegisteredTrial(movie, None, np.ones((6, 7, 1)), np.zeros(20, bool), 80.0) monkeypatch.setattr(trial_mod, "load_registered_trial", lambda *a: fake) seen = [] - def flaky(mov, *args, **kwargs): - """Fails like a numerical error unless the edges are NaN.""" + def flaky(mov: np.ndarray, *args: object, **kwargs: object) -> str: + """Fail like a numerical error unless the edges are NaN. + + Returns + ------- + str + "ok", when the first row of mov is all NaN. + + Raises + ------ + ValueError + If the first row of mov is not all NaN. + """ seen.append(bool(np.isnan(mov[:, 0, :]).all())) if not seen[-1]: raise ValueError("non-finite residuals") @@ -138,9 +155,14 @@ def flaky(mov, *args, **kwargs): "num_channels, activity_channel", [(2, 0), (2, 3), (0, 1), (2.0, 1), (2, True), (1, -1)], ) -def test_channel_arguments_checked(tmp_path, num_channels, activity_channel): - """Channel arguments outside 1..num_channels (0 would select the last - channel), or not integers, raise before anything is read.""" +def test_channel_arguments_checked( + tmp_path: Path, num_channels: float, activity_channel: int +) -> None: + """Check the channel arguments. + + Channel arguments outside 1..num_channels (0 would select the last + channel), or not integers, raise before anything is read. + """ with pytest.raises(ValueError, match="channel"): load_registered_trial( tmp_path, @@ -150,7 +172,7 @@ def test_channel_arguments_checked(tmp_path, num_channels, activity_channel): ) -def test_page_count_not_a_multiple_of_channels(tmp_path): +def test_page_count_not_a_multiple_of_channels(tmp_path: Path) -> None: """An incomplete last frame is left out, with a warning.""" tifffile = pytest.importorskip("tifffile") n, rows, cols = 400, 4, 5 @@ -165,15 +187,16 @@ def test_page_count_not_a_multiple_of_channels(tmp_path): f["alignHz"] = np.array([[80.0]]) f["recNegErr"] = np.full((1, n), -0.5) with pytest.warns(UserWarning, match="not a multiple"): - tr = load_registered_trial( - tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2 - ) + tr = load_registered_trial(tmp_path, f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.tif", 2) assert tr.movie.shape == (n, rows, cols) -def test_trial_halves_match_matlab(): - """trialHalves.m of GIAnT-MATLAB: alternating blocks, then the larger - half's last frames move over until the halves are equal to a frame.""" +def test_trial_halves_match_matlab() -> None: + """Match trialHalves.m of GIAnT-MATLAB. + + Alternating blocks, then the larger + half's last frames move over until the halves are equal to a frame. + """ cases = { (10, 3): [1, 1, 1, 2, 2, 2, 1, 1, 2, 2], (7, 2): [1, 1, 2, 2, 1, 1, 2], @@ -189,9 +212,12 @@ def test_trial_halves_match_matlab(): assert abs(int((half == 0).sum()) - int((half == 1).sum())) <= 1 -def test_half_mean_images_match_matlab(): - """The half-trial mean images of MATLAB's loadAndProcessTrialAsync on - a small movie with missing pixels (exactly: sums of whole counts).""" +def test_half_mean_images_match_matlab() -> None: + """Match the half-trial mean images of MATLAB's loadAndProcessTrialAsync. + + The check is on + a small movie with missing pixels (exactly: sums of whole counts). + """ with h5py.File(PLAN_FIXTURE, "r") as f: g = f["halves"] stack, half, ref = g["stack"][()], g["half"][()], g["half_ims"][()] @@ -202,9 +228,12 @@ def test_half_mean_images_match_matlab(): np.testing.assert_array_equal(out, ref) -def test_load_registered_trial_half_images(tmp_path): - """Half images are returned only when asked for; their mean is the - trial's mean image where nothing is missing.""" +def test_load_registered_trial_half_images(tmp_path: Path) -> None: + """Return half images only when asked for. + + Half images are returned only when asked for; their mean is the + trial's mean image where nothing is missing. + """ n, rows, cols = 120, 5, 6 rng = np.random.default_rng(3) data = rng.poisson(20, (2 * n, cols, rows)).astype(np.float32) @@ -222,15 +251,16 @@ def test_load_registered_trial_half_images(tmp_path): np.testing.assert_allclose(tr.half_ims.mean(axis=0), tr.mean_im, rtol=1e-6) stack = data.transpose(0, 2, 1).reshape(n, 2, rows, cols) first = np.r_[0:40, 80:100] - np.testing.assert_allclose( - tr.half_ims[0, :, :, 1], stack[first, 1].mean(axis=0), rtol=1e-6 - ) + np.testing.assert_allclose(tr.half_ims[0, :, :, 1], stack[first, 1].mean(axis=0), rtol=1e-6) -def test_channel_means_equal_the_joint_nanmean(): - """The mean image and the missing pixels, one channel at a time, are - those of ``nanmean`` and ``isnan(...).mean`` over all channels at once, - bit for bit (pixels without samples included).""" +def test_channel_means_equal_the_joint_nanmean() -> None: + """Match the joint nanmean with the channel means. + + The mean image and the missing pixels, one channel at a time, are + those of nanmean and isnan(...).mean over all channels at once, + bit for bit (pixels without samples included). + """ from giant_python.extraction.raster.trial import _channel_means rng = np.random.default_rng(3) @@ -248,10 +278,13 @@ def test_channel_means_equal_the_joint_nanmean(): np.testing.assert_array_equal(missing, gaps > 0.33) -def test_lazy_loading_gives_the_same_trial(tmp_path): - """Read 256 frames at a time, with the variance factor left on disk: the +def test_lazy_loading_gives_the_same_trial(tmp_path: Path) -> None: + """Read 256 frames at a time with lazy loading. + + The variance factor is left on disk: the movie, the mean image and the half images of the whole-movie read, bit - for bit; the reader gives the array's values at chosen pixels.""" + for bit; the reader gives the array's values at chosen pixels. + """ from giant_python.extraction.raster.trial import PixelReader, SparseMovie n, rows, cols = 600, 7, 9 # more than two blocks of 256 frames @@ -271,9 +304,7 @@ def test_lazy_loading_gives_the_same_trial(tmp_path): f["slap2/varFacDS"] = vf for ch in (1, 2): a = load_registered_trial(tmp_path, name, 2, ch, half_ims=True) - b = load_registered_trial( - tmp_path, name, 2, ch, half_ims=True, lazy=True - ) + b = load_registered_trial(tmp_path, name, 2, ch, half_ims=True, lazy=True) assert isinstance(b.movie, SparseMovie) assert np.asarray(b.movie).dtype == a.movie.dtype assert b.mean_im.dtype == a.mean_im.dtype @@ -305,9 +336,12 @@ def test_lazy_loading_gives_the_same_trial(tmp_path): assert got.flags["F_CONTIGUOUS"] == want.flags["F_CONTIGUOUS"] -def test_pixel_reader_reads_only_the_tiles_it_needs(tmp_path): - """A dataset stored in small tiles is read tile by tile: the values of - the whole array at the pixels asked for.""" +def test_pixel_reader_reads_only_the_tiles_it_needs(tmp_path: Path) -> None: + """Read a dataset stored in small tiles tile by tile. + + The values of + the whole array at the pixels asked for. + """ from giant_python.extraction.raster.trial import PixelReader rng = np.random.default_rng(6) diff --git a/tests/raster/test_raster_trial_data.py b/tests/raster/test_raster_trial_data.py index 6089722c..77b5b33d 100644 --- a/tests/raster/test_raster_trial_data.py +++ b/tests/raster/test_raster_trial_data.py @@ -1,11 +1,12 @@ """Tests of the SLAP2 trial loader (SILo's loadTrial and its helpers). The helpers are checked against values computed by MATLAB R2024b -(``data/matlab_trial_data.mat``, made by ``data/make_matlab_trial_data.m``), +(data/matlab_trial_data.mat, made by data/make_matlab_trial_data.m), the frames against slow loops written from the definition, and the whole loader on small synthetic recordings of a static scene under known motion. """ +from collections.abc import Callable, Iterable, Sequence from pathlib import Path import numpy as np @@ -19,6 +20,7 @@ OnlineCompensation, RigidShift, TrialAlignment, + TrialData, TrialLoadParams, block_compensation, block_edges, @@ -37,7 +39,7 @@ upsample_discard, upsample_motion, ) -from giant_python.io.slap2_raster import read_raster_samples +from giant_python.io.slap2_raster import RasterLayout, read_raster_samples from giant_python.registration import multiroi from giant_python.registration.compensation import MAPPING, line_offsets from giant_python.registration.frames import FrameFormer, PixelFormer @@ -53,14 +55,28 @@ @pytest.fixture(scope="module") -def ref(): - """Values computed by MATLAB.""" +def ref() -> dict: + """Return the values computed by MATLAB. + + Returns + ------- + dict + The contents of the MATLAB data file by variable name. + """ return scipy.io.loadmat(DATA) @pytest.fixture(scope="module") -def recording(tmp_path_factory): - """Layout, samples and true motion of a short recording.""" +def recording( + tmp_path_factory: pytest.TempPathFactory, +) -> tuple[RasterLayout, np.ndarray, np.ndarray]: + """Return the layout, samples and true motion of a short recording. + + Returns + ------- + tuple[RasterLayout, np.ndarray, np.ndarray] + The layout, the samples and the true motion. + """ path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" layout = make_layout(path, n_cycles=500, seed=3) truth = write_recording(layout, seed=4, invalid=0.02) @@ -69,8 +85,16 @@ def recording(tmp_path_factory): @pytest.fixture(scope="module") -def online_recording(tmp_path_factory): - """A recording whose online offsets move the DMD pattern.""" +def online_recording( + tmp_path_factory: pytest.TempPathFactory, +) -> tuple[RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray]]: + """Return a recording whose online offsets move the DMD pattern. + + Returns + ------- + tuple[RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray]] + The layout, the samples, the true motion and the online offsets. + """ path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" layout = make_layout(path, n_cycles=1400, seed=5) online = online_offsets(layout.total_lines) @@ -80,27 +104,59 @@ def online_recording(tmp_path_factory): class Noiseless: - """Stands in for the generator of ``write_recording``: samples are 20 - times their expected count instead of Poisson draws.""" + """Stands in for the generator of write_recording. - def __init__(self, seed): + Samples are 20 + times their expected count instead of Poisson draws. + """ + + def __init__(self, seed: int) -> None: """Keep a real generator for the other draws.""" self._rng = np.random.Generator(np.random.PCG64(seed)) - def poisson(self, lam): - """The expected count, scaled to keep whole-number rounding small.""" + def poisson(self, lam: np.ndarray) -> np.ndarray: + """Return the expected count, scaled to keep whole-number rounding small. + + Parameters + ---------- + lam : np.ndarray + The expected counts. + + Returns + ------- + np.ndarray + 20 times lam, rounded. + """ return np.round(20 * lam) - def random(self, n): - """Uniform draws (which samples are invalid).""" + def random(self, n: int) -> np.ndarray: + """Draw uniform values (which samples are invalid). + + Parameters + ---------- + n : int + Number of draws. + + Returns + ------- + np.ndarray + The draws. + """ return self._rng.random(n) @pytest.fixture(scope="module") -def quiet_online_recording(tmp_path_factory): - """A noise-free recording whose online offsets move the DMD pattern: - what varies in its motion-corrected samples is motion-correction - error (as GIAnT-MATLAB's TestCompensatedExtraction).""" +def quiet_online_recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: + """Return a noise-free recording whose online offsets move the DMD pattern. + + What varies in its motion-corrected samples is motion-correction + error (as GIAnT-MATLAB's TestCompensatedExtraction). + + Returns + ------- + RasterLayout + The layout of the written recording. + """ from tests.registration import synthetic path = tmp_path_factory.mktemp("rec") / "quiet_DMD1-TRIAL000001.dat" @@ -115,7 +171,7 @@ def quiet_online_recording(tmp_path_factory): # ---------------------------------------------------------------- MATLAB -def test_movmean_matches_smoothdata(ref): +def test_movmean_matches_smoothdata(ref: dict) -> None: """Even, odd and fractional windows are placed as smoothdata's.""" x = ref["mm_x"] for w, want in zip(ref["mm_w"].ravel(), ref["mm_y"]): @@ -129,19 +185,20 @@ def test_movmean_matches_smoothdata(ref): assert np.isnan(movmean(np.full((1, 5), np.nan), 3)).all() -def test_medfilt3_and_labeled_pixels(ref): +def test_medfilt3_and_labeled_pixels(ref: dict) -> None: """medfilt2 is NaN wherever its window holds a NaN; zero padding.""" got = medfilt3(ref["med_in"]) np.testing.assert_array_equal(got, ref["med_out"]) - np.testing.assert_array_equal( - labeled_pixels(ref["med_in"]), ref["labeled"].astype(bool) - ) + np.testing.assert_array_equal(labeled_pixels(ref["med_in"]), ref["labeled"].astype(bool)) assert not labeled_pixels(np.full((4, 4), np.nan)).any() -def test_upsample_motion_matches_interp1_pchip(ref): - """pchip with extrapolation, as interp1; frames without motion left - out; one frame's motion used throughout.""" +def test_upsample_motion_matches_interp1_pchip(ref: dict) -> None: + """Check upsample_motion against interp1 with pchip. + + Pchip with extrapolation, as interp1; frames without motion left + out; one frame's motion used throughout. + """ x, y = ref["pchip_x"].ravel(), ref["pchip_y"].ravel() q = ref["pchip_q"].ravel() got = upsample_motion(x, y, q) @@ -158,20 +215,18 @@ def test_upsample_motion_matches_interp1_pchip(ref): upsample_motion(x, np.full(x.size, np.nan), q) -def test_upsample_discard_and_block_edges(ref): +def test_upsample_discard_and_block_edges(ref: dict) -> None: """A frame is discarded if either registered frame around it is.""" d = ref["disc_in"].ravel() > 0 want = ref["disc_out"].ravel() > 0 np.testing.assert_array_equal(upsample_discard(d, want.size), want) assert upsample_discard(np.array([True]), 4).all() assert not upsample_discard(np.array([False]), 4).any() - np.testing.assert_array_equal( - block_edges(5633, 600), ref["blocks"].ravel() - 1 - ) + np.testing.assert_array_equal(block_edges(5633, 600), ref["blocks"].ravel() - 1) np.testing.assert_array_equal(block_edges(10, 600), [0, 10]) -def test_frame_lines_are_ceil_of_matlab_colon(): +def test_frame_lines_are_ceil_of_matlab_colon() -> None: """``ceil(first:dt:last)``, with fractional line ranges.""" lines = frame_lines(1.0, 300974.0, 53.43333333333334) assert lines.size == 5633 and lines[0] == 1 @@ -179,22 +234,16 @@ def test_frame_lines_are_ceil_of_matlab_colon(): np.testing.assert_array_equal(frame_lines(2.5, 20.0, 4.0)[:3], [3, 7, 11]) -def test_roi_svd_trace_matches_matlab(ref): - """nansvd and the component choice of loadTrial.""" +def test_roi_svd_trace_matches_matlab(ref: dict) -> None: + """Check nansvd and the component choice of loadTrial.""" d = ref["svd_d"] u, s, v, bg = nansvd(d, 3, 10, 0.33) np.testing.assert_allclose(s, ref["svd_s"].ravel(), rtol=1e-8) np.testing.assert_allclose(bg, ref["svd_bg"], rtol=1e-12) - np.testing.assert_allclose( - (u * s) @ v.T, ref["svd_recon"], rtol=1e-6, atol=1e-8 - ) - np.testing.assert_allclose( - roi_svd_trace(d, 0.33), ref["svd_trace"].ravel(), rtol=1e-8 - ) + np.testing.assert_allclose((u * s) @ v.T, ref["svd_recon"], rtol=1e-6, atol=1e-8) + np.testing.assert_allclose(roi_svd_trace(d, 0.33), ref["svd_trace"].ravel(), rtol=1e-8) # a one-pixel ROI has one component; the others are padded - np.testing.assert_allclose( - roi_svd_trace(d[4:5], 0.33), ref["svd1_trace"].ravel(), rtol=1e-8 - ) + np.testing.assert_allclose(roi_svd_trace(d[4:5], 0.33), ref["svd1_trace"].ravel(), rtol=1e-8) u1, s1, _, _ = nansvd(d[4:5], 3, 10, 0.33) assert np.isnan(u1[:, 1:]).all() and np.all(s1[1:] == 0) # nothing usable: every pixel misses too many frames, or no data @@ -205,10 +254,12 @@ def test_roi_svd_trace_matches_matlab(ref): assert np.isnan(roi_svd_trace(sparse, 0.33)).all() -def test_nansvd_selects_until_the_choice_is_stable(): - """Rows and columns are left out until the choice no longer changes: - leaving a column out can bring a row back, and the rows and columns - kept each miss less than the threshold among the other kept ones.""" +def test_nansvd_selects_until_the_choice_is_stable() -> None: + """Check rows and columns are left out until the choice no longer changes. + + Leaving a column out can bring a row back, and the rows and columns + kept each miss less than the threshold among the other kept ones. + """ rng = np.random.default_rng(3) d = rng.standard_normal((8, 30)) + 5 d[0, :12] = np.nan # misses 40%: out, until ... @@ -223,28 +274,29 @@ def test_nansvd_selects_until_the_choice_is_stable(): assert np.isfinite(s).all() and np.isnan(bg[:, :6]).all() -@pytest.mark.parametrize( - "dtype, rtol", [(np.float64, 1e-12), (np.float32, 2e-6)] -) +@pytest.mark.parametrize("dtype, rtol", [(np.float64, 1e-12), (np.float32, 2e-6)]) @pytest.mark.parametrize("rows", [2, 512]) -def test_finish_pixels_matches_matlab(ref, dtype, rtol, rows): - """Discards, outliers and gap filling as at the end of loadTrial: a +def test_finish_pixels_matches_matlab( + ref: dict, dtype: type[np.floating], rtol: float, rows: int +) -> None: + """Check discards, outliers and gap filling as at the end of loadTrial. + + That is a pixel without samples, gaps longer than the window (15 passes over - everything), and the variance multiplier of filled samples.""" + everything), and the variance multiplier of filled samples. + """ y = ref["fin_y_in"].transpose(1, 0, 2).astype(dtype) # channels first finv = ref["fin_finv_in"].astype(dtype) discard = upsample_discard(ref["fin_discard_in"].ravel() > 0, y.shape[2]) np.testing.assert_array_equal(discard, ref["fin_discard"].ravel() > 0) assert int(ref["fin_passes"].ravel()[0]) == 15 finish_pixels(y, finv, discard, float(ref["fin_window"].ravel()[0]), rows) - np.testing.assert_allclose( - y, ref["fin_y"].transpose(1, 0, 2), rtol=rtol, atol=rtol - ) + np.testing.assert_allclose(y, ref["fin_y"].transpose(1, 0, 2), rtol=rtol, atol=rtol) np.testing.assert_allclose(finv, ref["fin_finv"], rtol=rtol) assert not np.isnan(y).any() and not np.isnan(finv).any() -def test_finish_pixels_without_gaps_changes_nothing(): +def test_finish_pixels_without_gaps_changes_nothing() -> None: """No discards and no missing samples: data and multiplier are kept.""" rng = np.random.default_rng(0) y = 5 + rng.random((2, 7, 40)) @@ -255,11 +307,14 @@ def test_finish_pixels_without_gaps_changes_nothing(): np.testing.assert_array_equal(finv, f0) -def test_finish_pixels_rejects_what_it_cannot_fill(): - """A window that reaches no frame ahead never fills a gap at the start +def test_finish_pixels_rejects_what_it_cannot_fill() -> None: + """Check that gaps that cannot be filled are errors. + + A window that reaches no frame ahead never fills a gap at the start (MATLAB's loop would not end), and without any sample there is no variance multiplier to give: both are errors. No pixels: nothing to - do.""" + do. + """ rng = np.random.default_rng(0) y = 5 + rng.random((2, 4, 30)) finv = 1 + rng.random((4, 30)) @@ -282,12 +337,24 @@ def test_finish_pixels_rejects_what_it_cannot_fill(): # ------------------------------------------------- frames, by definition -def raw_reference(layout, samples, times, dt, channels, shift=None): - """Num and Den images by the definition (slow loops). - - getImages' kernel without the lines exactly ``max(3 dt, P)`` from the - frame, invalid samples left out; ``shift(line) -> (dr, dc)`` moves a - line's samples. Returns ``(channels, frames, rows, cols)`` arrays. +def raw_reference( + layout: RasterLayout, + samples: np.ndarray, + times: np.ndarray, + dt: int, + channels: Sequence[int], + shift: Callable[[int], tuple[int, int]] | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Return the Num and Den images by the definition (slow loops). + + getImages' kernel without the lines exactly max(3 dt, P) from the + frame, invalid samples left out; shift(line) -> (dr, dc) moves a + line's samples. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The Num and the Den images, each a (channels, frames, rows, cols) array. """ p, total = layout.lines_per_cycle, layout.total_lines reach = max(3 * dt, p) @@ -301,9 +368,7 @@ def raw_reference(layout, samples, times, dt, channels, shift=None): sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) dr, dc = shift(ln) if shift else (0, 0) r, c = pr[sel] + dr, pc[sel] + dc - ok = ( - (r >= 0) & (r < layout.n_rows) & (c >= 0) & (c < layout.n_cols) - ) + ok = (r >= 0) & (r < layout.n_rows) & (c >= 0) & (c < layout.n_cols) for k, ch in enumerate(channels): x = samples[ch, sel, (ln - 1) // p].astype(float) use = ok & (x != -32768) @@ -312,11 +377,24 @@ def raw_reference(layout, samples, times, dt, channels, shift=None): return num, den -def frames_reference(num, den, trim_rows, trim_cols, r_d, c_d, m_r, m_c): - """slap2FramesAt's interpolation by the definition. - - ``num`` and ``den`` are whole-DMD sums. Returns ``(channels, points, - frames)`` values and ``(points, frames)`` variance multipliers. +def frames_reference( + num: np.ndarray, + den: np.ndarray, + trim_rows: np.ndarray, + trim_cols: np.ndarray, + r_d: np.ndarray, + c_d: np.ndarray, + m_r: np.ndarray, + m_c: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Compute slap2FramesAt's interpolation by the definition. + + num and den are whole-DMD sums. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + (channels, points, frames) values and (points, frames) variance multipliers. """ rows = slice(trim_rows[0] - 1, trim_rows[-1]) cols = slice(trim_cols[0] - 1, trim_cols[-1]) @@ -352,8 +430,17 @@ def frames_reference(num, den, trim_rows, trim_cols, r_d, c_d, m_r, m_c): return y, fq -def collect(parts): - """All parts of :func:`frames_at` as NumPy arrays.""" +def collect( + parts: Iterable[tuple[slice, torch.Tensor, torch.Tensor]], +) -> tuple[np.ndarray, np.ndarray]: + """Collect all parts of :func:`frames_at` as NumPy arrays. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The values (channels, points, frames) and the variance multipliers + (points, frames), the parts joined along the frames. + """ ys, fqs = [], [] for _, y, fq in parts: ys.append(y.numpy()) @@ -361,8 +448,14 @@ def collect(parts): return np.concatenate(ys, 2), np.concatenate(fqs, 1) -def raster_window(layout): - """One-based DMD rows and columns of the raster's bounding box.""" +def raster_window(layout: RasterLayout) -> tuple[np.ndarray, np.ndarray]: + """Return the one-based DMD rows and columns of the raster's bounding box. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The one-based DMD rows and the one-based DMD columns of the bounding box. + """ rows = (layout.slot_pixel - 1) // layout.n_cols + 1 cols = (layout.slot_pixel - 1) % layout.n_cols + 1 return ( @@ -371,9 +464,13 @@ def raster_window(layout): ) -def test_exclusive_boundary_and_pixel_sums(recording): - """The exclusive kernel leaves out the lines exactly max(3 dt, P) from - a frame; PixelFormer's sums are FrameFormer's, pixel by pixel.""" +def test_exclusive_boundary_and_pixel_sums( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], +) -> None: + """The exclusive kernel leaves out the lines exactly max(3 dt, P) from a frame. + + PixelFormer's sums are FrameFormer's, pixel by pixel. + """ layout, samples, _ = recording times, dt = np.array([30, 500, 1777, 3480]), 8 num, den = raw_reference(layout, samples, times, dt, [1, 0]) @@ -388,25 +485,23 @@ def test_exclusive_boundary_and_pixel_sums(recording): pixel = PixelFormer(layout, samples, 0, exclusive=True, band=band) ((shift, frames, p_num, p_den),) = pixel.pixel_sums(times, dt, [1, 0]) assert shift == (0, 0) and list(frames) == [0, 1, 2, 3] - np.testing.assert_allclose( - p_num.numpy(), s_num.numpy().transpose(0, 2, 1), rtol=1e-12 - ) - np.testing.assert_allclose( - p_den.numpy(), s_den.numpy().transpose(0, 2, 1), rtol=1e-12 - ) + np.testing.assert_allclose(p_num.numpy(), s_num.numpy().transpose(0, 2, 1), rtol=1e-12) + np.testing.assert_allclose(p_den.numpy(), s_den.numpy().transpose(0, 2, 1), rtol=1e-12) assert (samples == -32768).any() # some sums leave samples out -def test_pixel_sums_with_shifts_match_shifted_sums(online_recording): +def test_pixel_sums_with_shifts_match_shifted_sums( + online_recording: tuple[ + RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray] + ], +) -> None: """Grouped by displacement, as FrameFormer.shifted_sums.""" layout, samples, _, _ = online_recording offsets = line_offsets(layout, (1, layout.total_lines)) comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) times, dt = np.arange(900, 1500, 97), 8 args = (times, dt, comp.displacement) - want = list( - FrameFormer(layout, samples, 0, exclusive=True).shifted_sums(*args) - ) + want = list(FrameFormer(layout, samples, 0, exclusive=True).shifted_sums(*args)) got = list( PixelFormer(layout, samples, 0, exclusive=True).pixel_sums( times, dt, None, comp.displacement @@ -416,16 +511,21 @@ def test_pixel_sums_with_shifts_match_shifted_sums(online_recording): for (s0, f0, n0, d0), (s1, f1, n1, d1) in zip(want, got): assert s0 == s1 np.testing.assert_array_equal(f0, f1) - np.testing.assert_allclose( - n1.numpy(), n0.numpy().transpose(0, 2, 1), rtol=1e-12 - ) - np.testing.assert_allclose( - d1.numpy(), d0.numpy().transpose(0, 2, 1), rtol=1e-12 - ) + np.testing.assert_allclose(n1.numpy(), n0.numpy().transpose(0, 2, 1), rtol=1e-12) + np.testing.assert_allclose(d1.numpy(), d0.numpy().transpose(0, 2, 1), rtol=1e-12) -def view_points(layout, step=1): - """Whole-pixel points of a registered frame around the raster.""" +def view_points( + layout: RasterLayout, step: int = 1 +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Return whole-pixel points of a registered frame around the raster. + + Returns + ------- + tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + The one-based trimmed rows and columns of the raster, and the row and + column of each point. + """ trim_rows, trim_cols = raster_window(layout) r, c = np.meshgrid( np.arange(1 - MARGIN, trim_rows.size + MARGIN + 1, step), @@ -440,9 +540,13 @@ def view_points(layout, step=1): ) -def test_frames_at_matches_definition(recording): - """Frames at whole-pixel and at fractional points, with motion that - crosses whole pixels and takes points off the image.""" +def test_frames_at_matches_definition( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], +) -> None: + """Frames at whole-pixel and at fractional points match the definition. + + The motion crosses whole pixels and takes points off the image. + """ layout, samples, _ = recording trim_rows, trim_cols, r_d, c_d = view_points(layout, 2) times, dt = np.arange(200, 3300, 61), 8 @@ -455,22 +559,22 @@ def test_frames_at_matches_definition(recording): args = (layout, [0, 1], times, dt, trim_rows, trim_cols) for dr, dc in ((0.0, 0.0), (0.37, -0.21)): rq, cq = r_d + dr, c_d + dc - want = frames_reference( - num, den, trim_rows, trim_cols, rq, cq, m_r, m_c - ) + want = frames_reference(num, den, trim_rows, trim_cols, rq, cq, m_r, m_c) for whole in (True, False): - got = collect( - frames_at(*args, rq, cq, m_r, m_c, chunk=7, whole_pixels=whole) - ) + got = collect(frames_at(*args, rq, cq, m_r, m_c, chunk=7, whole_pixels=whole)) for g, w in zip(got, want): np.testing.assert_array_equal(np.isnan(g), np.isnan(w)) np.testing.assert_allclose(g, w, rtol=1e-10, atol=1e-12) assert np.isnan(want[0]).any() and not np.isnan(want[0]).all() -def test_frames_at_points_off_the_raster(recording): - """Points whose neighbours are all outside the image need no sample: - every value is missing.""" +def test_frames_at_points_off_the_raster( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], +) -> None: + """Points whose neighbours are all outside the image need no sample. + + Every value is missing. + """ layout, _, _ = recording trim_rows, trim_cols = raster_window(layout) r_d = np.array([-40.0, -41.0, trim_rows.size + 30.0]) @@ -513,9 +617,15 @@ def test_frames_at_points_off_the_raster(recording): assert y.shape == (2, 0, times.size) and fq.shape == (0, times.size) -def test_frames_at_compensated_matches_definition(online_recording): - """With compensation, each line's samples move by its online offset - relative to the block's reference, also past the trimmed raster.""" +def test_frames_at_compensated_matches_definition( + online_recording: tuple[ + RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray] + ], +) -> None: + """With compensation, each line's samples move by its online offset. + + The offset is relative to the block's reference, also past the trimmed raster. + """ layout, samples, _, _ = online_recording offsets = line_offsets(layout, (1, layout.total_lines)) comp = OnlineCompensation(offsets, offsets.median_xy, MAPPING) @@ -528,8 +638,14 @@ def test_frames_at_compensated_matches_definition(online_recording): pad = compensation_pad(comp_b, layout, times, dt) assert pad >= 1 and compensation_pad(None, layout, times, dt) == 0 - def shift(line): - """A line's displacement around the block's reference.""" + def shift(line: int) -> tuple[int, int]: + """Return a line's displacement around the block's reference. + + Returns + ------- + tuple[int, int] + The line's displacement in rows and in columns. + """ return ( int(offsets.y_eff[line - 1] - comp_b.ref_offset[1]), int(offsets.x[line - 1] - comp_b.ref_offset[0]), @@ -538,9 +654,7 @@ def shift(line): num, den = raw_reference(layout, samples, times, dt, [0, 1], shift) rows = np.arange(trim_rows[0] - pad, trim_rows[-1] + pad + 1) cols = np.arange(trim_cols[0] - pad, trim_cols[-1] + pad + 1) - want = frames_reference( - num, den, rows, cols, r_d + pad, c_d + pad, m_r - d_b[0], m_c - d_b[1] - ) + want = frames_reference(num, den, rows, cols, r_d + pad, c_d + pad, m_r - d_b[0], m_c - d_b[1]) got = collect( frames_at( layout, @@ -583,10 +697,17 @@ def shift(line): np.testing.assert_allclose(got[0][inner], other[0][inner], rtol=1e-9) -def test_compensation_helpers(online_recording): - """onlineCompensation: the motion to interpolate is the saved motion - plus each registered frame's offset; blocks take their median.""" - layout, _, _, (x, y, y_dmd) = online_recording +def test_compensation_helpers( + online_recording: tuple[ + RasterLayout, np.ndarray, np.ndarray, tuple[np.ndarray, np.ndarray, np.ndarray] + ], +) -> None: + """Check onlineCompensation. + + The motion to interpolate is the saved motion plus each registered frame's + offset; blocks take their median. + """ + layout, _, _, (x, _y, y_dmd) = online_recording ds = np.arange(100.0, 9000.0, 20.0) ref = np.array([2.0, 0.0]) fx = x[ds.astype(int) - 1].astype(float) @@ -608,9 +729,7 @@ def test_compensation_helpers(online_recording): "yLead": np.array([2.0, 6.0]), }, ) - comp, mot_r, mot_c = online_compensation( - alignment, layout, (100, 9000), 20 - ) + comp, mot_r, mot_c = online_compensation(alignment, layout, (100, 9000), 20) np.testing.assert_allclose(mot_r, alignment.motion_r + fy - ref[1]) np.testing.assert_allclose(mot_c, alignment.motion_c + fx - ref[0]) np.testing.assert_array_equal(comp.offsets.y_eff[99:9000], y_dmd[99:9000]) @@ -636,15 +755,26 @@ def test_compensation_helpers(online_recording): # ------------------------------------------------------- the whole loader -def loader_inputs(layout, truth, shift=(0.0, 0.0), ds_step=20): - """Alignment, maps and masks for loading a synthetic recording. +def loader_inputs( + layout: RasterLayout, + truth: np.ndarray, + shift: tuple[float, float] = (0.0, 0.0), + ds_step: int = 20, +) -> tuple[TrialAlignment, np.ndarray, np.ndarray, list[np.ndarray], np.ndarray, np.ndarray]: + """Build the alignment, maps and masks for loading a synthetic recording. The registered frame is the raster's bounding box with MARGIN pixels around it; registration's motion is the true motion at its frames. - Returns also the scene where the trial's ``shift`` reads each pixel of - the consensus canvas (``truth``); the mean image is its square / 20 + The scene returned is the one where the trial's shift reads each pixel of + the consensus canvas (truth); the mean image is its square / 20 (and half that in channel 2), so that it has dim and bright parts as a recording's, and differs from the data it normalizes. + + Returns + ------- + tuple[TrialAlignment, np.ndarray, np.ndarray, list[np.ndarray], np.ndarray, np.ndarray] + The alignment, the selected-pixel map, the mean image, the three ROI + masks, the discarded registered frames, and the scene. """ trim_rows, trim_cols = raster_window(layout) shape = (trim_rows.size + 2 * MARGIN, trim_cols.size + 2 * MARGIN) @@ -676,9 +806,7 @@ def loader_inputs(layout, truth, shift=(0.0, 0.0), ds_step=20): & (cc <= trim_cols[-1] - 1) ) image = np.full(canvas, np.nan) - image[inside] = map_coordinates( - scene(layout), [rr[inside], cc[inside]], order=1 - ) + image[inside] = map_coordinates(scene(layout), [rr[inside], cc[inside]], order=1) mean = np.stack([image**2 / 20, image**2 / 40], 2) roi_a = np.zeros(canvas, dtype=bool) roi_a[10:14, 12:17] = True @@ -691,16 +819,18 @@ def loader_inputs(layout, truth, shift=(0.0, 0.0), ds_step=20): return alignment, sel, mean, [roi_a, roi_b, roi_c], discard, image -def test_load_trial_follows_the_scene(recording, monkeypatch): - """Motion-corrected samples of a static scene are steady and equal the - scene at each pixel's position; traces, discards and filled samples - are as loadTrial makes them.""" +def test_load_trial_follows_the_scene( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """Motion-corrected samples of a static scene are steady and equal the scene there. + + That is the scene at each pixel's position; traces, discards and filled samples + are as loadTrial makes them. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) shift = (0.3, -0.4) - alignment, sel, mean, rois, discard, image = loader_inputs( - layout, truth, shift - ) + alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) params = TrialLoadParams(block_frames=37, baseline_window_s=0.2) first, last = 10.0, layout.total_lines - 30.5 td = load_trial( @@ -718,17 +848,13 @@ def test_load_trial_follows_the_scene(recording, monkeypatch): n_f = td.frame_lines.size assert td.y.shape == (2, sel.sum(), n_f) and td.y.dtype == np.float32 assert td.finv.shape == (sel.sum(), n_f) and td.photon_scale == 25.0 - np.testing.assert_array_equal( - td.frame_lines, frame_lines(first, last, 8.0) - ) + np.testing.assert_array_equal(td.frame_lines, frame_lines(first, last, 8.0)) np.testing.assert_array_equal(td.discard, upsample_discard(discard, n_f)) assert 0 < td.discard.sum() < 20 # pixels in MATLAB's column-major order of the map np.testing.assert_array_equal(td.pixel_rc, np.argwhere(sel.T)[:, ::-1]) np.testing.assert_allclose(td.trial_rc, td.pixel_rc + np.array(shift)) - want_r = upsample_motion( - alignment.ds_frames, alignment.motion_r, td.frame_lines - ) + want_r = upsample_motion(alignment.ds_frames, alignment.motion_r, td.frame_lines) np.testing.assert_allclose(td.motion_r, want_r + shift[0]) assert np.isfinite(td.y).all() and np.isfinite(td.finv).all() @@ -740,9 +866,7 @@ def test_load_trial_follows_the_scene(recording, monkeypatch): assert not filled[~never][:, ~td.discard].any() # 1000 times the mean over all samples, those of discarded frames too assert np.ptp(td.finv[filled]) == 0 - np.testing.assert_allclose( - td.finv[filled][0], 1000 * td.finv[~filled].mean(), rtol=5e-3 - ) + np.testing.assert_allclose(td.finv[filled][0], 1000 * td.finv[~filled].mean(), rtol=5e-3) keep = ~td.discard got = td.y[:, ~never][:, :, keep].astype(np.float64) * 25.0 @@ -769,18 +893,9 @@ def test_load_trial_follows_the_scene(recording, monkeypatch): for k, gain in enumerate((1.0, 0.5)): m = mean_v[..., k] want_g = gain * view[lab].sum() / m[lab].sum() * np.nansum(m) - np.testing.assert_allclose( - td.global_f[k, keep].mean(), want_g, rtol=0.05 - ) - want_r = ( - gain - * view[: shape[0], : shape[1]][ - rois[0][: shape[0], : shape[1]] - ].sum() - ) - np.testing.assert_allclose( - td.roi_f[0, k, keep].mean(), want_r, rtol=0.03 - ) + np.testing.assert_allclose(td.global_f[k, keep].mean(), want_g, rtol=0.05) + want_r = gain * view[: shape[0], : shape[1]][rois[0][: shape[0], : shape[1]]].sum() + np.testing.assert_allclose(td.roi_f[0, k, keep].mean(), want_r, rtol=0.03) np.testing.assert_allclose( td.roi_fsvd[0, k, keep].mean(), want_r / rois[0].sum(), rtol=0.03 ) @@ -802,18 +917,18 @@ def test_load_trial_follows_the_scene(recording, monkeypatch): ) np.testing.assert_allclose(td.y, one.y, rtol=2e-6, atol=1e-6) np.testing.assert_allclose(td.finv, one.finv, rtol=2e-6) - np.testing.assert_allclose( - td.global_f, one.global_f, rtol=1e-9, equal_nan=True - ) - np.testing.assert_allclose( - td.roi_fsvd, one.roi_fsvd, rtol=1e-7, equal_nan=True - ) + np.testing.assert_allclose(td.global_f, one.global_f, rtol=1e-9, equal_nan=True) + np.testing.assert_allclose(td.roi_fsvd, one.roi_fsvd, rtol=1e-7, equal_nan=True) + +def test_load_trial_with_a_general_warp( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """A callable warp is evaluated at every pixel. -def test_load_trial_with_a_general_warp(recording, monkeypatch): - """A callable warp is evaluated at every pixel: the same shift given as - a function gives the same data, and an affine map samples the scene at - the mapped positions.""" + The same shift given as a function gives the same data, and an affine map + samples the scene at the mapped positions. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth) @@ -824,8 +939,14 @@ def test_load_trial_with_a_general_warp(recording, monkeypatch): shift = (0.3, -0.4) rigid = load_trial(*args, RigidShift(*shift), *rest, dtype=np.float64) - def as_function(r, c): - """The shift as a general coordinate map.""" + def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return the shift as a general coordinate map. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The shifted rows and columns. + """ return r + shift[0], c + shift[1] general = load_trial(*args, as_function, *rest, dtype=np.float64) @@ -837,8 +958,14 @@ def as_function(r, c): a = np.array([[1.02, 0.015], [-0.01, 0.98]]) x0 = np.array([12.0, 17.0]) - def affine(r, c): - """A stretch and shear about the field's centre, plus a shift.""" + def affine(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return a stretch and shear about the field's centre, plus a shift. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The mapped rows and columns. + """ p = a @ (np.stack([r, c]) - x0[:, None]) + x0[:, None] return p[0] + 0.25, p[1] - 0.15 @@ -857,18 +984,18 @@ def affine(r, c): def test_load_trial_reads_selected_pixels_beyond_the_frame( - recording, monkeypatch -): - """The consensus frame may be larger than a trial's registered frame. A - selected pixel beyond the frame is read where the warp puts it: with a + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """The consensus frame may be larger than a trial's registered frame. + + A selected pixel beyond the frame is read where the warp puts it: with a shift of nine rows up it stays on the raster under the motion, and has - data.""" + data. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) shift = (-9.3, 0.2) - alignment, sel, mean, rois, discard, image = loader_inputs( - layout, truth, shift - ) + alignment, sel, mean, rois, discard, image = loader_inputs(layout, truth, shift) beyond = (alignment.view_shape[0] + 1, 5) assert sel[beyond] and np.isfinite(image[beyond]) args = (layout.files[0], 10.0, 3000.0, alignment, sel) @@ -878,12 +1005,16 @@ def test_load_trial_reads_selected_pixels_beyond_the_frame( np.testing.assert_allclose(td.trial_rc[k], np.add(beyond, shift)) keep = ~td.discard assert (td.finv[k, keep] < 100 * np.median(td.finv[k])).all() - np.testing.assert_allclose( - td.y[0, k, keep].mean() * 25.0, image[beyond], rtol=0.1 - ) + np.testing.assert_allclose(td.y[0, k, keep].mean() * 25.0, image[beyond], rtol=0.1) - def as_function(r, c): - """The shift as a general coordinate map.""" + def as_function(r: np.ndarray, c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return the shift as a general coordinate map. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The shifted rows and columns. + """ return r + shift[0], c + shift[1] general = load_trial(*args, as_function, *rest, dtype=np.float64) @@ -892,12 +1023,16 @@ def as_function(r, c): def test_recording_layout_is_read_once_per_file( - recording, monkeypatch, tmp_path -): - """Trials of one recording file (a continuous recording's line - ranges) read its layout once, also when loaded at the same time; a - changed file, another file or a missing one is read again; the loads - are the same as with a layout read every time.""" + recording: tuple[RasterLayout, np.ndarray, np.ndarray], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """Trials of one recording file read its layout once. + + These are a continuous recording's line ranges; they read it once also when + loaded at the same time; a changed file, another file or a missing one is + read again; the loads are the same as with a layout read every time. + """ import os import threading from concurrent.futures import ThreadPoolExecutor @@ -906,8 +1041,14 @@ def test_recording_layout_is_read_once_per_file( calls = [] lock = threading.Lock() - def counted(path): - """The fake layout, counting reads.""" + def counted(path: str | Path) -> RasterLayout: + """Return the fake layout, counting reads. + + Returns + ------- + RasterLayout + The fake layout. + """ with lock: calls.append(str(path)) return layout @@ -917,8 +1058,14 @@ def counted(path): rest = (discard, mean, rois, TrialLoadParams(baseline_window_s=0.2)) path = layout.files[0] - def load(first, last): - """One line range of the recording.""" + def load(first: float, last: float) -> TrialData: + """Load one line range of the recording. + + Returns + ------- + TrialData + The trial data of the line range. + """ return load_trial(path, first, last, alignment, sel, RigidShift(), *rest, dtype=np.float64) # fmt: skip @@ -967,18 +1114,20 @@ def load(first, last): def test_recording_layout_follows_segments_and_metadata( - recording, monkeypatch, tmp_path -): - """A CYCLE-split recording's layout is read again when a segment is - added or removed or its metadata changes, and the path as given is - part of the key (its name decides how the reader opens it).""" + recording: tuple[RasterLayout, np.ndarray, np.ndarray], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """A CYCLE-split recording's layout is read again when a segment is added or removed. + + It is also read again when its metadata changes, and the path as given is + part of the key (its name decides how the reader opens it). + """ import os layout = recording[0] calls = [] - monkeypatch.setattr( - trial_data, "raster_layout", lambda path: calls.append(path) or layout - ) + monkeypatch.setattr(trial_data, "raster_layout", lambda path: calls.append(path) or layout) folder = tmp_path / "split" folder.mkdir() first = folder / "rec_DMD1-TRIAL000001-CYCLE-000000.dat" @@ -1034,9 +1183,13 @@ def test_recording_layout_follows_segments_and_metadata( assert len(calls) == 8 # not the cached layout of folder/first -def test_load_trial_without_selected_pixels(recording, monkeypatch): - """No selected pixel, no ROI and no labeled pixel: empty data, and the - traces are missing. A selection that is never sampled is an error.""" +def test_load_trial_without_selected_pixels( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """No selected pixel, no ROI and no labeled pixel: empty data. + + The traces are missing. A selection that is never sampled is an error. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, _, discard, _ = loader_inputs(layout, truth) @@ -1053,29 +1206,31 @@ def test_load_trial_without_selected_pixels(recording, monkeypatch): load_trial(*args, margin, RigidShift(), discard, mean) -def test_load_trial_rejects_bad_inputs(recording, monkeypatch): +def test_load_trial_rejects_bad_inputs( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: """The activity channel and the mean image must fit the recording.""" layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) args = (layout.files[0], 10.0, 3000.0, alignment, sel, RigidShift()) with pytest.raises(ValueError, match="activity_channel"): - load_trial( - *args, discard, mean, rois, TrialLoadParams(activity_channel=3) - ) + load_trial(*args, discard, mean, rois, TrialLoadParams(activity_channel=3)) with pytest.raises(ValueError, match="2 channels"): load_trial(*args, discard, mean[..., :1], rois) for bad in (2.9, 1.0, True, "1"): # not cut to a channel below with pytest.raises(ValueError, match="must be an integer"): TrialLoadParams(activity_channel=bad).ordered_channels(2) - assert TrialLoadParams(activity_channel=np.int64(2)).ordered_channels( - 2 - ) == [1, 0] + assert TrialLoadParams(activity_channel=np.int64(2)).ordered_channels(2) == [1, 0] + +def test_load_trial_second_activity_channel( + recording: tuple[RasterLayout, np.ndarray, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """With activityChannel 2, channel 0 of the data is the file's second channel. -def test_load_trial_second_activity_channel(recording, monkeypatch): - """With activityChannel 2, channel 0 of the data is the file's second - channel; the global trace stays in the file's order.""" + The global trace stays in the file's order. + """ layout, _, truth = recording monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) alignment, sel, mean, rois, discard, _ = loader_inputs(layout, truth) @@ -1090,9 +1245,7 @@ def test_load_trial_second_activity_channel(recording, monkeypatch): dtype=np.float64, ) keep = ~one.discard - np.testing.assert_allclose( - two.global_f[:, keep], one.global_f[:, keep], rtol=0.02 - ) + np.testing.assert_allclose(two.global_f[:, keep], one.global_f[:, keep], rtol=0.02) # (the channels' invalid samples differ, and with them the shares of # the neighbours: equal on average, not sample by sample) np.testing.assert_allclose( @@ -1106,24 +1259,22 @@ def test_load_trial_second_activity_channel(recording, monkeypatch): def test_load_trial_after_compensated_registration( - quiet_online_recording, tmp_path, monkeypatch -): - """Registered with compensateOnline, the loader undoes the online - correction too: samples of the static, noise-free scene vary less than + quiet_online_recording: RasterLayout, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Registered with compensateOnline, the loader undoes the online correction too. + + Samples of the static, noise-free scene vary less than after an uncompensated registration, none is filled in, and the block - size does not show.""" + size does not show. + """ layout = quiet_online_recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) monkeypatch.setattr(trial_data, "raster_layout", lambda path: layout) spread, loaded = {}, {} for comp in (False, True): - params = multiroi.MultiRoiRegistrationParams( - maxshift=6, compensate_online=comp - ) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) adata = tmp_path / f"{comp}_ALIGNMENTDATA.h5" - multiroi.register_trial( - layout.files[0], 1, 6000, tmp_path / f"{comp}.tif", adata, params - ) + multiroi.register_trial(layout.files[0], 1, 6000, tmp_path / f"{comp}.tif", adata, params) alignment = read_alignment(adata) assert (alignment.compensation is not None) == comp assert alignment.view_shape == (20 + 12, 30 + 12) @@ -1132,9 +1283,7 @@ def test_load_trial_after_compensated_registration( mean = np.ones(alignment.view_shape + (2,)) discard = np.zeros(alignment.ds_frames.size, dtype=bool) args = (layout.files[0], 1, 6000, alignment, sel, RigidShift()) - td = load_trial( - *args, discard, mean, (), TrialLoadParams(block_frames=60) - ) + td = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=60)) y = td.y[0].astype(np.float64) spread[comp] = np.median(y.std(1)) / y.mean(1).std() loaded[comp] = (td, args, discard, mean) @@ -1146,16 +1295,16 @@ def test_load_trial_after_compensated_registration( assert spread[True] < 0.8 * spread[False] assert spread[True] < 0.06 td, args, discard, mean = loaded[True] - other = load_trial( - *args, discard, mean, (), TrialLoadParams(block_frames=100000) - ) + other = load_trial(*args, discard, mean, (), TrialLoadParams(block_frames=100000)) np.testing.assert_allclose(td.y, other.y, rtol=1e-5, atol=1e-6) np.testing.assert_allclose(td.finv, other.finv, rtol=1e-5) -def test_read_alignment_orientation(tmp_path): - """viewR and viewC are read in MATLAB's orientation from files written - column-major (MATLAB, GIAnT-Python) or row-major.""" +def test_read_alignment_orientation(tmp_path: Path) -> None: + """``viewR`` and viewC are read in MATLAB's orientation. + + The files are written column-major (MATLAB, GIAnT-Python) or row-major. + """ import h5py view_r = np.repeat(np.arange(-2.0, 5.0)[:, None], 4, 1) # 7 x 4 @@ -1181,7 +1330,7 @@ def test_read_alignment_orientation(tmp_path): assert a.align_hz == 80.0 and a.motion_c.shape == (5,) -def test_cuda_matches_cpu(recording): +def test_cuda_matches_cpu(recording: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: """Frames agree on CUDA and CPU (skipped without a GPU).""" if not torch.cuda.is_available(): pytest.skip("no CUDA device") @@ -1210,33 +1359,27 @@ def test_cuda_matches_cpu(recording): np.testing.assert_allclose(f0, f1, rtol=1e-9, equal_nan=True) -def test_leading_svd_gives_the_full_svds_leading_components(): - """The leading components from the Gram matrix are numpy's, up to - sign, for wide, tall and rank-deficient data; and the user-ROI trace - is the one the full decomposition gives.""" +def test_leading_svd_gives_the_full_svds_leading_components() -> None: + """The leading components from the Gram matrix are numpy's, up to sign. + + This holds for wide, tall and rank-deficient data; and the user-ROI trace + is the one the full decomposition gives. + """ from giant_python.extraction.raster import trial_data as td rng = np.random.default_rng(0) for shape in ((300, 500), (500, 300), (80, 80)): - low = rng.standard_normal((shape[0], 4)) @ rng.standard_normal( - (4, shape[1]) - ) + low = rng.standard_normal((shape[0], 4)) @ rng.standard_normal((4, shape[1])) x = 5 * low + rng.standard_normal(shape) u, s, vt = td.leading_svd(x, 3) u0, s0, vt0 = np.linalg.svd(x, full_matrices=False) np.testing.assert_allclose(s, s0[:3], rtol=1e-9) - np.testing.assert_allclose( - (u * s) @ vt, (u0[:, :3] * s0[:3]) @ vt0[:3], atol=1e-8 - ) + np.testing.assert_allclose((u * s) @ vt, (u0[:, :3] * s0[:3]) @ vt0[:3], atol=1e-8) thin = np.outer(rng.standard_normal(200), rng.standard_normal(300)) u, s, vt = td.leading_svd(thin, 3) # rank 1: falls back to the full SVD np.testing.assert_allclose((u * s) @ vt, thin, atol=1e-9) - d = ( - 3 - + rng.standard_normal((400, 600)) - + np.outer(np.ones(400), np.sin(np.arange(600) / 20)) - ) + d = 3 + rng.standard_normal((400, 600)) + np.outer(np.ones(400), np.sin(np.arange(600) / 20)) d[rng.random(d.shape) < 0.05] = np.nan fast = td.roi_svd_trace(d, 0.33) full = td.leading_svd @@ -1251,11 +1394,13 @@ def test_leading_svd_gives_the_full_svds_leading_components(): np.testing.assert_allclose(fast, slow, rtol=1e-7, atol=1e-9) -def test_leading_svd_uses_the_full_svd_at_tied_singular_values(): - """Where two of the leading singular values are equal, the data do not - determine how their components split, and an eigensolver may split them +def test_leading_svd_uses_the_full_svd_at_tied_singular_values() -> None: + """Where two of the leading singular values are equal, the full SVD is used. + + The data do not determine how their components split, and an eigensolver may split them otherwise than the SVD: the full SVD's components are returned, exactly, - for a tie at the last component asked for and for one among them.""" + for a tie at the last component asked for and for one among them. + """ from giant_python.extraction.raster import trial_data as td rng = np.random.default_rng(3) @@ -1278,14 +1423,14 @@ def test_leading_svd_uses_the_full_svd_at_tied_singular_values(): u, s, vt = td.leading_svd(x, 3) u0, s0, vt0 = np.linalg.svd(x, full_matrices=False) np.testing.assert_allclose(s, s0[:3], rtol=1e-12) - np.testing.assert_allclose( - (u * s) @ vt, (u0[:, :3] * s0[:3]) @ vt0[:3], atol=1e-12 - ) + np.testing.assert_allclose((u * s) @ vt, (u0[:, :3] * s0[:3]) @ vt0[:3], atol=1e-12) + +def test_leading_svd_and_nansvd_with_no_components() -> None: + """Zero components give empty arrays of the full SVD's shapes. -def test_leading_svd_and_nansvd_with_no_components(): - """Zero components give empty arrays of the full SVD's shapes, also for - data large enough for the Gram-matrix path.""" + This is also so for data large enough for the Gram-matrix path. + """ from giant_python.extraction.raster import trial_data as td rng = np.random.default_rng(5) @@ -1298,21 +1443,30 @@ def test_leading_svd_and_nansvd_with_no_components(): assert u.shape == (100, 0) and s.shape == (0,) and v.shape == (150, 0) -def test_leading_svd_accuracy_over_conditioning_and_types(): - """From well-conditioned data down to a third singular value 1e-6 of +def test_leading_svd_accuracy_over_conditioning_and_types() -> None: + """Check the accuracy from well-conditioned data to a nearly rank-deficient one. + + From well-conditioned data down to a third singular value 1e-6 of the first, the three leading components reconstruct what the full SVD's do, to 1e-10 of the largest singular value (1e-13 while the third is at least 1e-3 of the first), and the singular values agree ten times less closely; below 1e-7 and for float32 data the full SVD is used, so - the result is numpy's exactly.""" + the result is numpy's exactly. + """ from giant_python.extraction.raster import trial_data as td rng = np.random.default_rng(7) q_u, _ = np.linalg.qr(rng.standard_normal((400, 400))) q_v, _ = np.linalg.qr(rng.standard_normal((300, 300))) - def data(third): - """400 x 300 with singular values 1, 3 * third, third, then less.""" + def data(third: float) -> np.ndarray: + """Return 400 x 300 with singular values 1, 3 * third, third, then less. + + Returns + ------- + np.ndarray + The (400, 300) matrix. + """ tail = third * 0.5 * rng.random(297) s_true = np.r_[1.0, min(0.7, 3 * third), third, tail] return (q_u[:, :300] * np.sort(s_true)[::-1]) @ q_v.T diff --git a/tests/raster/test_raster_variance_interp.py b/tests/raster/test_raster_variance_interp.py index b91c8b92..5be4e2e3 100644 --- a/tests/raster/test_raster_variance_interp.py +++ b/tests/raster/test_raster_variance_interp.py @@ -1,6 +1,10 @@ -"""Tests for pooling-conserved kernel variance, projected SNR, clamped bicubic -resampling, pooling-deattenuated solver /sd, and discard-masked varFacDS.""" +"""Tests for pooling-conserved kernel variance and related resampling. +Covers projected SNR, clamped bicubic resampling, pooling-deattenuated solver /sd, and +discard-masked varFacDS. +""" + +from pathlib import Path from types import SimpleNamespace import h5py @@ -30,10 +34,12 @@ def test_kernel_variance_mode_tracks_scan_phase_and_preserves_pooling( - tmp_path, -): - """variance_mode='kernel' matches kappa_dt * F2 / F1^2 across scan phases - while remaining invariant to subpixel shifts (spatial ROI conservation).""" + tmp_path: Path, +) -> None: + """Check variance_mode='kernel' matches kappa_dt * F2 / F1^2 across scan phases. + + The variance also remains invariant to subpixel shifts (spatial ROI conservation). + """ path = tmp_path / "phase_DMD1-TRIAL000001.dat" layout = make_layout(path, n_cycles=80, seed=11) write_recording(layout, seed=12, invalid=0.0) @@ -50,20 +56,13 @@ def test_kernel_variance_mode_tracks_scan_phase_and_preserves_pooling( pix_c = (layout.slot_pixel - 1) % layout.n_cols + 1 grid = np.zeros((layout.n_rows + 2, layout.n_cols + 2), bool) grid[pix_r, pix_c] = True - ok2 = ( - grid[1:-2, 1:-2] - & grid[2:-1, 1:-2] - & grid[1:-2, 2:-1] - & grid[2:-1, 2:-1] - ) + ok2 = grid[1:-2, 1:-2] & grid[2:-1, 1:-2] & grid[1:-2, 2:-1] & grid[2:-1, 2:-1] rr, cc = np.nonzero(ok2) r_d = (rr[:4] + 1).astype(np.float64) c_d = (cc[:4] + 1).astype(np.float64) zeros = np.zeros(times.size) - ((_, _, fq_fresh),) = frames_at( - layout, [0], times, dt, trim_r, trim_c, r_d, c_d, zeros, zeros - ) + ((_, _, fq_fresh),) = frames_at(layout, [0], times, dt, trim_r, trim_c, r_d, c_d, zeros, zeros) ((_, _, fq_kern_int),) = frames_at( layout, [0], @@ -95,16 +94,13 @@ def test_kernel_variance_mode_tracks_scan_phase_and_preserves_pooling( f_half = fq_kern_half.numpy() assert np.isfinite(f_int).all() and (f_int > 0).all() # Exact analytical F2 / F1^2 * kappa_dt at integer shift for pixel 0 - s_slots = layout.slot_line[ - layout.slot_pixel == (int(r_d[0]) - 1) * layout.n_cols + int(c_d[0]) - ] + s_slots = layout.slot_line[layout.slot_pixel == (int(r_d[0]) - 1) * layout.n_cols + int(c_d[0])] reach = max(3 * dt, layout.lines_per_cycle) - 1 k_sc = _kernel_scale(dt, layout.lines_per_cycle, exclusive=True) want = [] for t in times: lines = ( - np.arange(layout.num_cycles)[:, None] * layout.lines_per_cycle - + s_slots[None, :] + np.arange(layout.num_cycles)[:, None] * layout.lines_per_cycle + s_slots[None, :] ).ravel() d = np.abs(lines - t) w = np.exp(-d[d <= reach] / dt) @@ -128,8 +124,7 @@ def test_kernel_variance_mode_tracks_scan_phase_and_preserves_pooling( for pid in corner_ids: sl = layout.slot_line[layout.slot_pixel == pid] lines = ( - np.arange(layout.num_cycles)[:, None] * layout.lines_per_cycle - + sl[None, :] + np.arange(layout.num_cycles)[:, None] * layout.lines_per_cycle + sl[None, :] ).ravel() d = np.abs(lines - t) w = np.exp(-d[d <= reach] / dt) @@ -139,23 +134,24 @@ def test_kernel_variance_mode_tracks_scan_phase_and_preserves_pooling( np.testing.assert_allclose(f_half[0], want_half, rtol=1e-10) -def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): - """snr_mode='projected' accounts for bilinear spatial covariance on +def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr() -> None: + """Check snr_mode='projected' handles spatial and temporal correlation. + + It accounts for bilinear spatial covariance on half-pixel patches and short-lag temporal correlation, whereas 'diagonal' - overestimates SNR on half-pixel patches by ~2x.""" + overestimates SNR on half-pixel patches by ~2x. + """ rng = np.random.default_rng(7) n_t = 3000 gh, gw = 7, 7 raw = rng.standard_normal((gh + 1, gw + 1, n_t + 2)) # Add 200 Hz-like temporal kernel correlation across adjacent frames - raw = ( - 0.25 * raw[:, :, :-2] + 1.0 * raw[:, :, 1:-1] + 0.25 * raw[:, :, 2:] - ) / np.sqrt(1.125) + raw = (0.25 * raw[:, :, :-2] + 1.0 * raw[:, :, 1:-1] + 0.25 * raw[:, :, 2:]) / np.sqrt(1.125) # Integer-aligned patch (f=0) vs half-pixel patch (f=0.5) of same raw noise noise_int = raw[:gh, :gw].reshape(gh * gw, n_t) - noise_half = ( - 0.25 * (raw[:-1, :-1] + raw[1:, :-1] + raw[:-1, 1:] + raw[1:, 1:]) - ).reshape(gh * gw, n_t) + noise_half = (0.25 * (raw[:-1, :-1] + raw[1:, :-1] + raw[:-1, 1:] + raw[1:, 1:])).reshape( + gh * gw, n_t + ) rr, cc = np.mgrid[0:gh, 0:gw] fp = np.exp(-((rr - 3) ** 2 + (cc - 3) ** 2) / (2 * 1.3**2)) @@ -169,7 +165,7 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): _, xn_d_int, snr_d_int = activity_noise( b + h @ x + noise_int, finv, b, h, x, tau, snr_mode="diagonal" ) - _, xn_d_half, snr_d_half = activity_noise( + _, _xn_d_half, snr_d_half = activity_noise( b + h @ x + noise_half, finv, b, h, x, tau, snr_mode="diagonal" ) _, xn_p_int, snr_p_int = activity_noise( @@ -182,19 +178,13 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): assert snr_d_half[0] > 1.6 * snr_d_int[0] # Projected captures spatial + temporal correlation -> patch-invariant SNR assert abs(snr_p_half[0] / snr_p_int[0] - 1.0) < 0.15 - assert ( - xn_p_int[0] > 1.15 * xn_d_int[0] - ) # temporal lag correlation included + assert xn_p_int[0] > 1.15 * xn_d_int[0] # temporal lag correlation included # White noise with negative mean residual (as after nonnegative x >= 0 fit) # must NOT be mistaken for positive temporal lag correlation white = rng.standard_normal((gh * gw, n_t)) - b_over = np.full( - (gh * gw, n_t), 5.35 - ) # positive baseline -> negative resid - _, xn_w_zero, _ = activity_noise( - 5.0 + h @ x + white, finv, b, h, x, tau, snr_mode="projected" - ) + b_over = np.full((gh * gw, n_t), 5.35) # positive baseline -> negative resid + _, xn_w_zero, _ = activity_noise(5.0 + h @ x + white, finv, b, h, x, tau, snr_mode="projected") _, xn_w_p, _ = activity_noise( 5.0 + h @ x + white, finv, b_over, h, x, tau, snr_mode="projected" ) @@ -206,9 +196,7 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): e0 = rng.standard_normal((gh * gw, n_t + 2)) lag2_only = (e0[:, :-2] + 0.8 * e0[:, 2:]) / np.sqrt(1.64) finv_gap = np.ones((gh * gw, n_t)) - finv_gap[:, 1::2] = ( - 1000.0 # odd frames discarded -> lag-1 pairs have 0 obs! - ) + finv_gap[:, 1::2] = 1000.0 # odd frames discarded -> lag-1 pairs have 0 obs! # With tau = 1.9, max_lag = 1: true lag-1 corr is 0, while compressed obs # array has lag-1 corr = 0.8 / 1.64 = 0.49! _, xn_gap_d, _ = activity_noise( @@ -237,12 +225,8 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): y_noisy = b + h @ x + noise_half x_ls = np.linalg.lstsq(h, y_noisy - b, rcond=None)[0] x_nnls = np.maximum(0.0, x_ls) - _, xn_fit_ls, _ = activity_noise( - y_noisy, finv, b, h, x_ls, tau, snr_mode="projected" - ) - _, xn_fit_nnls, _ = activity_noise( - y_noisy, finv, b, h, x_nnls, tau, snr_mode="projected" - ) + _, xn_fit_ls, _ = activity_noise(y_noisy, finv, b, h, x_ls, tau, snr_mode="projected") + _, xn_fit_nnls, _ = activity_noise(y_noisy, finv, b, h, x_nnls, tau, snr_mode="projected") assert abs(xn_fit_ls[0] / xn_p_half[0] - 1.0) < 0.08 assert abs(xn_fit_nnls[0] / xn_p_half[0] - 1.0) < 0.08 @@ -253,16 +237,14 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): peak_px = int(np.argmax(h[:, 0])) y_syn[peak_px, 200:500] = 5000.0 # huge synthetic fill at peak pixel only finv_syn[peak_px, 200:500] = 1000.0 - _, xn_syn, _ = activity_noise( - y_syn, finv_syn, b, h, x_nnls, tau, snr_mode="projected" - ) + _, xn_syn, _ = activity_noise(y_syn, finv_syn, b, h, x_nnls, tau, snr_mode="projected") assert abs(xn_syn[0] / xn_p_half[0] - 1.0) < 0.08 # Varying finv (3x range so 1/finv drops below 0.5x of 25th-pct ref) + # baseline offset must keep high-finv frames without biasing noise low finv_var = np.where(np.arange(n_t)[None, :] % 2 == 0, 0.5, 1.5) white_var = rng.standard_normal((gh * gw, n_t)) * np.sqrt(finv_var) - _, xn_var_d, _ = activity_noise( + _, _xn_var_d, _ = activity_noise( 5.0 + h @ x + white_var, finv_var, b, h, x, tau, snr_mode="diagonal" ) _, xn_var_zero, _ = activity_noise( @@ -277,9 +259,7 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): tau, snr_mode="projected", ) - true_sd = float( - np.sqrt(finv_var.mean() / ((h[:, 0] ** 2).sum() * float(tau))) - ) + true_sd = float(np.sqrt(finv_var.mean() / ((h[:, 0] ** 2).sum() * float(tau)))) assert abs(xn_var_zero[0] / true_sd - 1.0) < 0.08 assert abs(xn_var_off[0] / xn_var_zero[0] - 1.0) < 0.08 @@ -292,21 +272,17 @@ def test_projected_snr_is_invariant_to_subpixel_phase_and_temporal_corr(): x2 = np.zeros((2, n_t)) finv_col = np.ones((gh * gw, n_t)) finv_col[10:12, 5] = 1000.0 # frame 5 drops pixels 10..11 -> collinear! - _, xn_col_clean, _ = activity_noise( - b + noise_half, finv, b, h2, x2, tau, snr_mode="projected" - ) - _, xn_col_p, _ = activity_noise( - b + noise_half, finv_col, b, h2, x2, tau, snr_mode="projected" - ) - _, xn_col_d, _ = activity_noise( - b + noise_half, finv_col, b, h2, x2, tau, snr_mode="diagonal" - ) + _, xn_col_clean, _ = activity_noise(b + noise_half, finv, b, h2, x2, tau, snr_mode="projected") + _, xn_col_p, _ = activity_noise(b + noise_half, finv_col, b, h2, x2, tau, snr_mode="projected") + _, xn_col_d, _ = activity_noise(b + noise_half, finv_col, b, h2, x2, tau, snr_mode="diagonal") assert np.allclose(xn_col_p, xn_col_clean, rtol=0.02) assert (xn_col_p > 1.12 * xn_col_d).all() -def test_estimate_photon_scale_deattenuation(): - """estimate_photon_scale recovers true per-sample gain from kernel-formed +def test_estimate_photon_scale_deattenuation() -> None: + """Check estimate_photon_scale recovers the true per-sample gain. + + It recovers the gain from kernel-formed noise for both kernel and freshness modes, ignoring filled and NaN frames. """ rng = np.random.default_rng(13) @@ -315,9 +291,7 @@ def test_estimate_photon_scale_deattenuation(): n_lines = n_cycles * p_cyc true_gain = 4.0 # Include dim background pixels (for 5th-percentile vb) + bright pixels - means = np.concatenate( - [np.full(15, 0.05), np.linspace(5.0, 40.0, n_px - 15)] - ) + means = np.concatenate([np.full(15, 0.05), np.linspace(5.0, 40.0, n_px - 15)]) # 4 corner raw pixel streams per pixel at half-pixel shift (0.5, 0.5) raw_corners = means[:, None, None] + np.sqrt( true_gain * means[:, None, None] @@ -354,33 +328,27 @@ def test_estimate_photon_scale_deattenuation(): y[:, -15:] = means[:, None] raw_est = estimate_photon_scale(y, finv_fresh) - est_kern = estimate_photon_scale( - y, finv_kern, q_spatial=q_sp, kernel_scale=k_kern - ) - est_fresh = estimate_photon_scale( - y, finv_fresh, q_spatial=q_sp, kernel_scale=k_fresh - ) + est_kern = estimate_photon_scale(y, finv_kern, q_spatial=q_sp, kernel_scale=k_kern) + est_fresh = estimate_photon_scale(y, finv_fresh, q_spatial=q_sp, kernel_scale=k_fresh) assert np.isfinite(est_kern) and np.isfinite(est_fresh) assert raw_est < 0.25 * true_gain assert 0.78 * true_gain < est_kern < 1.22 * true_gain assert 0.78 * true_gain < est_fresh < 1.22 * true_gain -def test_cubic_clamped_preserves_peaks_without_negative_ringing(): - """interp2_cubic_clamped and sample_spatial('cubic_clamped') preserve +def test_cubic_clamped_preserves_peaks_without_negative_ringing() -> None: + """Check clamped cubic interpolation preserves peaks. + + interp2_cubic_clamped and sample_spatial('cubic_clamped') preserve dendritic Gaussian peaks at half-pixel shifts without negative overshoot. """ rr, cc = np.mgrid[0:15, 0:15].astype(np.float64) - gauss = 100.0 * np.exp( - -((rr - 7.5) ** 2 + (cc - 7.5) ** 2) / (2 * 1.33**2) - ) + gauss = 100.0 * np.exp(-((rr - 7.5) ** 2 + (cc - 7.5) ** 2) / (2 * 1.33**2)) # Evaluate right at the true continuous peak (7.5, 7.5) from integer grid v_lin = float(interp2_linear(gauss, 7.5, 7.5)) v_clamped = float(interp2_cubic_clamped(gauss, 7.5, 7.5)) assert v_lin < 88.0 # >12% peak droop under bilinear - assert ( - v_clamped > 96.0 - ) # Keys' bicubic reconstructs >96% of subpixel peak! + assert v_clamped > 96.0 # Keys' bicubic reconstructs >96% of subpixel peak! # Off-peak shoulder: cubic_clamped recovers curvature better than linear s_true = float(100.0 * np.exp(-(1.0**2) / (2 * 1.33**2))) s_lin = float(interp2_linear(gauss, 6.5, 7.5)) @@ -397,29 +365,26 @@ def test_cubic_clamped_preserves_peaks_without_negative_ringing(): # sample_spatial on 3-D stack with NaN border fallback stack = np.broadcast_to(imp[None], (4, 12, 12)).copy() stack[:, 0, :] = np.nan - pts = np.array( - [[4.5, 6.0], [1.5, 6.0]] - ) # second point's 4x4 touches row 0 NaN + pts = np.array([[4.5, 6.0], [1.5, 6.0]]) # second point's 4x4 touches row 0 NaN s_cub, _ = sample_spatial(stack, pts, method="cubic") s_cl, _ = sample_spatial(stack, pts, method="cubic_clamped") s_ln, _ = sample_spatial(stack, pts, method="linear") assert (s_cub[0] < -1.0).all() and (s_cl[0] >= 0.0).all() np.testing.assert_allclose(s_cl[1], s_ln[1]) - w = warp_trial_image( - imp, TrialWarp.from_shifts([[0.5, 0.5]]), 0, "cubic_clamped" - ) + w = warp_trial_image(imp, TrialWarp.from_shifts([[0.5, 0.5]]), 0, "cubic_clamped") assert np.nanmin(w) >= 0.0 # Unaligned trial with NaN warp coordinates returns NaNs without IndexError - w_nan = warp_trial_image( - imp, TrialWarp.from_shifts([[np.nan, np.nan]]), 0, "cubic_clamped" - ) + w_nan = warp_trial_image(imp, TrialWarp.from_shifts([[np.nan, np.nan]]), 0, "cubic_clamped") assert np.isnan(w_nan).all() -def test_apply_trial_sd_finv_and_discard_masked_read_varfac(tmp_path): - """apply_trial_sd_finv scales finv by pooling-deattenuated /sd without +def test_apply_trial_sd_finv_and_discard_masked_read_varfac(tmp_path: Path) -> None: + """Check apply_trial_sd_finv scales finv and excludes discarded frames. + + apply_trial_sd_finv scales finv by pooling-deattenuated /sd without losing 200 Hz temporal modulation; read_varfac and apply_trial_sd_finv - both exclude motion-discarded frames.""" + both exclude motion-discarded frames. + """ rng = np.random.default_rng(21) n80, rows, cols = 400, 10, 12 adata = tmp_path / "E1T1DMD1_ALIGNMENTDATA.h5" @@ -461,12 +426,8 @@ def test_apply_trial_sd_finv_and_discard_masked_read_varfac(tmp_path): spatial_interp="cubic_clamped", ) finv0 = np.array([[1.0, 2.0, 1.5], [1.0, 2.0, 1.5]], dtype=np.float64) - trial_spike = SimpleNamespace( - trial_rc=rc, photon_scale=25.0, finv=finv0.copy() - ) - assert apply_trial_sd_finv( - trial_spike, base_h5, adata, tb, spatial_interp="cubic_clamped" - ) + trial_spike = SimpleNamespace(trial_rc=rc, photon_scale=25.0, finv=finv0.copy()) + assert apply_trial_sd_finv(trial_spike, base_h5, adata, tb, spatial_interp="cubic_clamped") assert tb.identity.get("has_sd") is True # Compare against identical clean file with no spike on frames 200..201 with h5py.File(adata, "r+") as f: @@ -482,37 +443,30 @@ def test_apply_trial_sd_finv_and_discard_masked_read_varfac(tmp_path): 25.0, spatial_interp="cubic_clamped", ) - trial_clean = SimpleNamespace( - trial_rc=rc, photon_scale=25.0, finv=finv0.copy() - ) + trial_clean = SimpleNamespace(trial_rc=rc, photon_scale=25.0, finv=finv0.copy()) assert apply_trial_sd_finv( trial_clean, base_h5, adata, tb_clean, spatial_interp="cubic_clamped" ) # Discarded frames 200..201 must not bias scale relative to clean data! np.testing.assert_allclose(trial_spike.finv, trial_clean.finv, rtol=1e-3) # Row 3 had 2x SD -> 4x finv relative to row 6, keeping 200 Hz ratios - np.testing.assert_allclose( - trial_spike.finv[0] / trial_spike.finv[1], 4.0, rtol=0.05 - ) - np.testing.assert_allclose( - trial_spike.finv[0] / trial_spike.finv[0, 0], [1.0, 2.0, 1.5] - ) + np.testing.assert_allclose(trial_spike.finv[0] / trial_spike.finv[1], 4.0, rtol=0.05) + np.testing.assert_allclose(trial_spike.finv[0] / trial_spike.finv[0, 0], [1.0, 2.0, 1.5]) -def test_shorth_center_exact_m_window_and_final_window(): - """_shorth_center scores exact m-element windows including the final - window.""" +def test_shorth_center_exact_m_window_and_final_window() -> None: + """Check _shorth_center scores the final window. + + _shorth_center scores exact m-element windows including the final + window. + """ from giant_python.extraction.raster.solver_baseline import _shorth_center low = np.array( - [0.0 + 0.01 * k for k in range(8)] - + [100.0 + 0.001 * k for k in range(7)] - + [101.0] + [0.0 + 0.01 * k for k in range(8)] + [100.0 + 0.001 * k for k in range(7)] + [101.0] ) assert np.isclose(_shorth_center(low), 0.035) high = np.array( - [0.0] - + [0.5 + 0.001 * k for k in range(7)] - + [200.0 + 0.0001 * k for k in range(8)] + [0.0] + [0.5 + 0.001 * k for k in range(7)] + [200.0 + 0.0001 * k for k in range(8)] ) assert np.isclose(_shorth_center(high), 200.00035) diff --git a/tests/raster/test_raster_wmf.py b/tests/raster/test_raster_wmf.py index 35397647..e486b818 100644 --- a/tests/raster/test_raster_wmf.py +++ b/tests/raster/test_raster_wmf.py @@ -29,21 +29,39 @@ _FIXTURE = Path(__file__).parent / "data" / "matlab_wmf.h5" -def _grid_at(first, stop, step): - """Return the off-centre Cartesian grid in MATLAB's source order.""" +def _grid_at(first: float, stop: float, step: float) -> np.ndarray: + """Return the off-centre Cartesian grid in MATLAB's source order. + + Returns + ------- + np.ndarray + Source positions (sources, 2) as (row, column), in MATLAB's source order. + """ axis = np.arange(first, stop, step) rows, cols = np.meshgrid(axis, axis, indexing="ij") return np.column_stack((rows.ravel("F"), cols.ravel("F"))) + [0.3, -0.2] -def _grid(): - """Place 24 sources on a 16 px grid with its central position free.""" +def _grid() -> np.ndarray: + """Place 24 sources on a 16 px grid with its central position free. + + Returns + ------- + np.ndarray + Source positions (24, 2) as (row, column). + """ src = _grid_at(15, 80, 16) return src[np.hypot(src[:, 0] - 47, src[:, 1] - 47) >= 1] -def _gaussian(center, sigma): - """Sample a unit-height Gaussian with independent row and column widths.""" +def _gaussian(center: np.ndarray, sigma: tuple[float, float]) -> np.ndarray: + """Sample a unit-height Gaussian with independent row and column widths. + + Returns + ------- + np.ndarray + The Gaussian sampled on the (96, 96) image grid. + """ return np.exp( -( (_ROWS - center[0]) ** 2 / (2 * sigma[0] ** 2) @@ -53,9 +71,20 @@ def _gaussian(center, sigma): def _simulate( - src, amp=1, n_trials=_N_TRIALS, sigma=(1.2, 1.2), seed=0, surround=False -): - """Simulate Gaussian sources on unit-SD, row-correlated noise.""" + src: np.ndarray, + amp: float | np.ndarray = 1, + n_trials: int = _N_TRIALS, + sigma: tuple[float, float] = (1.2, 1.2), + seed: int = 0, + surround: bool = False, +) -> np.ndarray: + """Simulate Gaussian sources on unit-SD, row-correlated noise. + + Returns + ------- + np.ndarray + Simulated trial images (trials, rows, columns). + """ rng = np.random.default_rng(seed) patches = np.array([_gaussian(center, sigma) for center in src]) if surround: @@ -64,9 +93,7 @@ def _simulate( for t in range(n_trials): noise = rng.standard_normal((_SHAPE[0], _SHAPE[1] + 2)) # conv2(noise, [1 2 1] / sqrt(6), 'valid'). - image = (noise[:, :-2] + 2 * noise[:, 1:-1] + noise[:, 2:]) / np.sqrt( - 6 - ) + image = (noise[:, :-2] + 2 * noise[:, 1:-1] + noise[:, 2:]) / np.sqrt(6) heights = _AMP * np.asarray(amp) * (0.5 + rng.random(len(src))) for height, patch in zip(heights, patches): image += height * patch @@ -74,28 +101,56 @@ def _simulate( return act -def _with_elongated_source(n_trials=_N_TRIALS, grid_amp=1, blob_amp=2, seed=0): - """Add one elongated source of constant brightness to the isolated grid.""" +def _with_elongated_source( + n_trials: int = _N_TRIALS, grid_amp: float = 1, blob_amp: float = 2, seed: int = 0 +) -> np.ndarray: + """Add one elongated source of constant brightness to the isolated grid. + + Returns + ------- + np.ndarray + Simulated trial images (trials, rows, columns) of the grid plus the elongated source. + """ act = _simulate(_grid(), grid_amp, n_trials, seed=seed) return act + blob_amp * _AMP * _gaussian(_ELONGATED, (1.1, 3)) -def _find(act, deblend_th=8, mask=None): - """Use the threshold and coverage defaults in TestFindSourcesWMF.""" +def _find( + act: np.ndarray, deblend_th: float = 8, mask: np.ndarray | None = None +) -> tuple[np.ndarray, dict]: + """Use the threshold and coverage defaults in TestFindSourcesWMF. + + Returns + ------- + tuple[np.ndarray, dict] + The seeds and the diagnostics returned by :func:`find_sources_wmf`. + """ return find_sources_wmf(act, 5, 3, deblend_th, 0.33, mask) -def _distance(seeds, center): - """Return the Euclidean distance from each seed to one centre.""" +def _distance(seeds: np.ndarray, center: np.ndarray) -> np.ndarray: + """Return the Euclidean distance from each seed to one centre. + + Returns + ------- + np.ndarray + The distance from each seed to center. + """ return np.hypot(seeds[:, 0] - center[0], seeds[:, 1] - center[1]) -def _nearest(sources, seeds): - """Return the distance from each source to its nearest seed.""" +def _nearest(sources: np.ndarray, seeds: np.ndarray) -> np.ndarray: + """Return the distance from each source to its nearest seed. + + Returns + ------- + np.ndarray + The distance of each source to its nearest seed (infinite without seeds). + """ return np.array([_distance(seeds, s).min(initial=np.inf) for s in sources]) -def test_finds_isolated_sources(): +def test_finds_isolated_sources() -> None: """Each isolated source has one seed within 1 px, ordered by strength.""" src = _grid() seeds, info = _find(_simulate(src)) @@ -105,7 +160,7 @@ def test_finds_isolated_sources(): assert (np.diff(info["value"]) <= 0).all() -def test_elongated_source_gives_one_seed(): +def test_elongated_source_gives_one_seed() -> None: """The dip test leaves one seed within 1 px of an elongated centre.""" seeds, _ = _find(_with_elongated_source(), deblend_th=np.inf) d = _distance(seeds, _ELONGATED) @@ -113,7 +168,7 @@ def test_elongated_source_gives_one_seed(): assert d[d < 6].item() < 1 -def test_deblending_keeps_seeds_on_elongated_source(): +def test_deblending_keeps_seeds_on_elongated_source() -> None: """Fitted seeds stay on the elongated source and near its centre.""" seeds, info = _find(_with_elongated_source()) d = _distance(seeds, _ELONGATED) @@ -125,7 +180,7 @@ def test_deblending_keeps_seeds_on_elongated_source(): assert info["added"].sum() == near.sum() - 1 -def test_deblending_resolves_close_pair(): +def test_deblending_resolves_close_pair() -> None: """A reproducible residual splits the close pair and preserves its grid.""" src = _grid() pair = np.array([[47.3, 46.2], [47.3, 48.2]]) @@ -141,12 +196,11 @@ def test_deblending_resolves_close_pair(): @pytest.mark.filterwarnings("error::scipy.sparse.linalg.MatrixRankWarning") -def test_deblending_with_unmeasured_half_keeps_fit_without_additions(): +def test_deblending_with_unmeasured_half_keeps_fit_without_additions() -> None: """An empty half vetoes residual seeds and has zero fit amplitudes.""" y, x = np.mgrid[:32, :32] signal = 40 * ( - np.exp(-((y - 16) ** 2 + (x - 15) ** 2) / 2) - + np.exp(-((y - 16) ** 2 + (x - 17) ** 2) / 2) + np.exp(-((y - 16) ** 2 + (x - 15) ** 2) / 2) + np.exp(-((y - 16) ** 2 + (x - 17) ** 2) / 2) ) act = signal + np.random.default_rng(0).normal(size=(5, 32, 32)) for offset in range(3): @@ -157,12 +211,10 @@ def test_deblending_with_unmeasured_half_keeps_fit_without_additions(): assert len(seeds) == len(initial) == 1 assert not np.allclose(seeds, initial) np.testing.assert_array_equal(info["added"], [False]) - np.testing.assert_array_equal( - _ridge_ls(csc_matrix((0, 1)), np.empty(0)), [0.0] - ) + np.testing.assert_array_equal(_ridge_ls(csc_matrix((0, 1)), np.empty(0)), [0.0]) -def test_fallback_kernel_keeps_row_and_column_widths(): +def test_fallback_kernel_keeps_row_and_column_widths() -> None: """Paired anisotropic sources yield a wider fallback along columns.""" src = _grid_at(13, 74, 20) paired = np.vstack((src, src + [0, 5])) @@ -172,7 +224,7 @@ def test_fallback_kernel_keeps_row_and_column_widths(): assert (k * x**2).sum() / (k * y**2).sum() > 1.5 -def test_unimaged_pixels(): +def test_unimaged_pixels() -> None: """Unimaged columns and the half-imaged band have no seeds.""" src = _grid() act = _simulate(src) @@ -185,7 +237,7 @@ def test_unimaged_pixels(): assert _nearest(src[keep], seeds).max() < 1 -def test_source_active_in_one_trial_is_dropped(): +def test_source_active_in_one_trial_is_dropped() -> None: """A strong event present in just one trial has no seed.""" act = _simulate(_grid()) center = np.array([47, 47]) @@ -194,7 +246,7 @@ def test_source_active_in_one_trial_is_dropped(): assert _distance(seeds, center).min() > 3 -def test_one_trial_peak_does_not_suppress_neighbour(): +def test_one_trial_peak_does_not_suppress_neighbour() -> None: """A one-trial peak cannot suppress a persistent neighbour.""" src = _grid() neighbor = _ELONGATED + [0, 4.5] @@ -205,13 +257,11 @@ def test_one_trial_peak_does_not_suppress_neighbour(): assert _distance(seeds, neighbor).min() > 2 -def test_excluded_peak_does_not_suppress_neighbour(): +def test_excluded_peak_does_not_suppress_neighbour() -> None: """An excluded strong peak leaves its weaker neighbour seeded.""" src = _grid() adjacent = _ELONGATED + [0, 4.5] - act = _simulate( - np.vstack((src, _ELONGATED, adjacent)), np.r_[np.ones(len(src)), 3, 1] - ) + act = _simulate(np.vstack((src, _ELONGATED, adjacent)), np.r_[np.ones(len(src)), 3, 1]) mask = np.hypot(_ROWS - _ELONGATED[0], _COLS - _ELONGATED[1]) <= 1.5 for threshold in (np.inf, 8): seeds, _ = _find(act, deblend_th=threshold, mask=mask) @@ -221,7 +271,7 @@ def test_excluded_peak_does_not_suppress_neighbour(): assert _nearest(src, seeds).max() < 1 -def test_flat_and_sparse_trials(): +def test_flat_and_sparse_trials() -> None: """Flat and sparse trials preserve finite scores and the original seeds.""" src = _grid() act = _simulate(src, n_trials=4) @@ -236,7 +286,7 @@ def test_flat_and_sparse_trials(): assert _nearest(ref, seeds).max() < 1 -def test_no_background_to_measure_noise(): +def test_no_background_to_measure_noise() -> None: """Fully active coverage leaves the noise autocorrelation white.""" act = _simulate(_grid_at(44, 55, 5), 8, sigma=(0.8, 0.8)) mask = np.zeros(_SHAPE, dtype=bool) @@ -247,7 +297,7 @@ def test_no_background_to_measure_noise(): assert np.isfinite(info["F"][mask]).all() -def test_no_seed_on_unimaged_pixel(): +def test_no_seed_on_unimaged_pixel() -> None: """A seed over a gap falls back to an imaged neighbour.""" src = _grid() center = np.array([47, 47]) @@ -259,7 +309,7 @@ def test_no_seed_on_unimaged_pixel(): assert _distance(seeds, center).min() < 1.5 -def test_negative_surround_falls_back_to_gaussian(): +def test_negative_surround_falls_back_to_gaussian() -> None: """Zero-integral sources yield a centred kernel and recover the grid.""" src = _grid() seeds, info = _find(_simulate(src, sigma=(1, 1), surround=True)) @@ -268,7 +318,7 @@ def test_negative_surround_falls_back_to_gaussian(): @pytest.mark.parametrize("n_trials", [1, 2, 3]) -def test_few_trials(n_trials): +def test_few_trials(n_trials: int) -> None: """Few trials seed each strong source and the elongated source once.""" src = _grid() act = _with_elongated_source(n_trials, grid_amp=4, blob_amp=8) @@ -278,7 +328,7 @@ def test_few_trials(n_trials): assert len(seeds) == len(src) + 1 -def test_no_imaged_pixels(): +def test_no_imaged_pixels() -> None: """All-NaN and zero-trial stacks return empty two-column seed arrays.""" seeds, info = _find(np.full((4, *_SHAPE), np.nan)) assert seeds.shape == (0, 2) @@ -287,7 +337,7 @@ def test_no_imaged_pixels(): assert seeds.shape == (0, 2) -def test_equal_candidates_follow_matlab_find_order(): +def test_equal_candidates_follow_matlab_find_order() -> None: """Tied maxima retain column-major order after sorting.""" f = np.zeros((5, 6)) f[1, 3] = f[3, 1] = 5 @@ -296,7 +346,7 @@ def test_equal_candidates_follow_matlab_find_order(): np.testing.assert_array_equal(got, [[3, 1, 5], [1, 3, 5]]) -def test_partial_nan_dip_requires_measured_half_endpoints(): +def test_partial_nan_dip_requires_measured_half_endpoints() -> None: """Interior NaNs allow a dip if the half has both measured endpoints.""" f = np.zeros((7, 9)) f[2, 2:7] = [10, np.nan, 1, 7, 8] @@ -304,12 +354,10 @@ def test_partial_nan_dip_requires_measured_half_endpoints(): np.testing.assert_array_equal(_keep_candidates(cand, f, (f, f), 3), cand) half = f.copy() half[2, 6] = np.nan - np.testing.assert_array_equal( - _keep_candidates(cand, f, (f, half), 3), cand[:1] - ) + np.testing.assert_array_equal(_keep_candidates(cand, f, (f, half), 3), cand[:1]) -def test_empty_trial_and_activity_padding(): +def test_empty_trial_and_activity_padding() -> None: """An empty trial counts toward missing coverage and skips zero padding.""" act = np.full((4, 11, 13), np.nan) act[:3, 5, 6] = 1 @@ -321,7 +369,7 @@ def test_empty_trial_and_activity_padding(): assert np.isnan(_combine_trials(z_t, 0.24)[5, 6]) -def test_empirical_kernel_uses_matlab_asymmetric_border(): +def test_empirical_kernel_uses_matlab_asymmetric_border() -> None: """Flipping the fifth isolated source across the frame changes K.""" z = np.zeros((50, 60)) for r, c in ((5, 12), (18, 12), (18, 32), (34, 12), (34, 32)): @@ -335,10 +383,8 @@ def test_empirical_kernel_uses_matlab_asymmetric_border(): assert _source_kernel(z[::-1], 4)[3, 3] > 0 -@pytest.mark.parametrize( - "case", ["fallback_kernel", "islands_nan", "three_trials", "real_crop"] -) -def test_matches_matlab_reference(case): +@pytest.mark.parametrize("case", ["fallback_kernel", "islands_nan", "three_trials", "real_crop"]) +def test_matches_matlab_reference(case: str) -> None: """Ordered seeds, scores, trial counts, flags and images match MATLAB.""" with h5py.File(_FIXTURE) as f: act, mask, params, out, _ = load_case(f[case]) @@ -349,28 +395,23 @@ def test_matches_matlab_reference(case): for key in ("K", "R", "value", "F", "Z"): if key in out: rtol = 1e-12 if key == "Z" else 1e-9 - np.testing.assert_allclose( - info[key], out[key], atol=1e-12, rtol=rtol, equal_nan=True - ) + np.testing.assert_allclose(info[key], out[key], atol=1e-12, rtol=rtol, equal_nan=True) -@pytest.mark.parametrize( - "name", ["wmf_peak_th", "wmf_dip", "wmf_deblend_th", "nan_thresh"] -) -def test_nan_thresholds_are_refused(name): - """A NaN threshold would silently switch its test off (every - comparison with it is false); it is refused, and an infinite - deblending threshold is still taken.""" - kw = dict( - wmf_peak_th=3.0, wmf_dip=3.0, wmf_deblend_th=np.inf, nan_thresh=0.33 - ) +@pytest.mark.parametrize("name", ["wmf_peak_th", "wmf_dip", "wmf_deblend_th", "nan_thresh"]) +def test_nan_thresholds_are_refused(name: str) -> None: + """A NaN threshold would silently switch its test off (every comparison with it is false). + + It is refused, and an infinite deblending threshold is still taken. + """ + kw = {"wmf_peak_th": 3.0, "wmf_dip": 3.0, "wmf_deblend_th": np.inf, "nan_thresh": 0.33} act = np.random.default_rng(0).normal(size=(4, 16, 16)) find_sources_wmf(act, **kw) with pytest.raises(ValueError, match=name): find_sources_wmf(act, **dict(kw, **{name: np.nan})) -def test_checkpoint_comparator_explains_compact_fixture(): +def test_checkpoint_comparator_explains_compact_fixture() -> None: """The full audit tells callers how to obtain missing checkpoints.""" with h5py.File(_FIXTURE) as f: with pytest.raises(ValueError, match="dbg/added.*make_matlab_wmf.m"): diff --git a/tests/raster/test_raster_wmf_deblend.py b/tests/raster/test_raster_wmf_deblend.py index e07ee561..45d49284 100644 --- a/tests/raster/test_raster_wmf_deblend.py +++ b/tests/raster/test_raster_wmf_deblend.py @@ -6,7 +6,7 @@ from giant_python.extraction.raster.wmf import _design, _fit_seeds, _ridge_ls -def test_design_zeroes_exterior_samples_before_differencing(): +def test_design_zeroes_exterior_samples_before_differencing() -> None: """A constant patch has nonzero gradients at its support boundary.""" k = np.ones((9, 9)) valid = np.ones_like(k, dtype=bool) @@ -24,12 +24,10 @@ def test_design_zeroes_exterior_samples_before_differencing(): coeff = np.array([1.7, 0.4, -0.2]) diagonal = np.array([81, 72, 72]) fitted = _ridge_ls(design, expected @ coeff) - np.testing.assert_allclose( - fitted, coeff * diagonal / (diagonal + 81e-6), rtol=1e-13 - ) + np.testing.assert_allclose(fitted, coeff * diagonal / (diagonal + 81e-6), rtol=1e-13) -def test_fit_shift_bound_applies_to_each_axis(): +def test_fit_shift_bound_applies_to_each_axis() -> None: """A diagonal displacement can exceed 1.5 px in Euclidean distance.""" axis = np.arange(-4, 5) k = np.exp(-(axis[:, None] ** 2 + axis**2) / 2) diff --git a/tests/raster/wmf_reference.py b/tests/raster/wmf_reference.py index f35bca6e..99f441f3 100644 --- a/tests/raster/wmf_reference.py +++ b/tests/raster/wmf_reference.py @@ -1,5 +1,6 @@ """Read MATLAB's WMF fixtures in the port's axis and coordinate conventions.""" +import h5py import numpy as np _PARAM_NAMES = { @@ -10,8 +11,15 @@ } -def _arrays(group): - """Restore array axes, zero-based positions and flat per-seed vectors.""" +def _arrays(group: h5py.Group) -> dict[str, np.ndarray]: + """Restore array axes, zero-based positions and flat per-seed vectors. + + Returns + ------- + dict[str, np.ndarray] + The group's arrays by name, with MATLAB axes reversed to the port's order, positions + shifted to zero-based, and per-seed vectors flattened. + """ arrays = {k: d[()].T for k, d in group.items() if k != "_"} for key, shape in group.attrs.items(): if key.endswith("_empty_size"): @@ -34,14 +42,27 @@ def _arrays(group): return arrays -def load_case(group): - """Read one HDF5 case, returning (act_t, mask, params, out, dbg).""" +def load_case( + group: h5py.Group, +) -> tuple[np.ndarray, np.ndarray, dict[str, float], dict[str, np.ndarray], dict[str, np.ndarray]]: + """Read one HDF5 case, returning (act_t, mask, params, out, dbg). + + Returns + ------- + act_t : np.ndarray + The input activity, as float64 with the last two axes swapped. + mask : np.ndarray + The input exclusion mask, as a boolean array. + params : dict[str, float] + The input parameters, by the port's names. + out : dict[str, np.ndarray] + The expected output arrays. + dbg : dict[str, np.ndarray] + The expected intermediate arrays; empty if the case has none. + """ inp = group["in"] act_t = inp["actT"][()].transpose(0, 2, 1).astype(np.float64) mask = inp["excludeMask"][()].T.astype(bool) - params = { - py: float(np.asarray(inp.attrs[mat]).item()) - for mat, py in _PARAM_NAMES.items() - } + params = {py: float(np.asarray(inp.attrs[mat]).item()) for mat, py in _PARAM_NAMES.items()} dbg = _arrays(group["dbg"]) if "dbg" in group else {} return act_t, mask, params, _arrays(group["out"]), dbg diff --git a/tests/registration/test_cli.py b/tests/registration/test_cli.py index a38b93ad..125ce548 100644 --- a/tests/registration/test_cli.py +++ b/tests/registration/test_cli.py @@ -1,4 +1,4 @@ -"""The ``giant register`` command's summary and exit code.""" +"""The giant register command's summary and exit code.""" from pathlib import Path @@ -6,6 +6,7 @@ import pytest from giant_python import cli +from giant_python.models.params import ExecutionOptions, MultiRoiRegistrationParams @pytest.mark.parametrize( @@ -18,10 +19,18 @@ ], ) def test_register_reports_failed_trials( - monkeypatch, capsys, failed, names, recorded, code -): - """Flagged trials are listed; a trial that raised makes the exit code - nonzero; a cell without a recording is listed as skipped.""" + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + failed: list[list[bool]], + names: list[list[str]], + recorded: list[list[str]], + code: int, +) -> None: + """Flagged trials are listed. + + A trial that raised makes the exit code nonzero; a cell without a + recording is listed as skipped. + """ from types import SimpleNamespace from giant_python.io import trial_table @@ -47,11 +56,11 @@ def test_register_reports_failed_trials( assert ("No recording (skipped): trial 2 (path 1)" in out) == (n_rec == 1) -@pytest.mark.parametrize( - "flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)] -) -def test_register_movie_format(monkeypatch, flags, save_tif): - """Registered movies are HDF5 unless ``--tif`` asks for TIFF.""" +@pytest.mark.parametrize("flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)]) +def test_register_movie_format( + monkeypatch: pytest.MonkeyPatch, flags: list[str], save_tif: bool +) -> None: + """Registered movies are HDF5 unless --tif asks for TIFF.""" from types import SimpleNamespace from giant_python.io import trial_table @@ -59,8 +68,14 @@ def test_register_movie_format(monkeypatch, flags, save_tif): seen = {} - def fake(table, params, **kwargs): - """A registration that records its parameters and writes nothing.""" + def fake(table: str | Path, params: MultiRoiRegistrationParams, **kwargs: object) -> dict: + """Fake a registration that records its parameters and writes nothing. + + Returns + ------- + dict + The result fields of a single registered trial. + """ seen["params"] = params return { "registration_failed": np.array([[False]]), @@ -76,13 +91,13 @@ def fake(table, params, **kwargs): assert seen["params"].save_tif is save_tif -def test_register_movie_formats_exclusive(): - """``--tif`` and ``--h5`` cannot be combined.""" +def test_register_movie_formats_exclusive() -> None: + """``--tif`` and --h5 cannot be combined.""" with pytest.raises(SystemExit): cli.main(["register", "trial_table.h5", "--tif", "--h5"]) -def test_register_gpu_workers_reach_the_pipeline(monkeypatch): +def test_register_gpu_workers_reach_the_pipeline(monkeypatch: pytest.MonkeyPatch) -> None: """``--gpu-workers`` sets the execution option (default 1).""" from types import SimpleNamespace @@ -91,8 +106,19 @@ def test_register_gpu_workers_reach_the_pipeline(monkeypatch): seen = [] - def fake(table, params, execution=None, **kwargs): - """A registration that records its execution options.""" + def fake( + table: str | Path, + params: MultiRoiRegistrationParams, + execution: ExecutionOptions | None = None, + **kwargs: object, + ) -> dict: + """Fake a registration that records its execution options. + + Returns + ------- + dict + The result fields of a single registered trial. + """ seen.append(execution.gpu_workers) return { "registration_failed": np.array([[False]]), @@ -109,9 +135,12 @@ def fake(table, params, execution=None, **kwargs): assert seen == [1, 8] -def test_job_workers_per_device(): - """Processes and threads per process: ``max_workers`` on the CPU, - ``gpu_workers`` on CUDA, never more processes than trials.""" +def test_job_workers_per_device() -> None: + """Processes and threads per process. + + max_workers on the CPU, gpu_workers on CUDA, never more + processes than trials. + """ from giant_python.models.params import ExecutionOptions from giant_python.pipeline.register import GPU_JOB_THREADS, job_workers @@ -127,16 +156,26 @@ def test_job_workers_per_device(): def test_trials_short_of_device_memory_are_registered_again( - tmp_path, monkeypatch -): - """After several trials shared a device: a trial that ran out of memory - and a registered trial without its statistics file run again, alone; - other failures and complete trials do not.""" + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """After several trials shared a device, some trials run again. + + A trial that ran out of memory and a registered trial without its + statistics file run again, alone; other failures and complete trials do + not. + """ from giant_python.pipeline import register from giant_python.registration.stats.io import stats_path - def job(name, stats=True): - """A job whose movie is ``name`` in the test folder.""" + def job(name: str, stats: bool = True) -> dict: + """Build a job whose movie is name in the test folder. + + Returns + ------- + dict + The job: the recording, the movie, whether to compute statistics, + and its threads and GPU fraction. + """ movie = tmp_path / f"{name}_REGISTERED_DOWNSAMPLED-80Hz.h5" return { "dat": tmp_path / f"{name}.dat", @@ -158,8 +197,14 @@ def job(name, stats=True): ] again = [] - def fake(j): - """Record the job and report success.""" + def fake(j: dict) -> dict: + """Record the job and report success. + + Returns + ------- + dict + A result that is not failed and has no error. + """ again.append((Path(j["dat"]).stem, j["threads"], j["gpu_fraction"])) return {"failed": False, "error": None} diff --git a/tests/registration/test_curtain.py b/tests/registration/test_curtain.py index 9343f569..3fce524d 100644 --- a/tests/registration/test_curtain.py +++ b/tests/registration/test_curtain.py @@ -10,7 +10,6 @@ import dataclasses import types from pathlib import Path -from typing import Any import h5py import numpy as np @@ -358,12 +357,12 @@ def test_reg_stats_follow_the_alignment_file( masks = [] opened = multiroi.open_trial - def spy(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 (forwards to open_trial unchanged) + def spy(*args: object, **kwargs: object) -> object: """Record whether each open_trial call masks the unlit samples. Returns ------- - Any + object What open_trial returns for the same arguments. """ masks.append(args[5] if len(args) > 5 else kwargs["mask_unlit"]) diff --git a/tests/registration/test_growth.py b/tests/registration/test_growth.py index 3f860107..9c6c4d4c 100644 --- a/tests/registration/test_growth.py +++ b/tests/registration/test_growth.py @@ -272,7 +272,7 @@ def test_consensus_seeds_stay_within_maxshift( params = multiroi.MultiRoiRegistrationParams(maxshift=2, init_search=3, schedule="grow") lay, former, init, ds, dt = open_trial(layout.files[0], 1, 3000, params, torch.device("cpu")) source = make_source(lay, former, 1, 3000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) + state, _cons = build_template(source, init, params, torch.float32) grower = Grower(FrameCache(source, ds), state, params, [(10, 3, -3)], []) assert grower.seeds == [(10, 2, -2)] grower._seed_round() diff --git a/tests/registration/test_kernels.py b/tests/registration/test_kernels.py index d58e633a..ab58873a 100644 --- a/tests/registration/test_kernels.py +++ b/tests/registration/test_kernels.py @@ -159,7 +159,7 @@ def test_correlation_map_matches_matlab_loop(dtype: torch.dtype) -> None: def test_match_recovers_shift_with_subpixel_sign() -> None: """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" rng = np.random.default_rng(1) - frame, fresh, template = random_frame(rng, frac=0.0) + frame, _fresh, template = random_frame(rng, frac=0.0) frame = np.roll(template, (-1, 2), (0, 1)) frame[np.isnan(frame)] = 5.0 rows, cols = np.nonzero(~np.isnan(frame)) diff --git a/tests/registration/test_reg_stats.py b/tests/registration/test_reg_stats.py index e0ec137a..17424f4e 100644 --- a/tests/registration/test_reg_stats.py +++ b/tests/registration/test_reg_stats.py @@ -2,7 +2,7 @@ from collections.abc import Iterator from pathlib import Path -from typing import Any, NoReturn +from typing import NoReturn import h5py import numpy as np @@ -15,7 +15,11 @@ from giant_python.registration.frames import FrameFormer from giant_python.registration.interpolation import interp_frame from giant_python.registration.multiroi import frame_times -from giant_python.registration.sources import CompensatedFrames, PlainFrames, make_source +from giant_python.registration.sources import ( + CompensatedFrames, + PlainFrames, + make_source, +) from giant_python.registration.stats import ( STATS_VERSION, measure_gain_curves, @@ -688,7 +692,7 @@ def fail(*args: object, **kwargs: object) -> NoReturn: monkeypatch.setattr(io, "write_stats", fail) unlink = pathlib.Path.unlink - def locked(path: Path, *args: Any, **kwargs: Any) -> None: # noqa: ANN401 - forwarded to unlink + def locked(path: Path, *args: object, **kwargs: object) -> None: """Path.unlink, refusing the partial statistics file. Raises diff --git a/tests/registration/test_synthetic.py b/tests/registration/test_synthetic.py index fd2954ae..a6783287 100644 --- a/tests/registration/test_synthetic.py +++ b/tests/registration/test_synthetic.py @@ -16,7 +16,11 @@ from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 from giant_python.io.slap2 import is_cycle_split -from giant_python.io.slap2_raster import RasterLayout, read_line_offsets, read_raster_samples +from giant_python.io.slap2_raster import ( + RasterLayout, + read_line_offsets, + read_raster_samples, +) from giant_python.io.trial_table import read_trial_table from giant_python.registration import multiroi from giant_python.registration.frames import FrameFormer @@ -495,10 +499,10 @@ def test_rerun_keeps_the_saved_failure_flag( layout, _ = recording monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) table = one_trial_table(layout, tmp_path) - run = dict( - params={"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) + run = { + "params": {"maxshift": 5, "save_tif": False}, + "execution": {"device": "cpu", "max_workers": 1}, + } fields = register_multiroi(table, **run) assert not fields["registration_failed"][0, 0] adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] diff --git a/tests/simulation/test_injection.py b/tests/simulation/test_injection.py index dbda863e..c5c4158d 100644 --- a/tests/simulation/test_injection.py +++ b/tests/simulation/test_injection.py @@ -13,7 +13,11 @@ import torch from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import INVALID_SAMPLE, RasterLayout, read_raster_samples +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + read_raster_samples, +) from giant_python.pipeline.register import register_multiroi from giant_python.registration import multiroi from giant_python.simulation import injection as inj @@ -524,7 +528,7 @@ def run_injection( table: Path, out: Path, monkeypatch: pytest.MonkeyPatch, - **kw: Any, # noqa: ANN401 (forwarded to inject_session's keyword-only arguments) + **kw: Any, # noqa: ANN401 ) -> dict: """inject_session on the synthetic recording. @@ -781,8 +785,8 @@ def test_injection_changes_only_injected_samples( def test_truth_file_describes_the_injection(online: OnlineRecording, injected: Injected) -> None: """The truth has positions per trial, events and traces at frame lines.""" - layout, _, _ = online - out, summary, s = injected + _layout, _, _ = online + out, summary, _s = injected truth = inj.read_truth(out / inj.TRUTH_NAME) assert truth["seed"] == 11 assert truth["settings"]["size_classes"] == [4.0, 8.0] diff --git a/tests/spine/conftest.py b/tests/spine/conftest.py index b1b81b12..da53f668 100644 --- a/tests/spine/conftest.py +++ b/tests/spine/conftest.py @@ -1,15 +1,23 @@ """Shared settings of the spine tests.""" +from concurrent.futures import ProcessPoolExecutor +from typing import TYPE_CHECKING + import pytest +if TYPE_CHECKING: + from giant_python.spine.parallel import LazyPool + @pytest.fixture(autouse=True) -def _one_worker_by_default(monkeypatch, request): - """The readout runs its work here unless a test asks for workers: the - tests start no processes, except those marked ``processes`` (which +def _one_worker_by_default(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> None: + """Make the readout run its work here unless a test asks for workers. + + The tests start no processes, except those marked processes (which compare worker processes with one process, and are run where the - machine may take them). Tests marked ``default_workers`` see the real - default number of workers.""" + machine may take them). Tests marked default_workers see the real + default number of workers. + """ if request.node.get_closest_marker("processes") is not None: # these tests are about worker processes: doing the work here # because the workers could not be started fails them @@ -17,8 +25,14 @@ def _one_worker_by_default(monkeypatch, request): real = LazyPool._start - def start(self): - """The workers' pool, which must have started.""" + def start(self: "LazyPool") -> ProcessPoolExecutor: + """Return the workers' pool, which must have started. + + Returns + ------- + ProcessPoolExecutor + The workers' pool. + """ pool = real(self) assert pool is not None, "the workers could not be started" return pool @@ -30,11 +44,9 @@ def start(self): monkeypatch.setattr("giant_python.spine.parallel.DEFAULT_WORKERS", 1) -def pytest_configure(config): - """Register the ``processes`` and ``default_workers`` markers.""" - config.addinivalue_line( - "markers", "processes: the test starts worker processes" - ) +def pytest_configure(config: pytest.Config) -> None: + """Register the processes and default_workers markers.""" + config.addinivalue_line("markers", "processes: the test starts worker processes") config.addinivalue_line( "markers", "default_workers: the test sees the real default number of workers " diff --git a/tests/spine/test_spine_coverage.py b/tests/spine/test_spine_coverage.py index 1dea5af9..93cce02e 100644 --- a/tests/spine/test_spine_coverage.py +++ b/tests/spine/test_spine_coverage.py @@ -1,8 +1,10 @@ -"""Tests of the pixels a trial did not image -(:mod:`giant_python.spine.coverage`) and of their place in ``giant spine -readout``.""" +"""Tests of the pixels a trial did not image (:mod:`giant_python.spine.coverage`). + +The tests also cover their place in giant spine readout. +""" import warnings +from pathlib import Path import numpy as np import pytest @@ -16,16 +18,32 @@ from . import synthetic as syn -def _stack(T=6, H=12, W=16, level=10.0): - """Mean images with a NaN margin on the right (outside the scan).""" +def _stack(T: int = 6, H: int = 12, W: int = 16, level: float = 10.0) -> np.ndarray: + """Build mean images with a NaN margin on the right (outside the scan). + + Parameters + ---------- + T, H, W : int + Number of trials, rows and columns. + level : float + Value of the pixels inside the scan. + + Returns + ------- + np.ndarray + (T, H, W) mean images, NaN from column 14 on. + """ a = np.full((T, H, W), level) a[:, :, 14:] = np.nan return a -def test_band_at_the_scan_edge_is_found(): - """A near-zero band touching the missing pixels, in the later trials and - in every channel, is not imaged; one pixel around it too.""" +def test_band_at_the_scan_edge_is_found() -> None: + """A near-zero band touching the missing pixels is not imaged. + + The band is in the later trials and in every channel; one pixel around + it is not imaged too. + """ ch1, ch2 = _stack(), _stack(level=1.0) for c, lvl in ((ch1, 0.2), (ch2, 0.02)): c[3:, :, 11:14] = lvl @@ -34,14 +52,14 @@ def test_band_at_the_scan_edge_is_found(): assert un[3:, :, 11:14].all() assert un[3:, :, 10].all() and not un[3:, :, :10].any() # dilation assert not un[:, :, 14:].any() # missing pixels are not marked - assert not unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0)[ - 3:, :, 10 - ].any() + assert not unimaged_pixels([ch1, ch2], frac=0.5, dilate=0, max_share=1.0)[3:, :, 10].any() -def test_dimming_inside_the_field_or_in_one_channel_is_kept(): - """Dark pixels away from the scan's edge, or dark in one channel only, - are imaged.""" +def test_dimming_inside_the_field_or_in_one_channel_is_kept() -> None: + """Dark pixels away from the scan's edge are imaged. + + So are pixels that are dark in one channel only. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[3:, 5:7, 5:7] = 0.1 # interior, both channels ch2[3:, 5:7, 5:7] = 0.01 @@ -51,7 +69,7 @@ def test_dimming_inside_the_field_or_in_one_channel_is_kept(): assert not unimaged_pixels([ch1, ch2], frac=0.0).any() -def test_the_frame_border_counts_as_the_edge(): +def test_the_frame_border_counts_as_the_edge() -> None: """A band at the frame's border is found without missing pixels.""" ch = np.full((4, 8, 8), 5.0) ch[2:, :, 6:] = 0.0 @@ -59,7 +77,7 @@ def test_the_frame_border_counts_as_the_edge(): assert un[2:, :, 6:].all() and un.sum() == 2 * 8 * 2 -def test_unimaged_pixels_checks_its_input(): +def test_unimaged_pixels_checks_its_input() -> None: """Channels must share a shape, and there must be one.""" with pytest.raises(ValueError, match="shape"): unimaged_pixels([np.ones((2, 3, 3)), np.ones((2, 3, 4))]) @@ -67,7 +85,7 @@ def test_unimaged_pixels_checks_its_input(): unimaged_pixels([]) -def test_window_weight_kept(): +def test_window_weight_kept() -> None: """The share of each window's weight on the valid pixels.""" masks = np.zeros((2, 4, 4), bool) masks[0, :, :2] = True @@ -79,15 +97,46 @@ def test_window_weight_kept(): @pytest.fixture -def banded(tmp_path, monkeypatch): - """The synthetic session with a near-zero band at the right edge of - trials 3 and 4 (as left by a step of online motion correction) in every - per-trial image.""" +def banded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict: + """Build the synthetic session with a near-zero band in the trials' images. + + The band is at the right edge of trials 3 and 4 (as left by a step of + online motion correction) in every per-trial image. + + Parameters + ---------- + tmp_path : Path + Folder to write the session under. + monkeypatch : pytest.MonkeyPatch + Used to put the band into the per-trial images. + + Returns + ------- + dict + The session's folders, as returned by syn.make_session. + """ s = syn.make_session(tmp_path) real = RunSummary.per_trial_images - def with_band(self, path, name, channel): - """The run's per-trial images with the band.""" + def with_band(self: RunSummary, path: int, name: str, channel: int | None) -> np.ndarray: + """Return the run's per-trial images with the band. + + Parameters + ---------- + self : RunSummary + The run's summary. + path : int + Imaging path. + name : str + Name of the image. + channel : int or None + Channel of the image. + + Returns + ------- + np.ndarray + The images, with the band set to 0.02 where they have a value. + """ a = np.array(real(self, path, name, channel), dtype=np.float32) band = a[2:, :, 17:] a[2:, :, 17:] = np.where(np.isfinite(band), 0.02, band) @@ -97,10 +146,12 @@ def with_band(self, path, name, channel): return s -def test_readout_leaves_out_the_band(banded, tmp_path): - """The band is left out of every image, a source mostly in it gets NaN - sizes, and a source partly in it keeps the same window in every trial - (no dip).""" +def test_readout_leaves_out_the_band(banded: dict, tmp_path: Path) -> None: + """The band is left out of every image. + + A source mostly in the band gets NaN sizes, and a source partly in it + keeps the same window in every trial (no dip). + """ notes = [] rep = make_spine_summary( banded["run"], @@ -132,9 +183,11 @@ def test_readout_leaves_out_the_band(banded, tmp_path): assert p["image_attrs"]["mean_ch1"]["covers"] == "field" -def test_without_the_mask_the_band_makes_a_dip(banded, tmp_path): - """With the mask off, the partly covered source dips in the banded - trials (what the mask removes).""" +def test_without_the_mask_the_band_makes_a_dip(banded: dict, tmp_path: Path) -> None: + """With the mask off, the partly covered source dips in the banded trials. + + This is what the mask removes. + """ rep = make_spine_summary( banded["run"], banded["table"], @@ -157,21 +210,23 @@ def test_without_the_mask_the_band_makes_a_dip(banded, tmp_path): @pytest.mark.parametrize( "kw, match", [ - (dict(unimaged_frac=1.0), "unimaged_frac"), - (dict(unimaged_frac=-0.1), "unimaged_frac"), - (dict(unimaged_dilate=-1), "unimaged_dilate"), - (dict(min_window=1.5), "min_window"), + ({"unimaged_frac": 1.0}, "unimaged_frac"), + ({"unimaged_frac": -0.1}, "unimaged_frac"), + ({"unimaged_dilate": -1}, "unimaged_dilate"), + ({"min_window": 1.5}, "min_window"), ], ) -def test_coverage_settings_are_checked(tmp_path, kw, match): +def test_coverage_settings_are_checked(tmp_path: Path, kw: dict[str, float], match: str) -> None: """Settings that cannot work are refused before anything is read.""" with pytest.raises(ValueError, match=match): make_spine_summary(tmp_path, tmp_path / "t.h5", tmp_path / "o", **kw) -def test_a_dimmer_trial_is_not_a_band(): - """A trial whose whole field is dimmer (bleaching, laser power) is not - taken for a band, while a band in such a trial still is.""" +def test_a_dimmer_trial_is_not_a_band() -> None: + """A trial whose whole field is dimmer (bleaching, laser power) is not a band. + + It is not taken for a band, while a band in such a trial still is. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[4:] *= 0.2 ch2[4:] *= 0.2 @@ -182,9 +237,11 @@ def test_a_dimmer_trial_is_not_a_band(): assert un[5, :, 12:14].all() and un.sum() == 12 * 2 -def test_missing_pixels_of_any_channel_set_the_edge(): - """The scan's edge is where any channel lacks a value, whatever the - channels' order, and no missing pixel is marked.""" +def test_missing_pixels_of_any_channel_set_the_edge() -> None: + """The scan's edge is where any channel lacks a value. + + This holds whatever the channels' order, and no missing pixel is marked. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[:, :, 13] = np.nan # channel 1 misses one more column ch1[3:, :, 11:13] = 0.1 @@ -195,9 +252,11 @@ def test_missing_pixels_of_any_channel_set_the_edge(): assert a[3:, :, 11:13].all() and not a[:, :, 13:].any() -def test_no_source_left_is_not_a_reference(): - """When every source's sizes are NaN (all windows rejected), none is in - the normalization's reference set.""" +def test_no_source_left_is_not_a_reference() -> None: + """When every source's sizes are NaN (all windows rejected), none is a reference. + + That is, none is in the normalization's reference set. + """ from giant_python.spine.pipeline import _normalize nan = np.full((4, 3), np.nan) @@ -207,9 +266,11 @@ def test_no_source_left_is_not_a_reference(): assert np.isnan(norm["mean_ch1"]).all() -def test_a_trial_without_values_does_not_stop_the_search(): - """A trial with no value at all (not extracted) neither empties the - pixels every trial has nor gets marked.""" +def test_a_trial_without_values_does_not_stop_the_search() -> None: + """A trial with no value at all (not extracted) does not empty the pixels. + + It neither empties the pixels every trial has nor gets marked. + """ ch1, ch2 = _stack(), _stack(level=1.0) ch1[1] = np.nan ch2[1] = np.nan @@ -220,20 +281,24 @@ def test_a_trial_without_values_does_not_stop_the_search(): assert un.sum() == 3 * 12 * 3 -def test_a_wide_band_does_not_set_the_brightness_scale(): - """Without the share limit, a band covering most of the field in two - trials is found, and the rest of the field is not marked in the other - trials; with it (default), such trials are skipped.""" +def test_a_wide_band_does_not_set_the_brightness_scale() -> None: + """Without the share limit, a band covering most of the field in two trials is found. + + The rest of the field is not marked in the other trials; with the limit + (default), such trials are skipped. + """ ch = np.full((6, 10, 10), 10.0) ch[4:, :, 4:] = 0.2 # 60% of the pixels un = unimaged_pixels([ch], frac=0.5, dilate=0, max_share=1.0) assert un[4:, :, 4:].all() and un.sum() == 2 * 10 * 6 -def test_a_band_too_large_to_tell_from_the_scene_is_not_marked(): - """A brightness change together with a band over most of the field - cannot be told from a change of the scene: such trials get nothing - marked and are reported, rather than losing their windows.""" +def test_a_band_too_large_to_tell_from_the_scene_is_not_marked() -> None: + """A brightness change together with a band over most of the field is not marked. + + It cannot be told from a change of the scene: such trials get nothing + marked and are reported, rather than losing their windows. + """ ch = np.full((6, 10, 10), 2.0) ch[4:] = 10.0 ch[4:, :, 4:] = 0.2 @@ -248,9 +313,11 @@ def test_a_band_too_large_to_tell_from_the_scene_is_not_marked(): assert un[4:, :, 9:].all() and un.sum() == 2 * 10 and skipped.size == 0 -def test_wide_band_skipped_by_default(): - """With the default share limit, a band over 60% of the field is - reported, not marked.""" +def test_wide_band_skipped_by_default() -> None: + """With the default share limit, a band over 60% of the field is reported. + + It is reported, not marked. + """ ch = np.full((6, 10, 10), 10.0) ch[4:, :, 4:] = 0.2 un, skipped = unimaged_pixels([ch], frac=0.5, with_skipped=True) @@ -258,9 +325,11 @@ def test_wide_band_skipped_by_default(): np.testing.assert_array_equal(skipped, [4, 5]) -def test_nanpercentile_over_trials_is_numpys(): - """The sorted-stack percentile equals np.nanpercentile to the bit, for - pixels with few, one or no values and with infinite values.""" +def test_nanpercentile_over_trials_is_numpys() -> None: + """The sorted-stack percentile equals np.nanpercentile to the bit. + + This holds for pixels with few, one or no values and with infinite values. + """ from giant_python.spine.coverage import nanpercentile_over_trials rng = np.random.default_rng(0) @@ -274,9 +343,7 @@ def test_nanpercentile_over_trials_is_numpys(): with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) expect = np.nanpercentile(a, q, axis=0) - np.testing.assert_array_equal( - nanpercentile_over_trials(a, q), expect - ) + np.testing.assert_array_equal(nanpercentile_over_trials(a, q), expect) assert np.isnan(nanpercentile_over_trials(np.zeros((0, 2, 2)), 75)).all() # a percentile outside 0 to 100 is refused, as by numpy for q in (101, -1, np.nan): diff --git a/tests/spine/test_spine_gains.py b/tests/spine/test_spine_gains.py index 9811fab0..21bba126 100644 --- a/tests/spine/test_spine_gains.py +++ b/tests/spine/test_spine_gains.py @@ -181,12 +181,12 @@ def test_summary_key_follows_the_gain_plan(tmp_path: Path) -> None: """A changed plan gives a new summary, not the old one reused.""" s = syn.make_session(tmp_path) work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = dict( - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) + kw = { + "baseline_dir": s["baselines"], + "moco_dir": s["moco"], + "trim_s": 0.1, + "gain_work_dir": work, + } rep = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) with h5py.File(work / "plan" / "path1.h5", "a") as f: f.attrs["note"] = "replanned" @@ -204,12 +204,12 @@ def test_gains_need_the_images_baseline_files(tmp_path: Path) -> None: s = syn.make_session(tmp_path) work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = dict( - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) + kw = { + "baseline_dir": s["baselines"], + "moco_dir": s["moco"], + "trim_s": 0.1, + "gain_work_dir": work, + } make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) b = s["baselines"] / "E1T2DMD1_BASELINE-80Hz.h5" st = b.stat() diff --git a/tests/spine/test_spine_images.py b/tests/spine/test_spine_images.py index 0f484076..f82e9cd4 100644 --- a/tests/spine/test_spine_images.py +++ b/tests/spine/test_spine_images.py @@ -20,20 +20,20 @@ from . import synthetic as syn -def test_kept_frames_trims_both_ends(): +def test_kept_frames_trims_both_ends() -> None: """The first and last round(trim_s * align_hz) frames are left out.""" keep = kept_frames(np.zeros(100), align_hz=10.0, trim_s=0.5) assert not keep[:5].any() and not keep[-5:].any() assert keep[5:95].all() -def test_kept_frames_falls_back_when_too_short(): +def test_kept_frames_falls_back_when_too_short() -> None: """A trial too short to trim keeps its frames that are not discarded.""" keep = kept_frames(np.zeros(10), align_hz=10.0, trim_s=1.0) assert keep.all() -def test_kept_frames_drops_motion_discards(): +def test_kept_frames_drops_motion_discards() -> None: """Frames SiLo discards for motion do not enter.""" rne = np.zeros(400) rne[200:204] = 1.0 # a sharp rise of the registration error @@ -42,13 +42,13 @@ def test_kept_frames_drops_motion_discards(): assert keep[:150].all() -def _baseline_file(path, frames): - """Write ``frames`` ``(frame, rows, cols)`` as a baseline file.""" +def _baseline_file(path: Path, frames: np.ndarray) -> None: + """Write frames (frame, rows, cols) as a baseline file.""" with h5py.File(path, "w") as f: f["baseline"] = np.transpose(frames, (0, 2, 1)).astype(np.float32) -def test_baseline_trial_mean_matches_numpy(tmp_path): +def test_baseline_trial_mean_matches_numpy(tmp_path: Path) -> None: """The blockwise mean over kept frames equals numpy's, NaN kept out.""" rng = np.random.default_rng(1) frames = rng.random((70, 6, 9)) @@ -66,10 +66,12 @@ def test_baseline_trial_mean_matches_numpy(tmp_path): assert np.isnan(mean[0, 0]) -def test_baseline_trial_mean_same_for_any_storage_chunks(tmp_path): - """Reading whole storage chunks gives the mean of the blockwise read - of an unchunked file, to the bit (storage chunks that are, and are - not, a multiple of the block).""" +def test_baseline_trial_mean_same_for_any_storage_chunks(tmp_path: Path) -> None: + """Reading whole storage chunks gives the mean of the blockwise read of an unchunked file. + + The mean is the same to the bit (storage chunks that are, and are + not, a multiple of the block). + """ rng = np.random.default_rng(2) frames = (10 * rng.random((300, 5, 7))).astype(np.float16) frames[40:60, 1, 1] = np.nan @@ -96,10 +98,14 @@ def test_baseline_trial_mean_same_for_any_storage_chunks(tmp_path): np.testing.assert_allclose(means[0], expect, rtol=1e-12) -def test_baseline_trial_mean_reads_whole_storage_chunks(tmp_path, monkeypatch): - """Every read starts and ends on a storage-chunk boundary, also where - the chunks are not a multiple of the block that is summed: no - compressed chunk is read twice.""" +def test_baseline_trial_mean_reads_whole_storage_chunks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Every read starts and ends on a storage-chunk boundary. + + This is also so where the chunks are not a multiple of the block that is + summed: no compressed chunk is read twice. + """ frames = np.ones((300, 5, 7), np.float16) keep = np.ones(300, bool) real = h5py.Dataset.__getitem__ @@ -114,8 +120,14 @@ def test_baseline_trial_mean_reads_whole_storage_chunks(tmp_path, monkeypatch): ) reads = [] - def spy(ds, key): - """Record the frame ranges read from the dataset.""" + def spy(ds: h5py.Dataset, key: object) -> object: + """Record the frame ranges read from the dataset. + + Returns + ------- + object + What the real read of key from the dataset returns. + """ if isinstance(key, slice): reads.append((key.start, key.stop)) return real(ds, key) @@ -128,7 +140,7 @@ def spy(ds, key): assert a % depth == 0 and b == a2 -def test_baseline_trial_mean_checks_frame_count(tmp_path): +def test_baseline_trial_mean_checks_frame_count(tmp_path: Path) -> None: """A frame mask of the wrong length is refused.""" path = tmp_path / "b.h5" _baseline_file(path, np.ones((10, 3, 3))) @@ -136,11 +148,9 @@ def test_baseline_trial_mean_checks_frame_count(tmp_path): baseline_trial_mean(path, np.ones(9, bool)) -def test_to_consensus_undoes_a_shift(): +def test_to_consensus_undoes_a_shift() -> None: """A shifted trial image lands back on the consensus scene.""" - tmap = TrialMap( - np.array([[[1, 0, 0], [0, 1, 0]], [[1, 0, 2], [0, 1, -1]]], float) - ) + tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]], [[1, 0, 2], [0, 1, -1]]], float)) scene = syn.scene(1) trial = np.full_like(scene, np.nan) trial[2:, :-1] = scene[:-2, 1:] # trial pixel = consensus pixel + (2, -1) @@ -150,7 +160,7 @@ def test_to_consensus_undoes_a_shift(): np.testing.assert_allclose(out[ok], scene[ok]) -def test_to_consensus_places_small_trials_top_left(): +def test_to_consensus_places_small_trials_top_left() -> None: """A trial smaller than the frame is padded at the bottom right.""" tmap = TrialMap(np.array([[[1, 0, 0], [0, 1, 0]]], float)) img = np.arange(12.0).reshape(3, 4) @@ -159,19 +169,15 @@ def test_to_consensus_places_small_trials_top_left(): assert np.isnan(out[3:]).all() and np.isnan(out[:, 4:]).all() -def test_network_f0_stack_recovers_the_scene(tmp_path): - """Per-trial F0 images equal the scaled scene where the trial covers - it, and the trimmed frames do not enter.""" +def test_network_f0_stack_recovers_the_scene(tmp_path: Path) -> None: + """Per-trial F0 images equal the scaled scene where the trial covers it. + + The trimmed frames do not enter. + """ s = syn.make_session(tmp_path) - tmap = TrialMap( - np.stack([[[1, 0, dr], [0, 1, dc]] for dr, dc in syn.SHIFTS]).astype( - float - ) - ) + tmap = TrialMap(np.stack([[[1, 0, dr], [0, 1, dc]] for dr, dc in syn.SHIFTS]).astype(float)) stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] - st = network_f0_stack( - s["baselines"], s["moco"], stems, tmap, (syn.H, syn.W), trim_s=0.1 - ) + st = network_f0_stack(s["baselines"], s["moco"], stems, tmap, (syn.H, syn.W), trim_s=0.1) assert st.images.shape == (syn.N_TRIALS, syn.H, syn.W) assert (st.n_frames == syn.N_FRAMES - 16).all() for t in range(syn.N_TRIALS): @@ -184,22 +190,20 @@ def test_network_f0_stack_recovers_the_scene(tmp_path): assert st.inputs[0]["baseline"]["name"] == "E1T1DMD1_BASELINE-80Hz.h5" -def test_network_f0_stack_skips_missing_trials(tmp_path): +def test_network_f0_stack_skips_missing_trials(tmp_path: Path) -> None: """Trials without a stem, a baseline file or a map stay NaN.""" s = syn.make_session(tmp_path) affine = np.zeros((syn.N_TRIALS, 2, 3)) affine[:, :, :2] = np.eye(2) affine[2] = np.nan # trial 3 not aligned stems = ["E1T1DMD1", None, "E1T3DMD1", "missing"] - st = network_f0_stack( - s["baselines"], s["moco"], stems, TrialMap(affine), (syn.H, syn.W) - ) + st = network_f0_stack(s["baselines"], s["moco"], stems, TrialMap(affine), (syn.H, syn.W)) assert np.isfinite(st.images[0]).any() assert all(np.isnan(st.images[t]).all() for t in (1, 2, 3)) assert list(st.n_frames[1:]) == [0, 0, 0] -def test_stack_key_changes_with_inputs(): +def test_stack_key_changes_with_inputs() -> None: """The cache key depends on every part.""" a = stack_key("x", {"trim_s": 1.0}, np.zeros(3)) assert a == stack_key("x", {"trim_s": 1.0}, np.zeros(3)) @@ -207,9 +211,11 @@ def test_stack_key_changes_with_inputs(): assert a != stack_key("x", {"trim_s": 1.0}, np.ones(3)) -def test_file_identity_keeps_folders_apart(tmp_path): - """Two files with the same name, size and modification time in - different folders have different identities.""" +def test_file_identity_keeps_folders_apart(tmp_path: Path) -> None: + """Two files with the same name, size and modification time have different identities. + + This is so when they are in different folders. + """ import os a = tmp_path / "a" / "x.h5" @@ -225,9 +231,11 @@ def test_file_identity_keeps_folders_apart(tmp_path): assert ia != ib -def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path): - """The aligned flags (a scan of every trial's map) are read once, not - per trial.""" +def test_network_f0_stack_reads_the_aligned_flags_once(tmp_path: Path) -> None: + """The aligned flags are read once, not per trial. + + The flags are a scan of every trial's map. + """ s = syn.make_session(tmp_path) calls = [] @@ -235,21 +243,25 @@ class CountingMap(TrialMap): """A trial map that counts reads of its aligned flags.""" @property - def aligned(self): - """The flags, counting the read.""" + def aligned(self) -> np.ndarray: + """The flags, counting the read. + + Returns + ------- + np.ndarray + Which trials have a map (bool per trial). + """ calls.append(1) return TrialMap.aligned.fget(self) affine = np.zeros((syn.N_TRIALS, 2, 3)) affine[:, :, :2] = np.eye(2) stems = [f"E1T{t + 1}DMD1" for t in range(syn.N_TRIALS)] - network_f0_stack( - s["baselines"], s["moco"], stems, CountingMap(affine), (syn.H, syn.W) - ) + network_f0_stack(s["baselines"], s["moco"], stems, CountingMap(affine), (syn.H, syn.W)) assert len(calls) == 1 -def test_trim_dropped_flags_untrimmed_trials(): +def test_trim_dropped_flags_untrimmed_trials() -> None: """trim_dropped says whether kept_frames had to drop the trim.""" from giant_python.spine.images import trim_dropped @@ -261,10 +273,12 @@ def test_trim_dropped_flags_untrimmed_trials(): assert not trim_dropped(keep, 0) -def test_network_f0_stack_is_the_same_with_a_pool(tmp_path): - """Trials averaged by a pool's workers (here threads; the readout uses - processes) give the stack made here, bit for bit, in order, with the - progress of every trial.""" +def test_network_f0_stack_is_the_same_with_a_pool(tmp_path: Path) -> None: + """Trials averaged by a pool's workers give the stack made here. + + The workers are threads here; the readout uses processes. The stack is the + same bit for bit, in order, with the progress of every trial. + """ from concurrent.futures import ThreadPoolExecutor from giant_python.spine.parallel import LazyPool @@ -296,9 +310,17 @@ def test_network_f0_stack_is_the_same_with_a_pool(tmp_path): assert seen == list(range(syn.N_TRIALS)) -def _stack_args(s, missing=1): - """network_f0_stack's first arguments for the synthetic session ``s`` - (path 1, trial ``missing`` without a stem).""" +def _stack_args(s: dict, missing: int | None = 1) -> tuple[Path | str, Path | str, list, TrialMap]: + """Return network_f0_stack's first arguments for the synthetic session s. + + The path is 1, and trial missing is without a stem. + + Returns + ------- + tuple[Path | str, Path | str, list, TrialMap] + The baseline folder, the motion-correction folder, the trial stems and + the trial maps. + """ affine = np.zeros((syn.N_TRIALS, 2, 3)) affine[:, :, :2] = np.eye(2) affine[:, 0, 2] = [dr for dr, _ in syn.SHIFTS] @@ -311,10 +333,12 @@ def _stack_args(s, missing=1): @pytest.mark.parametrize("one", ["none", "lazy"]) def test_network_f0_stack_reports_each_trial_before_its_work( - tmp_path, monkeypatch, one -): - """Without workers each trial is reported before its files are read - (as before the workers), the trials left out too, in order.""" + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, one: str +) -> None: + """Without workers each trial is reported before its files are read. + + This is as before the workers; the trials left out too, in order. + """ from giant_python.spine import images from giant_python.spine.parallel import LazyPool @@ -322,8 +346,14 @@ def test_network_f0_stack_reports_each_trial_before_its_work( events = [] read = images.read_rec_neg_err - def reading(path): - """Record the trial whose alignment file is read.""" + def reading(path: str | Path) -> np.ndarray: + """Record the trial whose alignment file is read. + + Returns + ------- + np.ndarray + The recNegErr of the alignment file. + """ events.append(("read", int(Path(path).name[3]))) return read(path) @@ -343,10 +373,12 @@ def reading(path): @pytest.mark.parametrize("one", ["none", "lazy"]) def test_a_failing_first_trial_is_reported_and_stops_the_stack( - tmp_path, monkeypatch, one -): - """A trial whose alignment file cannot be read has been reported, and - its error surfaces before the next trial is read.""" + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, one: str +) -> None: + """A trial whose alignment file cannot be read has been reported. + + Its error surfaces before the next trial is read. + """ from giant_python.spine import images from giant_python.spine.parallel import LazyPool @@ -355,8 +387,14 @@ def test_a_failing_first_trial_is_reported_and_stops_the_stack( reads, seen = [], [] read = images.read_rec_neg_err - def reading(path): - """Record the alignment files read.""" + def reading(path: str | Path) -> np.ndarray: + """Record the alignment files read. + + Returns + ------- + np.ndarray + The recNegErr of the alignment file. + """ reads.append(Path(path).name) return read(path) @@ -372,17 +410,23 @@ def reading(path): assert seen == [0] and reads == ["E1T1DMD1_ALIGNMENTDATA.h5"] -def test_to_consensus_checks_the_image_first(): - """An unusable image is reported before an unusable map (as before the - grid positions were computed apart).""" +def test_to_consensus_checks_the_image_first() -> None: + """An unusable image is reported before an unusable map. + + This is as before the grid positions were computed apart. + """ with pytest.raises(AttributeError, match="shape"): to_consensus(None, None, 0, (4, 4)) @pytest.mark.processes -def test_workers_read_the_files_of_the_callers_folder(tmp_path, monkeypatch): - """Relative folders mean the caller's current folder to the workers - too, even when their pool was started from another folder.""" +def test_workers_read_the_files_of_the_callers_folder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Relative folders mean the caller's current folder to the workers. + + This is so even when their pool was started from another folder. + """ import os from giant_python.spine.parallel import LazyPool diff --git a/tests/spine/test_spine_parallel.py b/tests/spine/test_spine_parallel.py index adfbffaa..2e63bd3f 100644 --- a/tests/spine/test_spine_parallel.py +++ b/tests/spine/test_spine_parallel.py @@ -1,6 +1,7 @@ """Tests of the spine readout's workers (:mod:`giant_python.spine.parallel`). -The tests marked ``processes`` start a few worker processes.""" +The tests marked processes start a few worker processes. +""" import multiprocessing import os @@ -9,8 +10,10 @@ import threading import time import warnings -from concurrent.futures import ThreadPoolExecutor +from collections.abc import Callable, Iterator +from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor from contextlib import closing +from typing import NoReturn import pytest @@ -25,24 +28,43 @@ ) -def _square(x): - """A task.""" +def _square(x: int) -> int: + """Run a task. + + Returns + ------- + int + The square of x. + + Raises + ------ + ValueError + If x is negative. + """ if x < 0: raise ValueError("negative") return x * x -def _made(n, record): - """``range(n)`` as tasks, recording each task as it is made.""" +def _made(n: int, record: list[int]) -> Iterator[int]: + """``range(n)`` as tasks, recording each task as it is made. + + Yields + ------ + int + Each task, after it has been appended to record. + """ for i in range(n): record.append(i) yield i @pytest.mark.default_workers -def test_n_workers_defaults_to_up_to_eight_one_per_cpu(monkeypatch): - """None gives up to 8 workers, one per CPU (the real default, not the - one the other spine tests use).""" +def test_n_workers_defaults_to_up_to_eight_one_per_cpu(monkeypatch: pytest.MonkeyPatch) -> None: + """None gives up to 8 workers, one per CPU. + + This is the real default (not the one the other spine tests use). + """ assert parallel.DEFAULT_WORKERS == 8 real = max(1, min(8, os.cpu_count() or 1)) assert n_workers(None) == real and LazyPool().max_workers == real @@ -51,10 +73,11 @@ def test_n_workers_defaults_to_up_to_eight_one_per_cpu(monkeypatch): assert n_workers(None) == want -def test_n_workers_takes_numbers_and_checks_them(monkeypatch): - """A number is taken as by ``int`` (at least 1, as the readout's - threads did); anything else is refused with a clear error; Windows - takes at most 61.""" +def test_n_workers_takes_numbers_and_checks_them(monkeypatch: pytest.MonkeyPatch) -> None: + """A number is taken as by int (at least 1, as the readout's threads did). + + Anything else is refused with a clear error; Windows takes at most 61. + """ monkeypatch.setattr(sys, "platform", "linux") assert n_workers(3) == 3 and n_workers(0) == 1 and n_workers(-2) == 1 assert n_workers(2.7) == 2 and n_workers(64) == 64 @@ -68,9 +91,11 @@ def test_n_workers_takes_numbers_and_checks_them(monkeypatch): assert n_workers(None) == 61 -def test_lazy_pool_checks_workers_only_when_used(): - """A readout that has no work for its workers accepts any value (as - when they were threads); the value is checked when work comes.""" +def test_lazy_pool_checks_workers_only_when_used() -> None: + """A readout that has no work for its workers accepts any value (as when they were threads). + + The value is checked when work comes. + """ pool = LazyPool(float("nan")) assert list(ordered_map(pool, _square, [])) == [] with pytest.raises(ValueError, match="workers must be"): @@ -79,22 +104,22 @@ def test_lazy_pool_checks_workers_only_when_used(): @pytest.mark.parametrize("ahead", [1, 3, None]) -def test_ordered_map_keeps_the_order_and_bounds_the_tasks(ahead): - """Results come in the tasks' order, and when the i-th result is taken - exactly min(n, i + ahead) tasks have been made (default ahead: twice - the workers).""" +def test_ordered_map_keeps_the_order_and_bounds_the_tasks(ahead: int | None) -> None: + """Results come in the tasks' order. + + Also, when the i-th result is taken exactly min(n, i + ahead) tasks have been made (default + ahead: twice the workers). + """ made: list = [] with ThreadPoolExecutor(3) as pool: out = [] - for i, r in enumerate( - ordered_map(pool, _square, _made(20, made), ahead=ahead) - ): + for i, r in enumerate(ordered_map(pool, _square, _made(20, made), ahead=ahead)): assert len(made) == min(20, i + (ahead or 6)) out.append(r) assert out == [i * i for i in range(20)] -def test_ordered_map_default_bound_is_twice_the_workers(): +def test_ordered_map_default_bound_is_twice_the_workers() -> None: """The default bound follows the pool's workers (here 4: 8 ahead).""" made: list = [] with ThreadPoolExecutor(4) as pool: @@ -102,7 +127,7 @@ def test_ordered_map_default_bound_is_twice_the_workers(): assert len(made) == min(30, i + 8) -def test_ordered_map_checks_ahead(): +def test_ordered_map_checks_ahead() -> None: """``ahead`` must be a positive integer, checked at the call.""" with ThreadPoolExecutor(2) as pool: for bad in (0, -1, 1.5, True, "2"): @@ -111,10 +136,11 @@ def test_ordered_map_checks_ahead(): @pytest.mark.parametrize("kind", ["none", "lazy", "threads"]) -def test_ordered_map_with_one_worker_makes_nothing_ahead(kind): - """Without a pool or with one worker each task is made and run here - when its result is asked for, so a failing task stops before the next - is made.""" +def test_ordered_map_with_one_worker_makes_nothing_ahead(kind: str) -> None: + """Without a pool or with one worker each task is made and run here. + + This happens when its result is asked for, so a failing task stops before the next is made. + """ pool = { "none": None, "lazy": LazyPool(1), @@ -124,8 +150,14 @@ def test_ordered_map_with_one_worker_makes_nothing_ahead(kind): here = threading.get_ident() seen = [] - def task(x): - """Record where the task runs.""" + def task(x: int) -> int: + """Record where the task runs. + + Returns + ------- + int + The square of x. + """ seen.append(threading.get_ident()) return _square(x) @@ -134,9 +166,7 @@ def task(x): assert seen == [here] * 5 made.clear() with pytest.raises(ValueError, match="negative"): - list( - ordered_map(pool, _square, (made.append(x) or x for x in [-1, 2])) - ) + list(ordered_map(pool, _square, (made.append(x) or x for x in [-1, 2]))) assert made == [-1] if kind == "threads": pool.shutdown() @@ -145,25 +175,44 @@ def task(x): class _Recorder(ThreadPoolExecutor): """A thread pool that keeps the futures it returns.""" - def __init__(self, workers): - """A pool of ``workers`` threads.""" + def __init__(self, workers: int) -> None: + """Create a pool of workers threads.""" super().__init__(workers) self.futures = [] - def submit(self, *args, **kwargs): - """Submit and keep the future.""" + def submit(self, *args: object, **kwargs: object) -> Future: + """Submit and keep the future. + + Returns + ------- + Future + The future of the submitted task. + """ fut = super().submit(*args, **kwargs) self.futures.append(fut) return fut -def test_ordered_map_cancels_waiting_tasks_when_a_task_fails(): - """A task's error surfaces at once: the tasks not yet started are - cancelled and no more tasks are made.""" +def test_ordered_map_cancels_waiting_tasks_when_a_task_fails() -> None: + """A task's error surfaces at once. + + The tasks not yet started are cancelled and no more tasks are made. + """ gate = threading.Event() - def task(x): - """Fail for -1; otherwise wait for the gate.""" + def task(x: int) -> int: + """Fail for -1; otherwise wait for the gate. + + Returns + ------- + int + The argument x, once the gate is set. + + Raises + ------ + ValueError + If x is negative. + """ if x < 0: raise ValueError("negative") gate.wait(10) @@ -172,8 +221,14 @@ def task(x): pool = _Recorder(2) made: list = [] - def tasks(): - """-1, then 0, 1, ..., recording each.""" + def tasks() -> Iterator[int]: + """-1, then 0, 1, ..., recording each. + + Yields + ------ + int + Each task, after it has been recorded in made. + """ for x in [-1] + list(range(10)): made.append(x) yield x @@ -191,26 +246,36 @@ def tasks(): @pytest.mark.parametrize("error", [RuntimeError, KeyboardInterrupt]) -def test_ordered_map_cancels_waiting_tasks_when_the_caller_stops(error): - """When the caller raises (an interrupt too) and closes the iterator, - the tasks not yet started are cancelled and no more are made.""" +def test_ordered_map_cancels_waiting_tasks_when_the_caller_stops( + error: type[BaseException], +) -> None: + """The tasks not yet started are cancelled and no more are made. + + This is so when the caller raises (an interrupt too) and closes the iterator. + """ gate = threading.Event() - def task(x): - """Return 0 at once; wait for the gate otherwise.""" + def task(x: int) -> int: + """Return 0 at once; wait for the gate otherwise. + + Returns + ------- + int + The argument x, after the wait for the gate unless x is 0. + """ if x: gate.wait(10) return x pool = _Recorder(2) made: list = [] - with pytest.raises(error): - with closing( - ordered_map(pool, task, _made(10, made), ahead=4) - ) as results: - for r in results: - assert r == 0 - raise error("stop") + with ( + pytest.raises(error), + closing(ordered_map(pool, task, _made(10, made), ahead=4)) as results, + ): + for r in results: + assert r == 0 + raise error("stop") # 1 and 2 run in the two threads; 3 waits assert made == [0, 1, 2, 3] assert pool.futures[3].cancelled() @@ -218,9 +283,11 @@ def task(x): pool.shutdown() -def test_lazy_pool_with_one_worker_runs_here(): - """With one worker nothing is started; tasks run at submission and - their errors reach the caller.""" +def test_lazy_pool_with_one_worker_runs_here() -> None: + """With one worker nothing is started. + + Tasks run at submission and their errors reach the caller. + """ pool = LazyPool(1) assert pool.submit(_square, 4).result() == 16 with pytest.raises(ValueError, match="negative"): @@ -230,17 +297,29 @@ def test_lazy_pool_with_one_worker_runs_here(): @pytest.mark.parametrize("why", ["daemon", "start", "check"]) -def test_lazy_pool_runs_here_when_workers_cannot_start(monkeypatch, why): - """In a daemonic process no start is tried; when the start fails (a - broken pool, as from a script read from standard input, or workers - refused by the start-up check) a warning is given once; in both cases - the tasks run here, in order.""" +def test_lazy_pool_runs_here_when_workers_cannot_start( + monkeypatch: pytest.MonkeyPatch, why: str +) -> None: + """In a daemonic process no start is tried. + + When the start fails (a broken pool, as from a script read from standard input, or workers + refused by the start-up check) a warning is given once; in both cases the tasks run here, + in order. + """ from concurrent.futures.process import BrokenProcessPool starts = [] - def failing(workers): - """A start that fails.""" + def failing(workers: int) -> NoReturn: + """Fail a start. + + Raises + ------ + BrokenProcessPool + If why is "start". + RuntimeError + Otherwise. + """ # noqa: DOC502 starts.append(workers) raise (BrokenProcessPool if why == "start" else RuntimeError)("no") @@ -266,15 +345,30 @@ def failing(workers): @pytest.mark.parametrize("error", [ValueError, KeyboardInterrupt]) -def test_fallback_stops_at_the_first_failing_task(monkeypatch, error): - """When the workers cannot be started (here: a daemonic process), the - tasks run here one after the other with nothing ahead, so the task - after one that fails or is interrupted is not run.""" +def test_fallback_stops_at_the_first_failing_task( + monkeypatch: pytest.MonkeyPatch, error: type[BaseException] +) -> None: + """When the workers cannot be started (here: a daemonic process), the tasks run here. + + They run one after the other with nothing ahead, so the task after one that fails or is + interrupted is not run. + """ monkeypatch.setattr(multiprocessing.current_process(), "daemon", True) ran = [] - def task(x): - """Record the task; the first one fails.""" + def task(x: int) -> int: + """Record the task; the first one fails. + + Returns + ------- + int + The argument x. + + Raises + ------ + BaseException + The error of the test (as given), for the first task. + """ # noqa: DOC502 ran.append(x) if x == 0: raise error("stop") @@ -286,17 +380,41 @@ def task(x): assert ran == [0] and made == [0] -def test_ordered_map_raises_a_task_makers_error_in_its_turn(): - """An error of the iterable while it makes a later task does not come - before the error of an earlier task, nor before earlier results.""" +def test_ordered_map_raises_a_task_makers_error_in_its_turn() -> None: + """An error of the iterable while it makes a later task does not come early. + + It does not come before the error of an earlier task, nor before earlier results. + """ + + def tasks(n_good: int) -> Iterator[int]: + """``n_good`` tasks, then the maker fails. + + Yields + ------ + int + Each of the n_good tasks, 0 to n_good - 1. - def tasks(n_good): - """``n_good`` tasks, then the maker fails.""" + Raises + ------ + RuntimeError + After the n_good tasks (the maker fails). + """ yield from range(n_good) raise RuntimeError("maker") - def task(x): - """Fail for task 1.""" + def task(x: int) -> int: + """Fail for task 1. + + Returns + ------- + int + The argument x. + + Raises + ------ + ValueError + If x is 1. + """ if x == 1: raise ValueError("task 1") return x @@ -311,27 +429,36 @@ def task(x): assert got == [0] -def test_lazy_pool_start_error_is_raised_while_importing_main(monkeypatch): - """In a spawned process that is still importing its main module (the - worker of an unguarded script), the start's error is raised as it is: - the worker ends instead of doing the script's work again.""" +def test_lazy_pool_start_error_is_raised_while_importing_main( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """In a spawned process that is still importing its main module, the start's error is raised. + + The process is the worker of an unguarded script; the error is raised as it is: the worker + ends instead of doing the script's work again. + """ - def failing(workers): - """The standard library's refusal.""" + def failing(workers: int) -> NoReturn: + """Refuse as the standard library does. + + Raises + ------ + RuntimeError + Always (bootstrapping phase). + """ raise RuntimeError("bootstrapping phase") monkeypatch.setattr(parallel, "make_pool", failing) - monkeypatch.setattr( - multiprocessing.current_process(), "_inheriting", True, raising=False - ) + monkeypatch.setattr(multiprocessing.current_process(), "_inheriting", True, raising=False) with pytest.raises(RuntimeError, match="bootstrapping"): LazyPool(2).submit(_square, 2) -def test_check_started_refuses_missing_or_threaded_workers(): - """The start-up check wants every worker, each with one thread (a - worker whose BLAS counts could not be read is judged by its - variables).""" +def test_check_started_refuses_missing_or_threaded_workers() -> None: + """The start-up check wants every worker, each with one thread. + + A worker whose BLAS counts could not be read is judged by its variables. + """ one = {k: "1" for k in THREAD_VARS} ok = [{"pid": p, "env": one, "blas": {"lib": 1}} for p in (1, 2)] parallel._check_started(ok, 2) @@ -345,28 +472,41 @@ def test_check_started_refuses_missing_or_threaded_workers(): parallel._check_started([ok[0], dict(ok[1], blas={"lib": 64})], 2) -def test_ordered_map_keeps_the_awaited_task_cancellable(): - """A wait that is interrupted cancels the task waited for too, if it - has not started (it is still among the pending ones).""" +def test_ordered_map_keeps_the_awaited_task_cancellable() -> None: + """A wait that is interrupted cancels the task waited for too, if it has not started. + + It is still among the pending ones. + """ from concurrent.futures import Future class Pool: - """An executor of two workers whose first future's wait is - interrupted.""" + """An executor of two workers whose first future's wait is interrupted.""" _max_workers = 2 - def __init__(self): + def __init__(self) -> None: """No futures yet.""" self.futures = [] - def submit(self, func, task): - """A future that never runs.""" + def submit(self, func: Callable[..., object], task: object) -> Future: + """Return a future that never runs. + + Returns + ------- + Future + A future that never runs (the first one's wait is interrupted). + """ fut = Future() if not self.futures: - def interrupted(timeout=None): - """An interrupted wait.""" + def interrupted(timeout: float | None = None) -> NoReturn: + """Interrupt the wait. + + Raises + ------ + KeyboardInterrupt + Always. + """ raise KeyboardInterrupt fut.result = interrupted @@ -384,14 +524,25 @@ def interrupted(timeout=None): @pytest.fixture -def reports(monkeypatch): - """The start reports of the pools that are started, one list per - pool.""" +def reports(monkeypatch: pytest.MonkeyPatch) -> list[list[dict]]: + """Return the start reports of the pools that are started, one list per pool. + + Returns + ------- + list[list[dict]] + The start reports, one list per pool that is started (filled as the pools start). + """ kept = [] real = parallel.spawn_pool - def spawn(*args, **kwargs): - """spawn_pool, its workers' reports kept.""" + def spawn(*args: object, **kwargs: object) -> tuple[ProcessPoolExecutor, list[dict]]: + """Call spawn_pool and keep its workers' reports. + + Returns + ------- + tuple[ProcessPoolExecutor, list[dict]] + The pool and the reports of its workers, as spawn_pool gives them. + """ pool, started = real(*args, **kwargs) kept.append(started) return pool, started @@ -400,9 +551,11 @@ def spawn(*args, **kwargs): return kept -def _assert_one_thread(started, n): - """``n`` distinct workers, each with the thread variables at 1 and, - where they can be read, one BLAS thread.""" +def _assert_one_thread(started: list[dict], n: int) -> None: + """``n`` distinct workers, each with the thread variables at 1. + + And where they can be read, each has one BLAS thread. + """ assert len({r["pid"] for r in started}) == n readable = shared.blas_threads() is not None # numpy is loaded here for r in started: @@ -411,14 +564,25 @@ def _assert_one_thread(started, n): assert bool(r["blas"]) == readable, r -def _thread_env(): - """The parent's thread variables.""" +def _thread_env() -> dict[str, str | None]: + """Return the parent's thread variables. + + Returns + ------- + dict[str, str | None] + The value of each thread variable in the parent's environment (None when unset). + """ return {k: os.environ.get(k) for k in THREAD_VARS} -def _none_left(before, seconds: float = 30.0) -> bool: - """Whether the child processes started since ``before`` end within - ``seconds``.""" +def _none_left(before: set[multiprocessing.process.BaseProcess], seconds: float = 30.0) -> bool: + """Return whether the child processes started since before end within seconds. + + Returns + ------- + bool + True if no child process started since before is still running after seconds. + """ deadline = time.monotonic() + seconds while time.monotonic() < deadline: if not set(multiprocessing.active_children()) - before: @@ -428,10 +592,14 @@ def _none_left(before, seconds: float = 30.0) -> bool: @pytest.mark.processes -def test_every_worker_starts_with_one_thread(monkeypatch, reports): - """Every worker of a pool has one thread per numerical library, - whatever the parent's variables say; the parent's variables are as - before, an unset one unset.""" +def test_every_worker_starts_with_one_thread( + monkeypatch: pytest.MonkeyPatch, reports: list[list[dict]] +) -> None: + """Every worker of a pool has one thread per numerical library. + + This holds whatever the parent's variables say; the parent's variables are as before, an + unset one unset. + """ monkeypatch.delenv("OMP_NUM_THREADS", raising=False) monkeypatch.setenv("OPENBLAS_NUM_THREADS", "3") monkeypatch.setenv("MKL_NUM_THREADS", "2") @@ -451,18 +619,20 @@ def test_every_worker_starts_with_one_thread(monkeypatch, reports): @pytest.mark.processes def test_pools_started_from_two_threads_restore_the_environment( - monkeypatch, reports -): - """Two pools started at once from two threads leave the parent's - variables as they were, and both have one thread per worker.""" + monkeypatch: pytest.MonkeyPatch, reports: list[list[dict]] +) -> None: + """Two pools started at once from two threads leave the parent's variables as they were. + + Both have one thread per worker. + """ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "12") monkeypatch.delenv("OMP_NUM_THREADS", raising=False) before = _thread_env() go = threading.Barrier(2) pools = [None, None] - def start(i): - """Start pool ``i`` when the other thread does.""" + def start(i: int) -> None: + """Start pool i when the other thread does.""" go.wait() pools[i] = make_pool(2) @@ -484,10 +654,11 @@ def start(i): @pytest.mark.processes @pytest.mark.parametrize("how", ["timeout", "check", "interrupt"]) -def test_a_failed_start_leaves_no_worker(monkeypatch, how): - """A start that fails (workers that do not all start in time, a failed - check) or is interrupted ends the started workers and restores the - parent's variables.""" +def test_a_failed_start_leaves_no_worker(monkeypatch: pytest.MonkeyPatch, how: str) -> None: + """A failed or interrupted start ends the started workers and restores the parent's variables. + + A start fails when workers do not all start in time or the check fails. + """ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "5") before = _thread_env() children = set(multiprocessing.active_children()) @@ -497,7 +668,7 @@ def test_a_failed_start_leaves_no_worker(monkeypatch, how): else: error = RuntimeError if how == "check" else KeyboardInterrupt - def fail(reports, n): + def fail(reports: list, n: int) -> NoReturn: """Fail after the workers started.""" assert len(reports) == n raise error("stop") @@ -510,9 +681,11 @@ def fail(reports, n): @pytest.mark.processes -def test_lazy_pool_does_not_wait_for_its_workers_when_cancelled(): - """``shutdown(cancel=True)`` does not wait for running tasks, and the - workers end by themselves once the tasks they hold have ended.""" +def test_lazy_pool_does_not_wait_for_its_workers_when_cancelled() -> None: + """``shutdown(cancel=True)`` does not wait for running tasks. + + The workers end by themselves once the tasks they hold have ended. + """ pool = LazyPool(2) children = set(multiprocessing.active_children()) held = [pool.submit(time.sleep, 2) for _ in range(3)] diff --git a/tests/spine/test_spine_pipeline.py b/tests/spine/test_spine_pipeline.py index 9419a0ef..32746da6 100644 --- a/tests/spine/test_spine_pipeline.py +++ b/tests/spine/test_spine_pipeline.py @@ -1,6 +1,8 @@ -"""End-to-end tests of ``giant spine`` on a synthetic session.""" +"""End-to-end tests of giant spine on a synthetic session.""" import json +from pathlib import Path +from typing import NoReturn import numpy as np import pytest @@ -20,12 +22,18 @@ @pytest.fixture -def session(tmp_path): - """The synthetic session's folders.""" +def session(tmp_path: Path) -> dict: + """Return the synthetic session's folders. + + Returns + ------- + dict + The session's folders, as from :func:`synthetic.make_session`. + """ return syn.make_session(tmp_path) -def test_run_summary_reads_matlab_orientation(session): +def test_run_summary_reads_matlab_orientation(session: dict) -> None: """Arrays come back in MATLAB's dimension order and orientation.""" run = RunSummary(session["run"]) assert run.paths == [1, 2] @@ -41,25 +49,27 @@ def test_run_summary_reads_matlab_orientation(session): np.testing.assert_allclose(act["mean_dF"][:, 0], 10 * np.arange(4) + 4.5) -def test_trial_map_needs_a_base_only_for_affine_maps(session): +def test_trial_map_needs_a_base_only_for_affine_maps(session: dict) -> None: """Shift maps need no index base; true affine ones do.""" run = RunSummary(session["run"]) tm = run.trial_map(1) assert isinstance(tm, TrialMap) and tm.displacement is None - r, c = tm.grid_coords(1, (2, 2)) + r, _c = tm.grid_coords(1, (2, 2)) np.testing.assert_allclose(r, [[1, 1], [2, 2]]) -def test_table_trials(session): +def test_table_trials(session: dict) -> None: """Stems from the registered movies, numbers from the raw files.""" stems, acq = table_trials(session["table"], 2) assert stems[0] == "E1T1DMD2" np.testing.assert_array_equal(acq, [2, 3, 4, 5]) -def test_readout_writes_a_product(session, tmp_path): - """The readout's images, windows and normalized sizes are consistent, - and a rerun reuses the cache and the output.""" +def test_readout_writes_a_product(session: dict, tmp_path: Path) -> None: + """Check that the readout's images, windows and normalized sizes are consistent. + + A rerun reuses the cache and the output. + """ out = tmp_path / "out" rep = make_spine_summary( session["run"], @@ -122,8 +132,10 @@ def test_readout_writes_a_product(session, tmp_path): assert not rep3["paths"][1]["f0_reused"] -def test_cli_readout_and_images(session, tmp_path, capsys): - """``giant spine images`` fills the cache that ``readout`` reuses.""" +def test_cli_readout_and_images( + session: dict, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """``giant spine images`` fills the cache that readout reuses.""" out = tmp_path / "cli" common = [ str(session["run"]), @@ -147,7 +159,7 @@ def test_cli_readout_and_images(session, tmp_path, capsys): assert rep["paths"]["1"]["f0_reused"] and list(rep["paths"]) == ["1"] -def test_readout_without_baselines(tmp_path): +def test_readout_without_baselines(tmp_path: Path) -> None: """Without baselines the run's own images are read out.""" s = syn.make_session(tmp_path, with_f0_silo=False) rep = make_spine_summary(s["run"], s["table"], tmp_path / "o") @@ -155,7 +167,7 @@ def test_readout_without_baselines(tmp_path): assert set(p["images"]) == {"mean_ch1", "mean_ch2"} -def test_baselines_need_the_moco_folder(session, tmp_path): +def test_baselines_need_the_moco_folder(session: dict, tmp_path: Path) -> None: """A baseline folder without the motion-correction folder is refused.""" with pytest.raises(ValueError, match="both"): make_spine_summary( @@ -166,34 +178,34 @@ def test_baselines_need_the_moco_folder(session, tmp_path): ) -def test_activity_uses_the_activity_channel(tmp_path): - """Activity comes from ``params/activityChannel``; a trial without - traces is NaN, not inactive.""" +def test_activity_uses_the_activity_channel(tmp_path: Path) -> None: + """Check that activity comes from params/activityChannel. + + A trial without traces is NaN, not inactive. + """ s = syn.make_session(tmp_path, activity_channel=2, missing_trial=1) run = RunSummary(s["run"]) assert run.activity_channel() == 2 act = run.activity(1) - np.testing.assert_allclose( - act["mean_dF"][[0, 2, 3], 0], 1000 + 10 * np.array([0, 2, 3]) + 4.5 - ) + np.testing.assert_allclose(act["mean_dF"][[0, 2, 3], 0], 1000 + 10 * np.array([0, 2, 3]) + 4.5) np.testing.assert_allclose(act["event_frames"][[0, 2, 3], 0], 10) assert np.isnan(act["mean_dF"][1]).all() assert np.isnan(act["event_frames"][1]).all() -def test_summary_key_follows_the_paths(tmp_path): +def test_summary_key_follows_the_paths(tmp_path: Path) -> None: """Different path selections give different summaries.""" s = syn.make_session(tmp_path) keys = { - tuple(sel or ()): make_spine_summary( - s["run"], s["table"], tmp_path / "out", paths=sel - )["key"] + tuple(sel or ()): make_spine_summary(s["run"], s["table"], tmp_path / "out", paths=sel)[ + "key" + ] for sel in (None, [1], [2]) } assert len(set(keys.values())) == 3 -def test_network_images_take_a_trial_warp(session, tmp_path): +def test_network_images_take_a_trial_warp(session: dict, tmp_path: Path) -> None: """The extraction plan's TrialWarp works as the trial map.""" from giant_python.extraction.raster.alignment import TrialWarp from giant_python.spine.images import network_f0_stack @@ -203,22 +215,23 @@ def test_network_images_take_a_trial_warp(session, tmp_path): stems, _ = table_trials(session["table"], 1) args = (session["baselines"], session["moco"], stems) a = network_f0_stack(*args, tmap, run.shape(1), trim_s=0.1) - b = network_f0_stack( - *args, TrialWarp(tmap.affine), run.shape(1), trim_s=0.1 - ) + b = network_f0_stack(*args, TrialWarp(tmap.affine), run.shape(1), trim_s=0.1) np.testing.assert_allclose(a.images, b.images, equal_nan=True) assert np.isfinite(a.images).any() -def test_write_atomic_gives_each_writer_its_own_file(tmp_path): - """A writer that starts while another is writing the same file does not +def test_write_atomic_gives_each_writer_its_own_file(tmp_path: Path) -> None: + """Check that each writer gets its own temporary file. + + A writer that starts while another is writing the same file does not share its temporary file; both finish, and nothing is left behind. A - failed write leaves no file.""" + failed write leaves no file. + """ from giant_python.spine.pipeline import _write_atomic dest = tmp_path / "out" / "x.txt" - def outer(tmp): + def outer(tmp: Path) -> None: """Write, with a second writer of the same file in between.""" tmp.write_text("outer") _write_atomic(dest, lambda t: t.write_text("inner")) @@ -228,8 +241,14 @@ def outer(tmp): assert dest.read_text() == "outer" assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] - def fail(tmp): - """A write that fails.""" + def fail(tmp: Path) -> None: + """Write, then fail. + + Raises + ------ + RuntimeError + Always, after the partial write. + """ tmp.write_text("partial") raise RuntimeError("stop") @@ -239,7 +258,7 @@ def fail(tmp): assert [p.name for p in dest.parent.iterdir()] == ["x.txt"] -def test_stem_strips_windows_folders(): +def test_stem_strips_windows_folders() -> None: """A table written on Windows gives the bare stem on any system.""" name = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif" assert _stem("C:\\moco\\" + name) == "E1T1DMD1" @@ -247,27 +266,31 @@ def test_stem_strips_windows_folders(): assert _stem("E1T1DMD1.tif") is None -def test_network_images_follow_the_runs_discards(tmp_path): - """Without overrides the network images leave out the frames the run - discarded (``params/discardInitial_s``); an explicit value wins.""" +def test_network_images_follow_the_runs_discards(tmp_path: Path) -> None: + """Check that the network images leave out the frames the run discarded. + + Without overrides the network images leave out the frames the run + discarded (params/discardInitial_s); an explicit value wins. + """ s = syn.make_session(tmp_path, discard_initial_s=0.5) - kw = dict(baseline_dir=s["baselines"], moco_dir=s["moco"], trim_s=0.1) + kw = {"baseline_dir": s["baselines"], "moco_dir": s["moco"], "trim_s": 0.1} rep = make_spine_summary(s["run"], s["table"], tmp_path / "a", **kw) prod = read_product(rep["output"]) assert prod["attrs"]["settings"]["discard_initial_s"] == 0.5 n_run = prod["paths"][1]["image_attrs"]["f0_net"]["n_frames"] # 40 discarded frames at the start, 8 trimmed at the end assert (n_run == syn.N_FRAMES - 48).all() - rep0 = make_spine_summary( - s["run"], s["table"], tmp_path / "b", discard_initial_s=0.0, **kw - ) + rep0 = make_spine_summary(s["run"], s["table"], tmp_path / "b", discard_initial_s=0.0, **kw) n0 = read_product(rep0["output"])["paths"][1]["image_attrs"]["f0_net"] assert (n0["n_frames"] == syn.N_FRAMES - 16).all() -def test_affine_maps_convert_from_one_based(tmp_path): - """A true affine map written one-based (GIAnT-MATLAB) gives the same - zero-based positions as the zero-based map (GIAnT-Python).""" +def test_affine_maps_convert_from_one_based(tmp_path: Path) -> None: + """Check that a one-based affine map gives the zero-based positions. + + A true affine map written one-based (GIAnT-MATLAB) gives the same + zero-based positions as the zero-based map (GIAnT-Python). + """ lin = np.array([[1.01, 0.02], [-0.015, 0.99]]) b0 = np.array([1.5, -2.25]) a0 = np.zeros((syn.N_TRIALS, 2, 3)) @@ -290,7 +313,7 @@ def test_affine_maps_convert_from_one_based(tmp_path): np.testing.assert_allclose(c, expect_c, atol=1e-12) -def test_product_records_the_activity_channel(tmp_path): +def test_product_records_the_activity_channel(tmp_path: Path) -> None: """The product says which file channel is the run's activity.""" s = syn.make_session(tmp_path, activity_channel=2) rep = make_spine_summary(s["run"], s["table"], tmp_path / "out") @@ -299,10 +322,13 @@ def test_product_records_the_activity_channel(tmp_path): assert {"mean_ch1", "mean_ch2"} <= set(prod["paths"][1]["images"]) -def test_displacement_maps_end_to_end(tmp_path): - """A run with a displacement field (patchwise alignment) puts the - network's trials in place through the field, not the affine maps.""" - kw = dict(trim_s=0.1) +def test_displacement_maps_end_to_end(tmp_path: Path) -> None: + """Check that a displacement field puts the network's trials in place. + + A run with a displacement field (patchwise alignment) puts the + network's trials in place through the field, not the affine maps. + """ + kw = {"trim_s": 0.1} s = syn.make_session(tmp_path / "d", displacement=True) run = RunSummary(s["run"]) assert run.trial_map(1).displacement is not None @@ -322,9 +348,7 @@ def test_displacement_maps_end_to_end(tmp_path): p["images"]["f0_silo_ch1"][:, ok], rtol=1e-3, ) - np.testing.assert_allclose( - p["normalized"]["sources"]["f0_net"], 0, atol=2e-3 - ) + np.testing.assert_allclose(p["normalized"]["sources"]["f0_net"], 0, atol=2e-3) # the same maps as affine identity alone leave the trials displaced a = np.zeros((syn.N_TRIALS, 2, 3)) a[:, :, :2] = np.eye(2) @@ -343,17 +367,18 @@ def test_displacement_maps_end_to_end(tmp_path): assert np.abs(net / p0["images"]["f0_silo_ch1"][1:, ok0] - 1).max() > 1e-2 -def test_fitted_images_do_not_shrink_the_windows(tmp_path): - """SILo's own F0 images, with values only at the pixels it fitted, are +def test_fitted_images_do_not_shrink_the_windows(tmp_path: Path) -> None: + """Check that SILo's own F0 images do not shrink the windows. + + SILo's own F0 images, with values only at the pixels it fitted, are read out in the windows of the field images: the sources (inside the fitted pixels) read as before, a user ROI partly outside keeps its readouts of the other images and gets NaN in f0_silo, and the report - counts it.""" - kw = dict(trim_s=0.1) + counts it. + """ + kw = {"trim_s": 0.1} full = syn.make_session(tmp_path / "full") - box = syn.make_session( - tmp_path / "box", f0_silo_box=(slice(4, 20), slice(5, 25)) - ) + box = syn.make_session(tmp_path / "box", f0_silo_box=(slice(4, 20), slice(5, 25))) reps, prods = {}, {} for name, s in (("full", full), ("box", box)): reps[name] = make_spine_summary( @@ -368,23 +393,15 @@ def test_fitted_images_do_not_shrink_the_windows(tmp_path): a, b = prods["full"], prods["box"] np.testing.assert_array_equal(a["valid"], b["valid"]) for k in a["readout"]["sources"]: - np.testing.assert_allclose( - a["readout"]["sources"][k], b["readout"]["sources"][k] - ) + np.testing.assert_allclose(a["readout"]["sources"][k], b["readout"]["sources"][k]) for k in a["normalized"]["sources"]: - np.testing.assert_allclose( - a["normalized"]["sources"][k], b["normalized"]["sources"][k] - ) + np.testing.assert_allclose(a["normalized"]["sources"][k], b["normalized"]["sources"][k]) ua, ub = a["readout"]["user"], b["readout"]["user"] np.testing.assert_array_equal(ua["n_pixels"], ub["n_pixels"]) np.testing.assert_allclose(ua["f0_net"], ub["f0_net"]) assert np.isnan(ub["f0_silo_ch1"][:, 0]).all() # roi A: partly outside - np.testing.assert_allclose( - ub["f0_silo_ch1"][:, 1], ua["f0_silo_ch1"][:, 1] - ) - assert reps["box"]["paths"][1]["not_covered"] == { - "user": {"f0_silo_ch1": 1, "f0_silo_ch2": 1} - } + np.testing.assert_allclose(ub["f0_silo_ch1"][:, 1], ua["f0_silo_ch1"][:, 1]) + assert reps["box"]["paths"][1]["not_covered"] == {"user": {"f0_silo_ch1": 1, "f0_silo_ch2": 1}} assert "not_covered" not in reps["full"]["paths"][1] assert b["image_attrs"]["f0_silo_ch1"]["covers"] == "fitted" assert b["image_attrs"]["f0_net"]["covers"] == "field" @@ -405,9 +422,12 @@ def test_fitted_images_do_not_shrink_the_windows(tmp_path): assert sum("does not cover" in m for m in notes) == 4 # 2 images x 2 paths -def test_no_shared_trial_reads_nothing(): - """Field images without a trial in common leave no trial and no valid - pixel, with a note, rather than windows over the whole frame.""" +def test_no_shared_trial_reads_nothing() -> None: + """Check that field images without a trial in common read nothing. + + Field images without a trial in common leave no trial and no valid + pixel, with a note, rather than windows over the whole frame. + """ from giant_python.spine.readout import common_valid a = np.ones((4, 3, 3)) @@ -425,10 +445,13 @@ def test_no_shared_trial_reads_nothing(): assert not common_valid([a, b], used).any() -def test_acquisition_numbers_from_the_file_name(tmp_path): - """The acquisition number is read from the raw file's own name (not a +def test_acquisition_numbers_from_the_file_name(tmp_path: Path) -> None: + """Check that the acquisition number is read from the raw file's own name. + + The number is read from the raw file's own name (not a folder that also says TRIAL, with either separator), and a table whose - raw and registered lists differ in length is refused.""" + raw and registered lists differ in length is refused. + """ from giant_python.io.hdf5 import save_struct_h5 reg = np.array( @@ -470,11 +493,14 @@ def test_acquisition_numbers_from_the_file_name(tmp_path): table_trials(table, 1) -def test_untrimmed_trials_are_reported(session, tmp_path): - """A trial too short for the trim is averaged whole, as GIAnT-MATLAB - does, and the product, the report and a note say so.""" +def test_untrimmed_trials_are_reported(session: dict, tmp_path: Path) -> None: + """Check that a trial too short for the trim is averaged whole. + + It is averaged whole, as GIAnT-MATLAB + does, and the product, the report and a note say so. + """ notes = [] - kw = dict(baseline_dir=session["baselines"], moco_dir=session["moco"]) + kw = {"baseline_dir": session["baselines"], "moco_dir": session["moco"]} # 160 frames: a 1 s trim at 80 Hz leaves nothing rep = make_spine_summary( session["run"], @@ -490,26 +516,22 @@ def test_untrimmed_trials_are_reported(session, tmp_path): assert (attrs["n_frames"] == syn.N_FRAMES).all() assert rep["paths"][1]["f0_untrimmed"] == [1, 2, 3, 4] assert sum("too short for the trim" in m for m in notes) == 2 - rep = make_spine_summary( - session["run"], session["table"], tmp_path / "short", trim_s=0.1, **kw - ) + rep = make_spine_summary(session["run"], session["table"], tmp_path / "short", trim_s=0.1, **kw) p = read_product(rep["output"])["paths"][1] assert not p["image_attrs"]["f0_net"]["untrimmed"].any() assert "f0_untrimmed" not in rep["paths"][1] -def test_readout_runs_the_trend_tests(session, tmp_path): - """Every normalized image gets the trend tests over its trials, with - trial positions as trial-table indices; the test settings change the - output's key but not the network images' cache.""" +def test_readout_runs_the_trend_tests(session: dict, tmp_path: Path) -> None: + """Check that every normalized image gets the trend tests over its trials. + + The trial positions are trial-table indices; the test settings change the + output's key but not the network images' cache. + """ from giant_python.spine.trends import trend_tests - kw = dict( - baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1 - ) - rep = make_spine_summary( - session["run"], session["table"], tmp_path / "o", n_perm=200, **kw - ) + kw = {"baseline_dir": session["baselines"], "moco_dir": session["moco"], "trim_s": 0.1} + rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) p = read_product(rep["output"])["paths"][1] norm = p["normalized"]["sources"] tr = p["trends"]["sources"] @@ -532,14 +554,10 @@ def test_readout_runs_the_trend_tests(session, tmp_path): # -1 elsewhere step = tested & (direct["step_k"] > 0) assert step.any() - np.testing.assert_array_equal( - rec["step_after"][step], rows[direct["step_k"][step] - 1] - ) + np.testing.assert_array_equal(rec["step_after"][step], rows[direct["step_k"][step] - 1]) assert (rec["step_after"][~step] == -1).all() run = tested & (direct["brief_start"] >= 0) - np.testing.assert_array_equal( - rec["brief_first"][run], rows[direct["brief_start"][run]] - ) + np.testing.assert_array_equal(rec["brief_first"][run], rows[direct["brief_start"][run]]) assert (rec["brief_first"][~run] == -1).all() np.testing.assert_array_equal(rec["brief_len"][tested & ~run], 0) assert rec["attrs"]["n_perm"] == 200 @@ -547,38 +565,44 @@ def test_readout_runs_the_trend_tests(session, tmp_path): summ = rep["paths"][1]["trends"]["f0_net"] assert summ["tested"] == int(tested.sum()) assert summ["counts"] == direct["counts"] - rep2 = make_spine_summary( - session["run"], session["table"], tmp_path / "o", n_perm=0, **kw - ) + rep2 = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=0, **kw) assert rep2["output"] != rep["output"] and not rep2["reused"] assert rep2["paths"][1]["f0_reused"] p2 = read_product(rep2["output"])["paths"][1] assert np.isnan(p2["trends"]["sources"]["f0_net"]["step_p"]).all() -def test_readout_refuses_bad_trend_settings(session, tmp_path): - """Invalid trend settings are refused before anything is read or - reused.""" +def test_readout_refuses_bad_trend_settings(session: dict, tmp_path: Path) -> None: + """Check that invalid trend settings are refused. + + They are refused before anything is read or reused. + """ with pytest.raises(ValueError, match="fdr_q"): - make_spine_summary( - session["run"], session["table"], tmp_path / "o", fdr_q=2.0 - ) + make_spine_summary(session["run"], session["table"], tmp_path / "o", fdr_q=2.0) with pytest.raises(ValueError, match="min_change"): - make_spine_summary( - session["run"], session["table"], tmp_path / "o", min_change=1.5 - ) + make_spine_summary(session["run"], session["table"], tmp_path / "o", min_change=1.5) assert not (tmp_path / "o").exists() -def test_trials_without_numbers_are_noted(session, tmp_path, monkeypatch): - """A trial whose raw file has no acquisition number is left out of the - brief test's runs, and the summary's notes say so.""" +def test_trials_without_numbers_are_noted( + session: dict, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Check that a trial whose raw file has no acquisition number is left out. + + It is left out of the brief test's runs, and the summary's notes say so. + """ import giant_python.spine.pipeline as pl real = pl.table_trials - def no_number(table, path): - """The table's trials with trial 2 unnumbered.""" + def no_number(table: str | Path, path: int) -> tuple[list, np.ndarray]: + """Return the table's trials with trial 2 unnumbered. + + Returns + ------- + tuple[list, np.ndarray] + The trials' stems and their acquisition numbers, with trial 2's set to -1. + """ stems, acq = real(table, path) acq = acq.copy() acq[1] = -1 @@ -599,48 +623,43 @@ def no_number(table, path): assert blocks[1] != blocks[0] and blocks[1] != blocks[2] -def test_unnumbered_trials_follow_the_path_not_the_image(): - """With some numbered trials on the path, unnumbered trials stay +def test_unnumbered_trials_follow_the_path_not_the_image() -> None: + """Check that unnumbered trials stay blocks of their own. + + With some numbered trials on the path, unnumbered trials stay blocks of their own even in an image that covers only them; with no - numbers on the path, the table's order stands in (gaps split).""" + numbers on the path, the table's order stands in (gaps split). + """ from giant_python.spine.pipeline import _trends vals = np.random.default_rng(0).normal(size=(6, 4)) * 0.1 norm = {"img": vals.copy(), "ok": np.ones(4, bool)} norm["img"][[0, 1]] = np.nan # the image covers trials 2-5 only - opts = dict(n_perm=0, fdr_q=0.1, max_brief=3, seed=1, min_change=0.1) + opts = {"n_perm": 0, "fdr_q": 0.1, "max_brief": 3, "seed": 1, "min_change": 0.1} acq = np.array([3, 4, -1, -1, -1, -1]) tr, _ = _trends(1, norm, acq, opts, 1, lambda m: None, lambda m: None) - np.testing.assert_array_equal( - tr["img"]["arrays"]["blocks"], [-1, -1, 0, 1, 2, 3] - ) + np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, 1, 2, 3]) norm["img"][3] = np.nan # a gap in table order - tr, _ = _trends( - 1, norm, np.full(6, -1), opts, 1, lambda m: None, lambda m: None - ) - np.testing.assert_array_equal( - tr["img"]["arrays"]["blocks"], [-1, -1, 0, -1, 1, 1] - ) + tr, _ = _trends(1, norm, np.full(6, -1), opts, 1, lambda m: None, lambda m: None) + np.testing.assert_array_equal(tr["img"]["arrays"]["blocks"], [-1, -1, 0, -1, 1, 1]) + +def test_readout_calls_and_quality_columns( + session: dict, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """Check that the default image and its calls go into the summary and the report. -def test_readout_calls_and_quality_columns(session, tmp_path, capsys): - """The default image and its calls go into the summary and the report; - every image but the structural one gets the structural channel's change + Every image but the structural one gets the structural channel's change at its own split; the windows' motion beyond the trials' shifts is 0 - for shifts.""" + for shifts. + """ from giant_python.spine.qc import structural_change - kw = dict( - baseline_dir=session["baselines"], moco_dir=session["moco"], trim_s=0.1 - ) - rep = make_spine_summary( - session["run"], session["table"], tmp_path / "o", n_perm=200, **kw - ) + kw = {"baseline_dir": session["baselines"], "moco_dir": session["moco"], "trim_s": 0.1} + rep = make_spine_summary(session["run"], session["table"], tmp_path / "o", n_perm=200, **kw) p = read_product(rep["output"])["paths"][1] assert p["primary_image"] == "f0_net" - np.testing.assert_allclose( - p["readout"]["sources"]["align_px"], 0, atol=1e-9 - ) + np.testing.assert_allclose(p["readout"]["sources"]["align_px"], 0, atol=1e-9) norm = p["normalized"]["sources"] tr = p["trends"]["sources"] assert "structural_d" not in tr["mean_ch2"] @@ -693,25 +712,28 @@ def test_readout_calls_and_quality_columns(session, tmp_path, capsys): assert pr["paths"][1]["primary_image"] == "f0_silo_ch1" -def test_window_motion_needs_no_affine_base(tmp_path): - """Affine maps without a given index base still get the column (the - base moves only the translation).""" +def test_window_motion_needs_no_affine_base(tmp_path: Path) -> None: + """Check that affine maps without a given index base still get the column. + + The base moves only the translation. + """ a = np.zeros((syn.N_TRIALS, 2, 3)) for t, ang in enumerate((0.0, 0.01, -0.01, 0.02)): c, s_ = np.cos(ang), np.sin(ang) a[t] = [[c, -s_, syn.SHIFTS[t][0]], [s_, c, syn.SHIFTS[t][1]]] s = syn.make_session(tmp_path / "a", affine=a) rep = make_spine_summary(s["run"], s["table"], tmp_path / "a" / "o") - m = read_product(rep["output"])["paths"][1]["readout"]["sources"][ - "align_px" - ] + m = read_product(rep["output"])["paths"][1]["readout"]["sources"]["align_px"] assert np.isfinite(m).all() and (m > 0).all() -def test_default_image_without_trend_tests(tmp_path, monkeypatch): - """With too few trials for the trend tests, the default image still +def test_default_image_without_trend_tests(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Check the default image when there are too few trials for the trend tests. + + The default image still comes from the images with sizes (here the run's F0 of activity - channel 2), and no calls are reported.""" + channel 2), and no calls are reported. + """ import giant_python.spine.pipeline as pl monkeypatch.setattr(pl, "_trends", lambda *a, **k: ({}, {})) @@ -723,10 +745,13 @@ def test_default_image_without_trend_tests(tmp_path, monkeypatch): assert "calls" not in rep["paths"][1] -def test_default_image_needs_finite_sizes(tmp_path): - """An image that covers no window keeps its key with only NaN sizes; +def test_default_image_needs_finite_sizes(tmp_path: Path) -> None: + """Check that an image that covers no window is not the default. + + An image that covers no window keeps its key with only NaN sizes; it is not the default (here the run's F0 limited to a corner, so the - activity channel's mean takes its place).""" + activity channel's mean takes its place). + """ s = syn.make_session(tmp_path, f0_silo_box=(slice(0, 2), slice(0, 2))) rep = make_spine_summary(s["run"], s["table"], tmp_path / "o", n_perm=50) p = read_product(rep["output"])["paths"][1] @@ -735,14 +760,21 @@ def test_default_image_needs_finite_sizes(tmp_path): assert rep["paths"][1]["calls"]["image"] == "mean_ch1" -def _datasets(path) -> dict: - """Every dataset of a file: its shape, dtype and values (object and - string datasets as lists of their values, the others as bytes).""" +def _datasets(path: str | Path) -> dict: + """Return every dataset of a file: its shape, dtype and values. + + Object and string datasets are given as lists of their values, the others as bytes. + + Returns + ------- + dict + For each dataset name, a tuple of its shape, dtype string, dtype name and values. + """ import h5py out = {} - def add(name, obj): + def add(name: str, obj: h5py.Group | h5py.Dataset) -> None: """Add one dataset.""" if not isinstance(obj, h5py.Dataset): return @@ -757,10 +789,13 @@ def add(name, obj): @pytest.mark.processes -def test_worker_processes_give_the_same_product(session, tmp_path): - """Worker processes (F0 images and permutations) give the product of +def test_worker_processes_give_the_same_product(session: dict, tmp_path: Path) -> None: + """Check that worker processes (F0 images and permutations) give the same product. + + It is the product of one process: every dataset, string and object ones included, with the - same shape, dtype and values.""" + same shape, dtype and values. + """ reps = { w: make_spine_summary( session["run"], @@ -782,26 +817,32 @@ def test_worker_processes_give_the_same_product(session, tmp_path): def test_cached_images_and_no_permutations_start_no_workers( - session, tmp_path, monkeypatch -): - """A readout that reuses its cached images and runs no permutations - starts no workers, whatever their number (even one the workers would - refuse, as when they were threads).""" + session: dict, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Check that a readout reusing cached images and running no permutations starts no workers. + + It starts no workers, whatever their number (even one the workers would + refuse, as when they were threads). + """ from giant_python.spine import parallel - kw = dict( - baseline_dir=session["baselines"], - moco_dir=session["moco"], - cache_dir=tmp_path / "cache", - trim_s=0.1, - n_perm=0, - ) - first = make_spine_summary( - session["run"], session["table"], tmp_path / "o1", workers=1, **kw - ) + kw = { + "baseline_dir": session["baselines"], + "moco_dir": session["moco"], + "cache_dir": tmp_path / "cache", + "trim_s": 0.1, + "n_perm": 0, + } + first = make_spine_summary(session["run"], session["table"], tmp_path / "o1", workers=1, **kw) - def no_pool(workers): - """Fail: no pool may start.""" + def no_pool(workers: int | float) -> NoReturn: + """Fail: no pool may start. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("a pool was started") monkeypatch.setattr(parallel, "make_pool", no_pool) @@ -826,13 +867,24 @@ def no_pool(workers): @pytest.mark.default_workers -def test_no_workers_unless_asked_for(session, tmp_path, monkeypatch): - """Called without ``workers``, the readout does everything in the - calling process, permutations and fresh F0 images included.""" +def test_no_workers_unless_asked_for( + session: dict, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Check that, called without workers, the readout starts no pool. + + It does everything in the + calling process, permutations and fresh F0 images included. + """ from giant_python.spine import parallel - def no_pool(workers): - """Fail: no pool may start.""" + def no_pool(workers: int | float) -> NoReturn: + """Fail: no pool may start. + + Raises + ------ + AssertionError + Always. + """ raise AssertionError("a pool was started") monkeypatch.setattr(parallel, "make_pool", no_pool) @@ -851,11 +903,17 @@ def no_pool(workers): @pytest.mark.parametrize("error", [None, RuntimeError, KeyboardInterrupt]) def test_the_workers_stop_at_once_on_an_error( - session, tmp_path, monkeypatch, error -): - """The readout's workers are stopped when it ends: after their tasks + session: dict, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + error: type[BaseException] | None, +) -> None: + """Check that the readout's workers are stopped when it ends. + + They are stopped after their tasks when it succeeds, at once (cancelled) when it raises or is - interrupted.""" + interrupted. + """ from giant_python.spine import parallel, pipeline calls = [] @@ -866,8 +924,14 @@ def test_the_workers_stop_at_once_on_an_error( ) if error is not None: - def fail(*args): - """Fail inside the readout.""" + def fail(*args: object) -> NoReturn: + """Fail inside the readout. + + Raises + ------ + BaseException + The parametrized error, always. + """ # noqa: DOC502 raise error("stop") monkeypatch.setattr(pipeline, "_spine_summary", fail) @@ -875,20 +939,29 @@ def fail(*args): make_spine_summary(session["run"], session["table"], tmp_path) assert calls == [True] else: - make_spine_summary( - session["run"], session["table"], tmp_path, n_perm=0 - ) + make_spine_summary(session["run"], session["table"], tmp_path, n_perm=0) assert calls == [False] -def test_cli_images_takes_workers(session, tmp_path, monkeypatch, capsys): - """``giant spine images`` takes ``--workers`` like ``readout``.""" +def test_cli_images_takes_workers( + session: dict, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """``giant spine images`` takes --workers like readout.""" from giant_python.spine import pipeline got = {} - def fake(*args, **kwargs): - """Record the arguments.""" + def fake(*args: object, **kwargs: object) -> dict: + """Record the arguments. + + Returns + ------- + dict + An empty report. + """ got.update(kwargs) return {} diff --git a/tests/spine/test_spine_trends.py b/tests/spine/test_spine_trends.py index 40313d13..a34462e9 100644 --- a/tests/spine/test_spine_trends.py +++ b/tests/spine/test_spine_trends.py @@ -1,6 +1,8 @@ -"""Tests of the trend tests (:mod:`giant_python.spine.trends`), against -direct transcriptions of GIAnT-MATLAB's ``spineTrends.m`` and -``spineTrendsResid.m``.""" +"""Tests of the trend tests (:mod:`giant_python.spine.trends`). + +They run against direct transcriptions of GIAnT-MATLAB's spineTrends.m and +spineTrendsResid.m. +""" import math @@ -20,8 +22,18 @@ ) -def _step_loop(x): - """``stepStat2`` as written in MATLAB (rows = series).""" +def _step_loop(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``stepStat2`` as written in MATLAB (rows = series). + + Returns + ------- + tb : np.ndarray + The best step statistic of each series. + kb : np.ndarray + The split (number of trials before the step) at which it is reached. + db : np.ndarray + The step size (mean after minus mean before) at that split. + """ n, T = x.shape tb, kb, db = np.zeros(n), np.ones(n, int), np.zeros(n) for k in range(1, T): @@ -36,8 +48,22 @@ def _step_loop(x): return tb, kb, db -def _brief_loop(x, blk, max_w): - """``briefStat`` as written in MATLAB, zero-based, with np.median.""" +def _brief_loop( + x: np.ndarray, blk: np.ndarray, max_w: int +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """``briefStat`` as written in MATLAB, zero-based, with np.median. + + Returns + ------- + tb : np.ndarray + The best brief-run statistic of each series. + sb : np.ndarray + The zero-based first trial of that run. + wb : np.ndarray + The length of that run. + db : np.ndarray + The size of the run (its mean minus the mean of its neighbours). + """ n, T = x.shape tb, db = np.zeros(n), np.zeros(n) sb, wb = np.zeros(n, int), np.ones(n, int) @@ -53,11 +79,7 @@ def _brief_loop(x, blk, max_w): away[a - 1 : e + 1] = False sg = np.median(dd[:, away], axis=1) / (0.6745 * math.sqrt(2)) left = [i for i in range(max(a - 2, 0), a) if blk[i] == blk[a]] - right = [ - i - for i in range(e + 1, min(e + 2, T - 1) + 1) - if blk[i] == blk[a] - ] + right = [i for i in range(e + 1, min(e + 2, T - 1) + 1) if blk[i] == blk[a]] m = x[:, a : e + 1].mean(1) ml, mr = x[:, left].mean(1), x[:, right].mean(1) tl = (m - ml) / (sg * math.sqrt(1 / w + 1 / len(left))) @@ -70,38 +92,38 @@ def _brief_loop(x, blk, max_w): return tb, sb, wb, db -def test_trial_blocks_split_at_gaps(): - """A new block starts where the acquisition number jumps by more than 1 - (a repeat or a decrease does not start one, as in MATLAB).""" - np.testing.assert_array_equal( - trial_blocks([2, 3, 4, 7, 8, 8, 6, 10]), [0, 0, 0, 1, 1, 1, 1, 2] - ) +def test_trial_blocks_split_at_gaps() -> None: + """A new block starts where the acquisition number jumps by more than 1. + + A repeat or a decrease does not start one, as in MATLAB. + """ + np.testing.assert_array_equal(trial_blocks([2, 3, 4, 7, 8, 8, 6, 10]), [0, 0, 0, 1, 1, 1, 1, 2]) assert trial_blocks([]).size == 0 -def test_trials_without_numbers_are_blocks_of_their_own(): - """A trial without an acquisition number is neither in a brief run nor - a neighbour of one; with no numbers at all, trials are consecutive.""" - np.testing.assert_array_equal( - trial_blocks([10, 11, -1, -1, 14, 15]), [0, 0, 1, 2, 3, 3] - ) +def test_trials_without_numbers_are_blocks_of_their_own() -> None: + """A trial without an acquisition number is neither in a brief run nor a neighbour of one. + + With no numbers at all, trials are consecutive. + """ + np.testing.assert_array_equal(trial_blocks([10, 11, -1, -1, 14, 15]), [0, 0, 1, 2, 3, 3]) np.testing.assert_array_equal(trial_blocks([-1, -1, -1]), [0, 0, 0]) - np.testing.assert_array_equal( - trial_blocks([-1, -1, -1], unknown_consecutive=False), [0, 1, 2] - ) + np.testing.assert_array_equal(trial_blocks([-1, -1, -1], unknown_consecutive=False), [0, 1, 2]) x = np.zeros((1, 7)) x[0, 3] = 1.0 # a transient at the trial without a number x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, -1, 5, 6, 7]), 1) assert start[0] != 3 - t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, 4, 5, 6, 7]), 1) + _t, start, _, _ = brief_stat(x, trial_blocks([1, 2, 3, 4, 5, 6, 7]), 1) assert start[0] == 3 -def test_image_blocks_keep_the_paths_boundaries(): - """A subset of a path's trials keeps the path's block boundaries, also - with acquisition numbers out of order, and splits where it skips a - trial.""" +def test_image_blocks_keep_the_paths_boundaries() -> None: + """A subset of a path's trials keeps the path's block boundaries. + + This holds also with acquisition numbers out of order, and it splits + where it skips a trial. + """ from giant_python.spine.trends import image_blocks pb = trial_blocks([1, 5, 2, 3]) # 1 | 5, 2, 3 (a decrease joins) @@ -111,14 +133,10 @@ def test_image_blocks_keep_the_paths_boundaries(): np.testing.assert_array_equal(trial_blocks([1, 2, 3]), [0, 0, 0]) # a skipped trial splits a block pb = trial_blocks(np.arange(6)) - np.testing.assert_array_equal( - image_blocks(pb, [0, 1, 3, 4, 5]), [0, 0, 1, 1, 1] - ) + np.testing.assert_array_equal(image_blocks(pb, [0, 1, 3, 4, 5]), [0, 0, 1, 1, 1]) # trend_tests takes the blocks as given x = np.random.default_rng(2).normal(size=(5, 2)) - r = trend_tests( - x, np.ones(2, bool), [9, 9, 9, 9, 9], n_perm=0, blocks=[0, 0, 1, 1, 1] - ) + r = trend_tests(x, np.ones(2, bool), [9, 9, 9, 9, 9], n_perm=0, blocks=[0, 0, 1, 1, 1]) np.testing.assert_array_equal(r["blocks"], [0, 0, 1, 1, 1]) with pytest.raises(ValueError, match="blocks"): trend_tests(x, np.ones(2, bool), np.arange(5), n_perm=0, blocks=[0, 1]) @@ -127,23 +145,23 @@ def test_image_blocks_keep_the_paths_boundaries(): @pytest.mark.parametrize( "kw, match", [ - (dict(n_perm=-1), "n_perm"), - (dict(max_brief=0), "max_brief"), - (dict(fdr_q=2.0), "fdr_q"), - (dict(fdr_q=0.0), "fdr_q"), - (dict(seed=-3), "seed"), - (dict(min_change=-0.1), "min_change"), - (dict(min_change=1.0), "min_change"), - (dict(min_change=float("nan")), "min_change"), + ({"n_perm": -1}, "n_perm"), + ({"max_brief": 0}, "max_brief"), + ({"fdr_q": 2.0}, "fdr_q"), + ({"fdr_q": 0.0}, "fdr_q"), + ({"seed": -3}, "seed"), + ({"min_change": -0.1}, "min_change"), + ({"min_change": 1.0}, "min_change"), + ({"min_change": float("nan")}, "min_change"), ], ) -def test_trend_settings_are_checked(kw, match): +def test_trend_settings_are_checked(kw: dict[str, float], match: str) -> None: """Settings the tests cannot use are refused.""" with pytest.raises(ValueError, match=match): trend_tests(np.zeros((5, 2)), np.ones(2, bool), np.arange(5), **kw) -def test_step_stat_is_the_matlab_loop(): +def test_step_stat_is_the_matlab_loop() -> None: """Cumulative sums give MATLAB's statistic, split and size.""" rng = np.random.default_rng(3) x = rng.normal(size=(200, 17)) * 0.1 @@ -158,10 +176,12 @@ def test_step_stat_is_the_matlab_loop(): np.testing.assert_allclose(d, got[2], rtol=1e-10, atol=1e-15) -def test_no_step_or_run_keeps_a_missing_position(): - """A series without a non-zero statistic reports no split and no run - (not the first trial), and so does the summary through the pipeline's - mapping.""" +def test_no_step_or_run_keeps_a_missing_position() -> None: + """A series without a non-zero statistic reports no split and no run. + + It reports no first trial, and so does the summary through the + pipeline's mapping. + """ x = np.zeros((2, 8)) x[1] = np.arange(8) * 0.01 t, k, d = step_stat(x) @@ -184,24 +204,24 @@ def test_no_step_or_run_keeps_a_missing_position(): assert r["brief_start"][0] == -1 and r["brief_len"][0] == 0 -def test_step_at_out_of_range_is_nan(): +def test_step_at_out_of_range_is_nan() -> None: """A split outside 1..T-1 gives NaN.""" t, d = step_at(np.zeros((2, 5)) + [[0, 1, 2, 3, 4]], [0, 2]) assert np.isnan(t[0]) and np.isnan(d[0]) and d[1] == 2.5 -def test_median_without_matches_numpy(): - """The median once some ranks are taken out equals np.median of what - is left, ties included.""" +def test_median_without_matches_numpy() -> None: + """The median once some ranks are taken out equals np.median of what is left. + + Ties are included. + """ rng = np.random.default_rng(5) for m_all, k in ((9, 2), (10, 3), (12, 4), (5, 4)): vals = rng.integers(0, 4, size=(300, m_all)).astype(float) order = np.argsort(vals, axis=1, kind="stable") srt = np.take_along_axis(vals, order, 1) rank = np.empty_like(order) - np.put_along_axis( - rank, order, np.broadcast_to(np.arange(m_all), order.shape), 1 - ) + np.put_along_axis(rank, order, np.broadcast_to(np.arange(m_all), order.shape), 1) cols = np.sort(rng.choice(m_all, size=k, replace=False)) keep = np.setdiff1d(np.arange(m_all), cols) got = _median_without(srt, rank[:, cols], m_all - k) @@ -211,7 +231,7 @@ def test_median_without_matches_numpy(): np.testing.assert_array_equal(got, np.median(vals[:, keep], 1)) -def test_brief_stat_is_the_matlab_loop(): +def test_brief_stat_is_the_matlab_loop() -> None: """The brief statistic, run and size equal MATLAB's, with blocks.""" rng = np.random.default_rng(4) T = 15 @@ -231,18 +251,18 @@ def test_brief_stat_is_the_matlab_loop(): assert np.median(start) == 6 and np.median(length) == 2 -def test_brief_stat_keeps_runs_inside_blocks(): +def test_brief_stat_keeps_runs_inside_blocks() -> None: """No run (or its neighbours) crosses a block boundary.""" x = np.zeros((1, 8)) x[0, 3] = 1.0 # trial 3 starts block 1: no neighbours before it there x += np.random.default_rng(0).normal(size=x.shape) * 1e-3 blk = trial_blocks([1, 2, 3, 10, 11, 12, 13, 14]) - t, start, _, _ = brief_stat(x, blk, 1) + _t, start, _, _ = brief_stat(x, blk, 1) assert start[0] != 3 -def test_bh_adjust_is_the_step_up_rule(): - """q <= level exactly where the step-up rule rejects; NaN stays NaN.""" +def test_bh_adjust_is_the_step_up_rule() -> None: + """Q <= level exactly where the step-up rule rejects; NaN stays NaN.""" rng = np.random.default_rng(6) p = np.concatenate([rng.uniform(size=80), rng.uniform(0, 0.002, 20)]) p[5] = np.nan @@ -256,14 +276,14 @@ def test_bh_adjust_is_the_step_up_rule(): if below.size: expect[fin] = p[fin] <= ps[below[-1]] np.testing.assert_array_equal(q <= 0.1, expect) - np.testing.assert_allclose( - bh_adjust([0.01, 0.04, 0.03]), [0.03, 0.04, 0.04] - ) + np.testing.assert_allclose(bh_adjust([0.01, 0.04, 0.03]), [0.03, 0.04, 0.04]) + +def test_shared_mode_sign_and_share() -> None: + """A rank-one pattern is recovered with all the variance. -def test_shared_mode_sign_and_share(): - """A rank-one pattern is recovered with all the variance, signed - positive at the end.""" + It is signed positive at the end. + """ v0 = np.linspace(1, -1, 10) v0 /= np.linalg.norm(v0) x = np.outer([1.0, -2.0, 0.5], v0) @@ -274,21 +294,30 @@ def test_shared_mode_sign_and_share(): assert np.isnan(v).all() and np.isnan(share) -def _session(rng, n_src=40, T=20, step=0.25): - """Normalized-like sizes (trials, sources): noise, a shared drift (most - of the variance, as in real sessions) and one source with a step after - trial 9.""" +def _session( + rng: np.random.Generator, n_src: int = 40, T: int = 20, step: float = 0.25 +) -> np.ndarray: + """Normalized-like sizes (trials, sources). + + Noise, a shared drift (most of the variance, as in real sessions) and one + source with a step after trial 9. + + Returns + ------- + np.ndarray + The (trials, sources) array, centred over trials. + """ drift = np.linspace(-0.2, 0.2, T) - x = rng.normal(size=(T, n_src)) * 0.05 + drift[:, None] * rng.normal( - size=n_src - ) + x = rng.normal(size=(T, n_src)) * 0.05 + drift[:, None] * rng.normal(size=n_src) x[10:, 0] += step return x - x.mean(0) -def test_trend_tests_find_a_planted_step(): - """A planted step has small p and q; beyond the shared drift, the other - sources do not pile up at small p.""" +def test_trend_tests_find_a_planted_step() -> None: + """A planted step has small p and q. + + Beyond the shared drift, the other sources do not pile up at small p. + """ rng = np.random.default_rng(7) x = _session(rng) ok = np.ones(x.shape[1], bool) @@ -306,7 +335,7 @@ def test_trend_tests_find_a_planted_step(): v = shared_mode(lx)[0] np.testing.assert_allclose(r["shared_v"], v) np.testing.assert_allclose(r["shared_loading"][tested], lx @ v) - rt, rk, rd = step_stat(lx - np.outer(lx @ v, v)) + rt, rk, _rd = step_stat(lx - np.outer(lx @ v, v)) np.testing.assert_allclose(r["resid_t"][tested], rt) np.testing.assert_array_equal(r["resid_k"][tested], rk) # every source follows the drift (a real step for the step test); @@ -317,11 +346,13 @@ def test_trend_tests_find_a_planted_step(): assert r["shared_v"].shape == (20,) and 0 < r["var_share"] < 1 -def test_trend_tests_p_does_not_depend_on_the_others_or_threads(): - """Each source has its own trial orders: the step and brief p are the - same whichever other sources are tested, and no p depends on the - threads; the beyond-trend test depends on the tested set through the - shared trend.""" +def test_trend_tests_p_does_not_depend_on_the_others_or_threads() -> None: + """Each source has its own trial orders. + + The step and brief p are the same whichever other sources are tested, and + no p depends on the threads; the beyond-trend test depends on the tested + set through the shared trend. + """ rng = np.random.default_rng(8) x = _session(rng, n_src=6, T=12) acq = np.arange(12) @@ -349,9 +380,12 @@ def test_trend_tests_p_does_not_depend_on_the_others_or_threads(): assert not np.allclose(c["shared_v"], a["shared_v"]) -def test_ties_at_the_edge_split_count(): - """One outlying first trial: every order that puts it first or last - gives the same statistic, so p is about 2/T, not tiny.""" +def test_ties_at_the_edge_split_count() -> None: + """One outlying first trial. + + Every order that puts it first or last gives the same statistic, so p is + about 2/T, not tiny. + """ rng = np.random.default_rng(9) T = 20 x = rng.normal(size=(T, 1)) * 0.01 @@ -361,10 +395,12 @@ def test_ties_at_the_edge_split_count(): assert r["step_p"][0] == pytest.approx(2 / T, abs=0.02) -def test_noise_free_edge_outlier_ties_with_its_mirror(): - """A series without spread apart from one end trial has an infinite - step statistic, equal for the series and its mirror image, so every - order that puts the trial at either end ties (p about 2/T).""" +def test_noise_free_edge_outlier_ties_with_its_mirror() -> None: + """A series without spread apart from one end trial has an infinite step statistic. + + It is equal for the series and its mirror image, so every order that puts + the trial at either end ties (p about 2/T). + """ x = np.zeros((2, 10)) x[0, -1] = 1.0 x[1, 0] = 1.0 @@ -383,7 +419,7 @@ def test_noise_free_edge_outlier_ties_with_its_mirror(): np.testing.assert_array_equal(step_at(x, [9, 1])[0], step_stat(x)[0]) -def test_trend_tests_without_permutations(): +def test_trend_tests_without_permutations() -> None: """n_perm 0 gives the statistics without p or q.""" rng = np.random.default_rng(10) x = _session(rng, n_src=5, T=10) @@ -393,15 +429,17 @@ def test_trend_tests_without_permutations(): assert r["counts"]["step"]["fdr_up"] == 0 -def test_trend_tests_need_three_trials(): +def test_trend_tests_need_three_trials() -> None: """Fewer than three trials: nothing is tested.""" r = trend_tests(np.zeros((2, 3)), np.ones(3, bool), [1, 2], n_perm=10) assert not r["tested"].any() and np.isnan(r["step_t"]).all() -def test_permutations_in_chunks_give_the_same_p(): - """The orders are drawn in chunks to bound memory; the p-values do not - depend on the chunk size.""" +def test_permutations_in_chunks_give_the_same_p() -> None: + """The orders are drawn in chunks to bound memory. + + The p-values do not depend on the chunk size. + """ from giant_python.spine.trends import _perm_p rng = np.random.default_rng(11) @@ -418,7 +456,7 @@ def test_permutations_in_chunks_give_the_same_p(): assert _perm_p(x, resid, t_obs, 1, 3, 200, blocks, 3, rows) == one -def test_trial_orders_are_seeded_permutations(): +def test_trial_orders_are_seeded_permutations() -> None: """Each row is a permutation; the same seed and source repeat.""" o = trial_orders(1, 7, 50, 9) assert (np.sort(o, axis=1) == np.arange(9)).all() @@ -427,10 +465,12 @@ def test_trial_orders_are_seeded_permutations(): assert trial_orders(1, 7, 0, 9).shape == (0, 9) -def test_calls_need_q_and_the_minimum_change(): - """A call is a change beyond the shared trend with q <= fdr_q and a - relative size of at least min_change, in either direction; a small - change that the test finds is not called, an untested source never.""" +def test_calls_need_q_and_the_minimum_change() -> None: + """A call is a change beyond the shared trend with q <= fdr_q. + + It has a relative size of at least min_change, in either direction; a + small change that the test finds is not called, an untested source never. + """ rng = np.random.default_rng(3) T, n_src = 20, 40 # a shared drift orthogonal to the planted steps' shape, so that @@ -438,25 +478,21 @@ def test_calls_need_q_and_the_minimum_change(): step = (np.arange(T) >= 10) - 0.5 drift = np.linspace(-0.2, 0.2, T) drift -= (drift @ step) / (step @ step) * step - x = rng.normal(size=(T, n_src)) * 0.005 + drift[:, None] * rng.normal( - size=n_src - ) + x = rng.normal(size=(T, n_src)) * 0.005 + drift[:, None] * rng.normal(size=n_src) x[10:, 0] += 0.2 # +22% x[10:, 1] += 0.04 # +4%, far above the noise x[10:, 2] -= 0.2 # -18% x = x - x.mean(0) ok = np.ones(n_src, bool) ok[5] = False - kw = dict(n_perm=2000, workers=2) + kw = {"n_perm": 2000, "workers": 2} r = trend_tests(x, ok, np.arange(T), **kw) assert r["resid_q"][:3].max() <= 0.1 assert r["call"][0] and r["call"][2] and not r["call"][1] assert not r["call"][5] and not r["tested"][5] # the rule, source by source expect = ( - r["tested"] - & (r["resid_q"] <= 0.1) - & (np.abs(np.expm1(np.nan_to_num(r["resid_d"]))) >= 0.1) + r["tested"] & (r["resid_q"] <= 0.1) & (np.abs(np.expm1(np.nan_to_num(r["resid_d"]))) >= 0.1) ) np.testing.assert_array_equal(r["call"], expect) up = int((r["call"] & (r["resid_d"] > 0)).sum()) diff --git a/tests/viewer/test_viewer_render.py b/tests/viewer/test_viewer_render.py index 7ec8ed53..8065deea 100644 --- a/tests/viewer/test_viewer_render.py +++ b/tests/viewer/test_viewer_render.py @@ -232,7 +232,7 @@ def test_run_reader(tmp_path: Path) -> None: assert tr["dF_denoised"].shape == (2 * syn["lines"].size, 3) fps = run.footprints(1) assert len(fps) == N_TRIALS and fps[0][3].sum() == pytest.approx(3.0) - patch, r0, c0 = run.profile_patch(1, 0) + patch, _r0, _c0 = run.profile_patch(1, 0) assert patch.shape == (15, 15) w = footprint_width(gaussian((H, W), CENTRES[0]), *CENTRES[0]) assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 From 95a6cc7584a7ce9c7bcaba55808084f861fc98d0 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 14:42:24 -0800 Subject: [PATCH 11/14] Normalize line endings to LF in the repository Add '* text=auto' to .gitattributes and renormalize tracked files, so diffs against main show only real changes. Working-tree files keep CRLF on Windows via core.autocrlf. No content changes. --- .gitattributes | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 76 +- .github/ISSUE_TEMPLATE/feature_request.md | 40 +- .github/ISSUE_TEMPLATE/user-story.md | 54 +- .github/dependabot.yml | 30 +- .gitignore | 284 +- CODE_OF_CONDUCT.md | 266 +- CONTRIBUTING.md | 154 +- docs/Makefile | 40 +- docs/make.bat | 70 +- docs/source/_static/dark-logo.svg | 48 +- docs/source/_static/light-logo.svg | 48 +- docs/source/f0_export.rst | 1078 +-- docs/source/migration.rst | 340 +- docs/source/reg_stats.rst | 706 +- docs/source/traces.rst | 234 +- examples/extract_band.py | 784 +- src/giant_python/export/__init__.py | 10 +- src/giant_python/export/f0_events.py | 564 +- src/giant_python/export/f0_injected.py | 1380 ++-- src/giant_python/export/f0_layout.py | 2596 +++---- src/giant_python/export/f0_mask.py | 574 +- src/giant_python/export/f0_qc.py | 898 +-- src/giant_python/extraction/__init__.py | 2 +- src/giant_python/extraction/band/__init__.py | 2 +- src/giant_python/extraction/band/activity.py | 660 +- .../extraction/band/annotation.py | 564 +- .../extraction/band/background.py | 998 +-- src/giant_python/extraction/band/geometry.py | 476 +- src/giant_python/extraction/band/inputs.py | 708 +- .../extraction/band/localization.py | 1884 ++--- .../extraction/band/motion_binning.py | 204 +- src/giant_python/extraction/band/operators.py | 588 +- .../extraction/band/result_assembly.py | 422 +- src/giant_python/extraction/band/rois.py | 392 +- .../extraction/band/summary_images.py | 1282 ++-- src/giant_python/extraction/band/traces.py | 1624 ++--- src/giant_python/extraction/band/transient.py | 788 +- .../extraction/band/trial_data.py | 686 +- src/giant_python/extraction/band/types.py | 84 +- src/giant_python/extraction/band/workflow.py | 1280 ++-- .../extraction/raster/__init__.py | 10 +- .../extraction/raster/annotations.py | 758 +- .../extraction/raster/container.py | 1502 ++-- src/giant_python/extraction/raster/peaks.py | 2202 +++--- .../extraction/raster/refit_test.py | 1220 ++-- src/giant_python/extraction/raster/spots.py | 1382 ++-- .../extraction/raster/stage_files.py | 780 +- src/giant_python/gui/__init__.py | 8 +- src/giant_python/gui/parameters_gui.py | 272 +- src/giant_python/gui/roi_editor.py | 440 +- src/giant_python/io/__init__.py | 140 +- src/giant_python/io/annotations.py | 206 +- src/giant_python/io/hdf5.py | 630 +- src/giant_python/io/slap2.py | 662 +- src/giant_python/io/slap2_raster.py | 1128 +-- src/giant_python/io/tiff.py | 42 +- src/giant_python/io/trial_table.py | 110 +- src/giant_python/models/__init__.py | 92 +- src/giant_python/models/trial_table.py | 204 +- src/giant_python/numerics/__init__.py | 8 +- src/giant_python/numerics/baseline.py | 374 +- src/giant_python/numerics/interpolation.py | 56 +- src/giant_python/numerics/morphology.py | 116 +- src/giant_python/numerics/peaks.py | 1672 ++--- src/giant_python/pipeline/__init__.py | 40 +- src/giant_python/pipeline/annotate.py | 112 +- src/giant_python/pipeline/extract.py | 240 +- src/giant_python/pipeline/pipeline.py | 358 +- src/giant_python/pipeline/reg_stats.py | 1268 ++-- src/giant_python/pipeline/trial_table.py | 1670 ++--- src/giant_python/progress.py | 126 +- src/giant_python/registration/__init__.py | 28 +- src/giant_python/registration/compensation.py | 476 +- src/giant_python/registration/growth.py | 1898 ++--- .../registration/interpolation.py | 268 +- src/giant_python/registration/matching.py | 696 +- src/giant_python/registration/multiroi.py | 1690 ++--- src/giant_python/registration/outputs.py | 1018 +-- src/giant_python/registration/sources.py | 842 +-- .../registration/stats/__init__.py | 188 +- .../registration/stats/accumulate.py | 1580 ++-- src/giant_python/registration/stats/gain.py | 922 +-- .../registration/stats/geometry.py | 1674 ++--- src/giant_python/registration/stats/io.py | 328 +- src/giant_python/registration/stats/maps.py | 686 +- .../registration/stats/session.py | 354 +- src/giant_python/registration/stats/svd.py | 606 +- src/giant_python/registration/stats/worker.py | 414 +- src/giant_python/registration/template.py | 544 +- src/giant_python/simulation/__init__.py | 16 +- src/giant_python/simulation/injection.py | 6338 ++++++++--------- src/giant_python/simulation/render.py | 386 +- src/giant_python/spine/__init__.py | 44 +- src/giant_python/spine/gains.py | 844 +-- src/giant_python/spine/product.py | 702 +- src/giant_python/spine/qc.py | 394 +- src/giant_python/spine/readout.py | 356 +- src/giant_python/spine/rois.py | 538 +- src/giant_python/spine/summary_io.py | 1068 +-- src/giant_python/spine/view/__init__.py | 12 +- src/giant_python/spine/view/data.py | 2080 +++--- src/giant_python/spine/view/export.py | 906 +-- src/giant_python/spine/view/page.html | 2064 +++--- src/giant_python/spine/view/server.py | 796 +-- src/giant_python/viewer/__init__.py | 14 +- src/giant_python/viewer/page.html | 2172 +++--- src/giant_python/viewer/render.py | 1036 +-- src/giant_python/viewer/run.py | 1212 ++-- src/giant_python/viewer/server.py | 1424 ++-- src/giant_python/viewer/trial.py | 1514 ++-- tests/__init__.py | 2 +- tests/export/__init__.py | 2 +- tests/export/test_f0_injected.py | 558 +- tests/export/test_f0_layout.py | 1686 ++--- tests/export/test_f0_training.py | 1952 ++--- tests/raster/__init__.py | 2 +- tests/raster/alignment_synthetic.py | 360 +- tests/raster/data/make_matlab_kinetics.m | 110 +- tests/raster/data/make_matlab_kinetics_h5.py | 84 +- tests/raster/data/make_matlab_trial_data.m | 162 +- tests/raster/test_raster_alignment.py | 700 +- tests/raster/test_raster_annotations.py | 342 +- tests/raster/test_raster_baseline_map.py | 552 +- tests/raster/test_raster_f0_images.py | 660 +- tests/raster/test_raster_peaks.py | 616 +- tests/raster/test_raster_refit.py | 702 +- tests/raster/test_raster_seed_acceptance.py | 954 +-- tests/raster/test_raster_silo_alignment.py | 552 +- tests/raster/test_raster_silo_noise_seeds.py | 72 +- tests/raster/test_raster_solver.py | 1144 +-- tests/raster/test_raster_solver_baseline.py | 992 +-- .../test_raster_solver_baseline_modes.py | 1024 +-- tests/raster/test_raster_solver_fits.py | 932 +-- tests/raster/test_raster_solver_setup.py | 790 +- tests/raster/test_raster_stage_files.py | 224 +- tests/raster/test_raster_summary_model.py | 958 +-- tests/registration/__init__.py | 2 +- tests/registration/synthetic.py | 460 +- tests/registration/test_compensation.py | 458 +- tests/registration/test_curtain.py | 762 +- tests/registration/test_growth.py | 642 +- tests/registration/test_kernels.py | 578 +- tests/registration/test_reg_stats.py | 1974 ++--- tests/registration/test_synthetic.py | 1938 ++--- tests/simulation/__init__.py | 2 +- tests/simulation/test_injection.py | 3034 ++++---- tests/spine/__init__.py | 2 +- tests/spine/synthetic.py | 750 +- tests/spine/test_spine_gains.py | 492 +- tests/spine/test_spine_qc.py | 358 +- tests/spine/test_spine_readout.py | 302 +- tests/spine/test_spine_view.py | 1684 ++--- tests/trial_table/__init__.py | 2 +- tests/trial_table/test_build_slap2.py | 1250 ++-- tests/viewer/__init__.py | 2 +- tests/viewer/synthetic.py | 560 +- tests/viewer/test_viewer_render.py | 810 +-- tests/viewer/test_viewer_server.py | 306 +- 159 files changed, 55688 insertions(+), 55687 deletions(-) diff --git a/.gitattributes b/.gitattributes index f03672c5..d5917cc6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ +* text=auto uv.lock linguist-generated \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6867cf8d..dd84ea78 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,38 +1,38 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: '' -assignees: '' - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Desktop (please complete the following information):** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] - -**Smartphone (please complete the following information):** - - Device: [e.g. iPhone6] - - OS: [e.g. iOS8.1] - - Browser [e.g. stock browser, safari] - - Version [e.g. 22] - -**Additional context** -Add any other context about the problem here. +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 72718d5a..bbcbbe7d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,20 +1,20 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: '' -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/user-story.md b/.github/ISSUE_TEMPLATE/user-story.md index 38971a3e..0a635a0a 100644 --- a/.github/ISSUE_TEMPLATE/user-story.md +++ b/.github/ISSUE_TEMPLATE/user-story.md @@ -1,27 +1,27 @@ ---- -name: User story -about: This template provides a basic structure for user story issues. -title: '' -labels: '' -assignees: '' - ---- - -# User story -As a ..., I want to ..., so I can ... - -*Ideally, this is in the issue title, but if not, you can put it here. If so, delete this section.* - -# Acceptance criteria -- [ ] This is something that can be verified to show that this user story is satisfied. - -# Sprint Ready Checklist -- [ ] 1. Acceptance criteria defined -- [ ] 2. Team understands acceptance criteria -- [ ] 3. Team has defined solution / steps to satisfy acceptance criteria -- [ ] 4. Acceptance criteria is verifiable / testable -- [ ] 5. External / 3rd Party dependencies identified -- [ ] 6. Ticket is prioritized and sized - -# Notes -*Add any helpful notes here.* +--- +name: User story +about: This template provides a basic structure for user story issues. +title: '' +labels: '' +assignees: '' + +--- + +# User story +As a ..., I want to ..., so I can ... + +*Ideally, this is in the issue title, but if not, you can put it here. If so, delete this section.* + +# Acceptance criteria +- [ ] This is something that can be verified to show that this user story is satisfied. + +# Sprint Ready Checklist +- [ ] 1. Acceptance criteria defined +- [ ] 2. Team understands acceptance criteria +- [ ] 3. Team has defined solution / steps to satisfy acceptance criteria +- [ ] 4. Acceptance criteria is verifiable / testable +- [ ] 5. External / 3rd Party dependencies identified +- [ ] 6. Ticket is prioritized and sized + +# Notes +*Add any helpful notes here.* diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 97a7e314..fd396206 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,15 +1,15 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: -# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file - -version: 2 -updates: - - package-ecosystem: "pip" - directory: "/" - schedule: - interval: "weekly" - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.gitignore b/.gitignore index 1785a6b6..649f1f1d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,142 +1,142 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -.idea/ - -# VS Code -.vscode/ - -# MacOs -**/.DS_Store +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ + +# VS Code +.vscode/ + +# MacOs +**/.DS_Store diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 1bf7e89e..9850bc32 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,133 +1,133 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official email address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -ScientificComputing@AllenInstitute.onmicrosoft.com. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available -at [https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +ScientificComputing@AllenInstitute.onmicrosoft.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available +at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ff4948ae..b5828113 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,77 +1,77 @@ -# Contributing - -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]. - -In general, we use uv, pytest, ruff, and interrogate for out local development. - -### Installation - -To install the dependencies needed for local development: -```bash -uv sync --group dev -``` - -To install the dependencies to build the documentation locally: -```bash -uv sync --group docs -``` - -### Linters and testing - -- Please test your changes using the **pytest** library, which will run the tests and log a coverage report: - -```bash -uv run pytest . -``` - -- Use **interrogate** to check that modules, methods, etc. have been documented thoroughly: - -```bash -uv run interrogate . -``` - -- Use **ruff** to check that code is up to standards and auto-format: -```bash -uv run ruff check --fix -uv run ruff format -``` - -### Pull requests - -For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern: -```text -(): -``` - -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) -- **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 - -The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration): - -| Commit message | Release type | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- | -| `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release | -| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release | -| `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 -To generate the rst files source files for documentation, run -```bash -uv run sphinx-apidoc -o docs/source/ src -``` -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). - +# Contributing + +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]. + +In general, we use uv, pytest, ruff, and interrogate for out local development. + +### Installation + +To install the dependencies needed for local development: +```bash +uv sync --group dev +``` + +To install the dependencies to build the documentation locally: +```bash +uv sync --group docs +``` + +### Linters and testing + +- Please test your changes using the **pytest** library, which will run the tests and log a coverage report: + +```bash +uv run pytest . +``` + +- Use **interrogate** to check that modules, methods, etc. have been documented thoroughly: + +```bash +uv run interrogate . +``` + +- Use **ruff** to check that code is up to standards and auto-format: +```bash +uv run ruff check --fix +uv run ruff format +``` + +### Pull requests + +For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern: +```text +(): +``` + +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) +- **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 + +The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration): + +| Commit message | Release type | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- | +| `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release | +| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release | +| `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 +To generate the rst files source files for documentation, run +```bash +uv run sphinx-apidoc -o docs/source/ src +``` +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). + diff --git a/docs/Makefile b/docs/Makefile index 26b94228..d0c3cbf1 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,20 +1,20 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/make.bat b/docs/make.bat index 747ffb7b..dc1312ab 100644 --- a/docs/make.bat +++ b/docs/make.bat @@ -1,35 +1,35 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=source -set BUILDDIR=build - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.https://www.sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "" goto help - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=source +set BUILDDIR=build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/source/_static/dark-logo.svg b/docs/source/_static/dark-logo.svg index 7bd5c86d..33d6da25 100644 --- a/docs/source/_static/dark-logo.svg +++ b/docs/source/_static/dark-logo.svg @@ -1,25 +1,25 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/source/_static/light-logo.svg b/docs/source/_static/light-logo.svg index 8deed722..d14bae03 100644 --- a/docs/source/_static/light-logo.svg +++ b/docs/source/_static/light-logo.svg @@ -1,25 +1,25 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/source/f0_export.rst b/docs/source/f0_export.rst index 6efccc64..26a4da35 100644 --- a/docs/source/f0_export.rst +++ b/docs/source/f0_export.rst @@ -1,539 +1,539 @@ -Training data for the F0 network -================================ - -``giant export-f0`` writes training data for the SLAP2 F0 network -(`slap2-F0-network `_) -from a ``giant silo`` run: per trial and imaging path, the registered 80 Hz -movie and SILo's fitted activity on the same grid, so that the network's -training target is ``movie - activity``. It replaces slap2-F0-network's MATLAB -exporter (``code/matlab/exportF0TrainingData.m``) for runs made with -GIAnT-Python, and writes the same file layout, which ``slap2_f0.io.TrialFile`` -reads unchanged. - -The exporter lives in GIAnT-Python because it reads SILo's outputs (footprints, -traces, the across-trial maps, the 200 Hz frame lines and discards) and uses -the renderer of ``giant view``; GIAnT-Python does not import slap2-f0, and -slap2-f0 needs only the HDF5 layout below. - -Usage ------ - -.. code-block:: text - - giant export-f0 RUN OUT [--table TRIAL_TABLE] [--moco-dir MOTION_CORRECTION] - [--baseline-dir BASELINES] [--data-dir RAW] - [--kernel exact|matched|exporter] [--interp linear|cubic] - [--blur SIGMA] [--channels C ...] [--var-fac mean|full] - [--paths D ...] [--trials T ...] [--workers N] - [--label TEXT] [--giant-ref REF] [--deflate N] - [--activity-mask [--mask-k K] [--mask-margin PX] - [--mask-widen TAU] [--mask-share FRAMES] - [--mask-spots none|seeds]] [--event-stats] - -``RUN`` is the run folder (``experiment_summary.h5`` and -``per_trial_summary.h5``, directly or in ``source_extraction/``). The trial -table, registered movies and raw folder are found as ``giant view`` finds them. -``--baseline-dir`` names the F0 network baselines the run used; they are not -needed for the target, but give the file its provenance (``baselineFile``, -``f0Network``) and the QC values ``targetOverBaselineSupport`` and -``targetOverBaselineLabeled``. Each worker needs a few times the size of one -trial's movie in memory (14 GB for a two-channel 804 x 382 px trial of 28 s). - -Output ------- - -``OUT/Path/trial_.h5`` (trial numbers of the trial table) and -``OUT/export_summary.json`` (every trial's record, NaN as ``null``; a trial -that could not be exported, for example one without an across-trial map, is -listed with ``error`` and not written). Arrays as h5py reads them, on the -trial's registered grid cropped to the box around the valid pixels, MATLAB's -row and column orientation, pixel coordinates zero-based in the crop -(``cropOriginRC`` gives the box): - -============================= ======================== ===================================================== -dataset shape, type content -============================= ======================== ===================================================== -``movie`` (channel, frame, row, registered movie; NaN at discarded frames and where - col) float32 not imaged -``activity`` same SILo's footprints times ``dF_denoised`` at the - movie's frames; zero outside the footprints -``mean_image`` (channel, row, col) mean over the kept frames of each written channel; - NaN outside the valid pixels -``mask/valid`` (row, col) uint8 missing in less than ``nanThresh`` of the frames, - motion discards counted -``mask/labeled`` (row, col) uint8 3 x 3 median-filtered mean image above 3 x its 25th - percentile -``mask/footprint_support`` (row, col) uint8 pixels any footprint covers -``frame/discard`` (frame,) uint8 SILo's motion discards and frames whose kernel weight - lies mostly on discarded 200 Hz frames -``frame/motion_row``, ... (frame,) float32 registration motion, ``rec_neg_err``, online motion - (``onlineMotion{X,Y,Z}shift``), mean of valid pixels -``varfac`` (row, col) float32 per-pixel mean of ``slap2/varFacDS`` (every frame - with ``--var-fac full``) -``sources/peak_{row,col}`` (source,) int32 each kept source's peak pixel (-1: none in the trial) -============================= ======================== ===================================================== - -Root attributes: the MATLAB exporter's names (``path``, ``trial``, -``frames``, ``nSources``, ``validPixels``, ``kernelDtLines``, -``kernelHalfWidthLines``, ``linesPerCycle``, ``shiftRC``, ``blurSigma``, -``activityGain`` = 1, the QC values below, ``discardedFrames``, -``channels``, ``activityChannel``, ``alignHz``, ``photonScale``, ``label``, -``giantRef``) and ``exporter``, ``exporterVersion``, ``kernel``, -``kernelR``, ``kernelDt200Lines``, ``movieDtLines``, ``footprintInterp``, -``alignmentMode``, ``siloRun``, ``baselineSource``, ``baselineFile``, -``f0Network`` (SILo's record of the trial's network baseline, JSON) and -``registrationStem``, the stem that the trial's registration files share -(``E1T3DMD2`` of ``E1T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.h5``), by which -slap2-f0 finds the trial's statistics and layout files. -``shiftRC`` is the across-trial map's mean offset over the footprint pixels. - -How the activity is rendered ----------------------------- - -*Space.* Each trial's footprints are moved from SILo's consensus canvas into -the trial's registered frame through SILo's own across-trial map (rigid, -affine or patchwise): the footprint at trial pixel ``q`` is the canvas -footprint at the map's inverse of ``q``. SILo read the trial's data through -the same map. ``--interp linear`` (default, as ``giant view``) interpolates -bilinearly, which blurs a footprint moved by a fraction of a pixel (up to -about 10% off a 1.3 px footprint's peak pixel); ``--interp cubic`` uses a -cubic spline, which keeps the shape (small negative lobes at the edge are -kept, so the flux is unchanged). - -*Time.* The 80 Hz movie frame is a weighted mean of the raw samples within -``max(3 dt80, P)`` lines of its line, weights ``exp(-|dline| / dt80)``; SILo's -200 Hz frames are such means with ``dt200``. ``--kernel exact`` (default) -renders ``x80 = r x200(line) + (1 - r) avg80(x200)``, ``r = (dt200 / -dt80)**2``, where ``x200(line)`` is the 200 Hz trace interpolated at the 80 -Hz frame's line from kept frames and ``avg80`` the MATLAB exporter's average -(exact for densely sampled pixels; see -:func:`giant_python.viewer.render.exact_weights`). ``--kernel exporter`` is -the MATLAB exporter's average alone, which smooths fast events twice; -``--kernel matched`` narrows it to ``sqrt(dt80**2 - dt200**2)``. Both ``dt`` -values come from the data (``DSframes`` and SILo's frame lines). - -*Blur and scale.* No blur unless ``--blur`` is given; no scaling (footprints -sum to 1, traces in movie units). - -QC attributes -------------- - -As the MATLAB exporter computes them, for the activity as written, at the -activity channel, high-passed by an 81-frame running median: ``peakSlope`` and -``peakR`` (movie on activity at each source's peak pixel, medians over -sources), ``diskSlope`` and ``diskR`` (flux in the footprint pixels within 4 -px of the peak), ``activitySlope`` (``diskSlope`` at blur 0), -``blurShapeRatio`` (core over 1.5-3.5 px slope; above 1 when the activity is -broader than the movie's events), ``eventResidualFraction`` and ``nEvents`` -(event-triggered residual at the peaks over the event-triggered movie, events -on each source's own trace), and the selection-safe ring-event ratios -``eventRatioCore``, ``eventRatio2px``, ``eventRatioSources``, -``eventRatioEvents``, ``eventRatioArtifactSources`` (events picked on the -movie 3-5 px from each source; ``slap2_f0.ringqc`` reproduces them from the -written arrays). New: ``targetOverBaselineSupport`` and -``targetOverBaselineLabeled``, the time-mean of ``movie - activity`` over that -of the network baseline at valid footprint pixels and at valid labeled pixels -outside the footprints. - -Activity mask (``--activity-mask``) ------------------------------------ - -For fine-tuning on recordings with the loss zeroed during activity (the -network's targets are then the movie itself), ``mask/activity`` (frame, row, -col) uint8 marks the samples to leave out. It comes from SILo's source-level -fit, not from the samples themselves: a cut on the samples (``movie > -baseline + 2 SD``) keeps the samples whose noise happened to be low, which -biases the kept mean by -0.055 SD and the variance to 0.89. - -* **When** (``--mask-k``, ``--mask-widen``, ``--mask-share``): 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`` decay constants of the activity channel (SILo's ``tau_full``, - ``tau_s`` in frames: 24 ms for iGluSnFR4f, so 48 ms at the default 2), - moved to the nearest 80 Hz frame and widened by ``share`` 80 Hz frames on - both sides (the frames that share samples). -* **Where** (``--mask-margin``): the source's footprint support in the trial, - as the activity is placed, dilated by a disk of ``margin`` px. -* **Spots without a source** (``--mask-spots seeds``): SILo's seeds that kept - no source (the plan file's unused seeds and the kinetics-rejected sources), - a disk of ``margin + 1.5`` px in every frame. Off by default (see below). A - trial whose seeds cannot be placed (no across-trial map) is then refused, and - so is a run that kept no plan file (``source_extraction/silo/plan``): its - unused seeds are unknown. - -Attributes: ``activityMaskK``, ``activityMaskMarginPx``, -``activityMaskWidenTau``, ``activityMaskTauSeconds`` (the decay constant the -widening used, in seconds), ``activityMaskShareFrames``, -``activityMaskSpots``, ``activityMaskFraction`` (of the valid samples in kept -frames) and ``activityMaskFractionSupport`` (at the footprint support). Files -without ``activityMaskTauSeconds`` were written before the widening used the -activity channel's decay: they widen by channel 2's ``tau2`` (0.15 s). - -The defaults were chosen on GFP 847983 (5 trials x 2 paths, SILo at the dev -defaults with the s6_ft baseline) against its truth: the uninjected recording, -where every source SILo keeps is false, and copies with injected events -(sparse: 60 sources per path at 1 Hz; dim; close pairs; dense: 200 sources per -path at 2.3 Hz), on which the original recording (copy minus the drawn -injected photons) is the event-free truth. On the kept samples: the leftover -injected signal, and the truncation (the mean and mean square of the -original's 81-frame high-passed samples against all samples). - -At the defaults (``k`` 3, margin 1 px, widening 2 decay constants of 24 ms, -6 shared frames, no spots), per set of 10 trial-paths: - -============================= =========== ========== ==================== =========== -set masked (fp leftover truncation, SD mean square - / all) (% of b) (% of b) kept / all -============================= =========== ========== ==================== =========== -GFP control (false sources) 19% / 1% 0 -0.0046 (-0.38%) 0.993 -sparse copy 35% / 23% 0.14 -0.0046 (-0.37%) 0.994 -dim copy 35% / 27% 0.27 -0.0046 (-0.43%) 0.993 -close pairs 39% / 33% 0.29 -0.0046 (-0.41%) 0.994 -dense copy 74% / 69% 0.86 -0.0067 (-0.64%) 0.984 -============================= =========== ========== ==================== =========== - -A per-sample 2 SD cut would bias the kept mean by -0.055 SD and the mean -square to 0.89: the rule is 12 times smaller in the mean and 16 times in the -variance deficit, and its net bias (leftover plus truncation) stays within -0.4% of the baseline (the S6 networks' bias is 2-4%). Alternatives on the -sparse, dim and pair copies: no widening masks 29-33% of the footprint -samples (truncation -0.005 SD), one decay constant 32-36%, three 37-42%, and -the first version's 0.15 s (channel 2's ``tau2``, 6.25 decay constants) -45-50% (truncation -0.0037 SD); the leftover is the same at every widening. -``k`` 2 masks 55-59% (truncation -0.010 to -0.012 SD, mean square -0.982-0.986) for a leftover lower by 0.04-0.10% of the baseline. A larger -margin or the seed spots mask more without lowering the leftover (checked -with the 0.15 s widening). The leftover comes from injected sources SILo kept -no source for and from events below the threshold (sizes 0.25-1 keep 21-27% -of their flux, size 2 9%, size 8 0.6%), not from the mask's edges (it does -not depend on the distance from the nearest masked frame); the truncation sits -within 10 frames of a masked frame. Held-out trials 4-5 and trials 1-3 agree -within 0.001 SD. - -Event statistics (``--event-stats``) ------------------------------------- - -``event_statistics.json`` next to the trial files, per path: for each source -its canvas position, footprint width, SNR, kinetics score and noise (the -robust SD of ``dF_ls - dF_denoised``), 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, as quantiles, and the rates at 3, -4, 5, 6 and 8 SDs (``ratesPerMin``); the synchrony (the share of events with -another source's onset within 2 frames of the same trial, observed and -expected for independent sources, both over the partners observed at the -event); SILo's ``tau_s``, ``tau2_s`` and frame rate. Each -trial's record adds ``labeledPixels`` (valid labeled pixels), for the source -density. - -An event is a run of kept frames where ``dF_denoised`` exceeds 6 noise SDs. -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; on the sparse copy (1 Hz -injected, sizes 0.25-8) 75, 36, 27, 22 and 16. The rates and sizes therefore -describe events above the detection limit. Sizes stay in raw units: photons -need the session's gain from the registration statistics' photon model. -A source with activity but no noise estimate (no finite ``dF_ls``) is listed -with ``unavailable`` and null counts, not as a quiet source. A path without -``dF_denoised`` is listed with ``unavailable``; without ``F0`` the dF/F -sizes are null and the rest stands. An export without -``--event-stats`` removes an earlier ``event_statistics.json`` from the output -folder (it would describe another run). - -GFP kind: injected copies (``giant export-f0-injected``) --------------------------------------------------------- - -.. code-block:: text - - giant export-f0-injected COPY OUT [--device cpu|cuda] [--expected] - [--paths D ...] [--trials T ...] [--channels C ...] - [--var-fac mean|full] [--label TEXT] [--giant-ref REF] - -``COPY`` is a copy with injected events made by ``giant_python.simulation. -injection`` and registered (``trial_table.h5``, ``raw/``, -``motion_correction/``, ``injection_truth.h5``; ``injection compare`` run, so -that the truth has the sources' positions on the copy's grid). No SILo run is -involved: the trial's ``activity`` is the copy's raw samples minus the -original's, formed into the copy's registered 80 Hz frames as the movie is, -so ``movie - activity`` is the original recording on the copy's grid, noise -included. The training target is then the recording itself, and the injected -events are in the input only. ``--expected`` adds ``activity_expected``, the -noiseless injected signal, and ``drawnOverExpected`` (summed photons; 1 -within Poisson noise). ``mask/footprint_support`` and -``sources/peak_{row,col}`` describe the injected sources (footprints out to -each source's recorded radius, plus sqrt(2) px). Root attributes ``kind`` = -``gfp_injected``, ``injectionTruth``, ``originalTrial``, ``injectedSources`` -and ``injectedEvents``, and ``registrationStem`` of the copy's registration; -the SILo QC attributes are NaN (slap2-f0's -``filter_trials`` keeps files without ``peakR``). Trials are the copy's -(``--trials`` counts its columns); ``originalTrial`` names the recording's. -On the dim copy of 847983 (path 1 trial 1) the activity equals the truth that -the activity-mask check rendered on the GPU, and ``drawnOverExpected`` is -1.0006; the CPU takes about 100 s per trial-path. - -Raster layout for the simulator (``giant export-f0-layout``) ------------------------------------------------------------ - -.. code-block:: bash - - giant export-f0-layout path/to/trial_table.h5 [--out DIR] [--paths 1,2] - [--trials 1,2,3] [--datadr DIR] [--moco DIR] [--overwrite] - -slap2-F0-network's simulator draws raw photon samples and forms frames from -them as the recording's frames were formed, so that simulated noise has each -pixel's own sampling (how often it is sampled in a cycle, and where each -frame's time falls among its samples), the samples that consecutive frames -share, and the raw pixels that neighbouring registered pixels share. A -registered frame is linear in the raw samples; this command writes, for -every registered trial and path of a trial table, what fixes that linear map -and the photon statistics of the samples, in ``_F0LAYOUT.h5`` (about -1 MB, 10 s per trial on the CPU) next to the registered movie or in -``--out``. It reads the raw recording and the alignment file; the movie is -not needed. - -Registrations that undid the online motion correction (``giant register ---compensate-online``) are supported from version 4 of the file -(``layout_version``). There a sample is not placed at its slot's raster -pixel: it is moved by its line's online offset less the frame's own, rows -following y and columns x, and left out if that lies outside the window. The -file then also holds the offsets of every line of its cycles and each -frame's own offset (``lines/x``, ``lines/y_eff``, ``frames/ref_xy``; root -attributes ``compensated`` and ``y_lead``). ``reference_frames`` states the -rule and is checked against registration's movies with and without -compensation. Version 3 files (registrations without compensation) are still -read. - -Arrays are in NumPy's orientation. Lines are one-based; cycles, pixel -positions and slot indices are zero-based. - -============================= ===================== ====================================================== -dataset shape, type content -============================= ===================== ====================================================== -``frames/lines`` (frame,) int64 line time of each registered frame (``DSframes``) -``frames/motion`` (frame, 2) float64 the frames' row and column motion (NaN: no frame) -``slots/line`` (slot,) int32 line within the cycle on which the slot is sampled -``slots/pos`` (slot,) int32 position of the slot among its line's samples -``frames/ref_xy`` (frame, 2) int16 compensated registrations: the online offset [x, y] - each frame mostly saw -``lines/x``, ``lines/y_eff`` (line,) int16 compensated registrations: the online x offset and - the y on the DMD of every line of the cycles - ``cycle0 ... cycle0 + n_cycles - 1`` (index: line - - 1 - ``cycle0`` x ``lines_per_cycle``) -``slots/pixel`` (slot,) int32 the slot's raw pixel, an index into ``pixels`` (-1 - in a compensated file if no sample lands there) -``slots/row``, ``slots/col`` (slot,) int32 the slot's raster pixel in the registration window -``slots/next`` (slot,) int32 the slot that shares photon pulses with it: the one - sampled right after it on its line, if that is a - neighbouring pixel (-1: none) -``slots/line_end`` (slot,) uint8 1 if no sample follows that could share a pulse with - it (it ends its line, or the scan jumps to another - part of the raster); a slot without a next that is - not, is followed by a sample outside the file -``slots/index`` (slot,) int64 the slot's index in the recording's raster -``slots/mean`` (channel, slot) mean of the slot's valid samples over the trial -``slots/zero_share`` (channel, slot) share of its valid samples that are 0 -``slots/valid_share`` (channel, slot) share of its samples that are valid -``pixels/row`` (pixel,) int32 the row in the registration window of a raw pixel - that frames report (compensated: every pixel that a - sample can land on) -``pixels/col`` (pixel,) int32 its column -``photon/height_single`` (channel, 1024) int64 heights of pulses that fell into one sample -``photon/height_split`` (channel, 1024) int64 heights of pulses split between two samples -``photon/split_fraction`` (channel, 20) int64 share of a split pulse in the earlier sample -``photon/split_joint`` (channel, 64, 20) split events by height (bins of 16 raw units) and - int64 share in the earlier sample -``photon/burst_counts`` (channel, 5) int64 bursts of 1, 2, 3 and 4 samples, and longer ones -``photon/burst_1`` ... (channel, 8192, examples of the bursts of each length: their samples -``photon/burst_4`` length) int16 in scan order -``photon/burst_examples`` (channel, 4) int64 examples kept of each length (further rows are 0) -``photon/burst_cell_1`` ... (channel, 8192) int16 the type (cell) of each example -``photon/burst_cell_4`` -``photon/strata_edges`` (9,) edges of the brightness strata of dim chains (mean - sample, raw units) -``photon/strata_free`` (channel, 8) int64 samples of each stratum in which a burst could have - started -``photon/strata_mean`` (channel, 8) mean sample of each stratum -``photon/strata_bursts`` (channel, 8, 162) bursts of each stratum by cell - int64 -``photon/strata_longer`` (channel, 8) int64 bursts of more than four samples -``photon/level_edges`` (19,) edges of the brightness levels (mean sample, raw - units) -``photon/level_samples`` (channel, 18) int64 pairs of observations of each level -``photon/level_mean`` (channel, 18) mean sample of each level -``photon/level_zero`` (channel, 18) share of zeros -``photon/level_moments`` (channel, 18, 9) variance of a sample and its covariance with the 1st - to 8th sample after it on the line (raw units - squared) -``photon/level_revisits`` uint8 1 if the moments are measured against the next visit - of the same pixels within the cycle, 0 if against - the next cycle -``photon/pairs`` (channel,) int64 dim pairs used -``photon/pair_cycles`` (channel,) int64 their cycles in which the pair was isolated -============================= ===================== ====================================================== - -Attributes: ``lines_per_cycle``, ``line_period_s``, ``kernel_dt_lines`` and -``reach_lines`` (the frame kernel ``exp(-|line distance| / dt)`` and its -reach ``max(3 dt, P)``), ``cycle0`` and ``n_cycles`` (the cycles the trial's -frames reach), ``window_row0``, ``window_col0``, ``window_rows``, -``window_cols`` (the registration window on the DMD), ``margin`` (the -registered frame is the window padded by it on every side), ``unlit_masked`` -(whether the frames left out the samples behind the DMD curtain), -``first_line``, ``last_line``, ``path``, ``trial``, ``recording``, -``alignment``, ``layout_version``. - -Only the slots of the registration window are listed, on the registered -plane. :func:`giant_python.export.f0_layout.reference_frames` forms the -registered frames from the file and the samples of its slots; it states what -the file means. On a recording (780125, one trial and path: 72 463 slots of -37 785 raw pixels, 122 lines per cycle, 2 467 cycles, 2 254 frames) its -frames equal the registered movie's to float32 rounding (largest relative -difference 4e-7, the same missing pixels). - -*Pulses.* A raw sample is the summed height of the photon pulses that -arrived in it, and a pulse on the boundary between two consecutive samples -of a line is split between them (:doc:`reg_stats`), where the scan runs on -from a pixel to its neighbour: across a jump to another part of the raster -(from one ROI to the next) consecutive samples share nothing (on the GFP -recording 847983 they correlate by -0.01, against 0.17-0.22 for neighbouring -pixels), so ``slots/next`` links neighbouring pixels only. - -The histograms are measured on dim pairs ``(a, b)`` of consecutive slots, -both zero in at least 95% of their cycles (attribute ``dim_zero_share``), so -that unrelated pulses rarely coincide. Brighter pairs are never used: a -recording without dim pairs gets empty histograms, and its pulses have to be -taken from another recording of the same microscope. A cycle in which ``a`` -is not zero, while the samples before ``a`` and after ``b`` on the line are -zero, holds one whole event that arrived in ``a``, of height ``x_a + x_b``; -it is split when ``b`` is not zero either, by ``x_a / (x_a + x_b)``. Only -the earlier slot's events are counted, because a split one of the later slot -leaves the pair. The share of split events among the counted ones, -``sum(height_split) / (sum(height_single) + sum(height_split))``, is then -the probability that an event reaches into the next sample, whatever the -rates of the two slots. The sample before ``a`` must be a slot: at the start -of a run the sample before it is not recorded but still passes parts of its -pulses on (a fifth of the "unsplit pulses" measured there are below half a -pulse). The sample after ``b`` must be a slot or not exist; a pair next to a -sample that is not a raster slot is not used. - -*What the events are.* The acquisition zeroes events below half a photon -count, so no event inside a run has a total below about 50 raw units; a -count is about 105. Unsplit events peak there (100-120 raw units). Split -events are of two kinds, which ``photon/split_joint`` keeps apart: one pulse -on the boundary between the samples, at any fraction, and two pulses, one in -each sample, with about twice the height. Three in ten split events have a -total above 150 raw units on 847983 and 780125, against one in ten of the -unsplit ones. On 780125 (channel 1): half of the events reach into the next -sample, the unsplit ones 118 and the split ones 147 raw units high on -average. An event of ``a`` that coincides with an unrelated pulse of ``b`` -is counted as split too; the share of such coincidences among the counted -events is about the pulse rate per pair cycle, ``(sum(height_single) + -sum(height_split)) / pair_cycles``. - -*Bursts.* Some events are longer than two samples: on 847983 about 4% of -them span three, several times what unrelated pulses would give, and they -carry a fifth of the covariance of consecutive samples (measured directly, -that covariance is 23 per unit mean at the dimmest pairs; pulses confined to -two samples give 19). The pair histograms cannot hold them, because a pair -is counted only when the samples around it are zero. The library -``photon/burst_1`` ... ``burst_4`` therefore keeps whole events as they were -recorded: a burst starts in a slot whose sample is not zero while the sample -before it is zero, and runs on along the line until a sample is zero. It is -taken from chains of six consecutive slots whose mean sample is below 2 raw -units (attribute ``burst_level``; about one event in a hundred samples), so -that unrelated events rarely touch, and holds up to 8 192 examples of each -length, spread evenly over those found; ``burst_counts`` gives how often -each length occurs there. - -*Photon events and background.* Not every event is a photon of the tissue. -Some occur at a rate that does not depend on brightness: on 847983 and -780125 about 900 to 1 400 per million samples in either channel, most of -them 60-110 raw units in total, against a photon peak at 100-120. They are a -sixth of the events of the dimmest samples and a hundredth at 10 raw units -per sample, so the variance of a sample per unit mean rises from 125 raw -units at the dimmest samples to 133 where photon events dominate, and a -library taken from dim samples is a mixture of the two. ``photon/strata_*`` -lets a reader separate them. Chains are grouped into strata by their mean -sample (0 to 8 raw units; brighter ones are not counted), and the isolated -bursts of each stratum are counted by type. A burst's type (cell) is its -length and total, and for two samples also the smaller part's share: - -======= ======================================================== ======== -Samples Bins Cells -======= ======================================================== ======== -1 total in steps of 10 raw units (41 bins) 0-40 -2 total in steps of 20 (31 bins) x share of the smaller 41-133 - part in thirds of 0 to 0.5 (cell = 41 + 3 x total bin + - share bin) -3 total in steps of 50 (17 bins) 134-150 -4 total in steps of 100 (11 bins) 151-161 -======= ======================================================== ======== - -The last total bin of each length holds every larger total. Over the strata, -the rate of a cell per sample (``strata_bursts / strata_free``) rises in -proportion to ``strata_mean`` for photon events and is constant for the -background; unrelated events that touch add a term in its square. The -simulator fits the three and draws photon events at the rates it is given -and background events at their own. A chain's stratum is its mean over every -second block of eight cycles, and its bursts are counted in the other -blocks, then the other way round: a chain is then not placed among the dim -ones because it happened to have few events where they are counted. - -*Brightness.* ``photon/level_*`` gives the variance of a sample and its -covariance with the eight samples after it on the line, for chains grouped -by their mean sample (0.5 to 256 raw units in steps of a factor of 1.41). -With events that add up, both are proportional to the mean. They are so up -to about 10 raw units per sample, once the background is counted. Beyond -that, where more than a tenth of the samples are not zero, the recordings -have more of both: at 70 raw units per sample (0.5 events), 3% more variance -per unit mean than the events give, 17% more covariance with the next -sample, and covariance that reaches five samples on (847983; 780125 is -alike). The simulator does not model this; the table is kept to measure it. -The moments are measured against a second observation of the same tissue, -so that brightness which changes with brain motion is not counted: the next -visit of the same pixels within the cycle, on a later line (6.6 ms later on -847983; samples of one line can share pulses), or, for a raster that samples -each pixel on one line per cycle, the same slots one cycle later -(``level_revisits``). On 847983 the variance measured against the -next cycle (28 ms) is higher by 1% at the brightest level. - -Differences from the MATLAB exporter ------------------------------------- - -* SILo's across-trial map instead of a rigid offset searched per trial for the - best movie-activity correlation at the source peaks (the search could - prefer an offset that fits noise; patchwise maps cannot be expressed as one - offset). -* The exact time kernel instead of the double-smoothing average (fast events - kept 0.93-0.95 of their 80 Hz peak in the activity, so the targets kept - 5-7% of every fast event). -* No per-trial shape-matching blur; ``blurShapeRatio`` still reports the core - / ring slope ratio. -* ``mean_image`` holds the written channels (the MATLAB exporter wrote every - channel of the movie, which the reader indexes like ``movie``). It averages - the kept frames and is NaN outside the valid pixels, as slap2-f0 computes - the mean image at inference (``registered.ArrayTrial``); MATLAB's exporter - averaged the discarded frames too, so the network's input and its scale - differed between training and inference. The labeled mask is computed from - the same kept-frame mean. -* A trial whose sources have no ``dF_denoised`` traces, or for which SILo has - no 200 Hz frames, is reported and not written (its activity would be zero - and the target would keep every event). -* With ``--kernel exact`` or ``matched``, a trial whose 200 Hz frames are - wider than the movie's (``dt200 > dt80``, not the case for SLAP2's 200 Hz - analysis of 80 Hz movies) is reported and not written: no kernel undoes the - 200 Hz frames' own smoothing, and the renderer's ratio, capped at 1, would - only interpolate them. -* A trial that fails on a rerun loses its earlier file (the reader finds - files, not summaries). A default export (no ``--trials``) also removes the - earlier ``trial_.h5`` files of the exported paths that it does not - write, such as a trial SILo no longer analyses, and lists them under - ``removed`` in ``export_summary.json``; an export with ``--trials`` leaves - the other trials' files alone. Repeated ``--paths`` or ``--trials`` are - exported once; numbers the run or the trial table does not have are - refused. Invalid options (kernel, interpolation, ``var_fac``, a gzip level - outside 0-9, a negative or non-finite blur, channels the movie does not - have) are refused before any trial, so a rerun with one leaves the earlier - files in place. -* The labeled mask's median filter treats unimaged (NaN) pixels as the - largest values; MATLAB's ``medfilt2`` behaviour with NaN is not documented. +Training data for the F0 network +================================ + +``giant export-f0`` writes training data for the SLAP2 F0 network +(`slap2-F0-network `_) +from a ``giant silo`` run: per trial and imaging path, the registered 80 Hz +movie and SILo's fitted activity on the same grid, so that the network's +training target is ``movie - activity``. It replaces slap2-F0-network's MATLAB +exporter (``code/matlab/exportF0TrainingData.m``) for runs made with +GIAnT-Python, and writes the same file layout, which ``slap2_f0.io.TrialFile`` +reads unchanged. + +The exporter lives in GIAnT-Python because it reads SILo's outputs (footprints, +traces, the across-trial maps, the 200 Hz frame lines and discards) and uses +the renderer of ``giant view``; GIAnT-Python does not import slap2-f0, and +slap2-f0 needs only the HDF5 layout below. + +Usage +----- + +.. code-block:: text + + giant export-f0 RUN OUT [--table TRIAL_TABLE] [--moco-dir MOTION_CORRECTION] + [--baseline-dir BASELINES] [--data-dir RAW] + [--kernel exact|matched|exporter] [--interp linear|cubic] + [--blur SIGMA] [--channels C ...] [--var-fac mean|full] + [--paths D ...] [--trials T ...] [--workers N] + [--label TEXT] [--giant-ref REF] [--deflate N] + [--activity-mask [--mask-k K] [--mask-margin PX] + [--mask-widen TAU] [--mask-share FRAMES] + [--mask-spots none|seeds]] [--event-stats] + +``RUN`` is the run folder (``experiment_summary.h5`` and +``per_trial_summary.h5``, directly or in ``source_extraction/``). The trial +table, registered movies and raw folder are found as ``giant view`` finds them. +``--baseline-dir`` names the F0 network baselines the run used; they are not +needed for the target, but give the file its provenance (``baselineFile``, +``f0Network``) and the QC values ``targetOverBaselineSupport`` and +``targetOverBaselineLabeled``. Each worker needs a few times the size of one +trial's movie in memory (14 GB for a two-channel 804 x 382 px trial of 28 s). + +Output +------ + +``OUT/Path/trial_.h5`` (trial numbers of the trial table) and +``OUT/export_summary.json`` (every trial's record, NaN as ``null``; a trial +that could not be exported, for example one without an across-trial map, is +listed with ``error`` and not written). Arrays as h5py reads them, on the +trial's registered grid cropped to the box around the valid pixels, MATLAB's +row and column orientation, pixel coordinates zero-based in the crop +(``cropOriginRC`` gives the box): + +============================= ======================== ===================================================== +dataset shape, type content +============================= ======================== ===================================================== +``movie`` (channel, frame, row, registered movie; NaN at discarded frames and where + col) float32 not imaged +``activity`` same SILo's footprints times ``dF_denoised`` at the + movie's frames; zero outside the footprints +``mean_image`` (channel, row, col) mean over the kept frames of each written channel; + NaN outside the valid pixels +``mask/valid`` (row, col) uint8 missing in less than ``nanThresh`` of the frames, + motion discards counted +``mask/labeled`` (row, col) uint8 3 x 3 median-filtered mean image above 3 x its 25th + percentile +``mask/footprint_support`` (row, col) uint8 pixels any footprint covers +``frame/discard`` (frame,) uint8 SILo's motion discards and frames whose kernel weight + lies mostly on discarded 200 Hz frames +``frame/motion_row``, ... (frame,) float32 registration motion, ``rec_neg_err``, online motion + (``onlineMotion{X,Y,Z}shift``), mean of valid pixels +``varfac`` (row, col) float32 per-pixel mean of ``slap2/varFacDS`` (every frame + with ``--var-fac full``) +``sources/peak_{row,col}`` (source,) int32 each kept source's peak pixel (-1: none in the trial) +============================= ======================== ===================================================== + +Root attributes: the MATLAB exporter's names (``path``, ``trial``, +``frames``, ``nSources``, ``validPixels``, ``kernelDtLines``, +``kernelHalfWidthLines``, ``linesPerCycle``, ``shiftRC``, ``blurSigma``, +``activityGain`` = 1, the QC values below, ``discardedFrames``, +``channels``, ``activityChannel``, ``alignHz``, ``photonScale``, ``label``, +``giantRef``) and ``exporter``, ``exporterVersion``, ``kernel``, +``kernelR``, ``kernelDt200Lines``, ``movieDtLines``, ``footprintInterp``, +``alignmentMode``, ``siloRun``, ``baselineSource``, ``baselineFile``, +``f0Network`` (SILo's record of the trial's network baseline, JSON) and +``registrationStem``, the stem that the trial's registration files share +(``E1T3DMD2`` of ``E1T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.h5``), by which +slap2-f0 finds the trial's statistics and layout files. +``shiftRC`` is the across-trial map's mean offset over the footprint pixels. + +How the activity is rendered +---------------------------- + +*Space.* Each trial's footprints are moved from SILo's consensus canvas into +the trial's registered frame through SILo's own across-trial map (rigid, +affine or patchwise): the footprint at trial pixel ``q`` is the canvas +footprint at the map's inverse of ``q``. SILo read the trial's data through +the same map. ``--interp linear`` (default, as ``giant view``) interpolates +bilinearly, which blurs a footprint moved by a fraction of a pixel (up to +about 10% off a 1.3 px footprint's peak pixel); ``--interp cubic`` uses a +cubic spline, which keeps the shape (small negative lobes at the edge are +kept, so the flux is unchanged). + +*Time.* The 80 Hz movie frame is a weighted mean of the raw samples within +``max(3 dt80, P)`` lines of its line, weights ``exp(-|dline| / dt80)``; SILo's +200 Hz frames are such means with ``dt200``. ``--kernel exact`` (default) +renders ``x80 = r x200(line) + (1 - r) avg80(x200)``, ``r = (dt200 / +dt80)**2``, where ``x200(line)`` is the 200 Hz trace interpolated at the 80 +Hz frame's line from kept frames and ``avg80`` the MATLAB exporter's average +(exact for densely sampled pixels; see +:func:`giant_python.viewer.render.exact_weights`). ``--kernel exporter`` is +the MATLAB exporter's average alone, which smooths fast events twice; +``--kernel matched`` narrows it to ``sqrt(dt80**2 - dt200**2)``. Both ``dt`` +values come from the data (``DSframes`` and SILo's frame lines). + +*Blur and scale.* No blur unless ``--blur`` is given; no scaling (footprints +sum to 1, traces in movie units). + +QC attributes +------------- + +As the MATLAB exporter computes them, for the activity as written, at the +activity channel, high-passed by an 81-frame running median: ``peakSlope`` and +``peakR`` (movie on activity at each source's peak pixel, medians over +sources), ``diskSlope`` and ``diskR`` (flux in the footprint pixels within 4 +px of the peak), ``activitySlope`` (``diskSlope`` at blur 0), +``blurShapeRatio`` (core over 1.5-3.5 px slope; above 1 when the activity is +broader than the movie's events), ``eventResidualFraction`` and ``nEvents`` +(event-triggered residual at the peaks over the event-triggered movie, events +on each source's own trace), and the selection-safe ring-event ratios +``eventRatioCore``, ``eventRatio2px``, ``eventRatioSources``, +``eventRatioEvents``, ``eventRatioArtifactSources`` (events picked on the +movie 3-5 px from each source; ``slap2_f0.ringqc`` reproduces them from the +written arrays). New: ``targetOverBaselineSupport`` and +``targetOverBaselineLabeled``, the time-mean of ``movie - activity`` over that +of the network baseline at valid footprint pixels and at valid labeled pixels +outside the footprints. + +Activity mask (``--activity-mask``) +----------------------------------- + +For fine-tuning on recordings with the loss zeroed during activity (the +network's targets are then the movie itself), ``mask/activity`` (frame, row, +col) uint8 marks the samples to leave out. It comes from SILo's source-level +fit, not from the samples themselves: a cut on the samples (``movie > +baseline + 2 SD``) keeps the samples whose noise happened to be low, which +biases the kept mean by -0.055 SD and the variance to 0.89. + +* **When** (``--mask-k``, ``--mask-widen``, ``--mask-share``): 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`` decay constants of the activity channel (SILo's ``tau_full``, + ``tau_s`` in frames: 24 ms for iGluSnFR4f, so 48 ms at the default 2), + moved to the nearest 80 Hz frame and widened by ``share`` 80 Hz frames on + both sides (the frames that share samples). +* **Where** (``--mask-margin``): the source's footprint support in the trial, + as the activity is placed, dilated by a disk of ``margin`` px. +* **Spots without a source** (``--mask-spots seeds``): SILo's seeds that kept + no source (the plan file's unused seeds and the kinetics-rejected sources), + a disk of ``margin + 1.5`` px in every frame. Off by default (see below). A + trial whose seeds cannot be placed (no across-trial map) is then refused, and + so is a run that kept no plan file (``source_extraction/silo/plan``): its + unused seeds are unknown. + +Attributes: ``activityMaskK``, ``activityMaskMarginPx``, +``activityMaskWidenTau``, ``activityMaskTauSeconds`` (the decay constant the +widening used, in seconds), ``activityMaskShareFrames``, +``activityMaskSpots``, ``activityMaskFraction`` (of the valid samples in kept +frames) and ``activityMaskFractionSupport`` (at the footprint support). Files +without ``activityMaskTauSeconds`` were written before the widening used the +activity channel's decay: they widen by channel 2's ``tau2`` (0.15 s). + +The defaults were chosen on GFP 847983 (5 trials x 2 paths, SILo at the dev +defaults with the s6_ft baseline) against its truth: the uninjected recording, +where every source SILo keeps is false, and copies with injected events +(sparse: 60 sources per path at 1 Hz; dim; close pairs; dense: 200 sources per +path at 2.3 Hz), on which the original recording (copy minus the drawn +injected photons) is the event-free truth. On the kept samples: the leftover +injected signal, and the truncation (the mean and mean square of the +original's 81-frame high-passed samples against all samples). + +At the defaults (``k`` 3, margin 1 px, widening 2 decay constants of 24 ms, +6 shared frames, no spots), per set of 10 trial-paths: + +============================= =========== ========== ==================== =========== +set masked (fp leftover truncation, SD mean square + / all) (% of b) (% of b) kept / all +============================= =========== ========== ==================== =========== +GFP control (false sources) 19% / 1% 0 -0.0046 (-0.38%) 0.993 +sparse copy 35% / 23% 0.14 -0.0046 (-0.37%) 0.994 +dim copy 35% / 27% 0.27 -0.0046 (-0.43%) 0.993 +close pairs 39% / 33% 0.29 -0.0046 (-0.41%) 0.994 +dense copy 74% / 69% 0.86 -0.0067 (-0.64%) 0.984 +============================= =========== ========== ==================== =========== + +A per-sample 2 SD cut would bias the kept mean by -0.055 SD and the mean +square to 0.89: the rule is 12 times smaller in the mean and 16 times in the +variance deficit, and its net bias (leftover plus truncation) stays within +0.4% of the baseline (the S6 networks' bias is 2-4%). Alternatives on the +sparse, dim and pair copies: no widening masks 29-33% of the footprint +samples (truncation -0.005 SD), one decay constant 32-36%, three 37-42%, and +the first version's 0.15 s (channel 2's ``tau2``, 6.25 decay constants) +45-50% (truncation -0.0037 SD); the leftover is the same at every widening. +``k`` 2 masks 55-59% (truncation -0.010 to -0.012 SD, mean square +0.982-0.986) for a leftover lower by 0.04-0.10% of the baseline. A larger +margin or the seed spots mask more without lowering the leftover (checked +with the 0.15 s widening). The leftover comes from injected sources SILo kept +no source for and from events below the threshold (sizes 0.25-1 keep 21-27% +of their flux, size 2 9%, size 8 0.6%), not from the mask's edges (it does +not depend on the distance from the nearest masked frame); the truncation sits +within 10 frames of a masked frame. Held-out trials 4-5 and trials 1-3 agree +within 0.001 SD. + +Event statistics (``--event-stats``) +------------------------------------ + +``event_statistics.json`` next to the trial files, per path: for each source +its canvas position, footprint width, SNR, kinetics score and noise (the +robust SD of ``dF_ls - dF_denoised``), 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, as quantiles, and the rates at 3, +4, 5, 6 and 8 SDs (``ratesPerMin``); the synchrony (the share of events with +another source's onset within 2 frames of the same trial, observed and +expected for independent sources, both over the partners observed at the +event); SILo's ``tau_s``, ``tau2_s`` and frame rate. Each +trial's record adds ``labeledPixels`` (valid labeled pixels), for the source +density. + +An event is a run of kept frames where ``dF_denoised`` exceeds 6 noise SDs. +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; on the sparse copy (1 Hz +injected, sizes 0.25-8) 75, 36, 27, 22 and 16. The rates and sizes therefore +describe events above the detection limit. Sizes stay in raw units: photons +need the session's gain from the registration statistics' photon model. +A source with activity but no noise estimate (no finite ``dF_ls``) is listed +with ``unavailable`` and null counts, not as a quiet source. A path without +``dF_denoised`` is listed with ``unavailable``; without ``F0`` the dF/F +sizes are null and the rest stands. An export without +``--event-stats`` removes an earlier ``event_statistics.json`` from the output +folder (it would describe another run). + +GFP kind: injected copies (``giant export-f0-injected``) +-------------------------------------------------------- + +.. code-block:: text + + giant export-f0-injected COPY OUT [--device cpu|cuda] [--expected] + [--paths D ...] [--trials T ...] [--channels C ...] + [--var-fac mean|full] [--label TEXT] [--giant-ref REF] + +``COPY`` is a copy with injected events made by ``giant_python.simulation. +injection`` and registered (``trial_table.h5``, ``raw/``, +``motion_correction/``, ``injection_truth.h5``; ``injection compare`` run, so +that the truth has the sources' positions on the copy's grid). No SILo run is +involved: the trial's ``activity`` is the copy's raw samples minus the +original's, formed into the copy's registered 80 Hz frames as the movie is, +so ``movie - activity`` is the original recording on the copy's grid, noise +included. The training target is then the recording itself, and the injected +events are in the input only. ``--expected`` adds ``activity_expected``, the +noiseless injected signal, and ``drawnOverExpected`` (summed photons; 1 +within Poisson noise). ``mask/footprint_support`` and +``sources/peak_{row,col}`` describe the injected sources (footprints out to +each source's recorded radius, plus sqrt(2) px). Root attributes ``kind`` = +``gfp_injected``, ``injectionTruth``, ``originalTrial``, ``injectedSources`` +and ``injectedEvents``, and ``registrationStem`` of the copy's registration; +the SILo QC attributes are NaN (slap2-f0's +``filter_trials`` keeps files without ``peakR``). Trials are the copy's +(``--trials`` counts its columns); ``originalTrial`` names the recording's. +On the dim copy of 847983 (path 1 trial 1) the activity equals the truth that +the activity-mask check rendered on the GPU, and ``drawnOverExpected`` is +1.0006; the CPU takes about 100 s per trial-path. + +Raster layout for the simulator (``giant export-f0-layout``) +----------------------------------------------------------- + +.. code-block:: bash + + giant export-f0-layout path/to/trial_table.h5 [--out DIR] [--paths 1,2] + [--trials 1,2,3] [--datadr DIR] [--moco DIR] [--overwrite] + +slap2-F0-network's simulator draws raw photon samples and forms frames from +them as the recording's frames were formed, so that simulated noise has each +pixel's own sampling (how often it is sampled in a cycle, and where each +frame's time falls among its samples), the samples that consecutive frames +share, and the raw pixels that neighbouring registered pixels share. A +registered frame is linear in the raw samples; this command writes, for +every registered trial and path of a trial table, what fixes that linear map +and the photon statistics of the samples, in ``_F0LAYOUT.h5`` (about +1 MB, 10 s per trial on the CPU) next to the registered movie or in +``--out``. It reads the raw recording and the alignment file; the movie is +not needed. + +Registrations that undid the online motion correction (``giant register +--compensate-online``) are supported from version 4 of the file +(``layout_version``). There a sample is not placed at its slot's raster +pixel: it is moved by its line's online offset less the frame's own, rows +following y and columns x, and left out if that lies outside the window. The +file then also holds the offsets of every line of its cycles and each +frame's own offset (``lines/x``, ``lines/y_eff``, ``frames/ref_xy``; root +attributes ``compensated`` and ``y_lead``). ``reference_frames`` states the +rule and is checked against registration's movies with and without +compensation. Version 3 files (registrations without compensation) are still +read. + +Arrays are in NumPy's orientation. Lines are one-based; cycles, pixel +positions and slot indices are zero-based. + +============================= ===================== ====================================================== +dataset shape, type content +============================= ===================== ====================================================== +``frames/lines`` (frame,) int64 line time of each registered frame (``DSframes``) +``frames/motion`` (frame, 2) float64 the frames' row and column motion (NaN: no frame) +``slots/line`` (slot,) int32 line within the cycle on which the slot is sampled +``slots/pos`` (slot,) int32 position of the slot among its line's samples +``frames/ref_xy`` (frame, 2) int16 compensated registrations: the online offset [x, y] + each frame mostly saw +``lines/x``, ``lines/y_eff`` (line,) int16 compensated registrations: the online x offset and + the y on the DMD of every line of the cycles + ``cycle0 ... cycle0 + n_cycles - 1`` (index: line - + 1 - ``cycle0`` x ``lines_per_cycle``) +``slots/pixel`` (slot,) int32 the slot's raw pixel, an index into ``pixels`` (-1 + in a compensated file if no sample lands there) +``slots/row``, ``slots/col`` (slot,) int32 the slot's raster pixel in the registration window +``slots/next`` (slot,) int32 the slot that shares photon pulses with it: the one + sampled right after it on its line, if that is a + neighbouring pixel (-1: none) +``slots/line_end`` (slot,) uint8 1 if no sample follows that could share a pulse with + it (it ends its line, or the scan jumps to another + part of the raster); a slot without a next that is + not, is followed by a sample outside the file +``slots/index`` (slot,) int64 the slot's index in the recording's raster +``slots/mean`` (channel, slot) mean of the slot's valid samples over the trial +``slots/zero_share`` (channel, slot) share of its valid samples that are 0 +``slots/valid_share`` (channel, slot) share of its samples that are valid +``pixels/row`` (pixel,) int32 the row in the registration window of a raw pixel + that frames report (compensated: every pixel that a + sample can land on) +``pixels/col`` (pixel,) int32 its column +``photon/height_single`` (channel, 1024) int64 heights of pulses that fell into one sample +``photon/height_split`` (channel, 1024) int64 heights of pulses split between two samples +``photon/split_fraction`` (channel, 20) int64 share of a split pulse in the earlier sample +``photon/split_joint`` (channel, 64, 20) split events by height (bins of 16 raw units) and + int64 share in the earlier sample +``photon/burst_counts`` (channel, 5) int64 bursts of 1, 2, 3 and 4 samples, and longer ones +``photon/burst_1`` ... (channel, 8192, examples of the bursts of each length: their samples +``photon/burst_4`` length) int16 in scan order +``photon/burst_examples`` (channel, 4) int64 examples kept of each length (further rows are 0) +``photon/burst_cell_1`` ... (channel, 8192) int16 the type (cell) of each example +``photon/burst_cell_4`` +``photon/strata_edges`` (9,) edges of the brightness strata of dim chains (mean + sample, raw units) +``photon/strata_free`` (channel, 8) int64 samples of each stratum in which a burst could have + started +``photon/strata_mean`` (channel, 8) mean sample of each stratum +``photon/strata_bursts`` (channel, 8, 162) bursts of each stratum by cell + int64 +``photon/strata_longer`` (channel, 8) int64 bursts of more than four samples +``photon/level_edges`` (19,) edges of the brightness levels (mean sample, raw + units) +``photon/level_samples`` (channel, 18) int64 pairs of observations of each level +``photon/level_mean`` (channel, 18) mean sample of each level +``photon/level_zero`` (channel, 18) share of zeros +``photon/level_moments`` (channel, 18, 9) variance of a sample and its covariance with the 1st + to 8th sample after it on the line (raw units + squared) +``photon/level_revisits`` uint8 1 if the moments are measured against the next visit + of the same pixels within the cycle, 0 if against + the next cycle +``photon/pairs`` (channel,) int64 dim pairs used +``photon/pair_cycles`` (channel,) int64 their cycles in which the pair was isolated +============================= ===================== ====================================================== + +Attributes: ``lines_per_cycle``, ``line_period_s``, ``kernel_dt_lines`` and +``reach_lines`` (the frame kernel ``exp(-|line distance| / dt)`` and its +reach ``max(3 dt, P)``), ``cycle0`` and ``n_cycles`` (the cycles the trial's +frames reach), ``window_row0``, ``window_col0``, ``window_rows``, +``window_cols`` (the registration window on the DMD), ``margin`` (the +registered frame is the window padded by it on every side), ``unlit_masked`` +(whether the frames left out the samples behind the DMD curtain), +``first_line``, ``last_line``, ``path``, ``trial``, ``recording``, +``alignment``, ``layout_version``. + +Only the slots of the registration window are listed, on the registered +plane. :func:`giant_python.export.f0_layout.reference_frames` forms the +registered frames from the file and the samples of its slots; it states what +the file means. On a recording (780125, one trial and path: 72 463 slots of +37 785 raw pixels, 122 lines per cycle, 2 467 cycles, 2 254 frames) its +frames equal the registered movie's to float32 rounding (largest relative +difference 4e-7, the same missing pixels). + +*Pulses.* A raw sample is the summed height of the photon pulses that +arrived in it, and a pulse on the boundary between two consecutive samples +of a line is split between them (:doc:`reg_stats`), where the scan runs on +from a pixel to its neighbour: across a jump to another part of the raster +(from one ROI to the next) consecutive samples share nothing (on the GFP +recording 847983 they correlate by -0.01, against 0.17-0.22 for neighbouring +pixels), so ``slots/next`` links neighbouring pixels only. + +The histograms are measured on dim pairs ``(a, b)`` of consecutive slots, +both zero in at least 95% of their cycles (attribute ``dim_zero_share``), so +that unrelated pulses rarely coincide. Brighter pairs are never used: a +recording without dim pairs gets empty histograms, and its pulses have to be +taken from another recording of the same microscope. A cycle in which ``a`` +is not zero, while the samples before ``a`` and after ``b`` on the line are +zero, holds one whole event that arrived in ``a``, of height ``x_a + x_b``; +it is split when ``b`` is not zero either, by ``x_a / (x_a + x_b)``. Only +the earlier slot's events are counted, because a split one of the later slot +leaves the pair. The share of split events among the counted ones, +``sum(height_split) / (sum(height_single) + sum(height_split))``, is then +the probability that an event reaches into the next sample, whatever the +rates of the two slots. The sample before ``a`` must be a slot: at the start +of a run the sample before it is not recorded but still passes parts of its +pulses on (a fifth of the "unsplit pulses" measured there are below half a +pulse). The sample after ``b`` must be a slot or not exist; a pair next to a +sample that is not a raster slot is not used. + +*What the events are.* The acquisition zeroes events below half a photon +count, so no event inside a run has a total below about 50 raw units; a +count is about 105. Unsplit events peak there (100-120 raw units). Split +events are of two kinds, which ``photon/split_joint`` keeps apart: one pulse +on the boundary between the samples, at any fraction, and two pulses, one in +each sample, with about twice the height. Three in ten split events have a +total above 150 raw units on 847983 and 780125, against one in ten of the +unsplit ones. On 780125 (channel 1): half of the events reach into the next +sample, the unsplit ones 118 and the split ones 147 raw units high on +average. An event of ``a`` that coincides with an unrelated pulse of ``b`` +is counted as split too; the share of such coincidences among the counted +events is about the pulse rate per pair cycle, ``(sum(height_single) + +sum(height_split)) / pair_cycles``. + +*Bursts.* Some events are longer than two samples: on 847983 about 4% of +them span three, several times what unrelated pulses would give, and they +carry a fifth of the covariance of consecutive samples (measured directly, +that covariance is 23 per unit mean at the dimmest pairs; pulses confined to +two samples give 19). The pair histograms cannot hold them, because a pair +is counted only when the samples around it are zero. The library +``photon/burst_1`` ... ``burst_4`` therefore keeps whole events as they were +recorded: a burst starts in a slot whose sample is not zero while the sample +before it is zero, and runs on along the line until a sample is zero. It is +taken from chains of six consecutive slots whose mean sample is below 2 raw +units (attribute ``burst_level``; about one event in a hundred samples), so +that unrelated events rarely touch, and holds up to 8 192 examples of each +length, spread evenly over those found; ``burst_counts`` gives how often +each length occurs there. + +*Photon events and background.* Not every event is a photon of the tissue. +Some occur at a rate that does not depend on brightness: on 847983 and +780125 about 900 to 1 400 per million samples in either channel, most of +them 60-110 raw units in total, against a photon peak at 100-120. They are a +sixth of the events of the dimmest samples and a hundredth at 10 raw units +per sample, so the variance of a sample per unit mean rises from 125 raw +units at the dimmest samples to 133 where photon events dominate, and a +library taken from dim samples is a mixture of the two. ``photon/strata_*`` +lets a reader separate them. Chains are grouped into strata by their mean +sample (0 to 8 raw units; brighter ones are not counted), and the isolated +bursts of each stratum are counted by type. A burst's type (cell) is its +length and total, and for two samples also the smaller part's share: + +======= ======================================================== ======== +Samples Bins Cells +======= ======================================================== ======== +1 total in steps of 10 raw units (41 bins) 0-40 +2 total in steps of 20 (31 bins) x share of the smaller 41-133 + part in thirds of 0 to 0.5 (cell = 41 + 3 x total bin + + share bin) +3 total in steps of 50 (17 bins) 134-150 +4 total in steps of 100 (11 bins) 151-161 +======= ======================================================== ======== + +The last total bin of each length holds every larger total. Over the strata, +the rate of a cell per sample (``strata_bursts / strata_free``) rises in +proportion to ``strata_mean`` for photon events and is constant for the +background; unrelated events that touch add a term in its square. The +simulator fits the three and draws photon events at the rates it is given +and background events at their own. A chain's stratum is its mean over every +second block of eight cycles, and its bursts are counted in the other +blocks, then the other way round: a chain is then not placed among the dim +ones because it happened to have few events where they are counted. + +*Brightness.* ``photon/level_*`` gives the variance of a sample and its +covariance with the eight samples after it on the line, for chains grouped +by their mean sample (0.5 to 256 raw units in steps of a factor of 1.41). +With events that add up, both are proportional to the mean. They are so up +to about 10 raw units per sample, once the background is counted. Beyond +that, where more than a tenth of the samples are not zero, the recordings +have more of both: at 70 raw units per sample (0.5 events), 3% more variance +per unit mean than the events give, 17% more covariance with the next +sample, and covariance that reaches five samples on (847983; 780125 is +alike). The simulator does not model this; the table is kept to measure it. +The moments are measured against a second observation of the same tissue, +so that brightness which changes with brain motion is not counted: the next +visit of the same pixels within the cycle, on a later line (6.6 ms later on +847983; samples of one line can share pulses), or, for a raster that samples +each pixel on one line per cycle, the same slots one cycle later +(``level_revisits``). On 847983 the variance measured against the +next cycle (28 ms) is higher by 1% at the brightest level. + +Differences from the MATLAB exporter +------------------------------------ + +* SILo's across-trial map instead of a rigid offset searched per trial for the + best movie-activity correlation at the source peaks (the search could + prefer an offset that fits noise; patchwise maps cannot be expressed as one + offset). +* The exact time kernel instead of the double-smoothing average (fast events + kept 0.93-0.95 of their 80 Hz peak in the activity, so the targets kept + 5-7% of every fast event). +* No per-trial shape-matching blur; ``blurShapeRatio`` still reports the core + / ring slope ratio. +* ``mean_image`` holds the written channels (the MATLAB exporter wrote every + channel of the movie, which the reader indexes like ``movie``). It averages + the kept frames and is NaN outside the valid pixels, as slap2-f0 computes + the mean image at inference (``registered.ArrayTrial``); MATLAB's exporter + averaged the discarded frames too, so the network's input and its scale + differed between training and inference. The labeled mask is computed from + the same kept-frame mean. +* A trial whose sources have no ``dF_denoised`` traces, or for which SILo has + no 200 Hz frames, is reported and not written (its activity would be zero + and the target would keep every event). +* With ``--kernel exact`` or ``matched``, a trial whose 200 Hz frames are + wider than the movie's (``dt200 > dt80``, not the case for SLAP2's 200 Hz + analysis of 80 Hz movies) is reported and not written: no kernel undoes the + 200 Hz frames' own smoothing, and the renderer's ratio, capped at 1, would + only interpolate them. +* A trial that fails on a rerun loses its earlier file (the reader finds + files, not summaries). A default export (no ``--trials``) also removes the + earlier ``trial_.h5`` files of the exported paths that it does not + write, such as a trial SILo no longer analyses, and lists them under + ``removed`` in ``export_summary.json``; an export with ``--trials`` leaves + the other trials' files alone. Repeated ``--paths`` or ``--trials`` are + exported once; numbers the run or the trial table does not have are + refused. Invalid options (kernel, interpolation, ``var_fac``, a gzip level + outside 0-9, a negative or non-finite blur, channels the movie does not + have) are refused before any trial, so a rerun with one leaves the earlier + files in place. +* The labeled mask's median filter treats unimaged (NaN) pixels as the + largest values; MATLAB's ``medfilt2`` behaviour with NaN is not documented. diff --git a/docs/source/migration.rst b/docs/source/migration.rst index e031ac8d..25302057 100644 --- a/docs/source/migration.rst +++ b/docs/source/migration.rst @@ -1,171 +1,171 @@ -API and data conventions -======================== - -Public workflow and options ---------------------------- - -The lazy package-root exports provide ``extract_band_sources``, -``extract_sources``, ``annotate_rois``, ``Pipeline`` and the input, option and -result models. Both extraction functions accept an exact trial-table filename -or a loaded ``TrialTable`` and return ``ExperimentSummary``. -``Pipeline.from_trial_table(...).extract()`` returns the same pipeline; -read its result through ``pipeline.summary``. ``Pipeline.annotate()`` and -``annotate_rois(...)`` load existing annotations or draw them when permitted. - -The band service signature is -``extract_band_sources(input, params=None, *, execution=None, annotations=None)``. -``Pipeline`` uses the same option scopes. Generic services and ``Pipeline`` -take explicit ``microscope`` / ``scan_mode`` routing arguments; only -``microscope='slap2'`` with ``scan_mode='band'`` (or ``None``) is supported. -Unsupported standalone routing raises ``ValueError`` before input/backend -loading. Pipeline operations require a loaded table. - -The ``giant`` CLI offers ``annotate`` and ``extract``, each with a trial-table -filename and ``slap2`` / ``band`` routing choices. Invalid commands/options -are argument errors (exit code 2). For existing headless ROIs use -``--draw-user-rois --headless``, or in Python -``AnnotationOptions(enabled=True, interactive=False)``. Missing required -annotations fail explicitly rather than silently disabling ROIs. - -Configuration -------------- - -.. list-table:: Independent configuration scopes - :header-rows: 1 - - * - Argument - - Dataclass - - Scope - * - ``params`` - - ``BandSiloParams`` - - Band science only - * - ``execution`` - - ``ExecutionOptions`` - - ``max_workers``, ``verbose``, ``max_trials`` - * - ``annotations`` - - ``AnnotationOptions`` - - ``enabled``, ``interactive`` - -``resolve_band_options(params=None, execution=None, annotations=None)`` returns -fresh validated objects in the order shown above. Each input accepts **only -its corresponding dataclass, a dictionary of that scope's fields, or None**. -Mixed dictionaries, cross-scope fields, unknown keys and unrelated dataclasses -raise ``TypeError``. Caller-owned inputs are not mutated, even when acquisition -channel counts or GUI policy are later resolved. - -Defaults include peak threshold 7, analysis rate 100 Hz, decay 0.15 seconds, -baseline window 4 seconds, denoise window 1 second, VIF 1.38 and PSF dilation 17. -Execution defaults to six workers, no trial limit and verbosity off. Annotation -defaults to disabled with automatic interactivity. See :doc:`traces` for -temporal-fit controls, motion-bin tolerance and random-seed semantics. - -Channel count is inferred from acquisition metadata and retained in output -metadata. Source activity extraction always uses **channel zero**; other -source-activity channels contain NaNs. Neither channel count nor activity -channel is a scientific option. If channel count cannot be inferred, -extraction raises ``ValueError``; supply acquisition metadata for a kept trial. - -``gui.parameters_gui.run_parameter_gui(params=None, *, execution=None, -annotations=None)`` returns a validated ``(BandSiloParams, ExecutionOptions, -AnnotationOptions)`` triple, or ``None`` on cancellation, without mutating -inputs. Its sparse-factor control is in natural-log units. GUI toolkit imports -are lazy; see :doc:`architecture` for module ownership and numerical boundaries. - -Input identity and output location ----------------------------------- - -``Pipeline.from_trial_table`` loads an exact filename once and retains it as -``trial_table_path``; a loaded table is retained directly. ``source_path`` is -provenance, not a filename reconstructed from ``savedr``. Set ``datadr`` and -``savedr`` on the loaded ``TrialTable`` for explicit directory overrides and -pass that model to extraction. Copying the table file does not rewrite its -stored directories. - -Extraction writes beneath ``savedr`` to -``source_extraction/experiment_summary.h5``. Use a fresh output location: -updating an existing summary replaces supplied path groups but retains -unrelated paths and root parameters/layout flags. Array preparation before -each path replacement does not make writes file-wide atomic or provide -checkpoint/resume. Unknown external fields need not survive a model round-trip. -See :doc:`file_formats` for the persistence contract. - -Results API ------------ - -All imaging results belong to ``ExperimentSummary.paths``. Each ``PathSummary`` -owns its sources, ROIs, visualizations, ``FrameInfo``, depths and global -fluorescence. There are no flat or aggregate summary properties. ``path_index`` -is zero-based and maps to disk group ``Path{path_index + 1}``; a list position -is not necessarily that identity when reading selected paths. - -``FrameInfo`` exposes attributes and a shallow ``to_dict()`` only, not mapping -methods. Results are eager; per-source/ROI entries may share array storage. -They are neither lazy HDF5 proxies nor independent immutable snapshots. -Mutating shared storage can affect other views; serialization may stack -arrays and does not promise zero-copy writing. - -``io.experiment_summary.read_summary(path)`` returns ``ExperimentSummary``, -from BandSILo's files and raster SILo's (column-major, with its own fields -as the model's optional attributes), and ``write_summary(summary, path)`` -accepts that model, writes BandSILo's row-major schema, and returns ``None``. -Both functions are also exported by ``giant_python.io``. -``ExperimentSummary.from_h5`` / ``to_h5`` delegate to these canonical functions. - -Production summaries emit ``dF_ls``, ``dF_denoised`` and ``events`` alongside -source profiles, ``F0``, ``SNR``, visualizations, depths, global fluorescence -and frame information. ROI ``Fsvd`` is emitted as NaN unless explicitly -supplied through the model; BandSILo does not calculate it. Disabled and -enabled-but-empty annotations both emit zero-ROI datasets, distinguished by -the ``annotation_enabled`` attribute on the ``user_rois`` group. - -New summaries set ``row_major=1`` and preserve rank-two frame vectors. -Acquisition line indexes are one-based; summary spatial coordinates are -zero-based ``[z, y, x]``. ``PathSummary.z_depths`` maps to ``Z_depths`` on disk. -See :doc:`file_formats` for complete shapes, MATLAB layout decoding, annotation -coordinate flags and motion-sign provenance; see :doc:`traces` for temporal -output interpretation. BandSILo does not write per-trial summaries; raster -SILo does (:doc:`silo`). - -Staging example ---------------- - -The repository's ``examples/extract_band.py`` is safe to import: -there are no import-time filesystem operations, environment assignments, -matplotlib imports or heavy GIAnT imports. - -Provide ``--trial-table``, ``--data-dir``, ``--motion-correction`` and a **new** -``--results-dir``. The example copies the exact supplied table and copies -existing motion-correction assets by default. ``--stage-motion symlink`` -selects directory linking (Windows may require Developer Mode or link -privileges). ``--stage-data copy`` or ``symlink`` stages the complete raw -directory, including sidecars and reference TIFFs; ``none`` uses it in place. -This is staging of externally generated motion correction, not execution of -Python registration. - -Crucially, the example overrides ``datadr`` and ``savedr`` on the loaded -``TrialTable`` and passes that model directly to extraction. It does not -reload the copied file and lose those overrides. The copied file is an -unaltered provenance artifact: its stored directories are not rewritten, -and Python does not write trial tables. Input filename fields -must be relative without parent traversal; absolute names are rejected rather -than silently bypassing staging or being guessed from basenames. - -The example refuses any existing results file, directory or symlink, and -refuses output nested inside an input tree. It never deletes arbitrary -destinations or silently retries by replacing a link. Partial output after -failure is left for inspection; choose a new directory for another run. -Copied source symlinks are retained, so verify their targets when relocating -data between machines. Symlink mode is intentionally not a portable copy. - -``--joblib-temp`` optionally selects an existing directory with sufficient -space for worker memory maps. Paths, loaded metadata and scientific/run -options are validated before any staging or environment changes. Its -environment override is scoped to staging/extraction, before importing the -lazy extraction service, and restored even when extraction fails. Without -the flag, the existing environment and joblib defaults are left alone. -Dependencies must already be installed; the example does not install packages. - -Scientific and execution flags are explicit run choices, not changes to -library defaults. Use ``--use-rois --annotations-dir`` for existing headless -annotations, or add ``--interactive`` to permit drawing. Inspect ``--help`` +API and data conventions +======================== + +Public workflow and options +--------------------------- + +The lazy package-root exports provide ``extract_band_sources``, +``extract_sources``, ``annotate_rois``, ``Pipeline`` and the input, option and +result models. Both extraction functions accept an exact trial-table filename +or a loaded ``TrialTable`` and return ``ExperimentSummary``. +``Pipeline.from_trial_table(...).extract()`` returns the same pipeline; +read its result through ``pipeline.summary``. ``Pipeline.annotate()`` and +``annotate_rois(...)`` load existing annotations or draw them when permitted. + +The band service signature is +``extract_band_sources(input, params=None, *, execution=None, annotations=None)``. +``Pipeline`` uses the same option scopes. Generic services and ``Pipeline`` +take explicit ``microscope`` / ``scan_mode`` routing arguments; only +``microscope='slap2'`` with ``scan_mode='band'`` (or ``None``) is supported. +Unsupported standalone routing raises ``ValueError`` before input/backend +loading. Pipeline operations require a loaded table. + +The ``giant`` CLI offers ``annotate`` and ``extract``, each with a trial-table +filename and ``slap2`` / ``band`` routing choices. Invalid commands/options +are argument errors (exit code 2). For existing headless ROIs use +``--draw-user-rois --headless``, or in Python +``AnnotationOptions(enabled=True, interactive=False)``. Missing required +annotations fail explicitly rather than silently disabling ROIs. + +Configuration +------------- + +.. list-table:: Independent configuration scopes + :header-rows: 1 + + * - Argument + - Dataclass + - Scope + * - ``params`` + - ``BandSiloParams`` + - Band science only + * - ``execution`` + - ``ExecutionOptions`` + - ``max_workers``, ``verbose``, ``max_trials`` + * - ``annotations`` + - ``AnnotationOptions`` + - ``enabled``, ``interactive`` + +``resolve_band_options(params=None, execution=None, annotations=None)`` returns +fresh validated objects in the order shown above. Each input accepts **only +its corresponding dataclass, a dictionary of that scope's fields, or None**. +Mixed dictionaries, cross-scope fields, unknown keys and unrelated dataclasses +raise ``TypeError``. Caller-owned inputs are not mutated, even when acquisition +channel counts or GUI policy are later resolved. + +Defaults include peak threshold 7, analysis rate 100 Hz, decay 0.15 seconds, +baseline window 4 seconds, denoise window 1 second, VIF 1.38 and PSF dilation 17. +Execution defaults to six workers, no trial limit and verbosity off. Annotation +defaults to disabled with automatic interactivity. See :doc:`traces` for +temporal-fit controls, motion-bin tolerance and random-seed semantics. + +Channel count is inferred from acquisition metadata and retained in output +metadata. Source activity extraction always uses **channel zero**; other +source-activity channels contain NaNs. Neither channel count nor activity +channel is a scientific option. If channel count cannot be inferred, +extraction raises ``ValueError``; supply acquisition metadata for a kept trial. + +``gui.parameters_gui.run_parameter_gui(params=None, *, execution=None, +annotations=None)`` returns a validated ``(BandSiloParams, ExecutionOptions, +AnnotationOptions)`` triple, or ``None`` on cancellation, without mutating +inputs. Its sparse-factor control is in natural-log units. GUI toolkit imports +are lazy; see :doc:`architecture` for module ownership and numerical boundaries. + +Input identity and output location +---------------------------------- + +``Pipeline.from_trial_table`` loads an exact filename once and retains it as +``trial_table_path``; a loaded table is retained directly. ``source_path`` is +provenance, not a filename reconstructed from ``savedr``. Set ``datadr`` and +``savedr`` on the loaded ``TrialTable`` for explicit directory overrides and +pass that model to extraction. Copying the table file does not rewrite its +stored directories. + +Extraction writes beneath ``savedr`` to +``source_extraction/experiment_summary.h5``. Use a fresh output location: +updating an existing summary replaces supplied path groups but retains +unrelated paths and root parameters/layout flags. Array preparation before +each path replacement does not make writes file-wide atomic or provide +checkpoint/resume. Unknown external fields need not survive a model round-trip. +See :doc:`file_formats` for the persistence contract. + +Results API +----------- + +All imaging results belong to ``ExperimentSummary.paths``. Each ``PathSummary`` +owns its sources, ROIs, visualizations, ``FrameInfo``, depths and global +fluorescence. There are no flat or aggregate summary properties. ``path_index`` +is zero-based and maps to disk group ``Path{path_index + 1}``; a list position +is not necessarily that identity when reading selected paths. + +``FrameInfo`` exposes attributes and a shallow ``to_dict()`` only, not mapping +methods. Results are eager; per-source/ROI entries may share array storage. +They are neither lazy HDF5 proxies nor independent immutable snapshots. +Mutating shared storage can affect other views; serialization may stack +arrays and does not promise zero-copy writing. + +``io.experiment_summary.read_summary(path)`` returns ``ExperimentSummary``, +from BandSILo's files and raster SILo's (column-major, with its own fields +as the model's optional attributes), and ``write_summary(summary, path)`` +accepts that model, writes BandSILo's row-major schema, and returns ``None``. +Both functions are also exported by ``giant_python.io``. +``ExperimentSummary.from_h5`` / ``to_h5`` delegate to these canonical functions. + +Production summaries emit ``dF_ls``, ``dF_denoised`` and ``events`` alongside +source profiles, ``F0``, ``SNR``, visualizations, depths, global fluorescence +and frame information. ROI ``Fsvd`` is emitted as NaN unless explicitly +supplied through the model; BandSILo does not calculate it. Disabled and +enabled-but-empty annotations both emit zero-ROI datasets, distinguished by +the ``annotation_enabled`` attribute on the ``user_rois`` group. + +New summaries set ``row_major=1`` and preserve rank-two frame vectors. +Acquisition line indexes are one-based; summary spatial coordinates are +zero-based ``[z, y, x]``. ``PathSummary.z_depths`` maps to ``Z_depths`` on disk. +See :doc:`file_formats` for complete shapes, MATLAB layout decoding, annotation +coordinate flags and motion-sign provenance; see :doc:`traces` for temporal +output interpretation. BandSILo does not write per-trial summaries; raster +SILo does (:doc:`silo`). + +Staging example +--------------- + +The repository's ``examples/extract_band.py`` is safe to import: +there are no import-time filesystem operations, environment assignments, +matplotlib imports or heavy GIAnT imports. + +Provide ``--trial-table``, ``--data-dir``, ``--motion-correction`` and a **new** +``--results-dir``. The example copies the exact supplied table and copies +existing motion-correction assets by default. ``--stage-motion symlink`` +selects directory linking (Windows may require Developer Mode or link +privileges). ``--stage-data copy`` or ``symlink`` stages the complete raw +directory, including sidecars and reference TIFFs; ``none`` uses it in place. +This is staging of externally generated motion correction, not execution of +Python registration. + +Crucially, the example overrides ``datadr`` and ``savedr`` on the loaded +``TrialTable`` and passes that model directly to extraction. It does not +reload the copied file and lose those overrides. The copied file is an +unaltered provenance artifact: its stored directories are not rewritten, +and Python does not write trial tables. Input filename fields +must be relative without parent traversal; absolute names are rejected rather +than silently bypassing staging or being guessed from basenames. + +The example refuses any existing results file, directory or symlink, and +refuses output nested inside an input tree. It never deletes arbitrary +destinations or silently retries by replacing a link. Partial output after +failure is left for inspection; choose a new directory for another run. +Copied source symlinks are retained, so verify their targets when relocating +data between machines. Symlink mode is intentionally not a portable copy. + +``--joblib-temp`` optionally selects an existing directory with sufficient +space for worker memory maps. Paths, loaded metadata and scientific/run +options are validated before any staging or environment changes. Its +environment override is scoped to staging/extraction, before importing the +lazy extraction service, and restored even when extraction fails. Without +the flag, the existing environment and joblib defaults are left alone. +Dependencies must already be installed; the example does not install packages. + +Scientific and execution flags are explicit run choices, not changes to +library defaults. Use ``--use-rois --annotations-dir`` for existing headless +annotations, or add ``--interactive`` to permit drawing. Inspect ``--help`` for all flags. \ No newline at end of file diff --git a/docs/source/reg_stats.rst b/docs/source/reg_stats.rst index d490cd57..0c63344e 100644 --- a/docs/source/reg_stats.rst +++ b/docs/source/reg_stats.rst @@ -1,353 +1,353 @@ -Registration summary statistics -=============================== - -``giant register`` writes, next to each registered movie, a file of per-trial -summary statistics, ``_REGSTATS-80Hz.h5`` (``stats_version`` 1). They -are maps of the registered 80 Hz movie alone, made for the next version of the -F0 network (``slap2-F0-network``): how much each pixel varies beyond photon -noise slowly (drift, bleaching, slow motion) and fast (events), whether its -fast changes are positive transients, and how it follows the trial's shared -modes. Every moment comes with its expectation under photon noise alone at -that pixel, so that the normalised maps read 0 for photon noise at any -brightness, and both are stored, so that later versions can renormalise -without the movie. - -.. code-block:: bash - - giant register path/to/trial_table.h5 # writes the statistics too - giant register path/to/trial_table.h5 --no-stats # does not - giant reg-stats path/to/trial_table.h5 # for trials registered earlier - -``giant reg-stats`` computes the same maps for movies registered earlier, -GIAnT-Python's (HDF5 or TIFF) and GIAnT-MATLAB's: it reads each trial's raw -recording again (for the photon-noise model), then the registered movie and -``varFacDS`` frame by frame, and passes them through the same code as -registration, so the maps are equal: bit for bit on the same GPU, or on the -CPU with the same number of threads (as ``giant register`` and ``giant -reg-stats`` with the same ``--max-workers``); otherwise to float32 rounding -(with another CPU thread count, a few pixels differ by 1e-7 relative). Frame times, motion, registration -window and online compensation come from the alignment file and are checked -against the raw recording; a frame without data counts as missing whatever -motion the alignment file gives it, as in registration. Options: ``--out DIR`` (write the files there -instead of next to the movies), ``--datadr`` and ``--moco`` (folders that -moved since the trial table was written), ``--device``, ``--max-workers``, -``--overwrite`` (statistics that record the same version, frame times, -motion and movie size are otherwise kept). The command exits with status 1 -if a requested trial failed, a missing movie or alignment file included. - -From Python: - -.. code-block:: python - - from giant_python.registration.stats import read_stats, combine_trials - - st = read_stats("E1T1DMD1_REGSTATS-80Hz.h5") - st["maps"]["fast_skew_rel"] # (channels, rows, cols) - -Registration's other outputs do not change: the movie and the alignment file -are bit-identical with and without statistics, and nothing that reads them -(GIAnT-Python's loaders, ``slap2_f0``'s reader, MATLAB) sees the new file. A -registration that skips a trial because its outputs exist leaves the trial's -statistics as they are (``giant reg-stats`` replaces those of another -``stats_version`` or registration); one with ``--no-stats`` removes an existing file of -the trial, which would describe the earlier registration. If the statistics -fail, registration logs the error and publishes the movie without them. - -Definitions ------------ - -All statistics are per trial, per DMD and per channel, on the registered grid -(``meanIM``'s rows and columns), over every registered frame (SILo's motion -discards are not applied; they are made later). A pixel's value in a frame is -*valid* where the movie is not NaN. Frames are numbered from 0. - -Single frame - ``n_valid``: valid frames. ``mean``: the mean of the valid values, formed - in float32 exactly as registration forms ``meanIM`` (identical to it). - ``var``: ``mean(x^2) - mean(x)^2`` over the valid frames (population - variance, in float64). ``zero_share``: the share of valid frames that are - exactly 0. - -Slow part - Blocks of 64 frames from frame 0; a trailing partial block is dropped. A - block is valid at a pixel with at least 48 valid frames; its value is the - mean of those. ``slow_var``: the variance of the valid blocks' means with - ``J - 1`` in the denominator (``J``: valid blocks, ``n_blocks``). - -Fast part - ``z_t = x_t - (mean of the valid frames t - 32 .. t + 32)`` for centres - ``32 <= t <= N - 33`` (the 65-frame window inside the trial) whose own - frame is valid and whose window has at least 49 valid frames. - ``fast_var`` and ``fast_m3``: the second and third central moments of - ``z`` over those centres (``n_fast``). - -Shared modes (``svd/``) - 8-frame time bins from frame 0 (a trailing partial bin dropped); a - pixel's bin is the mean of its valid frames, missing with fewer than 6. - 2 x 2 pixel bins from pixel (0, 0) (a trailing odd row or column - dropped); a bin is the mean of its four pixels' bins, missing unless all - four are present. Spatial bins without a missing time bin enter the SVD, - each centred on its mean over time and divided by its photon-noise SD - (below). The top three components of ``Y = U S V^T`` are kept, each - signed so that its spatial vector sums to a non-negative value. Stored: - ``time_courses`` (unit norm), ``singular_values``, ``var_share`` - (``s^2 / sum(Y^2)``), ``skew`` and ``lag1`` (skewness and lag-1 - autocorrelation of each time course), ``total_var``, ``n_space``, - ``n_bins``, and every pixel's ``weight``: the coefficient of each time - course in a least-squares fit of the pixel's own 8-frame bin means (its - valid bins, at least 64, with an intercept), in movie units per unit of - the unit-norm time course; ``weight_ph`` divides it by the pixel's - ``sigma8_ph``. - -Photon-noise model ------------------- - -A raw SLAP2 sample is the summed height of the photon pulses that arrived -during it, and pulse heights vary (about 1 to 250 raw units per photon). A -sample of mean ``mu`` therefore has, under photon noise alone, variance -``g2 mu`` and third cumulant ``g3 mu`` (compound Poisson; ``g2 = E[A^2] / -E[A]``, ``g3 = E[A^3] / E[A]`` for pulse height ``A``). Both depend on -brightness on SLAP2 (``g2`` from about 110-120 in the dimmest slots to -130-140), so each trial measures them per channel as a curve over brightness -(``gain/``): for every slot and every three successive cycles with valid -samples, the second difference ``d = 2 x1 - x0 - x2`` has ``E[d^2] = 6 -kappa2`` and ``E[d^3] = 6 kappa3`` and does not see linear drift; slots are -sorted by their mean and split into 16 groups of equal size, and per group -``g2 = sum(d^2) / (6 sum(x1))``, ``g3 = sum(d^3) / (6 sum(x1))`` (exact -integer sums over all cycles the trial's frames read). A pixel's gains -(``gain_g2``, ``gain_g3``) are interpolated linearly in ``log(mean)`` and -held constant beyond the first and last group. The rate of non-zero -samples, ``nu = -log(share of zeros)``, is stored per unit mean. - -Consecutive samples on a line share photons: a pulse that falls on the -boundary between two samples is split between them. On SLAP2 the sample and -the next one (86-88% of the time the next pixel along the row, otherwise one -row up or down) are correlated by about 0.17-0.25 (channel 1) and 0.12-0.15 -(channel 2), with third cross-cumulants of 0.12-0.18 of ``kappa3``; a -pixel's own samples, on different lines and cycles, are uncorrelated. -Registration's bilinear resampling mixes neighbouring raw pixels, so this -correlation adds about 8% to a registered pixel's photon variance (more at -half-pixel shifts). The same second differences give, for every pair of -consecutive samples ``(s, n)``, ``c2 = cov / mu``, ``c3a = kappa(s, s, n) / -mu`` and ``c3b = kappa(s, n, n) / mu``, measured as curves over the pairs' -mean (``gain/mu_pair, c2, c3a, c3b``), and the share of a pair's non-zero -events that make both samples non-zero (``gain/zero_shared``; the trial's -value, the median over the dimmer half of the pair groups, is the attribute -``zero_shared``). - -A registered frame is linear in the raw samples: frame formation weights the -samples of raw pixel ``k`` with ``w_s(t) = exp(-|t - l_s| / dt)`` within -``max(3 dt, P)`` lines, and registration resamples by a rigid shift with -bilinear coefficients weighted by the raw pixels' summed weights, so that -``x_t(p) = sum_s a_ts x_s`` with ``a_ts = c_t(ab) w_s(t) / D_t(p)`` and -``D_t(p) = 1 / varFacDS``. With the samples of the pixel's mean ``mu``, -independent but for consecutive pairs, - -.. code-block:: text - - Cov(x_t, x_u) = mu (g2 A2(t, u) + 2 c2 QA2(t, u)) - A2(t, u) = sum_s a_ts a_us, QA2(t, u) = sum over pairs (s, n) of - (a_ts a_un + a_tn a_us) / 2 - kappa3(x_t) = mu (g3 A3(t, t, t) + 3 c3a QA3a(t) + 3 c3b QA3b(t)) - A3(t, t, u) = sum_s a_ts^2 a_us, QA3a = sum a_ts^2 a_tn, - QA3b = sum a_ts a_tn^2 - -Frames ``t`` and ``t + l`` share samples for ``l <= n_lags`` (6 at 80 Hz -for rasters of up to 402 lines per cycle). These sums are computed exactly, -frame by frame, from the raster's layout, the frame times and each frame's -motion, assuming every sample in reach is valid; they are rescaled by the -actual ``D_t(p)`` from ``varFacDS`` (where samples were invalid the -remaining ones are taken as proportional). The pair sums are exact for a -frame with itself; for two different frames that share samples they are -taken as the samples' own sums times the pixel's ratio ``r = sum_t QA2(t, t) -/ sum_t A2(t, t)`` (a pair lies on one line, so its kernel overlap between -frames is that of the samples), and the fast third cumulant's pair part is -its own-frame part's share of ``R0`` applied to the whole (within 0.5% at -SLAP2's pair correlations in tests). Each second moment's expectation is -``mu (g2 m_q + 2 c2 m_qa)``, where ``m_q`` comes from the ``A2`` and -``m_qa`` from the ``QA2`` sums in the same way; each follows from its -estimator: - -``var_q`` - ``S0 / n - (S0 + 2 S1) / n^2`` with ``S0 = sum_t A2(t, t)`` and ``S1`` - the sum of ``A2`` over pairs of valid frames ``t < u`` (the second term - is the variance of the mean). -``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`` the covariance of - adjacent blocks' means (from frames that share samples across the block - boundary). -``fast_q`` - the mean over centres of ``A2(t, t) - 2 L_t / n_t + P_t / n_t^2``, - where ``L_t`` sums ``A2(t, u)`` over the window and ``P_t`` over pairs - of window frames (exact). -``fast_q3`` - the mean over centres of ``R0 - 3 K_t / n_t + 3 L_t^2 / n_t^2 - - sum_u L_u^2 / n_t^3`` with ``R0 = A3(t, t, t)`` and ``K_t = sum_u - A3(t, t, u)``; the last two terms (products of three coefficients of - which two belong to other frames, about 0.5% of the total) are - approximated, within 0.25% of the exact third cumulant on synthetic - layouts. ``fast_q3a`` and ``fast_q3b`` are the means of the same times - ``QA3a / R0`` and ``QA3b / R0``; ``fast_m3_ph = mu (g3 fast_q3 + 3 c3a - fast_q3a + 3 c3b fast_q3b)``. -``sigma8_ph`` - ``sqrt(mu (g2 v8 + 2 c2 v8a))`` with ``v8`` and ``v8a`` the means over - valid 8-frame bins of the photon variance of the bin's mean per unit of - the gains (its own samples, and its consecutive-sample pairs). -``2 x 2 bins (shared modes)`` - A 2 x 2 bin's photon variance is ``sum over its pixels of mu v8 (g2 - spatial_factor + 2 c2 pair_bin_factor) / 16``. ``spatial_factor`` (an - attribute) is the trial's mean of ``(1 + rho_r)(1 + rho_c)``, ``rho = - f (1 - f) / ((1 - f)^2 + f^2)`` for the frame's fractional shifts ``f``, - by which bilinear interpolation's shared raw pixels raise the variance - of a 2 x 2 sum; ``pair_bin_factor`` (an attribute) is the trial's mean - of ``sum_d pi_d S_d / (4 Q_r Q_c)``, the consecutive-sample pairs inside - the sum (between its pixels as well as within each): ``pi_d`` is the - share of samples whose next sample is in the neighbouring direction - ``d``, ``Q = (1 - f)^2 + f^2`` per axis, and ``S_d`` the product over - the axes of ``(1 - f)^2 + 1 + f^2`` where ``d`` does not step and 1 - where it does (equal raw pixels assumed for both). -``zero_ph`` - a frame is exactly 0 when all of its ``N`` contributing samples are; - with ``M`` of them in consecutive pairs that has probability ``exp(-nu - (N - phi M))`` (``phi``: the trial's ``zero_shared``). Its sum over the - pixel's valid frames is accumulated at 33 rates from 1e-4 to 2 per - sample and interpolated at the pixel's rate ``nu``. - -For each moment ``m`` the file holds ``m``, ``m_q`` and ``m_qa`` (for the -fast third moment ``fast_q3``, ``fast_q3a``, ``fast_q3b``: the expectation's -parts per unit of the gains, properties of frame formation and -registration only), ``m_ph`` and the normalised map: - -* ``var_rel = var / var_ph - 1``, ``slow_rel``, ``fast_rel`` likewise - (``sqrt(1 + rel)`` is the SD relative to photon noise); -* ``fast_skew_rel = (fast_m3 - fast_m3_ph) / fast_var_ph^1.5``: the third - moment beyond photon noise, in units of the photon-noise SD; -* ``zero_excess = zero_share - zero_ph``. - -Under photon noise all read 0. A ratio estimated from few blocks is -unbiased, but its median is below 0 (as for a chi-square: about -0.02 for -34 blocks); likewise the median of ``fast_skew_rel`` at pixels with well -under one photon per frame is far below its mean (the third moment of a few -photons is heavy-tailed). - -**What the maps respond to.** Slow drift raises ``slow_rel`` and leaves the -fast maps at 0. Sparse events (positive transients) raise ``fast_skew_rel`` -and ``fast_rel`` at their sources, but also ``slow_rel``: the number and -size of events in a 64-frame block vary, and a block mean's photon noise is -small, so at bright sources ``slow_rel`` rises as much as ``fast_rel`` or -more. ``slow_rel`` therefore measures slow changes of the pixel's value, of -which baseline changes are one source; the fast skewness tells activity -apart. - -**Approximations.** The expectation is that of a pixel whose brightness is -its mean and the same for the 2 x 2 raw pixels it interpolates: at sharp -edges, under sub-pixel motion, it is off by the difference between the -coefficients' and their squares' weighting (and real motion at edges adds -true slow and fast variance). With online compensation, a sample that two -frames share is placed by the earlier frame's displacement (they differ only -around an x/y switch). Rasters whose frames share samples over more than 7 -frames (cycles longer than about 530 lines at 80 Hz) are not supported. -The fast moments are central (the mean of ``z`` over the centres is taken -out, which matters at edge pixels whose valid windows are uneven), but -their expectations are the means of the centres' own ``z`` moments: they -leave out the variance of that mean, so under photon noise ``fast_rel`` -reads about -0.3% (independent frames) to -0.8% (frames sharing samples) -at the minimum of 64 centres, and about -1e-6 for a pixel with data in -the whole of a 28 s trial. Frames are formed from each channel's own -valid samples, but registration's freshness and ``varFacDS`` follow the -first channel's: where another channel's invalid samples differ, its -expectations assume the first channel's samples. Such samples are counted -(attribute ``validity_differs``, per channel, with a warning); SLAP2 -recordings mark invalid samples in all channels alike (none differ on the -trials checked). - -Session maps ------------- - -Registered trials do not share a frame (each is registered to a template of -its own frames), so the files hold per-trial maps. -:func:`~giant_python.registration.stats.session.combine_trials` combines -them given SILo's across-trial alignment (``ExtractionPlan.warp``, or rigid -shifts): each trial's maps are resampled into the consensus frame and -averaged, each weighted by the frames behind it (``n_valid``, ``n_blocks``, -``n_fast``); the normalised maps are formed from the averaged moments and -expectations. The shared modes are not combined. - -File layout ------------ - -Arrays are in GIAnT's MATLAB layout, as the movie: 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``; -``read_stats`` returns Python's orientation. Maps are float32, NaN where a -pixel never had data or has too few frames (64 valid frames or fast -centres, 8 valid blocks):: - - _REGSTATS-80Hz.h5 - ├── (attributes) stats_version, layout, created, source (registration | - │ reg-stats), movie, movie_size, alignment, alignment_digest (SHA-256 - │ of DSframes, motionDSr, motionDSc), align_hz, n_frames, n_lags, - │ n_index, spatial_factor, pair_bin_factor, zero_shared, - │ validity_differs, device - ├── maps/ - │ ├── n_valid, mean, var, var_q, var_qa, var_ph, var_rel - │ ├── zero_share, zero_ph, zero_excess - │ ├── n_blocks, slow_var, slow_q, slow_qa, slow_var_ph, slow_rel - │ ├── n_fast, fast_var, fast_q, fast_qa, fast_var_ph, fast_rel, - │ │ fast_m3, fast_q3, fast_q3a, fast_q3b, fast_m3_ph, fast_skew_rel - │ └── gain_g2, gain_g3, gain_c2, gain_c3a, gain_c3b, sigma8_ph - ├── svd/ - │ ├── time_courses (channels, 3, time bins) - │ ├── singular_values, var_share, skew, lag1 (channels, 3) - │ ├── total_var, n_space (channels,), n_bins - │ └── weight, weight_ph (channels, 3, cols, rows) - └── gain/ - ├── mu, g2, g3, nu_per_mu, n_slots (channels, groups) - └── mu_pair, c2, c3a, c3b, zero_shared, n_pairs (channels, groups) - -Cost ----- - -The statistics are formed while registration writes the movie, on the -registration's device: on a GPU on a thread and a CUDA stream of their own -(their setup, the gain curves and the frame geometry, while the template -is built), on the CPU in line (a second thread there competes for the same -cores and was slower). On a 780125 trial (2 channels, 2,254 frames of 320 x -845 pixels) on a quiet machine (RTX 4060 Ti; 8 CPU threads of a -Threadripper PRO 5955WX), registration took: - -.. list-table:: - :header-rows: 1 - - * - device - - without statistics - - with - - memory added - * - GPU - - 20.9 s - - 27.8 s (+33%) - - 2.3 GB GPU, 0.5 GB RAM - * - CPU - - 71.6 s - - 166.3 s (+132%) - - 3.0 GB RAM - -The time is the statistics' own arithmetic: on the GPU their kernels (about -2.4 ms per frame, mostly the per-frame photon-noise geometry and the -64-frame blocks) and the Python work of launching them, on the CPU the same -arithmetic, memory-bound, at about 40 ms per frame. Registration on the CPU -can leave the statistics out (``--no-stats``) and ``giant reg-stats ---device cuda`` add them later (27 s for this trial, reading the raw -recording and the movie again). - -Memory grows with the trial in two places the statistics add: the shared -modes keep every pixel's 8-frame bin means until the trial ends (frames / -8 x pixels x channels x 4 bytes: 0.1 GB for this 28 s trial, about 2.3 GB -for a 10-minute one; their decomposition uses the smaller of the time-bin -and spatial-bin Gram matrices), and the frame geometry keeps its kernel -tables for every frame ((4 + 3 x lags) x frames x lines per cycle x 4 -bytes per displacement group: 25 MB here, about 0.5 GB for 10 minutes). -The trial's raw samples, which the gain curves read, are registration's -own (its frame former holds them in any case). The rest is held for a few -blocks of frames at a time. +Registration summary statistics +=============================== + +``giant register`` writes, next to each registered movie, a file of per-trial +summary statistics, ``_REGSTATS-80Hz.h5`` (``stats_version`` 1). They +are maps of the registered 80 Hz movie alone, made for the next version of the +F0 network (``slap2-F0-network``): how much each pixel varies beyond photon +noise slowly (drift, bleaching, slow motion) and fast (events), whether its +fast changes are positive transients, and how it follows the trial's shared +modes. Every moment comes with its expectation under photon noise alone at +that pixel, so that the normalised maps read 0 for photon noise at any +brightness, and both are stored, so that later versions can renormalise +without the movie. + +.. code-block:: bash + + giant register path/to/trial_table.h5 # writes the statistics too + giant register path/to/trial_table.h5 --no-stats # does not + giant reg-stats path/to/trial_table.h5 # for trials registered earlier + +``giant reg-stats`` computes the same maps for movies registered earlier, +GIAnT-Python's (HDF5 or TIFF) and GIAnT-MATLAB's: it reads each trial's raw +recording again (for the photon-noise model), then the registered movie and +``varFacDS`` frame by frame, and passes them through the same code as +registration, so the maps are equal: bit for bit on the same GPU, or on the +CPU with the same number of threads (as ``giant register`` and ``giant +reg-stats`` with the same ``--max-workers``); otherwise to float32 rounding +(with another CPU thread count, a few pixels differ by 1e-7 relative). Frame times, motion, registration +window and online compensation come from the alignment file and are checked +against the raw recording; a frame without data counts as missing whatever +motion the alignment file gives it, as in registration. Options: ``--out DIR`` (write the files there +instead of next to the movies), ``--datadr`` and ``--moco`` (folders that +moved since the trial table was written), ``--device``, ``--max-workers``, +``--overwrite`` (statistics that record the same version, frame times, +motion and movie size are otherwise kept). The command exits with status 1 +if a requested trial failed, a missing movie or alignment file included. + +From Python: + +.. code-block:: python + + from giant_python.registration.stats import read_stats, combine_trials + + st = read_stats("E1T1DMD1_REGSTATS-80Hz.h5") + st["maps"]["fast_skew_rel"] # (channels, rows, cols) + +Registration's other outputs do not change: the movie and the alignment file +are bit-identical with and without statistics, and nothing that reads them +(GIAnT-Python's loaders, ``slap2_f0``'s reader, MATLAB) sees the new file. A +registration that skips a trial because its outputs exist leaves the trial's +statistics as they are (``giant reg-stats`` replaces those of another +``stats_version`` or registration); one with ``--no-stats`` removes an existing file of +the trial, which would describe the earlier registration. If the statistics +fail, registration logs the error and publishes the movie without them. + +Definitions +----------- + +All statistics are per trial, per DMD and per channel, on the registered grid +(``meanIM``'s rows and columns), over every registered frame (SILo's motion +discards are not applied; they are made later). A pixel's value in a frame is +*valid* where the movie is not NaN. Frames are numbered from 0. + +Single frame + ``n_valid``: valid frames. ``mean``: the mean of the valid values, formed + in float32 exactly as registration forms ``meanIM`` (identical to it). + ``var``: ``mean(x^2) - mean(x)^2`` over the valid frames (population + variance, in float64). ``zero_share``: the share of valid frames that are + exactly 0. + +Slow part + Blocks of 64 frames from frame 0; a trailing partial block is dropped. A + block is valid at a pixel with at least 48 valid frames; its value is the + mean of those. ``slow_var``: the variance of the valid blocks' means with + ``J - 1`` in the denominator (``J``: valid blocks, ``n_blocks``). + +Fast part + ``z_t = x_t - (mean of the valid frames t - 32 .. t + 32)`` for centres + ``32 <= t <= N - 33`` (the 65-frame window inside the trial) whose own + frame is valid and whose window has at least 49 valid frames. + ``fast_var`` and ``fast_m3``: the second and third central moments of + ``z`` over those centres (``n_fast``). + +Shared modes (``svd/``) + 8-frame time bins from frame 0 (a trailing partial bin dropped); a + pixel's bin is the mean of its valid frames, missing with fewer than 6. + 2 x 2 pixel bins from pixel (0, 0) (a trailing odd row or column + dropped); a bin is the mean of its four pixels' bins, missing unless all + four are present. Spatial bins without a missing time bin enter the SVD, + each centred on its mean over time and divided by its photon-noise SD + (below). The top three components of ``Y = U S V^T`` are kept, each + signed so that its spatial vector sums to a non-negative value. Stored: + ``time_courses`` (unit norm), ``singular_values``, ``var_share`` + (``s^2 / sum(Y^2)``), ``skew`` and ``lag1`` (skewness and lag-1 + autocorrelation of each time course), ``total_var``, ``n_space``, + ``n_bins``, and every pixel's ``weight``: the coefficient of each time + course in a least-squares fit of the pixel's own 8-frame bin means (its + valid bins, at least 64, with an intercept), in movie units per unit of + the unit-norm time course; ``weight_ph`` divides it by the pixel's + ``sigma8_ph``. + +Photon-noise model +------------------ + +A raw SLAP2 sample is the summed height of the photon pulses that arrived +during it, and pulse heights vary (about 1 to 250 raw units per photon). A +sample of mean ``mu`` therefore has, under photon noise alone, variance +``g2 mu`` and third cumulant ``g3 mu`` (compound Poisson; ``g2 = E[A^2] / +E[A]``, ``g3 = E[A^3] / E[A]`` for pulse height ``A``). Both depend on +brightness on SLAP2 (``g2`` from about 110-120 in the dimmest slots to +130-140), so each trial measures them per channel as a curve over brightness +(``gain/``): for every slot and every three successive cycles with valid +samples, the second difference ``d = 2 x1 - x0 - x2`` has ``E[d^2] = 6 +kappa2`` and ``E[d^3] = 6 kappa3`` and does not see linear drift; slots are +sorted by their mean and split into 16 groups of equal size, and per group +``g2 = sum(d^2) / (6 sum(x1))``, ``g3 = sum(d^3) / (6 sum(x1))`` (exact +integer sums over all cycles the trial's frames read). A pixel's gains +(``gain_g2``, ``gain_g3``) are interpolated linearly in ``log(mean)`` and +held constant beyond the first and last group. The rate of non-zero +samples, ``nu = -log(share of zeros)``, is stored per unit mean. + +Consecutive samples on a line share photons: a pulse that falls on the +boundary between two samples is split between them. On SLAP2 the sample and +the next one (86-88% of the time the next pixel along the row, otherwise one +row up or down) are correlated by about 0.17-0.25 (channel 1) and 0.12-0.15 +(channel 2), with third cross-cumulants of 0.12-0.18 of ``kappa3``; a +pixel's own samples, on different lines and cycles, are uncorrelated. +Registration's bilinear resampling mixes neighbouring raw pixels, so this +correlation adds about 8% to a registered pixel's photon variance (more at +half-pixel shifts). The same second differences give, for every pair of +consecutive samples ``(s, n)``, ``c2 = cov / mu``, ``c3a = kappa(s, s, n) / +mu`` and ``c3b = kappa(s, n, n) / mu``, measured as curves over the pairs' +mean (``gain/mu_pair, c2, c3a, c3b``), and the share of a pair's non-zero +events that make both samples non-zero (``gain/zero_shared``; the trial's +value, the median over the dimmer half of the pair groups, is the attribute +``zero_shared``). + +A registered frame is linear in the raw samples: frame formation weights the +samples of raw pixel ``k`` with ``w_s(t) = exp(-|t - l_s| / dt)`` within +``max(3 dt, P)`` lines, and registration resamples by a rigid shift with +bilinear coefficients weighted by the raw pixels' summed weights, so that +``x_t(p) = sum_s a_ts x_s`` with ``a_ts = c_t(ab) w_s(t) / D_t(p)`` and +``D_t(p) = 1 / varFacDS``. With the samples of the pixel's mean ``mu``, +independent but for consecutive pairs, + +.. code-block:: text + + Cov(x_t, x_u) = mu (g2 A2(t, u) + 2 c2 QA2(t, u)) + A2(t, u) = sum_s a_ts a_us, QA2(t, u) = sum over pairs (s, n) of + (a_ts a_un + a_tn a_us) / 2 + kappa3(x_t) = mu (g3 A3(t, t, t) + 3 c3a QA3a(t) + 3 c3b QA3b(t)) + A3(t, t, u) = sum_s a_ts^2 a_us, QA3a = sum a_ts^2 a_tn, + QA3b = sum a_ts a_tn^2 + +Frames ``t`` and ``t + l`` share samples for ``l <= n_lags`` (6 at 80 Hz +for rasters of up to 402 lines per cycle). These sums are computed exactly, +frame by frame, from the raster's layout, the frame times and each frame's +motion, assuming every sample in reach is valid; they are rescaled by the +actual ``D_t(p)`` from ``varFacDS`` (where samples were invalid the +remaining ones are taken as proportional). The pair sums are exact for a +frame with itself; for two different frames that share samples they are +taken as the samples' own sums times the pixel's ratio ``r = sum_t QA2(t, t) +/ sum_t A2(t, t)`` (a pair lies on one line, so its kernel overlap between +frames is that of the samples), and the fast third cumulant's pair part is +its own-frame part's share of ``R0`` applied to the whole (within 0.5% at +SLAP2's pair correlations in tests). Each second moment's expectation is +``mu (g2 m_q + 2 c2 m_qa)``, where ``m_q`` comes from the ``A2`` and +``m_qa`` from the ``QA2`` sums in the same way; each follows from its +estimator: + +``var_q`` + ``S0 / n - (S0 + 2 S1) / n^2`` with ``S0 = sum_t A2(t, t)`` and ``S1`` + the sum of ``A2`` over pairs of valid frames ``t < u`` (the second term + is the variance of the mean). +``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`` the covariance of + adjacent blocks' means (from frames that share samples across the block + boundary). +``fast_q`` + the mean over centres of ``A2(t, t) - 2 L_t / n_t + P_t / n_t^2``, + where ``L_t`` sums ``A2(t, u)`` over the window and ``P_t`` over pairs + of window frames (exact). +``fast_q3`` + the mean over centres of ``R0 - 3 K_t / n_t + 3 L_t^2 / n_t^2 - + sum_u L_u^2 / n_t^3`` with ``R0 = A3(t, t, t)`` and ``K_t = sum_u + A3(t, t, u)``; the last two terms (products of three coefficients of + which two belong to other frames, about 0.5% of the total) are + approximated, within 0.25% of the exact third cumulant on synthetic + layouts. ``fast_q3a`` and ``fast_q3b`` are the means of the same times + ``QA3a / R0`` and ``QA3b / R0``; ``fast_m3_ph = mu (g3 fast_q3 + 3 c3a + fast_q3a + 3 c3b fast_q3b)``. +``sigma8_ph`` + ``sqrt(mu (g2 v8 + 2 c2 v8a))`` with ``v8`` and ``v8a`` the means over + valid 8-frame bins of the photon variance of the bin's mean per unit of + the gains (its own samples, and its consecutive-sample pairs). +``2 x 2 bins (shared modes)`` + A 2 x 2 bin's photon variance is ``sum over its pixels of mu v8 (g2 + spatial_factor + 2 c2 pair_bin_factor) / 16``. ``spatial_factor`` (an + attribute) is the trial's mean of ``(1 + rho_r)(1 + rho_c)``, ``rho = + f (1 - f) / ((1 - f)^2 + f^2)`` for the frame's fractional shifts ``f``, + by which bilinear interpolation's shared raw pixels raise the variance + of a 2 x 2 sum; ``pair_bin_factor`` (an attribute) is the trial's mean + of ``sum_d pi_d S_d / (4 Q_r Q_c)``, the consecutive-sample pairs inside + the sum (between its pixels as well as within each): ``pi_d`` is the + share of samples whose next sample is in the neighbouring direction + ``d``, ``Q = (1 - f)^2 + f^2`` per axis, and ``S_d`` the product over + the axes of ``(1 - f)^2 + 1 + f^2`` where ``d`` does not step and 1 + where it does (equal raw pixels assumed for both). +``zero_ph`` + a frame is exactly 0 when all of its ``N`` contributing samples are; + with ``M`` of them in consecutive pairs that has probability ``exp(-nu + (N - phi M))`` (``phi``: the trial's ``zero_shared``). Its sum over the + pixel's valid frames is accumulated at 33 rates from 1e-4 to 2 per + sample and interpolated at the pixel's rate ``nu``. + +For each moment ``m`` the file holds ``m``, ``m_q`` and ``m_qa`` (for the +fast third moment ``fast_q3``, ``fast_q3a``, ``fast_q3b``: the expectation's +parts per unit of the gains, properties of frame formation and +registration only), ``m_ph`` and the normalised map: + +* ``var_rel = var / var_ph - 1``, ``slow_rel``, ``fast_rel`` likewise + (``sqrt(1 + rel)`` is the SD relative to photon noise); +* ``fast_skew_rel = (fast_m3 - fast_m3_ph) / fast_var_ph^1.5``: the third + moment beyond photon noise, in units of the photon-noise SD; +* ``zero_excess = zero_share - zero_ph``. + +Under photon noise all read 0. A ratio estimated from few blocks is +unbiased, but its median is below 0 (as for a chi-square: about -0.02 for +34 blocks); likewise the median of ``fast_skew_rel`` at pixels with well +under one photon per frame is far below its mean (the third moment of a few +photons is heavy-tailed). + +**What the maps respond to.** Slow drift raises ``slow_rel`` and leaves the +fast maps at 0. Sparse events (positive transients) raise ``fast_skew_rel`` +and ``fast_rel`` at their sources, but also ``slow_rel``: the number and +size of events in a 64-frame block vary, and a block mean's photon noise is +small, so at bright sources ``slow_rel`` rises as much as ``fast_rel`` or +more. ``slow_rel`` therefore measures slow changes of the pixel's value, of +which baseline changes are one source; the fast skewness tells activity +apart. + +**Approximations.** The expectation is that of a pixel whose brightness is +its mean and the same for the 2 x 2 raw pixels it interpolates: at sharp +edges, under sub-pixel motion, it is off by the difference between the +coefficients' and their squares' weighting (and real motion at edges adds +true slow and fast variance). With online compensation, a sample that two +frames share is placed by the earlier frame's displacement (they differ only +around an x/y switch). Rasters whose frames share samples over more than 7 +frames (cycles longer than about 530 lines at 80 Hz) are not supported. +The fast moments are central (the mean of ``z`` over the centres is taken +out, which matters at edge pixels whose valid windows are uneven), but +their expectations are the means of the centres' own ``z`` moments: they +leave out the variance of that mean, so under photon noise ``fast_rel`` +reads about -0.3% (independent frames) to -0.8% (frames sharing samples) +at the minimum of 64 centres, and about -1e-6 for a pixel with data in +the whole of a 28 s trial. Frames are formed from each channel's own +valid samples, but registration's freshness and ``varFacDS`` follow the +first channel's: where another channel's invalid samples differ, its +expectations assume the first channel's samples. Such samples are counted +(attribute ``validity_differs``, per channel, with a warning); SLAP2 +recordings mark invalid samples in all channels alike (none differ on the +trials checked). + +Session maps +------------ + +Registered trials do not share a frame (each is registered to a template of +its own frames), so the files hold per-trial maps. +:func:`~giant_python.registration.stats.session.combine_trials` combines +them given SILo's across-trial alignment (``ExtractionPlan.warp``, or rigid +shifts): each trial's maps are resampled into the consensus frame and +averaged, each weighted by the frames behind it (``n_valid``, ``n_blocks``, +``n_fast``); the normalised maps are formed from the averaged moments and +expectations. The shared modes are not combined. + +File layout +----------- + +Arrays are in GIAnT's MATLAB layout, as the movie: 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``; +``read_stats`` returns Python's orientation. Maps are float32, NaN where a +pixel never had data or has too few frames (64 valid frames or fast +centres, 8 valid blocks):: + + _REGSTATS-80Hz.h5 + ├── (attributes) stats_version, layout, created, source (registration | + │ reg-stats), movie, movie_size, alignment, alignment_digest (SHA-256 + │ of DSframes, motionDSr, motionDSc), align_hz, n_frames, n_lags, + │ n_index, spatial_factor, pair_bin_factor, zero_shared, + │ validity_differs, device + ├── maps/ + │ ├── n_valid, mean, var, var_q, var_qa, var_ph, var_rel + │ ├── zero_share, zero_ph, zero_excess + │ ├── n_blocks, slow_var, slow_q, slow_qa, slow_var_ph, slow_rel + │ ├── n_fast, fast_var, fast_q, fast_qa, fast_var_ph, fast_rel, + │ │ fast_m3, fast_q3, fast_q3a, fast_q3b, fast_m3_ph, fast_skew_rel + │ └── gain_g2, gain_g3, gain_c2, gain_c3a, gain_c3b, sigma8_ph + ├── svd/ + │ ├── time_courses (channels, 3, time bins) + │ ├── singular_values, var_share, skew, lag1 (channels, 3) + │ ├── total_var, n_space (channels,), n_bins + │ └── weight, weight_ph (channels, 3, cols, rows) + └── gain/ + ├── mu, g2, g3, nu_per_mu, n_slots (channels, groups) + └── mu_pair, c2, c3a, c3b, zero_shared, n_pairs (channels, groups) + +Cost +---- + +The statistics are formed while registration writes the movie, on the +registration's device: on a GPU on a thread and a CUDA stream of their own +(their setup, the gain curves and the frame geometry, while the template +is built), on the CPU in line (a second thread there competes for the same +cores and was slower). On a 780125 trial (2 channels, 2,254 frames of 320 x +845 pixels) on a quiet machine (RTX 4060 Ti; 8 CPU threads of a +Threadripper PRO 5955WX), registration took: + +.. list-table:: + :header-rows: 1 + + * - device + - without statistics + - with + - memory added + * - GPU + - 20.9 s + - 27.8 s (+33%) + - 2.3 GB GPU, 0.5 GB RAM + * - CPU + - 71.6 s + - 166.3 s (+132%) + - 3.0 GB RAM + +The time is the statistics' own arithmetic: on the GPU their kernels (about +2.4 ms per frame, mostly the per-frame photon-noise geometry and the +64-frame blocks) and the Python work of launching them, on the CPU the same +arithmetic, memory-bound, at about 40 ms per frame. Registration on the CPU +can leave the statistics out (``--no-stats``) and ``giant reg-stats +--device cuda`` add them later (27 s for this trial, reading the raw +recording and the movie again). + +Memory grows with the trial in two places the statistics add: the shared +modes keep every pixel's 8-frame bin means until the trial ends (frames / +8 x pixels x channels x 4 bytes: 0.1 GB for this 28 s trial, about 2.3 GB +for a 10-minute one; their decomposition uses the smaller of the time-bin +and spatial-bin Gram matrices), and the frame geometry keeps its kernel +tables for every frame ((4 + 3 x lags) x frames x lines per cycle x 4 +bytes per displacement group: 25 MB here, about 0.5 GB for 10 minutes). +The trial's raw samples, which the gain curves read, are registration's +own (its frame former holds them in any case). The rest is held for a few +blocks of frames at a time. diff --git a/docs/source/traces.rst b/docs/source/traces.rst index f8ac0da3..c7bb491e 100644 --- a/docs/source/traces.rst +++ b/docs/source/traces.rst @@ -1,118 +1,118 @@ -Trace estimation -================ - -Production BandSILo extraction computes and saves least-squares -``sources/temporal/dF_ls``, convolution-constrained -``sources/temporal/dF_denoised``, and fitted ``sources/temporal/events``. -Each array has shape ``(sources, channels, total frames)``. Source activity -extraction uses **channel zero**; other channels and missing observations are -NaN. Both trace estimates are mandatory production outputs, not selectable -trace modes. Low-level loaded-array functions also support weighted averages -for diagnostics. See :doc:`file_formats` for the saved layout. - -Trial-wise objective --------------------- - -The trace-only solver holds spatial profiles fixed and minimizes - -.. math:: - - \min_{s \geq 0}\; \frac{1}{2} - \left\|(d-b)-H_{\mathrm{motion}} A K s\right\|_2^2 - + \beta \sum_j \sum_{t=1}^{T-1} s_{j,t}. - -Here ``d`` is the observed data, ``b`` is the background, ``A`` contains the -fixed source profiles, ``H_motion`` is the motion-dependent observation -operator, and ``K`` applies a causal unit-peak exponential. For each source, -:math:`s_{j,0}` is an unpenalized nonnegative initial state; the remaining entries -are nonnegative event amplitudes. The solver operates chronologically over -each complete trial, including motion changes and missing frames. No state or -event inference crosses trial boundaries. Localization, NMF, and profile -fitting are separate from this trace-only optimization. - -Returned fluorescence changes preserve the QR complete-frame validity mask. -The standard least-squares trace and its background retain baseline -re-estimation for ``dF_ls`` and ``F0``; ``F0`` comes from QR, not the transient -model. ``dF_denoised`` is the fitted convolution trace itself, with no second -baseline subtraction. ``events`` excludes the initial state at each trial's -first frame and stores NaN for discarded frames. - -Controls and convergence ------------------------- - -``BandSiloParams.decay_tau_s`` controls both the trace kernel and localization -filtering. Its default is 0.15 seconds, and it is saved as ``decayTau_s``. -The GUI's Decay Tau field and CLI ``--decay-tau-s`` flag change this shared -setting; there is no separate trace decay parameter. - -.. list-table:: Trace-only controls - :header-rows: 1 - :widths: 28 12 60 - - * - Parameter - - Default - - Meaning - * - ``trace_beta_fraction`` - - ``0.01`` - - Fraction of each trial's positive adjoint scale; zero disables L1. - * - ``trace_max_iter`` - - ``500`` - - Maximum L-BFGS-B iterations per optimization stage. - * - ``trace_tolerance`` - - ``1e-7`` - - Objective/gradient tolerance. - * - ``trace_debias`` - - ``False`` - - Refit selected events without L1 shrinkage. - * - ``trace_event_threshold`` - - ``1e-6`` - - Absolute event-amplitude threshold for debias support. - -These controls are recorded in summary parameters and are available as -hyphenated CLI flags (for example, ``--trace-beta-fraction``). -A nonconverged production fit raises an error rather than saving an unfinished -estimate. Increase the iteration limit or inspect a low-level fit when this -occurs. Per-trial optimizer diagnostics and latent in-gap predictions are not -saved in the summary. - -Motion selection and reproducibility ------------------------------------- - -``BandSiloParams(z_tol=1.5)`` sets the low-resolution motion-bin selection -tolerance in microns. Bins must lie within this absolute distance of the -median frame z and satisfy the minimum frame count. The value must be positive -and finite. The CLI and staging example expose ``--z-tol``; the parameter GUI -labels it **Z Tolerance (µm)**. - -``BandSiloParams(random_seed=0)`` seeds the random motion-bin order used by -source localization (NMF and Adam). It must be a nonnegative integer. Each -path and outer iteration uses its own generator derived from this seed, -independently of the global torch RNG. The seed is saved in summary parameters -and exposed as ``--random-seed``. It fixes random draws, not floating-point -results across hardware, thread counts, or package versions. - -Loaded-array API ----------------- - -For loaded arrays, pass ``transient_options=TransientOptions(...)`` and -``analyze_hz=...`` to -``giant_python.extraction.band.traces.compute_high_res_traces``. -``TransientOptions`` and ``fit_transient_traces`` are defined in -``giant_python.extraction.band.transient``. The latter accepts an absolute -``beta`` or an explicit causal kernel and exposes events, the initial state, -in-gap model predictions, actual beta, and convergence diagnostics. -Retain the complete chronological output grid, including gaps, when supplying -arrays. Low-level nonconvergence warns and returns diagnostics; callers must -check ``metadata['converged']`` before saving a result. -``TrialTraceResult`` retains its original eight fields in order and appends -``d_f_denoised`` and ``events``. - -Scientific interpretation -------------------------- - -This is an output-grid estimator: overlapping acquisition-line averaging is -not modeled exactly. In-gap predictions are not observations, and glutamate -events are not automatically neuronal spikes. A smoother trace alone does not -establish improved SNR. Use a fresh output location when comparing estimates -or settings; summary updates are not an atomic replacement or a resume +Trace estimation +================ + +Production BandSILo extraction computes and saves least-squares +``sources/temporal/dF_ls``, convolution-constrained +``sources/temporal/dF_denoised``, and fitted ``sources/temporal/events``. +Each array has shape ``(sources, channels, total frames)``. Source activity +extraction uses **channel zero**; other channels and missing observations are +NaN. Both trace estimates are mandatory production outputs, not selectable +trace modes. Low-level loaded-array functions also support weighted averages +for diagnostics. See :doc:`file_formats` for the saved layout. + +Trial-wise objective +-------------------- + +The trace-only solver holds spatial profiles fixed and minimizes + +.. math:: + + \min_{s \geq 0}\; \frac{1}{2} + \left\|(d-b)-H_{\mathrm{motion}} A K s\right\|_2^2 + + \beta \sum_j \sum_{t=1}^{T-1} s_{j,t}. + +Here ``d`` is the observed data, ``b`` is the background, ``A`` contains the +fixed source profiles, ``H_motion`` is the motion-dependent observation +operator, and ``K`` applies a causal unit-peak exponential. For each source, +:math:`s_{j,0}` is an unpenalized nonnegative initial state; the remaining entries +are nonnegative event amplitudes. The solver operates chronologically over +each complete trial, including motion changes and missing frames. No state or +event inference crosses trial boundaries. Localization, NMF, and profile +fitting are separate from this trace-only optimization. + +Returned fluorescence changes preserve the QR complete-frame validity mask. +The standard least-squares trace and its background retain baseline +re-estimation for ``dF_ls`` and ``F0``; ``F0`` comes from QR, not the transient +model. ``dF_denoised`` is the fitted convolution trace itself, with no second +baseline subtraction. ``events`` excludes the initial state at each trial's +first frame and stores NaN for discarded frames. + +Controls and convergence +------------------------ + +``BandSiloParams.decay_tau_s`` controls both the trace kernel and localization +filtering. Its default is 0.15 seconds, and it is saved as ``decayTau_s``. +The GUI's Decay Tau field and CLI ``--decay-tau-s`` flag change this shared +setting; there is no separate trace decay parameter. + +.. list-table:: Trace-only controls + :header-rows: 1 + :widths: 28 12 60 + + * - Parameter + - Default + - Meaning + * - ``trace_beta_fraction`` + - ``0.01`` + - Fraction of each trial's positive adjoint scale; zero disables L1. + * - ``trace_max_iter`` + - ``500`` + - Maximum L-BFGS-B iterations per optimization stage. + * - ``trace_tolerance`` + - ``1e-7`` + - Objective/gradient tolerance. + * - ``trace_debias`` + - ``False`` + - Refit selected events without L1 shrinkage. + * - ``trace_event_threshold`` + - ``1e-6`` + - Absolute event-amplitude threshold for debias support. + +These controls are recorded in summary parameters and are available as +hyphenated CLI flags (for example, ``--trace-beta-fraction``). +A nonconverged production fit raises an error rather than saving an unfinished +estimate. Increase the iteration limit or inspect a low-level fit when this +occurs. Per-trial optimizer diagnostics and latent in-gap predictions are not +saved in the summary. + +Motion selection and reproducibility +------------------------------------ + +``BandSiloParams(z_tol=1.5)`` sets the low-resolution motion-bin selection +tolerance in microns. Bins must lie within this absolute distance of the +median frame z and satisfy the minimum frame count. The value must be positive +and finite. The CLI and staging example expose ``--z-tol``; the parameter GUI +labels it **Z Tolerance (µm)**. + +``BandSiloParams(random_seed=0)`` seeds the random motion-bin order used by +source localization (NMF and Adam). It must be a nonnegative integer. Each +path and outer iteration uses its own generator derived from this seed, +independently of the global torch RNG. The seed is saved in summary parameters +and exposed as ``--random-seed``. It fixes random draws, not floating-point +results across hardware, thread counts, or package versions. + +Loaded-array API +---------------- + +For loaded arrays, pass ``transient_options=TransientOptions(...)`` and +``analyze_hz=...`` to +``giant_python.extraction.band.traces.compute_high_res_traces``. +``TransientOptions`` and ``fit_transient_traces`` are defined in +``giant_python.extraction.band.transient``. The latter accepts an absolute +``beta`` or an explicit causal kernel and exposes events, the initial state, +in-gap model predictions, actual beta, and convergence diagnostics. +Retain the complete chronological output grid, including gaps, when supplying +arrays. Low-level nonconvergence warns and returns diagnostics; callers must +check ``metadata['converged']`` before saving a result. +``TrialTraceResult`` retains its original eight fields in order and appends +``d_f_denoised`` and ``events``. + +Scientific interpretation +------------------------- + +This is an output-grid estimator: overlapping acquisition-line averaging is +not modeled exactly. In-gap predictions are not observations, and glutamate +events are not automatically neuronal spikes. A smoother trace alone does not +establish improved SNR. Use a fresh output location when comparing estimates +or settings; summary updates are not an atomic replacement or a resume mechanism. \ No newline at end of file diff --git a/examples/extract_band.py b/examples/extract_band.py index 6e38c75f..1f42fff2 100644 --- a/examples/extract_band.py +++ b/examples/extract_band.py @@ -1,392 +1,392 @@ -"""Extract registered band data, optionally staging inputs in a fresh run. - -Use --help for arguments. No files, environment variables, GUI toolkits, or -GIAnT modules are touched on import. This example copies existing motion -correction; it does not run the unimplemented Python registration stage. - -The source table must use relative recording/alignment filenames. Include -raw acquisition sidecars and reference TIFFs in --data-dir. A copied table -retains its original on-disk metadata: effective directory overrides are -made on the loaded model, not saved with the unsupported TrialTable writer. -""" - -from __future__ import annotations - -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 - -if TYPE_CHECKING: - from giant_python import ( - AnnotationOptions, - BandSiloParams, - ExecutionOptions, - TrialTable, - ) - - -@dataclass(frozen=True) -class InputPaths: - """Resolved input roots and a fresh destination, before any staging.""" - - table: Path - data: Path - motion: Path - results: Path - annotations: Path | None - joblib_temp: Path | None - - -@dataclass(frozen=True) -class PreparedRun: - """Validated paths, loaded metadata and independent run settings.""" - - paths: InputPaths - table: TrialTable - params: BandSiloParams - execution: ExecutionOptions - annotations: AnnotationOptions - - -def build_parser() -> argparse.ArgumentParser: - """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( - "--data-dir", - type=Path, - required=True, - help="Raw recordings, sidecars, and reference TIFF directory", - ) - parser.add_argument( - "--motion-correction", - type=Path, - required=True, - help="Existing alignment and band registration lookup directory", - ) - parser.add_argument( - "--results-dir", - type=Path, - required=True, - help="New directory; an existing file, directory, or link is refused", - ) - parser.add_argument( - "--stage-data", - choices=("none", "copy", "symlink"), - default="none", - help="Keep raw inputs in place (default), copy, or link the full tree", - ) - parser.add_argument( - "--stage-motion", - choices=("copy", "symlink"), - default="copy", - help="Copy existing registration assets (default), or link them", - ) - parser.add_argument( - "--annotations-dir", - type=Path, - help="Optional existing annotation directory to copy into the run", - ) - parser.add_argument( - "--joblib-temp", - type=Path, - help="Existing temporary directory; overrides JOBLIB_TEMP_FOLDER", - ) - parser.add_argument("--max-workers", type=int, default=6) - parser.add_argument("--max-trials", type=int) - parser.add_argument("--verbose", action="store_true") - parser.add_argument("--use-rois", action="store_true") - parser.add_argument("--interactive", action="store_true") - parser.add_argument("--analyze-hz", type=float, default=100.0) - parser.add_argument("--decay-tau-s", type=float, default=0.15) - parser.add_argument("--baseline-window-s", type=float, default=4.0) - parser.add_argument("--denoise-window-s", type=float, default=1.0) - parser.add_argument("--vif", type=float, default=1.38) - parser.add_argument("--d-xy", type=int, default=5) - parser.add_argument("--peak-buffer", type=int, default=3) - parser.add_argument("--psf-dilation", type=int, default=17) - parser.add_argument( - "--z-tol", - type=float, - default=1.5, - help="Z tolerance for motion-bin selection (microns)", - ) - return parser - - -def require_directory(path: Path) -> Path: - """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) - return resolved - - -def validate_relative_names(values: object, field: str) -> None: - """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: - if entry is None or str(entry) == "": - continue - name = str(entry) - posix = PurePosixPath(name) - windows = PureWindowsPath(name) - 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; " - "this example will not guess a replacement basename." - ) - - -def stage_directory(source: Path, destination: Path, mode: str) -> None: - """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": - shutil.copytree(source, destination, symlinks=True) - elif mode == "symlink": - destination.symlink_to(source, target_is_directory=True) - else: - raise ValueError(f"Unknown staging mode: {mode}") - - -def validate_annotation_arguments( - args: argparse.Namespace, parser: argparse.ArgumentParser -) -> None: - """Reject inconsistent GUI policy before touching inputs.""" - if args.interactive and not args.use_rois: - parser.error("--interactive requires --use-rois") - if args.use_rois and not args.interactive and not args.annotations_dir: - parser.error("Headless --use-rois requires --annotations-dir") - - -def require_file(path: Path) -> Path: - """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) - return resolved - - -def validate_destination(requested: Path, sources: tuple[Path, ...]) -> Path: - """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() - for source in sources: - if results.is_relative_to(source): - raise ValueError("Results must be outside all input directories") - return results - - -def validate_paths(args: argparse.Namespace) -> InputPaths: - """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) - require_file(motion / "bandRegLookupTable.h5") - annotations = None - sources = (data, motion) - if args.annotations_dir is not None: - annotations = require_directory(args.annotations_dir) - 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 - 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. - - 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, - BandSiloParams, - ExecutionOptions, - TrialTable, - ) - - table = TrialTable.from_h5(paths.table) - if table.slap2_info is None or not table.motion_correction: - raise ValueError("A pre-registered SLAP2 band trial table is required") - 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") - params = BandSiloParams( - analyze_hz=args.analyze_hz, - decay_tau_s=args.decay_tau_s, - baseline_window_s=args.baseline_window_s, - denoise_window_s=args.denoise_window_s, - vif=args.vif, - d_xy=args.d_xy, - peak_buffer=args.peak_buffer, - psf_dilation=args.psf_dilation, - z_tol=args.z_tol, - ) - execution = ExecutionOptions( - max_workers=args.max_workers, - max_trials=args.max_trials, - verbose=args.verbose, - ) - annotations = AnnotationOptions( - enabled=args.use_rois, - interactive=args.interactive, - ) - return PreparedRun(paths, table, params, execution, annotations) - - -@contextmanager -def joblib_environment( - directory: Path | None, -) -> Generator[None, None, None]: - """Temporarily override worker scratch space only for a validated run.""" - if directory is None: - yield - return - previous = os.environ.get("JOBLIB_TEMP_FOLDER") - os.environ["JOBLIB_TEMP_FOLDER"] = str(directory) - try: - yield - finally: - if previous is None: - os.environ.pop("JOBLIB_TEMP_FOLDER", None) - else: - os.environ["JOBLIB_TEMP_FOLDER"] = previous - - -def stage_and_extract(run: PreparedRun, args: argparse.Namespace) -> None: - """Stage validated inputs and pass the relocated model to extraction.""" - from giant_python import extract_band_sources - - paths = run.paths - results_dir = paths.results - data_dir = paths.data - - # No overwrite mode and no automatic cleanup: a failed run leaves its - # partial directory for inspection, never removes an existing tree/link. - 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) - if args.stage_data != "none": - staged_data = results_dir / "input" - stage_directory(data_dir, staged_data, args.stage_data) - data_dir = staged_data - if paths.annotations is not None: - stage_directory(paths.annotations, results_dir / "annotations", "copy") - - # Copying the HDF5 file does not rewrite the paths stored inside it. - # Pass this overridden model, not staged_table, to make staging effective. - table = replace( - run.table, - datadr=data_dir, - savedr=results_dir, - source_path=staged_table, - ) - summary = extract_band_sources( - table, run.params, execution=run.execution, annotations=run.annotations - ) - print(f"Extracted {len(summary.paths)} imaging path(s)") - print(results_dir / "source_extraction" / "experiment_summary.h5") - - -def main(argv: list[str] | None = None) -> int: - """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) - run = prepare_run(args) - with joblib_environment(run.paths.joblib_temp): - stage_and_extract(run, args) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) +"""Extract registered band data, optionally staging inputs in a fresh run. + +Use --help for arguments. No files, environment variables, GUI toolkits, or +GIAnT modules are touched on import. This example copies existing motion +correction; it does not run the unimplemented Python registration stage. + +The source table must use relative recording/alignment filenames. Include +raw acquisition sidecars and reference TIFFs in --data-dir. A copied table +retains its original on-disk metadata: effective directory overrides are +made on the loaded model, not saved with the unsupported TrialTable writer. +""" + +from __future__ import annotations + +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 + +if TYPE_CHECKING: + from giant_python import ( + AnnotationOptions, + BandSiloParams, + ExecutionOptions, + TrialTable, + ) + + +@dataclass(frozen=True) +class InputPaths: + """Resolved input roots and a fresh destination, before any staging.""" + + table: Path + data: Path + motion: Path + results: Path + annotations: Path | None + joblib_temp: Path | None + + +@dataclass(frozen=True) +class PreparedRun: + """Validated paths, loaded metadata and independent run settings.""" + + paths: InputPaths + table: TrialTable + params: BandSiloParams + execution: ExecutionOptions + annotations: AnnotationOptions + + +def build_parser() -> argparse.ArgumentParser: + """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( + "--data-dir", + type=Path, + required=True, + help="Raw recordings, sidecars, and reference TIFF directory", + ) + parser.add_argument( + "--motion-correction", + type=Path, + required=True, + help="Existing alignment and band registration lookup directory", + ) + parser.add_argument( + "--results-dir", + type=Path, + required=True, + help="New directory; an existing file, directory, or link is refused", + ) + parser.add_argument( + "--stage-data", + choices=("none", "copy", "symlink"), + default="none", + help="Keep raw inputs in place (default), copy, or link the full tree", + ) + parser.add_argument( + "--stage-motion", + choices=("copy", "symlink"), + default="copy", + help="Copy existing registration assets (default), or link them", + ) + parser.add_argument( + "--annotations-dir", + type=Path, + help="Optional existing annotation directory to copy into the run", + ) + parser.add_argument( + "--joblib-temp", + type=Path, + help="Existing temporary directory; overrides JOBLIB_TEMP_FOLDER", + ) + parser.add_argument("--max-workers", type=int, default=6) + parser.add_argument("--max-trials", type=int) + parser.add_argument("--verbose", action="store_true") + parser.add_argument("--use-rois", action="store_true") + parser.add_argument("--interactive", action="store_true") + parser.add_argument("--analyze-hz", type=float, default=100.0) + parser.add_argument("--decay-tau-s", type=float, default=0.15) + parser.add_argument("--baseline-window-s", type=float, default=4.0) + parser.add_argument("--denoise-window-s", type=float, default=1.0) + parser.add_argument("--vif", type=float, default=1.38) + parser.add_argument("--d-xy", type=int, default=5) + parser.add_argument("--peak-buffer", type=int, default=3) + parser.add_argument("--psf-dilation", type=int, default=17) + parser.add_argument( + "--z-tol", + type=float, + default=1.5, + help="Z tolerance for motion-bin selection (microns)", + ) + return parser + + +def require_directory(path: Path) -> Path: + """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) + return resolved + + +def validate_relative_names(values: object, field: str) -> None: + """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: + if entry is None or str(entry) == "": + continue + name = str(entry) + posix = PurePosixPath(name) + windows = PureWindowsPath(name) + 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; " + "this example will not guess a replacement basename." + ) + + +def stage_directory(source: Path, destination: Path, mode: str) -> None: + """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": + shutil.copytree(source, destination, symlinks=True) + elif mode == "symlink": + destination.symlink_to(source, target_is_directory=True) + else: + raise ValueError(f"Unknown staging mode: {mode}") + + +def validate_annotation_arguments( + args: argparse.Namespace, parser: argparse.ArgumentParser +) -> None: + """Reject inconsistent GUI policy before touching inputs.""" + if args.interactive and not args.use_rois: + parser.error("--interactive requires --use-rois") + if args.use_rois and not args.interactive and not args.annotations_dir: + parser.error("Headless --use-rois requires --annotations-dir") + + +def require_file(path: Path) -> Path: + """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) + return resolved + + +def validate_destination(requested: Path, sources: tuple[Path, ...]) -> Path: + """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() + for source in sources: + if results.is_relative_to(source): + raise ValueError("Results must be outside all input directories") + return results + + +def validate_paths(args: argparse.Namespace) -> InputPaths: + """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) + require_file(motion / "bandRegLookupTable.h5") + annotations = None + sources = (data, motion) + if args.annotations_dir is not None: + annotations = require_directory(args.annotations_dir) + 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 + 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. + + 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, + BandSiloParams, + ExecutionOptions, + TrialTable, + ) + + table = TrialTable.from_h5(paths.table) + if table.slap2_info is None or not table.motion_correction: + raise ValueError("A pre-registered SLAP2 band trial table is required") + 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") + params = BandSiloParams( + analyze_hz=args.analyze_hz, + decay_tau_s=args.decay_tau_s, + baseline_window_s=args.baseline_window_s, + denoise_window_s=args.denoise_window_s, + vif=args.vif, + d_xy=args.d_xy, + peak_buffer=args.peak_buffer, + psf_dilation=args.psf_dilation, + z_tol=args.z_tol, + ) + execution = ExecutionOptions( + max_workers=args.max_workers, + max_trials=args.max_trials, + verbose=args.verbose, + ) + annotations = AnnotationOptions( + enabled=args.use_rois, + interactive=args.interactive, + ) + return PreparedRun(paths, table, params, execution, annotations) + + +@contextmanager +def joblib_environment( + directory: Path | None, +) -> Generator[None, None, None]: + """Temporarily override worker scratch space only for a validated run.""" + if directory is None: + yield + return + previous = os.environ.get("JOBLIB_TEMP_FOLDER") + os.environ["JOBLIB_TEMP_FOLDER"] = str(directory) + try: + yield + finally: + if previous is None: + os.environ.pop("JOBLIB_TEMP_FOLDER", None) + else: + os.environ["JOBLIB_TEMP_FOLDER"] = previous + + +def stage_and_extract(run: PreparedRun, args: argparse.Namespace) -> None: + """Stage validated inputs and pass the relocated model to extraction.""" + from giant_python import extract_band_sources + + paths = run.paths + results_dir = paths.results + data_dir = paths.data + + # No overwrite mode and no automatic cleanup: a failed run leaves its + # partial directory for inspection, never removes an existing tree/link. + 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) + if args.stage_data != "none": + staged_data = results_dir / "input" + stage_directory(data_dir, staged_data, args.stage_data) + data_dir = staged_data + if paths.annotations is not None: + stage_directory(paths.annotations, results_dir / "annotations", "copy") + + # Copying the HDF5 file does not rewrite the paths stored inside it. + # Pass this overridden model, not staged_table, to make staging effective. + table = replace( + run.table, + datadr=data_dir, + savedr=results_dir, + source_path=staged_table, + ) + summary = extract_band_sources( + table, run.params, execution=run.execution, annotations=run.annotations + ) + print(f"Extracted {len(summary.paths)} imaging path(s)") + print(results_dir / "source_extraction" / "experiment_summary.h5") + + +def main(argv: list[str] | None = None) -> int: + """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) + run = prepare_run(args) + with joblib_environment(run.paths.joblib_temp): + stage_and_extract(run, args) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/giant_python/export/__init__.py b/src/giant_python/export/__init__.py index 9a98a0be..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. -""" +"""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. +""" diff --git a/src/giant_python/export/f0_events.py b/src/giant_python/export/f0_events.py index 0463e207..0ba2215b 100644 --- a/src/giant_python/export/f0_events.py +++ b/src/giant_python/export/f0_events.py @@ -1,282 +1,282 @@ -"""Event statistics of a SILo run, for simulations matched to a recording. - -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); -* synchrony: for each event, whether another source has an onset within - 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. - -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 -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. -""" - -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) -> 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) - d = np.diff(np.concatenate([[0], on.astype(np.int8), [0]])) - return np.flatnonzero(d == 1), np.flatnonzero(d == -1) - - -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])) - raw.append(float(den[k])) - if np.isfinite(f0[k]) and f0[k] > 0: - dff.append(float(den[k] / f0[k])) - return np.asarray(raw), np.asarray(dff) - - -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). - - 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 - out = {f"q{int(100 * q)}": float(np.quantile(x, q)) for q in QUANTILES} - out["mean"] = float(x.mean()) - return out - - -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 - frames (local to the trial) and its observed frames (bool, kept frames - 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: - n = len(starts) - if n < 2: - continue - obs = np.asarray(observed, bool) # (sources, frames) - T = obs.shape[1] - cover = np.zeros((n, T), bool) - for s, st in enumerate(starts): - for dd in range(-window, window + 1): - 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)]) - logq = np.log1p(-np.minimum(pr, 1 - 1e-12)) # log(1 - p) per source - for s, st in enumerate(starts): - if st.size == 0: - continue - seen = obs[:, st] # (sources, events): partners observed there - seen[s] = False - others = (cover[:, st] & seen).sum(0) - hits += int(np.sum(others > 0)) - tot += st.size - expect += float(np.sum(1.0 - np.exp(logq @ seen))) - if tot == 0: - return {"observed": None, "expected": None, "events": 0} - return { - "observed": hits / tot, - "expected": expect / tot, - "events": int(tot), - } - - -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. - - 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 = { - "path": d, - "analyzeHz": hz, - "tau_s": float(run.param("tau_s", np.nan)), - "tau2_s": float(run.param("tau2_s", np.nan)), - "thresholdSD": float(k), - "sources": [], - } - n = p.sources.n - if n == 0: - out["synchrony"] = synchrony([], sync_frames) - return out - tr = run.traces(d) - if "dF_denoised" not in tr: # nothing to count: say so - out["unavailable"] = "SILo wrote no dF_denoised traces" - out["synchrony"] = synchrony([], sync_frames) - return out - 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] - 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) - raw_all, dff_all = [[] for _ in range(n)], [[] for _ in range(n)] - per_trial = [] - for span in spans: - starts_t, expo_t = [], [] - for s in range(n): - x = den[span, s] - ok = keep[span] & np.isfinite(x) - expo_t.append(ok) - exposure[s] += ok.sum() - st = np.zeros(0, np.int64) - for j, kk in enumerate(ks): - thr = kk * sigma[s] if np.isfinite(sigma[s]) else np.inf - a, b = events(x, thr, ok) - counts[s, j] += a.size - if j == 0: - st = a - r, f = event_sizes(x, f0[span, s], a, b) - raw_all[s].append(r) - dff_all[s].append(f) - starts_t.append(st) - per_trial.append((starts_t, expo_t)) - 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(): - # 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: 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) - return out +"""Event statistics of a SILo run, for simulations matched to a recording. + +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); +* synchrony: for each event, whether another source has an onset within + 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. + +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 +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. +""" + +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) -> 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) + d = np.diff(np.concatenate([[0], on.astype(np.int8), [0]])) + return np.flatnonzero(d == 1), np.flatnonzero(d == -1) + + +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])) + raw.append(float(den[k])) + if np.isfinite(f0[k]) and f0[k] > 0: + dff.append(float(den[k] / f0[k])) + return np.asarray(raw), np.asarray(dff) + + +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). + + 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 + out = {f"q{int(100 * q)}": float(np.quantile(x, q)) for q in QUANTILES} + out["mean"] = float(x.mean()) + return out + + +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 + frames (local to the trial) and its observed frames (bool, kept frames + 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: + n = len(starts) + if n < 2: + continue + obs = np.asarray(observed, bool) # (sources, frames) + T = obs.shape[1] + cover = np.zeros((n, T), bool) + for s, st in enumerate(starts): + for dd in range(-window, window + 1): + 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)]) + logq = np.log1p(-np.minimum(pr, 1 - 1e-12)) # log(1 - p) per source + for s, st in enumerate(starts): + if st.size == 0: + continue + seen = obs[:, st] # (sources, events): partners observed there + seen[s] = False + others = (cover[:, st] & seen).sum(0) + hits += int(np.sum(others > 0)) + tot += st.size + expect += float(np.sum(1.0 - np.exp(logq @ seen))) + if tot == 0: + return {"observed": None, "expected": None, "events": 0} + return { + "observed": hits / tot, + "expected": expect / tot, + "events": int(tot), + } + + +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. + + 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 = { + "path": d, + "analyzeHz": hz, + "tau_s": float(run.param("tau_s", np.nan)), + "tau2_s": float(run.param("tau2_s", np.nan)), + "thresholdSD": float(k), + "sources": [], + } + n = p.sources.n + if n == 0: + out["synchrony"] = synchrony([], sync_frames) + return out + tr = run.traces(d) + if "dF_denoised" not in tr: # nothing to count: say so + out["unavailable"] = "SILo wrote no dF_denoised traces" + out["synchrony"] = synchrony([], sync_frames) + return out + 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] + 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) + raw_all, dff_all = [[] for _ in range(n)], [[] for _ in range(n)] + per_trial = [] + for span in spans: + starts_t, expo_t = [], [] + for s in range(n): + x = den[span, s] + ok = keep[span] & np.isfinite(x) + expo_t.append(ok) + exposure[s] += ok.sum() + st = np.zeros(0, np.int64) + for j, kk in enumerate(ks): + thr = kk * sigma[s] if np.isfinite(sigma[s]) else np.inf + a, b = events(x, thr, ok) + counts[s, j] += a.size + if j == 0: + st = a + r, f = event_sizes(x, f0[span, s], a, b) + raw_all[s].append(r) + dff_all[s].append(f) + starts_t.append(st) + per_trial.append((starts_t, expo_t)) + 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(): + # 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: 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) + return out diff --git a/src/giant_python/export/f0_injected.py b/src/giant_python/export/f0_injected.py index d9a91449..caf4e9b7 100644 --- a/src/giant_python/export/f0_injected.py +++ b/src/giant_python/export/f0_injected.py @@ -1,690 +1,690 @@ -"""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 -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: -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 channel; zero in other written channels); -* 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: - 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 - 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 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, - NO_KERNEL, - NO_QC, - ExportOptions, - TrialJob, - TrialSkipped, - _arrays, - _attr_value, - _check_channels, - _check_options, - _crop_box, - _frame_arrays, - _load, - _record, - _remove_unscheduled, - _write, - write_summary, -) - -if TYPE_CHECKING: - from ..simulation.injection import GaussianFootprint, InjectionSettings - -KIND = "gfp_injected" - - -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() - }) - - -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. - - 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 = [] - for prm in truth_path["footprint"]["params"]: - kind = prm.get("kind") - if kind == "gaussian": - sr, sc = (float(v) for v in prm["sigma_rc"]) - out.append( - inj.GaussianFootprint( - sigma_px=sr, - radius_sigmas=float(prm["radius_px"]) / max(sr, sc), - sigma_c_px=sc, - ) - ) - elif need_model: - raise ValueError( - f"footprint kind {kind!r} cannot be rebuilt from the truth: " - "export without --expected" - ) - else: - out.append(None) - return out - - -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: InjectionSettings, - copy_alignment: str | Path, - d: int, - t: int, - flat: np.ndarray, - ds_lines: np.ndarray, - align_hz: float, - device: str = "cpu", - expected: bool = False, - 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. - - 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, - read_raster_samples, - ) - from ..simulation import injection as inj - from ..simulation.render import iter_registered_frames - - detail = truth["paths"][d]["trials_detail"][t] - data_dir = Path(truth["origin"]["data_dir"]) - # the copy's raw files where the copy is now (default: where injection - # wrote them) - copy_dir = Path(copy_raw or truth["origin"]["copy_dir"]) - layout = raster_layout(data_dir / detail["filename"]) - copy = replace( - layout, - files=tuple(str(copy_dir / Path(f).name) for f in layout.files), - ) - dt = kernel_lines(layout, align_hz) - times = np.asarray(ds_lines, np.int64) - # only the cycles the frames' kernels reach (as expected_frames reads) - pl = layout.lines_per_cycle - reach = max(3 * dt, pl) - c0 = max(0, (int(times.min()) - reach - 1) // pl) - c1 = min(layout.num_cycles, (int(times.max()) + reach - 1) // pl + 1) - ch = settings.channel - # validity as the copy's registration read it: without the samples - # 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 = orig_all[ch] - new = read_raster_samples(copy, (c0, c1))[ch] - bad = orig == INVALID_SAMPLE - diff = np.where(bad, 0, new.astype(np.int64) - orig).astype(np.float32) - 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)) - del orig_all - layers.append(np.where(bad, INVALID_SAMPLE, diff)) - if expected: - pth = truth["paths"][d] - ev = pth["events"] - sel = ev["trial"] == t - fpk = pth["frame_peak"] - events = inj.Events( - ev["source"][sel], - ev["trial"][sel], - ev["onset_line"][sel], - ev["size_class"][sel], - ev["size"][sel] / fpk[ev["source"][sel]], - ) - pos = detail["positions_rc"] - fp = injected_footprints(pth, True) - 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) - 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 - layers.append(np.where(bad, INVALID_SAMPLE, exp)) - del exp - del orig, diff - samples = np.stack(layers).astype(np.float32) - 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) - grid = None - 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: 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: - n_ch = int(np.ravel(f["numChannels"][()])[0]) - hz = float(np.ravel(f["alignHz"][()])[0]) if "alignHz" in f else 80.0 - return { - "num_channels": n_ch, - "activity_channel": int(settings.channel) + 1, - "motion_thresh": 2.0, - "discard_initial_s": 0.0, - "nan_thresh": 0.33, - "ratio": 200.0 / hz, - "align_hz": hz, - "photon_scale": float(settings.photon_scale), - } - - -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) - 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: 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) - for (r, c), rad in zip(np.asarray(pos, np.float64).reshape(-1, 2), radii): - sup |= np.hypot(qr - r, qc - c) <= rad - return sup & valid_crop - - -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 - ach = st["activity_channel"] - crop = _crop_box(valid) - r0, r1, c0, c1 = crop - Y = stack[:, ach - 1].reshape(T, R * C).copy() - Y[disc] = np.nan - arrays = _arrays(job, stack, Y, None, None, valid, crop, disc, None) - del stack - qr, qc = np.mgrid[r0:r1, c0:c1] - flat = (qr * C + qc).ravel() - ds = np.asarray(al["ds_lines"], np.float64)[:T] - drawn, exp, grid, dt = injected_frames( - truth, - settings, - job.alignment_file, - job.path, - t_orig, - flat, - ds, - st["align_hz"], - 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)}") - chans = list(job.options.channels or (ach,)) - act = arrays["activity"] - for i, ch in enumerate(chans): # every occurrence of the injected one - if ch == ach: - 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) - ) - pth = truth["paths"][job.path] - detail = pth["trials_detail"][t_orig] - pos = np.asarray(detail["positions_copy_rc"], np.float64).reshape(-1, 2) - vc = valid[r0:r1, c0:c1] - prm = pth["footprint"]["params"] - # 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) - 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) - arrays["sources/peak_row"] = np.where(inside, pr - r0, -1).astype(np.int32) - arrays["sources/peak_col"] = np.where(inside, pc - c0, -1).astype(np.int32) - arrays.update(_frame_arrays(al, disc, Y, valid)) - q = _record(job, T, crop, valid, None, dict(NO_KERNEL), dict(NO_QC), disc) - ev = truth["paths"][job.path]["events"] - q.update( - kind=KIND, - nSources=int(pos.shape[0]), - injectedSources=int(pos.shape[0]), - injectedEvents=int(np.sum(ev["trial"] == t_orig)), - originalTrial=int(t_orig), - injectionTruth=str(job.provenance.get("truth", "")), - movieDtLines=dt, - labeledPixels=int((arrays["mask/labeled"].astype(bool) & vc).sum()), - ) - if exp is not None: - # frames whose kernel stays inside the trial: elsewhere the drawn - # photons may include a neighbouring injected trial of the file, - # which activity_expected (this trial's events) does not model - lo, hi = (int(v) for v in detail["lines"]) - reach = max(3 * dt, int(job.lines_per_cycle or 0)) - 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 - 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: 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 - log( - f"[export-f0-injected] {label} path {d}: removed earlier files " - f"of trials not exported now: {', '.join(removed)}" - ) - - -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) - q["seconds"] = round(time.time() - t0, 1) - except (TrialSkipped, OSError, ValueError, KeyError) as exc: - q = {"path": job.path, "trial": job.trial, "error": str(exc)} - if job.out_file.exists(): - job.out_file.unlink() - q["error"] += "; the earlier file was removed" - return q - - -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)) - if bad: - raise ValueError(f"paths {bad} are not among the copy's {paths}") - paths = sorted(set(options.paths)) - cols = list(range(1, len(originals) + 1)) - if options.trials: - bad = sorted(set(options.trials) - set(cols)) - if bad: - raise ValueError(f"trials {bad} are not among the copy's {cols}") - cols = sorted(set(options.trials)) - return paths, cols - - -def export_injected( - copy_dir: str | Path, - out_dir: str | Path, - options: ExportOptions | None = None, - device: str = "cpu", - expected: bool = False, - log: Callable[[str], None] = print, -) -> dict: - """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. - out_dir : str or Path - 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 - kernel, placement, blur, mask and event options do not (no SILo). - device : str - Where the copy's frames are formed (cpu or cuda). - expected : bool - Also write activity_expected and drawnOverExpected. - log : callable - - Returns - ------- - dict - The summary written to export_summary.json. - """ - from ..simulation import injection as inj - - options = options or ExportOptions() - _check_options(options) - copy_dir, out_dir = Path(copy_dir), Path(out_dir) - truth_path = copy_dir / inj.TRUTH_NAME - truth = inj.read_truth(truth_path) - settings = _injection_settings(truth) - originals = [int(t) for t in truth["origin"]["trials"]] - session = Session( - copy_dir / "trial_table.h5", - copy_dir / "motion_correction", - None, - copy_dir / "raw", - ) - label = options.label or copy_dir.name - summary = { - "label": label, - "kind": KIND, - "injectionTruth": str(truth_path), - "giantRef": options.giant_ref, - "exporter": EXPORTER, - "exporterVersion": __version__, - "options": asdict(options), - "trials": [], - } - out_dir.mkdir(parents=True, exist_ok=True) - paths, cols = _selection(options, truth, originals) - if not options.paths and not options.trials: # paths the copy lacks - for folder in sorted(out_dir.glob("Path*")): - k = folder.name[4:] - if k.isdigit() and int(k) not in paths: - _reconcile(out_dir, int(k), [], summary, label, log) - for d in paths: - detail = truth["paths"][d]["trials_detail"] - present = [k for k in cols if originals[k - 1] in detail] - for k in sorted(set(cols) - set(present)): # a ragged copy - log(f"[export-f0-injected] {label} path {d} trial {k}: no file") - if not present: - continue - if not options.trials: # a default export reconciles the path's files - _reconcile(out_dir, d, present, summary, label, log) - for k in present: - # each column's own settings (copies may mix 1- and 2-channel - # recordings) - st = _settings(settings, session.alignment_file(d - 1, k - 1)) - _check_channels(options.channels, st["num_channels"]) - job = TrialJob( - path=d, - trial=k, - out_file=out_dir / f"Path{d}" / f"trial_{k:03d}.h5", - movie_file=session.movie_file(d - 1, k - 1), - alignment_file=session.alignment_file(d - 1, k - 1), - baseline_file=None, - lines_per_cycle=session.lines_per_cycle(d - 1, k - 1), - settings=st, - options=options, - provenance={ - "label": label, - "truth": str(truth_path), - "copy_raw": str(copy_dir / "raw"), - }, - ) - q = _run_trial(job, truth, settings, originals[k - 1], device, expected) - summary["trials"].append(q) - write_summary(out_dir, summary) - log( - f"[export-f0-injected] {label} path {d} trial {k} " - f"(original {originals[k - 1]}): " - + (q["error"] if "error" in q else f"{q['frames']} frames") - ) - return summary - - -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/, " - "motion_correction/, injection_truth.h5)", - ) - p.add_argument("out", help="output folder (Path/trial_.h5)") - p.add_argument( - "--device", - default="cpu", - help="where the copy's frames are formed: cpu (default) or cuda", - ) - p.add_argument( - "--expected", - action="store_true", - help="also write activity_expected (the noiseless injected signal)", - ) - p.add_argument( - "--channels", - type=int, - nargs="+", - default=None, - help="one-based channels to write (default: the injected channel)", - ) - p.add_argument( - "--var-fac", - choices=("mean", "full"), - 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( - "--trials", - type=int, - nargs="+", - default=None, - help="the copy's one-based trials (default all)", - ) - - -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, - deflate=args.deflate, - label=args.label, - giant_ref=args.giant_ref, - paths=tuple(args.paths) if args.paths else None, - trials=tuple(args.trials) if args.trials else None, - ) - summary = export_injected( - args.copy, - args.out, - options, - device=args.device, - expected=args.expected, - ) - return int(any("error" in q for q in summary["trials"])) +"""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 +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: +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 channel; zero in other written channels); +* 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: + 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 + 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 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, + NO_KERNEL, + NO_QC, + ExportOptions, + TrialJob, + TrialSkipped, + _arrays, + _attr_value, + _check_channels, + _check_options, + _crop_box, + _frame_arrays, + _load, + _record, + _remove_unscheduled, + _write, + write_summary, +) + +if TYPE_CHECKING: + from ..simulation.injection import GaussianFootprint, InjectionSettings + +KIND = "gfp_injected" + + +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() + }) + + +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. + + 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 = [] + for prm in truth_path["footprint"]["params"]: + kind = prm.get("kind") + if kind == "gaussian": + sr, sc = (float(v) for v in prm["sigma_rc"]) + out.append( + inj.GaussianFootprint( + sigma_px=sr, + radius_sigmas=float(prm["radius_px"]) / max(sr, sc), + sigma_c_px=sc, + ) + ) + elif need_model: + raise ValueError( + f"footprint kind {kind!r} cannot be rebuilt from the truth: " + "export without --expected" + ) + else: + out.append(None) + return out + + +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: InjectionSettings, + copy_alignment: str | Path, + d: int, + t: int, + flat: np.ndarray, + ds_lines: np.ndarray, + align_hz: float, + device: str = "cpu", + expected: bool = False, + 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. + + 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, + read_raster_samples, + ) + from ..simulation import injection as inj + from ..simulation.render import iter_registered_frames + + detail = truth["paths"][d]["trials_detail"][t] + data_dir = Path(truth["origin"]["data_dir"]) + # the copy's raw files where the copy is now (default: where injection + # wrote them) + copy_dir = Path(copy_raw or truth["origin"]["copy_dir"]) + layout = raster_layout(data_dir / detail["filename"]) + copy = replace( + layout, + files=tuple(str(copy_dir / Path(f).name) for f in layout.files), + ) + dt = kernel_lines(layout, align_hz) + times = np.asarray(ds_lines, np.int64) + # only the cycles the frames' kernels reach (as expected_frames reads) + pl = layout.lines_per_cycle + reach = max(3 * dt, pl) + c0 = max(0, (int(times.min()) - reach - 1) // pl) + c1 = min(layout.num_cycles, (int(times.max()) + reach - 1) // pl + 1) + ch = settings.channel + # validity as the copy's registration read it: without the samples + # 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 = orig_all[ch] + new = read_raster_samples(copy, (c0, c1))[ch] + bad = orig == INVALID_SAMPLE + diff = np.where(bad, 0, new.astype(np.int64) - orig).astype(np.float32) + 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)) + del orig_all + layers.append(np.where(bad, INVALID_SAMPLE, diff)) + if expected: + pth = truth["paths"][d] + ev = pth["events"] + sel = ev["trial"] == t + fpk = pth["frame_peak"] + events = inj.Events( + ev["source"][sel], + ev["trial"][sel], + ev["onset_line"][sel], + ev["size_class"][sel], + ev["size"][sel] / fpk[ev["source"][sel]], + ) + pos = detail["positions_rc"] + fp = injected_footprints(pth, True) + 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) + 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 + layers.append(np.where(bad, INVALID_SAMPLE, exp)) + del exp + del orig, diff + samples = np.stack(layers).astype(np.float32) + 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) + grid = None + 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: 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: + n_ch = int(np.ravel(f["numChannels"][()])[0]) + hz = float(np.ravel(f["alignHz"][()])[0]) if "alignHz" in f else 80.0 + return { + "num_channels": n_ch, + "activity_channel": int(settings.channel) + 1, + "motion_thresh": 2.0, + "discard_initial_s": 0.0, + "nan_thresh": 0.33, + "ratio": 200.0 / hz, + "align_hz": hz, + "photon_scale": float(settings.photon_scale), + } + + +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) + 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: 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) + for (r, c), rad in zip(np.asarray(pos, np.float64).reshape(-1, 2), radii): + sup |= np.hypot(qr - r, qc - c) <= rad + return sup & valid_crop + + +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 + ach = st["activity_channel"] + crop = _crop_box(valid) + r0, r1, c0, c1 = crop + Y = stack[:, ach - 1].reshape(T, R * C).copy() + Y[disc] = np.nan + arrays = _arrays(job, stack, Y, None, None, valid, crop, disc, None) + del stack + qr, qc = np.mgrid[r0:r1, c0:c1] + flat = (qr * C + qc).ravel() + ds = np.asarray(al["ds_lines"], np.float64)[:T] + drawn, exp, grid, dt = injected_frames( + truth, + settings, + job.alignment_file, + job.path, + t_orig, + flat, + ds, + st["align_hz"], + 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)}") + chans = list(job.options.channels or (ach,)) + act = arrays["activity"] + for i, ch in enumerate(chans): # every occurrence of the injected one + if ch == ach: + 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) + ) + pth = truth["paths"][job.path] + detail = pth["trials_detail"][t_orig] + pos = np.asarray(detail["positions_copy_rc"], np.float64).reshape(-1, 2) + vc = valid[r0:r1, c0:c1] + prm = pth["footprint"]["params"] + # 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) + 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) + arrays["sources/peak_row"] = np.where(inside, pr - r0, -1).astype(np.int32) + arrays["sources/peak_col"] = np.where(inside, pc - c0, -1).astype(np.int32) + arrays.update(_frame_arrays(al, disc, Y, valid)) + q = _record(job, T, crop, valid, None, dict(NO_KERNEL), dict(NO_QC), disc) + ev = truth["paths"][job.path]["events"] + q.update( + kind=KIND, + nSources=int(pos.shape[0]), + injectedSources=int(pos.shape[0]), + injectedEvents=int(np.sum(ev["trial"] == t_orig)), + originalTrial=int(t_orig), + injectionTruth=str(job.provenance.get("truth", "")), + movieDtLines=dt, + labeledPixels=int((arrays["mask/labeled"].astype(bool) & vc).sum()), + ) + if exp is not None: + # frames whose kernel stays inside the trial: elsewhere the drawn + # photons may include a neighbouring injected trial of the file, + # which activity_expected (this trial's events) does not model + lo, hi = (int(v) for v in detail["lines"]) + reach = max(3 * dt, int(job.lines_per_cycle or 0)) + 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 + 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: 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 + log( + f"[export-f0-injected] {label} path {d}: removed earlier files " + f"of trials not exported now: {', '.join(removed)}" + ) + + +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) + q["seconds"] = round(time.time() - t0, 1) + except (TrialSkipped, OSError, ValueError, KeyError) as exc: + q = {"path": job.path, "trial": job.trial, "error": str(exc)} + if job.out_file.exists(): + job.out_file.unlink() + q["error"] += "; the earlier file was removed" + return q + + +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)) + if bad: + raise ValueError(f"paths {bad} are not among the copy's {paths}") + paths = sorted(set(options.paths)) + cols = list(range(1, len(originals) + 1)) + if options.trials: + bad = sorted(set(options.trials) - set(cols)) + if bad: + raise ValueError(f"trials {bad} are not among the copy's {cols}") + cols = sorted(set(options.trials)) + return paths, cols + + +def export_injected( + copy_dir: str | Path, + out_dir: str | Path, + options: ExportOptions | None = None, + device: str = "cpu", + expected: bool = False, + log: Callable[[str], None] = print, +) -> dict: + """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. + out_dir : str or Path + 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 + kernel, placement, blur, mask and event options do not (no SILo). + device : str + Where the copy's frames are formed (cpu or cuda). + expected : bool + Also write activity_expected and drawnOverExpected. + log : callable + + Returns + ------- + dict + The summary written to export_summary.json. + """ + from ..simulation import injection as inj + + options = options or ExportOptions() + _check_options(options) + copy_dir, out_dir = Path(copy_dir), Path(out_dir) + truth_path = copy_dir / inj.TRUTH_NAME + truth = inj.read_truth(truth_path) + settings = _injection_settings(truth) + originals = [int(t) for t in truth["origin"]["trials"]] + session = Session( + copy_dir / "trial_table.h5", + copy_dir / "motion_correction", + None, + copy_dir / "raw", + ) + label = options.label or copy_dir.name + summary = { + "label": label, + "kind": KIND, + "injectionTruth": str(truth_path), + "giantRef": options.giant_ref, + "exporter": EXPORTER, + "exporterVersion": __version__, + "options": asdict(options), + "trials": [], + } + out_dir.mkdir(parents=True, exist_ok=True) + paths, cols = _selection(options, truth, originals) + if not options.paths and not options.trials: # paths the copy lacks + for folder in sorted(out_dir.glob("Path*")): + k = folder.name[4:] + if k.isdigit() and int(k) not in paths: + _reconcile(out_dir, int(k), [], summary, label, log) + for d in paths: + detail = truth["paths"][d]["trials_detail"] + present = [k for k in cols if originals[k - 1] in detail] + for k in sorted(set(cols) - set(present)): # a ragged copy + log(f"[export-f0-injected] {label} path {d} trial {k}: no file") + if not present: + continue + if not options.trials: # a default export reconciles the path's files + _reconcile(out_dir, d, present, summary, label, log) + for k in present: + # each column's own settings (copies may mix 1- and 2-channel + # recordings) + st = _settings(settings, session.alignment_file(d - 1, k - 1)) + _check_channels(options.channels, st["num_channels"]) + job = TrialJob( + path=d, + trial=k, + out_file=out_dir / f"Path{d}" / f"trial_{k:03d}.h5", + movie_file=session.movie_file(d - 1, k - 1), + alignment_file=session.alignment_file(d - 1, k - 1), + baseline_file=None, + lines_per_cycle=session.lines_per_cycle(d - 1, k - 1), + settings=st, + options=options, + provenance={ + "label": label, + "truth": str(truth_path), + "copy_raw": str(copy_dir / "raw"), + }, + ) + q = _run_trial(job, truth, settings, originals[k - 1], device, expected) + summary["trials"].append(q) + write_summary(out_dir, summary) + log( + f"[export-f0-injected] {label} path {d} trial {k} " + f"(original {originals[k - 1]}): " + + (q["error"] if "error" in q else f"{q['frames']} frames") + ) + return summary + + +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/, " + "motion_correction/, injection_truth.h5)", + ) + p.add_argument("out", help="output folder (Path/trial_.h5)") + p.add_argument( + "--device", + default="cpu", + help="where the copy's frames are formed: cpu (default) or cuda", + ) + p.add_argument( + "--expected", + action="store_true", + help="also write activity_expected (the noiseless injected signal)", + ) + p.add_argument( + "--channels", + type=int, + nargs="+", + default=None, + help="one-based channels to write (default: the injected channel)", + ) + p.add_argument( + "--var-fac", + choices=("mean", "full"), + 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( + "--trials", + type=int, + nargs="+", + default=None, + help="the copy's one-based trials (default all)", + ) + + +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, + deflate=args.deflate, + label=args.label, + giant_ref=args.giant_ref, + paths=tuple(args.paths) if args.paths else None, + trials=tuple(args.trials) if args.trials else None, + ) + summary = export_injected( + args.copy, + args.out, + options, + device=args.device, + expected=args.expected, + ) + return int(any("error" in q for q in summary["trials"])) diff --git a/src/giant_python/export/f0_layout.py b/src/giant_python/export/f0_layout.py index c3b77ec2..7f524ebe 100644 --- a/src/giant_python/export/f0_layout.py +++ b/src/giant_python/export/f0_layout.py @@ -1,1298 +1,1298 @@ -"""Raster layout of registered trials, for the F0 network's simulator. - -A registered frame is linear in the raw samples: frame formation gives each -raw pixel the weighted mean of its samples around the frame's line time, and -registration resamples the raw pixels by the frame's rigid shift -(:mod:`giant_python.registration.frames`, -:mod:`giant_python.registration.interpolation`). The simulator of -`slap2-F0-network `_ -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: - -* 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 - with it) and how the trial's frames were formed - (frame lines, kernel, the frames' motion, the registration window); -* each slot's mean and share of zeros, per channel; -* the events of the trial: a library of measured bursts (one to four - consecutive non-zero samples), how often each type of burst occurs at - different brightness, the variance and covariance of consecutive samples - by brightness, and histograms of the pulse heights and of how a pulse is - split between a sample and the next one on its line. - -:func:`reference_frames` forms registered frames from such a file and the -samples of its slots. It states what the file means and is checked against -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 -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). - -Conventions: arrays as h5py reads them, in NumPy's orientation. Slot lines -and frame lines are one-based, as everywhere in GIAnT; cycles, pixel -positions and slot indices are zero-based. -""" - -from __future__ import annotations - -import argparse -import logging -import time -from collections.abc import Sequence -from pathlib import Path -from typing import TYPE_CHECKING - -import h5py -import numpy as np - -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).""" - -READABLE_VERSIONS = (3, 4) -"""Versions :func:`read_layout` reads. A version 3 file (registrations -without online compensation only) gets its slots' positions from its pixel -list.""" - -HEIGHT_BINS = 1024 -"""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.""" - -DIM_ZERO_SHARE = 0.95 -"""A pair of consecutive samples counts as dim when both are zero in at -least this share of its cycles. A pulse of the pair's earlier slot then -coincides with one of the later slot's own in at most about 2.5% of its -cycles, usually far fewer; such a coincidence is counted as one split pulse. -Brighter pairs are never used: a recording without dim pairs gets empty -histograms.""" - -MIN_PAIR_CYCLES = 100 -"""A pair needs this many cycles with both samples valid.""" - -PAIR_CHUNK = 2048 -"""Pairs whose samples are compared at once.""" - -BURST_MAX = 4 -"""Longest burst kept in the library, in samples.""" - -BURST_EXAMPLES = 8192 -"""Most examples kept of each burst length, per channel.""" - -BURST_LEVEL = 2.0 -"""Examples of bursts are kept from chains whose mean sample is below this -(raw units; about one event in 100 samples), where unrelated events rarely -touch (they would be read as one longer burst).""" - -STRATA_EDGES = (0.0, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0) -"""Edges of the brightness strata of the burst counts: a chain's mean sample -in raw units. Brighter chains are not counted.""" - -BURST_BLOCK = 8 -"""Cycles per block. A chain's level is its mean over every second block and -its bursts are counted in the other blocks, then the other way round, so -that a chain is not placed among the dim ones because it happened to have -few events where they are counted.""" - -MIN_BLOCK_CYCLES = 50 -"""A chain needs this many valid cycles in the blocks that give its level.""" - -CELL_STEPS = (10, 20, 50, 100) -"""Step of the total (raw units) in the cells of bursts of 1, 2, 3 and 4 -samples (:func:`burst_cells`).""" - -CELL_BINS = (41, 31, 17, 11) -"""Bins of the total for each length; the last holds every larger total.""" - -CELL_SHARES = 3 -"""Bins of the smaller part's share of a burst of two samples.""" - -_CELL_COUNTS = (CELL_BINS[0], CELL_BINS[1] * CELL_SHARES, *CELL_BINS[2:]) - -N_CELLS = sum(_CELL_COUNTS) -"""Number of burst cells.""" - -LEVEL_EDGES = tuple(float(0.5 * 2 ** (i / 2)) for i in range(19)) -"""Edges of the brightness levels of the sample moments: a chain's mean -sample, 0.5 to 256 raw units in steps of a factor of the square root of -2.""" - -LEVEL_LAGS = 8 -"""The sample moments reach this many samples along the line.""" - -LEVEL_CHUNK = 1024 -"""Chains whose samples are compared at once.""" - -MIN_REVISITS = 1000 -"""With fewer chains whose pixels are visited again within the cycle, the -sample moments are measured against the next cycle.""" - -_REGISTERED = "_REGISTERED_DOWNSAMPLED-" - - -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 - split between them only where the scan runs on from one pixel to its - neighbour. Where it jumps to another part of the raster (from one ROI - to the next), the two samples share nothing: on a GFP recording - (847983) consecutive samples of neighbouring pixels correlate by - 0.17-0.22, those across a jump by -0.01. - - Parameters - ---------- - layout : RasterLayout - The recording's layout. - - Returns - ------- - nxt : ndarray of int - For each slot, the slot that shares pulses with it: the one sampled - right after it on its line if that is a pixel within one row and - one column of its own, else -1. - start, end : ndarray of bool - 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. - """ - from ..registration.stats.gain import next_slots - - nxt = next_slots(layout.slot_line, layout.slot_pos) - row = (layout.slot_pixel - 1) // layout.n_cols - col = (layout.slot_pixel - 1) % layout.n_cols - to = np.maximum(nxt, 0) - near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) - jump = (nxt >= 0) & ~near - after_jump = np.zeros(nxt.size, dtype=bool) - after_jump[nxt[jump]] = True - last_pos = layout.n_per_channel[layout.slot_line - 1] - 1 - start = (layout.slot_pos == 0) | after_jump - end = (layout.slot_pos == last_pos) | jump - return np.where(jump, -1, nxt), start, end - - -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. - - Returns - ------- - Path - The layout file, in the movie's folder. - """ - p = Path(movie_path) - if _REGISTERED in p.name: - return p.with_name(p.name.split(_REGISTERED, 1)[0] + "_F0LAYOUT.h5") - return p.with_name(f"{p.stem}_F0LAYOUT.h5") - - -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. - - Returns - ------- - dict - mean and zero_share (channels, slots) float32 over each - slot's valid samples (NaN without any) and valid_share - (channels, slots) float32. - """ - import torch - - n_ch, n_slots, n_cycles = samples.shape - out = { - k: np.full((n_ch, n_slots), np.nan, np.float32) - for k in ("mean", "zero_share", "valid_share") - } - step = max(1, 4_000_000 // max(1, n_cycles)) - for ch in range(n_ch): - for a in range(0, n_slots, step): - x = samples[ch, a : a + step] - ok = x != INVALID_SAMPLE - n = ok.sum(1).to(torch.float64) - total = torch.where(ok, x, 0).to(torch.int64).sum(1) - zeros = (ok & (x == 0)).sum(1).to(torch.float64) - some = (n > 0).cpu().numpy() - n_np = n.cpu().numpy() - sl = slice(a, a + x.shape[0]) - out["valid_share"][ch, sl] = n_np / max(1, n_cycles) - mean = np.full(x.shape[0], np.nan) - zero = np.full(x.shape[0], np.nan) - mean[some] = total.cpu().numpy()[some] / n_np[some] - zero[some] = zeros.cpu().numpy()[some] / n_np[some] - out["mean"][ch, sl] = mean - out["zero_share"][ch, sl] = zero - return out - - -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 - 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 - two slots' rates. - - Split events are of two kinds, which the joint histogram of height and - fraction keeps apart: one pulse on the boundary between the two - samples (any fraction, the height of an unsplit pulse), and two pulses, - one in each sample (about twice the height, a fraction near one half). - On two recordings three in ten split events are of the second kind, far - 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 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 - 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 - concerned, -32768 where invalid. - nxt : ndarray of int - Each slot's next slot on its line, -1 for none - (:func:`sharing_slots`, or - :func:`giant_python.registration.stats.gain.next_slots` for lines of - neighbouring raster pixels only). - line_end : ndarray of bool, optional - Whether nothing follows each slot that could share a pulse with it - (:func:`sharing_slots`). Default: a slot without a next ends its - run. - - 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 - 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 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. - """ - import torch - - n_ch, n_slots, _n_cycles = samples.shape - nxt = np.asarray(nxt, dtype=np.int64) - first = np.flatnonzero(nxt >= 0) - second = nxt[first] - prev = np.full(n_slots, -1, dtype=np.int64) - prev[second] = first - before, after = prev[first], nxt[second] - # the sample before the pair must be seen; the one after it must be - # seen or not exist - seen = before >= 0 - if line_end is not None: - seen &= (after >= 0) | np.asarray(line_end, dtype=bool)[second] - first, second = first[seen], second[seen] - before, after = before[seen], after[seen] - out = { - "height_single": np.zeros((n_ch, HEIGHT_BINS), np.int64), - "height_split": np.zeros((n_ch, HEIGHT_BINS), np.int64), - "split_fraction": np.zeros((n_ch, SPLIT_BINS), np.int64), - "split_joint": np.zeros((n_ch, JOINT_BINS, SPLIT_BINS), np.int64), - "pairs": np.zeros(n_ch, np.int64), - "pair_cycles": np.zeros(n_ch, np.int64), - } - if first.size == 0: - return out - dev = samples.device - - 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) - - for ch in range(n_ch): - both_zero = np.zeros(first.size) - n_valid = np.zeros(first.size) - for a in range(0, first.size, PAIR_CHUNK): - sl = slice(a, a + PAIR_CHUNK) - xa, xb = rows(ch, first[sl]), rows(ch, second[sl]) - ok = (xa != INVALID_SAMPLE) & (xb != INVALID_SAMPLE) - n = ok.sum(1).to(torch.float64) - 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)) - 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) - xa = torch.where(alone, xa, 0).to(torch.int64) - xb = torch.where(alone, xb, 0).to(torch.int64) - height = xa + xb - cycles += int(alone.sum()) - split = (xa > 0) & (xb > 0) - single = (xa > 0) & (xb == 0) - for key, mask in ( - ("height_single", single), - ("height_split", split), - ): - h = height[mask].clamp(1, HEIGHT_BINS) - 1 - 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() - 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() - out["pair_cycles"][ch] = cycles - return out - - -def burst_cells(parts: np.ndarray) -> np.ndarray: - """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 - total in steps of 20 (31 bins) and by the smaller part's share of it - (three equal bins over 0 to 0.5); a burst of three by its total in - steps of 50 (17 bins); a burst of four in steps of 100 (11 bins). The - cells are numbered in that order: 0-40, 41-133 (total bin x 3 + share - bin), 134-150 and 151-161. - - Parameters - ---------- - parts : ndarray - (bursts, length) samples of bursts of one length (1-4). - - Returns - ------- - ndarray of int64 - (bursts,) cell of each burst. - """ - parts = np.asarray(parts, dtype=np.float64) - n = parts.shape[1] - total = parts.sum(1) - first = int(np.sum(_CELL_COUNTS[: n - 1])) - bins = (total // CELL_STEPS[n - 1]).astype(np.int64) - bins = np.clip(bins, 0, CELL_BINS[n - 1] - 1) - if n != 2: - return first + bins - share = parts.min(1) / np.maximum(total, 1e-9) - part = np.minimum((share * 2 * CELL_SHARES).astype(np.int64), 2) - return first + bins * CELL_SHARES + part - - -def _keep_bursts(out: dict, ch: int, found: list) -> None: - """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 - parts = np.concatenate([p for p, _ in items]) - cell = np.concatenate([c for _, c in items]) - if parts.shape[0] == 0: - continue - keep = min(BURST_EXAMPLES, parts.shape[0]) - pick = np.linspace(0, parts.shape[0] - 1, keep).round().astype(int) - out[f"burst_{n}"][ch, :keep] = parts[pick] - out[f"burst_cell_{n}"][ch, :keep] = cell[pick] - out["burst_examples"][ch, n - 1] = keep - - -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()) - rest = ok & ~use - n_rest = rest.sum(1) - level = (sum(xs) * rest).sum(1).to(torch.float64) - level = level / (len(xs) * n_rest.clamp(min=1)) - stratum = torch.bucketize(level, edges, right=True) - stratum[n_rest < MIN_BLOCK_CYCLES] = n_s - st = stratum.cpu().numpy() - inside = st < n_s - lib = inside & (level.cpu().numpy() < BURST_LEVEL) - good = ok & use - free = good & (xs[0] == 0) - - 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) - - out["strata_free"][ch] += per_stratum(free.sum(1)).astype(np.int64) - sums[0] += per_stratum((xs[1] * good).sum(1)) - sums[1] += per_stratum(good.sum(1)) - going = free & (xs[1] > 0) - going &= torch.from_numpy(inside).to(free.device)[:, None] - for n in range(1, BURST_MAX + 1): - ends = going & (xs[n + 1] == 0) - if ends.any(): - rows, cols = torch.nonzero(ends, as_tuple=True) - parts = torch.stack([x[rows, cols] for x in xs[1 : n + 1]], 1) - parts = parts.cpu().numpy() - rows = rows.cpu().numpy() - cell = burst_cells(parts) - np.add.at(out["strata_bursts"][ch], (st[rows], cell), 1) - keep = lib[rows] - out["burst_counts"][ch, n - 1] += int(keep.sum()) - found[n - 1].append((parts[keep].astype(np.int16), cell[keep])) - going = going & (xs[n + 1] > 0) - longer = going.sum(1) - out["strata_longer"][ch] += per_stratum(longer).astype(np.int64) - out["burst_counts"][ch, BURST_MAX] += int(longer.cpu().numpy()[lib].sum()) - - -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 - samples, and groups of pulses that follow each other (two in three in a - hundred events span three samples on two recordings, far more than - unrelated pulses would). What matters to the noise of a frame is how an - event's parts are divided between consecutive samples, so the library - keeps whole bursts as they were recorded, by length. - - A burst starts in a slot whose sample is non-zero while the sample - before it is zero, and runs on along the line until a sample is zero. - Bursts are taken from chains of six consecutive slots (the one before - the start and five from it), in cycles where all six are valid. Bursts - longer than :data:`BURST_MAX` are counted only. - - Not every event is a photon of the tissue: some occur at a rate that - does not depend on brightness, and they are smaller (on 847983 about - 1 300 per million samples, mostly 60-110 raw units in total, against a - photon peak at 100-120). They make up a sixth of the events of the - dimmest chains and a hundredth at 10 raw units per sample, so a library - of dim chains alone misstates the photon events. The counts by stratum - let a reader separate the two: per type of burst - (:func:`burst_cells`), the rate rises linearly with the stratum's mean - for photon events and is constant for the others. - - A chain's stratum is its mean sample over every second block of - :data:`BURST_BLOCK` cycles; its bursts are counted in the other blocks, - and then the other way round. Examples are kept from chains below - :data:`BURST_LEVEL`. - - Parameters - ---------- - samples : torch.Tensor of int16 - (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 - 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. - """ - import torch - - n_ch, n_slots, n_cycles = samples.shape - nxt = np.asarray(nxt, dtype=np.int64) - prev = np.full(n_slots, -1, dtype=np.int64) - prev[nxt[nxt >= 0]] = np.flatnonzero(nxt >= 0) - n_s = len(STRATA_EDGES) - 1 - out = { - "burst_counts": np.zeros((n_ch, BURST_MAX + 1), np.int64), - "burst_examples": np.zeros((n_ch, BURST_MAX), np.int64), - "strata_edges": np.asarray(STRATA_EDGES, dtype=np.float64), - "strata_free": np.zeros((n_ch, n_s), np.int64), - "strata_mean": np.zeros((n_ch, n_s), np.float64), - "strata_bursts": np.zeros((n_ch, n_s, N_CELLS), np.int64), - "strata_longer": np.zeros((n_ch, n_s), np.int64), - } - for n in range(1, BURST_MAX + 1): - out[f"burst_{n}"] = np.zeros((n_ch, BURST_EXAMPLES, n), np.int16) - out[f"burst_cell_{n}"] = np.zeros((n_ch, BURST_EXAMPLES), np.int16) - # chains: the slot before the start, the start and the four after it - chain = [prev, np.arange(n_slots)] - for _ in range(BURST_MAX): - last = chain[-1] - chain.append(np.where(last >= 0, nxt[np.maximum(last, 0)], -1)) - starts = np.flatnonzero(np.all([c >= 0 for c in chain], axis=0)) - dev = samples.device - edges = torch.tensor(STRATA_EDGES[1:], dtype=torch.float64, device=dev) - odd = (torch.arange(n_cycles, device=dev) // BURST_BLOCK) % 2 == 1 - for ch in range(n_ch): - found = [[] for _ in range(BURST_MAX)] - 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] - ok = xs[0] != INVALID_SAMPLE - for x in xs[1:]: - ok &= x != INVALID_SAMPLE - for use in (odd, ~odd): - _count_bursts(out, ch, xs, ok, use, edges, found, sums) - out["strata_mean"][ch] = sums[0] / np.maximum(sums[1], 1) - _keep_bursts(out, ch, found) - return out - - -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 - 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]: - the slot of that pixel's next visit, the visits forming a chain of - 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 - chain. - """ - n = nxt.size - chain = [np.arange(n)] - for _ in range(LEVEL_LAGS): - last = chain[-1] - chain.append(np.where(last >= 0, nxt[np.maximum(last, 0)], -1)) - whole = np.all([c >= 0 for c in chain], axis=0) - # each slot's first visit of the same pixel on a later line - pixel = np.asarray(pixel, dtype=np.int64) - key = pixel * (int(np.max(line, initial=0)) + 1) + line - order = np.argsort(key, kind="stable") - later = np.searchsorted(key[order], key, side="right") - cand = order[np.minimum(later, max(n - 1, 0))] if n else order - found = (later < n) & (pixel[cand] == pixel) & (pixel >= 0) - again = np.where(found, cand, -1) - other = [np.where(c >= 0, again[np.maximum(c, 0)], -1) for c in chain] - fine = whole & np.all([o >= 0 for o in other], axis=0) - for k in range(LEVEL_LAGS): - fine &= nxt[np.maximum(other[k], 0)] == other[k + 1] - if fine.sum() >= MIN_REVISITS: - return [c[fine] for c in chain], [o[fine] for o in other] - return [c[whole] for c in chain], None - - -def level_statistics( - 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. - - 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 - 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. - - Parameters - ---------- - samples : torch.Tensor of int16 - (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 - Each slot's pixel and line within the cycle. A negative pixel marks - a slot that is not to count as a visit (a slot of another plane). - - 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): - 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 - the next visit within the cycle, 0 if the next cycle. - """ - import torch - - n_ch = samples.shape[0] - nxt = np.asarray(nxt, dtype=np.int64) - chain, other = _second_visits(nxt, np.asarray(pixel), np.asarray(line)) - shift = 0 if other is not None else 1 - if other is None: - other = chain - n_l = len(LEVEL_EDGES) - 1 - out = { - "level_edges": np.asarray(LEVEL_EDGES, dtype=np.float64), - "level_samples": np.zeros((n_ch, n_l), np.int64), - "level_mean": np.zeros((n_ch, n_l), np.float64), - "level_zero": np.zeros((n_ch, n_l), np.float64), - "level_moments": np.zeros((n_ch, n_l, LEVEL_LAGS + 1), np.float64), - "level_revisits": np.uint8(shift == 0), - } - dev = samples.device - edges = torch.tensor(LEVEL_EDGES, dtype=torch.float64, device=dev) - for ch in range(n_ch): - acc = np.zeros((n_l, LEVEL_LAGS + 4)) - for a in range(0, chain[0].size, LEVEL_CHUNK): - sl = slice(a, a + LEVEL_CHUNK) - xs = [samples[ch, torch.from_numpy(c[sl]).to(dev)] for c in chain] - ys = [samples[ch, torch.from_numpy(c[sl]).to(dev)] for c in other] - if shift: - xs = [x[:, :-shift] for x in xs] - ys = [y[:, shift:] for y in ys] - ok = xs[0] != INVALID_SAMPLE - for v in xs[1:] + ys: - ok &= v != INVALID_SAMPLE - zeros = ((xs[0] == 0) & ok).sum(1) + ((ys[0] == 0) & ok).sum(1) - xs = [x.to(torch.float64) * ok for x in xs] - ys = [y.to(torch.float64) * ok for y in ys] - n = ok.sum(1) - sx = sum(x.sum(1) for x in xs) - sy = sum(y.sum(1) for y in ys) - level = (sx + sy) / (2 * len(xs) * n.clamp(min=1)) - b = torch.bucketize(level, edges, right=True) - 1 - good = (b >= 0) & (b < n_l) & (n >= MIN_PAIR_CYCLES) - good &= (sx > 0) & (sy > 0) - ratio = torch.ones_like(sx) if shift else sx / sy.clamp(min=1e-9) - cols = [n.to(torch.float64), (xs[0] + ys[0]).sum(1) / 2] - cols.append(zeros.to(torch.float64) / 2) - for k in range(LEVEL_LAGS + 1): - within = (xs[0] * xs[k]).sum(1) + (ys[0] * ys[k]).sum(1) - across = (xs[0] * ys[k]).sum(1) * ratio - across = across + (ys[0] * xs[k]).sum(1) / ratio.clamp(1e-9) - cols.append((within - across) / 2) - 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) - n = np.maximum(acc[:, 0], 1) - out["level_samples"][ch] = acc[:, 0].astype(np.int64) - out["level_mean"][ch] = acc[:, 1] / n - out["level_zero"][ch] = acc[:, 2] / n - out["level_moments"][ch] = acc[:, 3:] / n[:, None] - return out - - -def trial_layout( - dat: str | Path, - first_line: float, - last_line: float, - adata: str | Path, - settings: dict | None = None, - device: str = "cpu", -) -> dict: - """Build the layout record of one registered trial and path. - - Parameters - ---------- - dat : str or Path - The trial's raw recording. - first_line, last_line : float - The trial's line range (trial table). - adata : str or Path - The trial's alignment file. - settings : dict, optional - The trial table's registration settings, for registrations that do - not record their own (GIAnT-MATLAB's). - device : str - Where the samples are held. - - Returns - ------- - dict - attrs and the arrays :func:`write_layout` stores. - - Raises - ------ - ValueError - For a registration whose frame times, window or online compensation - differ from the alignment file's. - """ - 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) - former, win = source.former, source.window - h, w = win.shape - pad_r, pad_c = al["out_shape"][0] - h, al["out_shape"][1] - w - if pad_r != pad_c or pad_r < 0 or pad_r % 2: - raise ValueError( - f"{adata}: registered frame {al['out_shape']} does not fit the " - f"window {(h, w)} with an equal margin on every side" - ) - # 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() - 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) - in_cols = former.cols[inside] - (int(win.trim_cols[0]) - 1) - plane = layout.line_fast_z[layout.slot_line - 1] == former.z_idx - at = np.minimum(np.searchsorted(ids, layout.slot_pixel), ids.size - 1) - slots = np.flatnonzero(plane & (ids[at] == layout.slot_pixel)) - nxt_all, _, line_end = sharing_slots(layout) - renumber = np.full(layout.slot_line.size, -1, dtype=np.int64) - renumber[slots] = np.arange(slots.size) - 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)]) - shared = np.where(plane, nxt_all, -1) - pulses = pulse_statistics(samples, shared, line_end) - pulses.update(burst_statistics(samples, shared)) - pulses.update( - level_statistics( - samples, - shared, - np.where(plane, layout.slot_pixel, -1), - layout.slot_line, - ) - ) - p = layout.lines_per_cycle - dt = int(source.dt) - attrs = { - "layout_version": LAYOUT_VERSION, - "recording": Path(dat).name, - "alignment": Path(adata).name, - "lines_per_cycle": int(p), - "line_period_s": float(layout.line_period_s), - "total_lines": int(layout.total_lines), - "dmd_rows": int(layout.n_rows), - "dmd_cols": int(layout.n_cols), - "num_channels": int(layout.num_channels), - "align_hz": float(al["align_hz"]), - "kernel_dt_lines": dt, - "reach_lines": int(max(3 * dt, p)), - "cycle0": int(former.cycle0), - "n_cycles": int(former.n_cycles), - "first_line": float(first_line), - "last_line": float(last_line), - "window_row0": int(win.trim_rows[0]) - 1, - "window_col0": int(win.trim_cols[0]) - 1, - "window_rows": int(h), - "window_cols": int(w), - "margin": int(pad_r // 2), - "unlit_masked": bool(al["unlit_masked"]), - "compensated": comp, - "dim_zero_share": DIM_ZERO_SHARE, - "burst_level": BURST_LEVEL, - } - win_rows = win.rows.cpu().numpy().astype(np.int64) - win_cols = win.cols.cpu().numpy().astype(np.int64) - slot_rows, slot_cols = in_rows[at[slots]], in_cols[at[slots]] - extra = {} - if comp: - # the pixels that frames report are those a sample can land on; - # a slot's own raster pixel need not be one of them - lookup = np.full(h * w, -1, dtype=np.int64) - lookup[win_rows * w + win_cols] = np.arange(win_rows.size) - slot_pixel = lookup[slot_rows * w + slot_cols] - off = source.compensation - a = int(former.cycle0) * int(p) - b = a + int(former.n_cycles) * int(p) - attrs["y_lead"] = np.asarray(off.y_lead, dtype=np.int64) - extra = { - "lines/x": off.x[a:b].astype(np.int16), - "lines/y_eff": off.y_eff[a:b].astype(np.int16), - "frames/ref_xy": np.asarray(source.references(ds), np.int16), - } - else: - slot_pixel = at[slots] - return { - "attrs": attrs, - "frames/lines": np.asarray(ds, dtype=np.int64), - "frames/motion": np.asarray(al["motion"], dtype=np.float64), - **extra, - "slots/index": slots.astype(np.int64), - "slots/line": layout.slot_line[slots].astype(np.int32), - "slots/pos": layout.slot_pos[slots].astype(np.int32), - "slots/pixel": slot_pixel.astype(np.int32), - "slots/row": slot_rows.astype(np.int32), - "slots/col": slot_cols.astype(np.int32), - "slots/next": nxt.astype(np.int32), - "slots/line_end": line_end[slots].astype(np.uint8), - "slots/mean": stats["mean"], - "slots/zero_share": stats["zero_share"], - "slots/valid_share": stats["valid_share"], - "pixels/row": win_rows.astype(np.int32), - "pixels/col": win_cols.astype(np.int32), - **{f"photon/{k}": v for k, v in pulses.items()}, - } - - -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. - """ - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_name(path.name + ".partial") - try: - with h5py.File(tmp, "w") as f: - for key, value in record["attrs"].items(): - f.attrs[key] = value - for key, value in record.items(): - if key == "attrs": - continue - arr = np.asarray(value) - f.create_dataset( - key, - data=arr, - compression="gzip" if arr.size > 64 else None, - shuffle=arr.size > 64, - ) - tmp.replace(path) - finally: - if tmp.exists(): - tmp.unlink() - - -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 - 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 {READABLE_VERSIONS}" - ) - out["attrs"] = { - k: (v.item() if isinstance(v, np.generic) else v) for k, v in f.attrs.items() - } - - def visit(name: str, obj: h5py.HLObject) -> None: - """Collect every dataset.""" - if isinstance(obj, h5py.Dataset): - out[name] = obj[()] - - f.visititems(visit) - if "slots/row" not in out: # version 3: the slots' own pixels are listed - pix = out["slots/pixel"].astype(np.int64) - out["slots/row"] = out["pixels/row"][pix] - out["slots/col"] = out["pixels/col"][pix] - return out - - -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 - out[:, (cols < 0) | (cols >= w)] = np.nan - return out - - -def reference_frames( - layout: dict, samples: np.ndarray, frames: Sequence[int] | None = None -) -> np.ndarray: - """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 - 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 - window - 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. - - Parameters - ---------- - 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; - -32768 marks invalid samples. - frames : sequence of int, optional - Zero-based frames to form (default: all). - - Returns - ------- - ndarray of float64 - (channels, frames, window_rows + 2 margin, window_cols + 2 - margin). - """ - at = layout["attrs"] - p, dt, reach = ( - at["lines_per_cycle"], - at["kernel_dt_lines"], - at["reach_lines"], - ) - h, w, m = at["window_rows"], at["window_cols"], at["margin"] - lines = layout["frames/lines"] - motion = layout["frames/motion"] - slot_line = layout["slots/line"].astype(np.int64) - slot_r = layout["slots/row"].astype(np.int64) - slot_c = layout["slots/col"].astype(np.int64) - comp = bool(at.get("compensated", False)) - if comp: - 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 - 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) - out = np.full((n_ch, index.size, h + 2 * m, w + 2 * m), np.nan) - cycles = at["cycle0"] + np.arange(n_cycles) - for k, i in enumerate(index): - t = int(lines[i]) - 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)) - 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) - # where each sample goes: its slot's pixel, moved by its line's - # online offset less the frame's own (rows follow y, columns x) - rows = np.broadcast_to(slot_r[:, None], line.shape) - cols = np.broadcast_to(slot_c[:, None], line.shape) - if comp: - at_line = line - 1 - at["cycle0"] * p - rows = rows + off_y[at_line] - ref[i, 1] - cols = cols + off_x[at_line] - ref[i, 0] - landed = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w) - dest = np.where(landed, rows * w + cols, 0).ravel() - num = np.zeros((n_ch, h * w)) - den = np.zeros((n_ch, h * w)) - for ch in range(n_ch): - ok = valid[ch][:, near] & landed - wv = np.where(ok, wgt, 0.0) - np.add.at(num[ch], dest, (wv * x[ch][:, near]).ravel()) - np.add.at(den[ch], dest, wv.ravel()) - with np.errstate(invalid="ignore", divide="ignore"): - raw = np.where(den > 0, num / den, np.nan).reshape(n_ch, h, w) - fresh = den[0].reshape(h, w) - # the output grid's positions in the window (zero-based) - pos_r = np.arange(h + 2 * m) - m + float(motion[i, 0]) - pos_c = np.arange(w + 2 * m) - m + float(motion[i, 1]) - fr = pos_r[0] - np.floor(pos_r[0]) - fc = pos_c[0] - np.floor(pos_c[0]) - r_lo, r_hi = np.floor(pos_r).astype(int), np.ceil(pos_r).astype(int) - c_lo, c_hi = np.floor(pos_c).astype(int), np.ceil(pos_c).astype(int) - corners = ( - (r_lo, c_lo, (1 - fc) * (1 - fr)), - (r_lo, c_hi, fc * (1 - fr)), - (r_hi, c_lo, (1 - fc) * fr), - (r_hi, c_hi, fc * fr), - ) - den_out = np.zeros((h + 2 * m, w + 2 * m)) - num_out = np.zeros((n_ch, h + 2 * m, w + 2 * m)) - for rows, cols, coef in corners: - cf = coef * _corner_values(fresh, rows, cols) - den_out += cf - for ch in range(n_ch): - num_out[ch] += cf * _corner_values(raw[ch], rows, cols) - with np.errstate(invalid="ignore", divide="ignore"): - out[:, k] = num_out / den_out - return out - - -def export_layouts( - trial_table: str | Path, - out_dir: str | Path | None = None, - *, - datadr: str | Path | None = None, - moco: str | Path | None = None, - device: str = "cpu", - overwrite: bool = False, - 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). - 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 - each trial's samples are held. - overwrite : bool - Write files that exist again. - paths, trials : sequence of int, optional - One-based paths (DMDs) and trials (default: all). - - Returns - ------- - list of dict - 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 - from ..pipeline.register import recorded_cells - from ..registration.multiroi import resolve_device - - path = Path(trial_table) - tt = read_trial_table(path) - if tt.slap2_info is None: - raise ValueError("the trial table has no slap2_info") - files = np.atleast_2d(np.asarray(tt.filename, dtype=object)) - shape = files.shape - mc = tt.motion_correction or {} - fn_reg = _grid(mc.get("fn_reg_ds", np.full(shape, "")), shape) - fn_ad = _grid(mc.get("fn_adata", np.full(shape, "")), shape) - first = np.asarray(tt.slap2_info.first_line, float).reshape(shape) - last = np.asarray(tt.slap2_info.last_line, float).reshape(shape) - present = recorded_cells(files) & recorded_cells(fn_reg) - present &= _selected(shape, paths, trials) - moco = Path(moco) if moco else Path(tt.savedr) / "motion_correction" - datadr = Path(datadr) if datadr else Path(tt.datadr) - settings = _table_settings(path) - dev = str(resolve_device(device)) - results = [] - for d, t in zip(*np.nonzero(present)): - movie, adata = moco / str(fn_reg[d, t]), moco / str(fn_ad[d, t]) - out = layout_path(movie) - if out_dir is not None: - out = Path(out_dir) / out.name - res = {"out": str(out), "error": None, "seconds": 0.0} - results.append(res) - if out.exists() and not overwrite: - log.info("%s exists; skipping", out.name) - continue - start = time.perf_counter() - try: - if not adata.exists(): - raise FileNotFoundError(f"{adata.name} is missing") - record = trial_layout( - datadr / str(files[d, t]), - float(first[d, t]), - float(last[d, t]), - adata, - settings, - dev, - ) - record["attrs"]["path"] = int(d) + 1 - record["attrs"]["trial"] = int(t) + 1 - write_layout(out, record) - except Exception as exc: # reported per trial - log.exception("layout failed for %s", movie.name) - res["error"] = repr(exc) - res["seconds"] = time.perf_counter() - start - return results - - -def add_arguments(parser: argparse.ArgumentParser) -> None: - """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).", - ) - parser.add_argument( - "--datadr", - default=None, - help="Raw-data folder, if it moved since the table was written.", - ) - parser.add_argument( - "--moco", - default=None, - help="Motion-correction folder (default: /motion_correction).", - ) - parser.add_argument( - "--device", - default="cpu", - help="'cpu' (default), 'auto', 'cuda' or 'cuda:N'.", - ) - parser.add_argument( - "--overwrite", - action="store_true", - help="Write layout files that exist again.", - ) - for name in ("paths", "trials"): - parser.add_argument( - f"--{name}", - type=lambda v: [int(x) for x in v.split(",") if x], - default=None, - help=f"One-based {name}, comma-separated (default: all).", - ) - - -def run_command(args: argparse.Namespace) -> int: - """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( - args.trial_table, - args.out, - datadr=args.datadr, - moco=args.moco, - device=args.device, - overwrite=args.overwrite, - paths=args.paths, - trials=args.trials, - ) - failed = [r for r in results if r["error"] is not None] - print( - f"giant export-f0-layout: {len(results) - len(failed)} of " - f"{len(results)} trials written or kept." - ) - for r in failed: - print(f" failed: {r['out']}: {r['error']}") - return 1 if failed else 0 +"""Raster layout of registered trials, for the F0 network's simulator. + +A registered frame is linear in the raw samples: frame formation gives each +raw pixel the weighted mean of its samples around the frame's line time, and +registration resamples the raw pixels by the frame's rigid shift +(:mod:`giant_python.registration.frames`, +:mod:`giant_python.registration.interpolation`). The simulator of +`slap2-F0-network `_ +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: + +* 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 + with it) and how the trial's frames were formed + (frame lines, kernel, the frames' motion, the registration window); +* each slot's mean and share of zeros, per channel; +* the events of the trial: a library of measured bursts (one to four + consecutive non-zero samples), how often each type of burst occurs at + different brightness, the variance and covariance of consecutive samples + by brightness, and histograms of the pulse heights and of how a pulse is + split between a sample and the next one on its line. + +:func:`reference_frames` forms registered frames from such a file and the +samples of its slots. It states what the file means and is checked against +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 +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). + +Conventions: arrays as h5py reads them, in NumPy's orientation. Slot lines +and frame lines are one-based, as everywhere in GIAnT; cycles, pixel +positions and slot indices are zero-based. +""" + +from __future__ import annotations + +import argparse +import logging +import time +from collections.abc import Sequence +from pathlib import Path +from typing import TYPE_CHECKING + +import h5py +import numpy as np + +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).""" + +READABLE_VERSIONS = (3, 4) +"""Versions :func:`read_layout` reads. A version 3 file (registrations +without online compensation only) gets its slots' positions from its pixel +list.""" + +HEIGHT_BINS = 1024 +"""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.""" + +DIM_ZERO_SHARE = 0.95 +"""A pair of consecutive samples counts as dim when both are zero in at +least this share of its cycles. A pulse of the pair's earlier slot then +coincides with one of the later slot's own in at most about 2.5% of its +cycles, usually far fewer; such a coincidence is counted as one split pulse. +Brighter pairs are never used: a recording without dim pairs gets empty +histograms.""" + +MIN_PAIR_CYCLES = 100 +"""A pair needs this many cycles with both samples valid.""" + +PAIR_CHUNK = 2048 +"""Pairs whose samples are compared at once.""" + +BURST_MAX = 4 +"""Longest burst kept in the library, in samples.""" + +BURST_EXAMPLES = 8192 +"""Most examples kept of each burst length, per channel.""" + +BURST_LEVEL = 2.0 +"""Examples of bursts are kept from chains whose mean sample is below this +(raw units; about one event in 100 samples), where unrelated events rarely +touch (they would be read as one longer burst).""" + +STRATA_EDGES = (0.0, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0) +"""Edges of the brightness strata of the burst counts: a chain's mean sample +in raw units. Brighter chains are not counted.""" + +BURST_BLOCK = 8 +"""Cycles per block. A chain's level is its mean over every second block and +its bursts are counted in the other blocks, then the other way round, so +that a chain is not placed among the dim ones because it happened to have +few events where they are counted.""" + +MIN_BLOCK_CYCLES = 50 +"""A chain needs this many valid cycles in the blocks that give its level.""" + +CELL_STEPS = (10, 20, 50, 100) +"""Step of the total (raw units) in the cells of bursts of 1, 2, 3 and 4 +samples (:func:`burst_cells`).""" + +CELL_BINS = (41, 31, 17, 11) +"""Bins of the total for each length; the last holds every larger total.""" + +CELL_SHARES = 3 +"""Bins of the smaller part's share of a burst of two samples.""" + +_CELL_COUNTS = (CELL_BINS[0], CELL_BINS[1] * CELL_SHARES, *CELL_BINS[2:]) + +N_CELLS = sum(_CELL_COUNTS) +"""Number of burst cells.""" + +LEVEL_EDGES = tuple(float(0.5 * 2 ** (i / 2)) for i in range(19)) +"""Edges of the brightness levels of the sample moments: a chain's mean +sample, 0.5 to 256 raw units in steps of a factor of the square root of +2.""" + +LEVEL_LAGS = 8 +"""The sample moments reach this many samples along the line.""" + +LEVEL_CHUNK = 1024 +"""Chains whose samples are compared at once.""" + +MIN_REVISITS = 1000 +"""With fewer chains whose pixels are visited again within the cycle, the +sample moments are measured against the next cycle.""" + +_REGISTERED = "_REGISTERED_DOWNSAMPLED-" + + +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 + split between them only where the scan runs on from one pixel to its + neighbour. Where it jumps to another part of the raster (from one ROI + to the next), the two samples share nothing: on a GFP recording + (847983) consecutive samples of neighbouring pixels correlate by + 0.17-0.22, those across a jump by -0.01. + + Parameters + ---------- + layout : RasterLayout + The recording's layout. + + Returns + ------- + nxt : ndarray of int + For each slot, the slot that shares pulses with it: the one sampled + right after it on its line if that is a pixel within one row and + one column of its own, else -1. + start, end : ndarray of bool + 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. + """ + from ..registration.stats.gain import next_slots + + nxt = next_slots(layout.slot_line, layout.slot_pos) + row = (layout.slot_pixel - 1) // layout.n_cols + col = (layout.slot_pixel - 1) % layout.n_cols + to = np.maximum(nxt, 0) + near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) + jump = (nxt >= 0) & ~near + after_jump = np.zeros(nxt.size, dtype=bool) + after_jump[nxt[jump]] = True + last_pos = layout.n_per_channel[layout.slot_line - 1] - 1 + start = (layout.slot_pos == 0) | after_jump + end = (layout.slot_pos == last_pos) | jump + return np.where(jump, -1, nxt), start, end + + +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. + + Returns + ------- + Path + The layout file, in the movie's folder. + """ + p = Path(movie_path) + if _REGISTERED in p.name: + return p.with_name(p.name.split(_REGISTERED, 1)[0] + "_F0LAYOUT.h5") + return p.with_name(f"{p.stem}_F0LAYOUT.h5") + + +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. + + Returns + ------- + dict + mean and zero_share (channels, slots) float32 over each + slot's valid samples (NaN without any) and valid_share + (channels, slots) float32. + """ + import torch + + n_ch, n_slots, n_cycles = samples.shape + out = { + k: np.full((n_ch, n_slots), np.nan, np.float32) + for k in ("mean", "zero_share", "valid_share") + } + step = max(1, 4_000_000 // max(1, n_cycles)) + for ch in range(n_ch): + for a in range(0, n_slots, step): + x = samples[ch, a : a + step] + ok = x != INVALID_SAMPLE + n = ok.sum(1).to(torch.float64) + total = torch.where(ok, x, 0).to(torch.int64).sum(1) + zeros = (ok & (x == 0)).sum(1).to(torch.float64) + some = (n > 0).cpu().numpy() + n_np = n.cpu().numpy() + sl = slice(a, a + x.shape[0]) + out["valid_share"][ch, sl] = n_np / max(1, n_cycles) + mean = np.full(x.shape[0], np.nan) + zero = np.full(x.shape[0], np.nan) + mean[some] = total.cpu().numpy()[some] / n_np[some] + zero[some] = zeros.cpu().numpy()[some] / n_np[some] + out["mean"][ch, sl] = mean + out["zero_share"][ch, sl] = zero + return out + + +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 + 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 + two slots' rates. + + Split events are of two kinds, which the joint histogram of height and + fraction keeps apart: one pulse on the boundary between the two + samples (any fraction, the height of an unsplit pulse), and two pulses, + one in each sample (about twice the height, a fraction near one half). + On two recordings three in ten split events are of the second kind, far + 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 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 + 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 + concerned, -32768 where invalid. + nxt : ndarray of int + Each slot's next slot on its line, -1 for none + (:func:`sharing_slots`, or + :func:`giant_python.registration.stats.gain.next_slots` for lines of + neighbouring raster pixels only). + line_end : ndarray of bool, optional + Whether nothing follows each slot that could share a pulse with it + (:func:`sharing_slots`). Default: a slot without a next ends its + run. + + 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 + 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 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. + """ + import torch + + n_ch, n_slots, _n_cycles = samples.shape + nxt = np.asarray(nxt, dtype=np.int64) + first = np.flatnonzero(nxt >= 0) + second = nxt[first] + prev = np.full(n_slots, -1, dtype=np.int64) + prev[second] = first + before, after = prev[first], nxt[second] + # the sample before the pair must be seen; the one after it must be + # seen or not exist + seen = before >= 0 + if line_end is not None: + seen &= (after >= 0) | np.asarray(line_end, dtype=bool)[second] + first, second = first[seen], second[seen] + before, after = before[seen], after[seen] + out = { + "height_single": np.zeros((n_ch, HEIGHT_BINS), np.int64), + "height_split": np.zeros((n_ch, HEIGHT_BINS), np.int64), + "split_fraction": np.zeros((n_ch, SPLIT_BINS), np.int64), + "split_joint": np.zeros((n_ch, JOINT_BINS, SPLIT_BINS), np.int64), + "pairs": np.zeros(n_ch, np.int64), + "pair_cycles": np.zeros(n_ch, np.int64), + } + if first.size == 0: + return out + dev = samples.device + + 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) + + for ch in range(n_ch): + both_zero = np.zeros(first.size) + n_valid = np.zeros(first.size) + for a in range(0, first.size, PAIR_CHUNK): + sl = slice(a, a + PAIR_CHUNK) + xa, xb = rows(ch, first[sl]), rows(ch, second[sl]) + ok = (xa != INVALID_SAMPLE) & (xb != INVALID_SAMPLE) + n = ok.sum(1).to(torch.float64) + 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)) + 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) + xa = torch.where(alone, xa, 0).to(torch.int64) + xb = torch.where(alone, xb, 0).to(torch.int64) + height = xa + xb + cycles += int(alone.sum()) + split = (xa > 0) & (xb > 0) + single = (xa > 0) & (xb == 0) + for key, mask in ( + ("height_single", single), + ("height_split", split), + ): + h = height[mask].clamp(1, HEIGHT_BINS) - 1 + 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() + 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() + out["pair_cycles"][ch] = cycles + return out + + +def burst_cells(parts: np.ndarray) -> np.ndarray: + """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 + total in steps of 20 (31 bins) and by the smaller part's share of it + (three equal bins over 0 to 0.5); a burst of three by its total in + steps of 50 (17 bins); a burst of four in steps of 100 (11 bins). The + cells are numbered in that order: 0-40, 41-133 (total bin x 3 + share + bin), 134-150 and 151-161. + + Parameters + ---------- + parts : ndarray + (bursts, length) samples of bursts of one length (1-4). + + Returns + ------- + ndarray of int64 + (bursts,) cell of each burst. + """ + parts = np.asarray(parts, dtype=np.float64) + n = parts.shape[1] + total = parts.sum(1) + first = int(np.sum(_CELL_COUNTS[: n - 1])) + bins = (total // CELL_STEPS[n - 1]).astype(np.int64) + bins = np.clip(bins, 0, CELL_BINS[n - 1] - 1) + if n != 2: + return first + bins + share = parts.min(1) / np.maximum(total, 1e-9) + part = np.minimum((share * 2 * CELL_SHARES).astype(np.int64), 2) + return first + bins * CELL_SHARES + part + + +def _keep_bursts(out: dict, ch: int, found: list) -> None: + """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 + parts = np.concatenate([p for p, _ in items]) + cell = np.concatenate([c for _, c in items]) + if parts.shape[0] == 0: + continue + keep = min(BURST_EXAMPLES, parts.shape[0]) + pick = np.linspace(0, parts.shape[0] - 1, keep).round().astype(int) + out[f"burst_{n}"][ch, :keep] = parts[pick] + out[f"burst_cell_{n}"][ch, :keep] = cell[pick] + out["burst_examples"][ch, n - 1] = keep + + +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()) + rest = ok & ~use + n_rest = rest.sum(1) + level = (sum(xs) * rest).sum(1).to(torch.float64) + level = level / (len(xs) * n_rest.clamp(min=1)) + stratum = torch.bucketize(level, edges, right=True) + stratum[n_rest < MIN_BLOCK_CYCLES] = n_s + st = stratum.cpu().numpy() + inside = st < n_s + lib = inside & (level.cpu().numpy() < BURST_LEVEL) + good = ok & use + free = good & (xs[0] == 0) + + 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) + + out["strata_free"][ch] += per_stratum(free.sum(1)).astype(np.int64) + sums[0] += per_stratum((xs[1] * good).sum(1)) + sums[1] += per_stratum(good.sum(1)) + going = free & (xs[1] > 0) + going &= torch.from_numpy(inside).to(free.device)[:, None] + for n in range(1, BURST_MAX + 1): + ends = going & (xs[n + 1] == 0) + if ends.any(): + rows, cols = torch.nonzero(ends, as_tuple=True) + parts = torch.stack([x[rows, cols] for x in xs[1 : n + 1]], 1) + parts = parts.cpu().numpy() + rows = rows.cpu().numpy() + cell = burst_cells(parts) + np.add.at(out["strata_bursts"][ch], (st[rows], cell), 1) + keep = lib[rows] + out["burst_counts"][ch, n - 1] += int(keep.sum()) + found[n - 1].append((parts[keep].astype(np.int16), cell[keep])) + going = going & (xs[n + 1] > 0) + longer = going.sum(1) + out["strata_longer"][ch] += per_stratum(longer).astype(np.int64) + out["burst_counts"][ch, BURST_MAX] += int(longer.cpu().numpy()[lib].sum()) + + +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 + samples, and groups of pulses that follow each other (two in three in a + hundred events span three samples on two recordings, far more than + unrelated pulses would). What matters to the noise of a frame is how an + event's parts are divided between consecutive samples, so the library + keeps whole bursts as they were recorded, by length. + + A burst starts in a slot whose sample is non-zero while the sample + before it is zero, and runs on along the line until a sample is zero. + Bursts are taken from chains of six consecutive slots (the one before + the start and five from it), in cycles where all six are valid. Bursts + longer than :data:`BURST_MAX` are counted only. + + Not every event is a photon of the tissue: some occur at a rate that + does not depend on brightness, and they are smaller (on 847983 about + 1 300 per million samples, mostly 60-110 raw units in total, against a + photon peak at 100-120). They make up a sixth of the events of the + dimmest chains and a hundredth at 10 raw units per sample, so a library + of dim chains alone misstates the photon events. The counts by stratum + let a reader separate the two: per type of burst + (:func:`burst_cells`), the rate rises linearly with the stratum's mean + for photon events and is constant for the others. + + A chain's stratum is its mean sample over every second block of + :data:`BURST_BLOCK` cycles; its bursts are counted in the other blocks, + and then the other way round. Examples are kept from chains below + :data:`BURST_LEVEL`. + + Parameters + ---------- + samples : torch.Tensor of int16 + (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 + 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. + """ + import torch + + n_ch, n_slots, n_cycles = samples.shape + nxt = np.asarray(nxt, dtype=np.int64) + prev = np.full(n_slots, -1, dtype=np.int64) + prev[nxt[nxt >= 0]] = np.flatnonzero(nxt >= 0) + n_s = len(STRATA_EDGES) - 1 + out = { + "burst_counts": np.zeros((n_ch, BURST_MAX + 1), np.int64), + "burst_examples": np.zeros((n_ch, BURST_MAX), np.int64), + "strata_edges": np.asarray(STRATA_EDGES, dtype=np.float64), + "strata_free": np.zeros((n_ch, n_s), np.int64), + "strata_mean": np.zeros((n_ch, n_s), np.float64), + "strata_bursts": np.zeros((n_ch, n_s, N_CELLS), np.int64), + "strata_longer": np.zeros((n_ch, n_s), np.int64), + } + for n in range(1, BURST_MAX + 1): + out[f"burst_{n}"] = np.zeros((n_ch, BURST_EXAMPLES, n), np.int16) + out[f"burst_cell_{n}"] = np.zeros((n_ch, BURST_EXAMPLES), np.int16) + # chains: the slot before the start, the start and the four after it + chain = [prev, np.arange(n_slots)] + for _ in range(BURST_MAX): + last = chain[-1] + chain.append(np.where(last >= 0, nxt[np.maximum(last, 0)], -1)) + starts = np.flatnonzero(np.all([c >= 0 for c in chain], axis=0)) + dev = samples.device + edges = torch.tensor(STRATA_EDGES[1:], dtype=torch.float64, device=dev) + odd = (torch.arange(n_cycles, device=dev) // BURST_BLOCK) % 2 == 1 + for ch in range(n_ch): + found = [[] for _ in range(BURST_MAX)] + 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] + ok = xs[0] != INVALID_SAMPLE + for x in xs[1:]: + ok &= x != INVALID_SAMPLE + for use in (odd, ~odd): + _count_bursts(out, ch, xs, ok, use, edges, found, sums) + out["strata_mean"][ch] = sums[0] / np.maximum(sums[1], 1) + _keep_bursts(out, ch, found) + return out + + +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 + 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]: + the slot of that pixel's next visit, the visits forming a chain of + 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 + chain. + """ + n = nxt.size + chain = [np.arange(n)] + for _ in range(LEVEL_LAGS): + last = chain[-1] + chain.append(np.where(last >= 0, nxt[np.maximum(last, 0)], -1)) + whole = np.all([c >= 0 for c in chain], axis=0) + # each slot's first visit of the same pixel on a later line + pixel = np.asarray(pixel, dtype=np.int64) + key = pixel * (int(np.max(line, initial=0)) + 1) + line + order = np.argsort(key, kind="stable") + later = np.searchsorted(key[order], key, side="right") + cand = order[np.minimum(later, max(n - 1, 0))] if n else order + found = (later < n) & (pixel[cand] == pixel) & (pixel >= 0) + again = np.where(found, cand, -1) + other = [np.where(c >= 0, again[np.maximum(c, 0)], -1) for c in chain] + fine = whole & np.all([o >= 0 for o in other], axis=0) + for k in range(LEVEL_LAGS): + fine &= nxt[np.maximum(other[k], 0)] == other[k + 1] + if fine.sum() >= MIN_REVISITS: + return [c[fine] for c in chain], [o[fine] for o in other] + return [c[whole] for c in chain], None + + +def level_statistics( + 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. + + 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 + 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. + + Parameters + ---------- + samples : torch.Tensor of int16 + (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 + Each slot's pixel and line within the cycle. A negative pixel marks + a slot that is not to count as a visit (a slot of another plane). + + 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): + 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 + the next visit within the cycle, 0 if the next cycle. + """ + import torch + + n_ch = samples.shape[0] + nxt = np.asarray(nxt, dtype=np.int64) + chain, other = _second_visits(nxt, np.asarray(pixel), np.asarray(line)) + shift = 0 if other is not None else 1 + if other is None: + other = chain + n_l = len(LEVEL_EDGES) - 1 + out = { + "level_edges": np.asarray(LEVEL_EDGES, dtype=np.float64), + "level_samples": np.zeros((n_ch, n_l), np.int64), + "level_mean": np.zeros((n_ch, n_l), np.float64), + "level_zero": np.zeros((n_ch, n_l), np.float64), + "level_moments": np.zeros((n_ch, n_l, LEVEL_LAGS + 1), np.float64), + "level_revisits": np.uint8(shift == 0), + } + dev = samples.device + edges = torch.tensor(LEVEL_EDGES, dtype=torch.float64, device=dev) + for ch in range(n_ch): + acc = np.zeros((n_l, LEVEL_LAGS + 4)) + for a in range(0, chain[0].size, LEVEL_CHUNK): + sl = slice(a, a + LEVEL_CHUNK) + xs = [samples[ch, torch.from_numpy(c[sl]).to(dev)] for c in chain] + ys = [samples[ch, torch.from_numpy(c[sl]).to(dev)] for c in other] + if shift: + xs = [x[:, :-shift] for x in xs] + ys = [y[:, shift:] for y in ys] + ok = xs[0] != INVALID_SAMPLE + for v in xs[1:] + ys: + ok &= v != INVALID_SAMPLE + zeros = ((xs[0] == 0) & ok).sum(1) + ((ys[0] == 0) & ok).sum(1) + xs = [x.to(torch.float64) * ok for x in xs] + ys = [y.to(torch.float64) * ok for y in ys] + n = ok.sum(1) + sx = sum(x.sum(1) for x in xs) + sy = sum(y.sum(1) for y in ys) + level = (sx + sy) / (2 * len(xs) * n.clamp(min=1)) + b = torch.bucketize(level, edges, right=True) - 1 + good = (b >= 0) & (b < n_l) & (n >= MIN_PAIR_CYCLES) + good &= (sx > 0) & (sy > 0) + ratio = torch.ones_like(sx) if shift else sx / sy.clamp(min=1e-9) + cols = [n.to(torch.float64), (xs[0] + ys[0]).sum(1) / 2] + cols.append(zeros.to(torch.float64) / 2) + for k in range(LEVEL_LAGS + 1): + within = (xs[0] * xs[k]).sum(1) + (ys[0] * ys[k]).sum(1) + across = (xs[0] * ys[k]).sum(1) * ratio + across = across + (ys[0] * xs[k]).sum(1) / ratio.clamp(1e-9) + cols.append((within - across) / 2) + 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) + n = np.maximum(acc[:, 0], 1) + out["level_samples"][ch] = acc[:, 0].astype(np.int64) + out["level_mean"][ch] = acc[:, 1] / n + out["level_zero"][ch] = acc[:, 2] / n + out["level_moments"][ch] = acc[:, 3:] / n[:, None] + return out + + +def trial_layout( + dat: str | Path, + first_line: float, + last_line: float, + adata: str | Path, + settings: dict | None = None, + device: str = "cpu", +) -> dict: + """Build the layout record of one registered trial and path. + + Parameters + ---------- + dat : str or Path + The trial's raw recording. + first_line, last_line : float + The trial's line range (trial table). + adata : str or Path + The trial's alignment file. + settings : dict, optional + The trial table's registration settings, for registrations that do + not record their own (GIAnT-MATLAB's). + device : str + Where the samples are held. + + Returns + ------- + dict + attrs and the arrays :func:`write_layout` stores. + + Raises + ------ + ValueError + For a registration whose frame times, window or online compensation + differ from the alignment file's. + """ + 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) + former, win = source.former, source.window + h, w = win.shape + pad_r, pad_c = al["out_shape"][0] - h, al["out_shape"][1] - w + if pad_r != pad_c or pad_r < 0 or pad_r % 2: + raise ValueError( + f"{adata}: registered frame {al['out_shape']} does not fit the " + f"window {(h, w)} with an equal margin on every side" + ) + # 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() + 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) + in_cols = former.cols[inside] - (int(win.trim_cols[0]) - 1) + plane = layout.line_fast_z[layout.slot_line - 1] == former.z_idx + at = np.minimum(np.searchsorted(ids, layout.slot_pixel), ids.size - 1) + slots = np.flatnonzero(plane & (ids[at] == layout.slot_pixel)) + nxt_all, _, line_end = sharing_slots(layout) + renumber = np.full(layout.slot_line.size, -1, dtype=np.int64) + renumber[slots] = np.arange(slots.size) + 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)]) + shared = np.where(plane, nxt_all, -1) + pulses = pulse_statistics(samples, shared, line_end) + pulses.update(burst_statistics(samples, shared)) + pulses.update( + level_statistics( + samples, + shared, + np.where(plane, layout.slot_pixel, -1), + layout.slot_line, + ) + ) + p = layout.lines_per_cycle + dt = int(source.dt) + attrs = { + "layout_version": LAYOUT_VERSION, + "recording": Path(dat).name, + "alignment": Path(adata).name, + "lines_per_cycle": int(p), + "line_period_s": float(layout.line_period_s), + "total_lines": int(layout.total_lines), + "dmd_rows": int(layout.n_rows), + "dmd_cols": int(layout.n_cols), + "num_channels": int(layout.num_channels), + "align_hz": float(al["align_hz"]), + "kernel_dt_lines": dt, + "reach_lines": int(max(3 * dt, p)), + "cycle0": int(former.cycle0), + "n_cycles": int(former.n_cycles), + "first_line": float(first_line), + "last_line": float(last_line), + "window_row0": int(win.trim_rows[0]) - 1, + "window_col0": int(win.trim_cols[0]) - 1, + "window_rows": int(h), + "window_cols": int(w), + "margin": int(pad_r // 2), + "unlit_masked": bool(al["unlit_masked"]), + "compensated": comp, + "dim_zero_share": DIM_ZERO_SHARE, + "burst_level": BURST_LEVEL, + } + win_rows = win.rows.cpu().numpy().astype(np.int64) + win_cols = win.cols.cpu().numpy().astype(np.int64) + slot_rows, slot_cols = in_rows[at[slots]], in_cols[at[slots]] + extra = {} + if comp: + # the pixels that frames report are those a sample can land on; + # a slot's own raster pixel need not be one of them + lookup = np.full(h * w, -1, dtype=np.int64) + lookup[win_rows * w + win_cols] = np.arange(win_rows.size) + slot_pixel = lookup[slot_rows * w + slot_cols] + off = source.compensation + a = int(former.cycle0) * int(p) + b = a + int(former.n_cycles) * int(p) + attrs["y_lead"] = np.asarray(off.y_lead, dtype=np.int64) + extra = { + "lines/x": off.x[a:b].astype(np.int16), + "lines/y_eff": off.y_eff[a:b].astype(np.int16), + "frames/ref_xy": np.asarray(source.references(ds), np.int16), + } + else: + slot_pixel = at[slots] + return { + "attrs": attrs, + "frames/lines": np.asarray(ds, dtype=np.int64), + "frames/motion": np.asarray(al["motion"], dtype=np.float64), + **extra, + "slots/index": slots.astype(np.int64), + "slots/line": layout.slot_line[slots].astype(np.int32), + "slots/pos": layout.slot_pos[slots].astype(np.int32), + "slots/pixel": slot_pixel.astype(np.int32), + "slots/row": slot_rows.astype(np.int32), + "slots/col": slot_cols.astype(np.int32), + "slots/next": nxt.astype(np.int32), + "slots/line_end": line_end[slots].astype(np.uint8), + "slots/mean": stats["mean"], + "slots/zero_share": stats["zero_share"], + "slots/valid_share": stats["valid_share"], + "pixels/row": win_rows.astype(np.int32), + "pixels/col": win_cols.astype(np.int32), + **{f"photon/{k}": v for k, v in pulses.items()}, + } + + +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. + """ + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".partial") + try: + with h5py.File(tmp, "w") as f: + for key, value in record["attrs"].items(): + f.attrs[key] = value + for key, value in record.items(): + if key == "attrs": + continue + arr = np.asarray(value) + f.create_dataset( + key, + data=arr, + compression="gzip" if arr.size > 64 else None, + shuffle=arr.size > 64, + ) + tmp.replace(path) + finally: + if tmp.exists(): + tmp.unlink() + + +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 + 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 {READABLE_VERSIONS}" + ) + out["attrs"] = { + k: (v.item() if isinstance(v, np.generic) else v) for k, v in f.attrs.items() + } + + def visit(name: str, obj: h5py.HLObject) -> None: + """Collect every dataset.""" + if isinstance(obj, h5py.Dataset): + out[name] = obj[()] + + f.visititems(visit) + if "slots/row" not in out: # version 3: the slots' own pixels are listed + pix = out["slots/pixel"].astype(np.int64) + out["slots/row"] = out["pixels/row"][pix] + out["slots/col"] = out["pixels/col"][pix] + return out + + +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 + out[:, (cols < 0) | (cols >= w)] = np.nan + return out + + +def reference_frames( + layout: dict, samples: np.ndarray, frames: Sequence[int] | None = None +) -> np.ndarray: + """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 + 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 + window + 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. + + Parameters + ---------- + 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; + -32768 marks invalid samples. + frames : sequence of int, optional + Zero-based frames to form (default: all). + + Returns + ------- + ndarray of float64 + (channels, frames, window_rows + 2 margin, window_cols + 2 + margin). + """ + at = layout["attrs"] + p, dt, reach = ( + at["lines_per_cycle"], + at["kernel_dt_lines"], + at["reach_lines"], + ) + h, w, m = at["window_rows"], at["window_cols"], at["margin"] + lines = layout["frames/lines"] + motion = layout["frames/motion"] + slot_line = layout["slots/line"].astype(np.int64) + slot_r = layout["slots/row"].astype(np.int64) + slot_c = layout["slots/col"].astype(np.int64) + comp = bool(at.get("compensated", False)) + if comp: + 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 + 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) + out = np.full((n_ch, index.size, h + 2 * m, w + 2 * m), np.nan) + cycles = at["cycle0"] + np.arange(n_cycles) + for k, i in enumerate(index): + t = int(lines[i]) + 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)) + 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) + # where each sample goes: its slot's pixel, moved by its line's + # online offset less the frame's own (rows follow y, columns x) + rows = np.broadcast_to(slot_r[:, None], line.shape) + cols = np.broadcast_to(slot_c[:, None], line.shape) + if comp: + at_line = line - 1 - at["cycle0"] * p + rows = rows + off_y[at_line] - ref[i, 1] + cols = cols + off_x[at_line] - ref[i, 0] + landed = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w) + dest = np.where(landed, rows * w + cols, 0).ravel() + num = np.zeros((n_ch, h * w)) + den = np.zeros((n_ch, h * w)) + for ch in range(n_ch): + ok = valid[ch][:, near] & landed + wv = np.where(ok, wgt, 0.0) + np.add.at(num[ch], dest, (wv * x[ch][:, near]).ravel()) + np.add.at(den[ch], dest, wv.ravel()) + with np.errstate(invalid="ignore", divide="ignore"): + raw = np.where(den > 0, num / den, np.nan).reshape(n_ch, h, w) + fresh = den[0].reshape(h, w) + # the output grid's positions in the window (zero-based) + pos_r = np.arange(h + 2 * m) - m + float(motion[i, 0]) + pos_c = np.arange(w + 2 * m) - m + float(motion[i, 1]) + fr = pos_r[0] - np.floor(pos_r[0]) + fc = pos_c[0] - np.floor(pos_c[0]) + r_lo, r_hi = np.floor(pos_r).astype(int), np.ceil(pos_r).astype(int) + c_lo, c_hi = np.floor(pos_c).astype(int), np.ceil(pos_c).astype(int) + corners = ( + (r_lo, c_lo, (1 - fc) * (1 - fr)), + (r_lo, c_hi, fc * (1 - fr)), + (r_hi, c_lo, (1 - fc) * fr), + (r_hi, c_hi, fc * fr), + ) + den_out = np.zeros((h + 2 * m, w + 2 * m)) + num_out = np.zeros((n_ch, h + 2 * m, w + 2 * m)) + for rows, cols, coef in corners: + cf = coef * _corner_values(fresh, rows, cols) + den_out += cf + for ch in range(n_ch): + num_out[ch] += cf * _corner_values(raw[ch], rows, cols) + with np.errstate(invalid="ignore", divide="ignore"): + out[:, k] = num_out / den_out + return out + + +def export_layouts( + trial_table: str | Path, + out_dir: str | Path | None = None, + *, + datadr: str | Path | None = None, + moco: str | Path | None = None, + device: str = "cpu", + overwrite: bool = False, + 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). + 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 + each trial's samples are held. + overwrite : bool + Write files that exist again. + paths, trials : sequence of int, optional + One-based paths (DMDs) and trials (default: all). + + Returns + ------- + list of dict + 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 + from ..pipeline.register import recorded_cells + from ..registration.multiroi import resolve_device + + path = Path(trial_table) + tt = read_trial_table(path) + if tt.slap2_info is None: + raise ValueError("the trial table has no slap2_info") + files = np.atleast_2d(np.asarray(tt.filename, dtype=object)) + shape = files.shape + mc = tt.motion_correction or {} + fn_reg = _grid(mc.get("fn_reg_ds", np.full(shape, "")), shape) + fn_ad = _grid(mc.get("fn_adata", np.full(shape, "")), shape) + first = np.asarray(tt.slap2_info.first_line, float).reshape(shape) + last = np.asarray(tt.slap2_info.last_line, float).reshape(shape) + present = recorded_cells(files) & recorded_cells(fn_reg) + present &= _selected(shape, paths, trials) + moco = Path(moco) if moco else Path(tt.savedr) / "motion_correction" + datadr = Path(datadr) if datadr else Path(tt.datadr) + settings = _table_settings(path) + dev = str(resolve_device(device)) + results = [] + for d, t in zip(*np.nonzero(present)): + movie, adata = moco / str(fn_reg[d, t]), moco / str(fn_ad[d, t]) + out = layout_path(movie) + if out_dir is not None: + out = Path(out_dir) / out.name + res = {"out": str(out), "error": None, "seconds": 0.0} + results.append(res) + if out.exists() and not overwrite: + log.info("%s exists; skipping", out.name) + continue + start = time.perf_counter() + try: + if not adata.exists(): + raise FileNotFoundError(f"{adata.name} is missing") + record = trial_layout( + datadr / str(files[d, t]), + float(first[d, t]), + float(last[d, t]), + adata, + settings, + dev, + ) + record["attrs"]["path"] = int(d) + 1 + record["attrs"]["trial"] = int(t) + 1 + write_layout(out, record) + except Exception as exc: # reported per trial + log.exception("layout failed for %s", movie.name) + res["error"] = repr(exc) + res["seconds"] = time.perf_counter() - start + return results + + +def add_arguments(parser: argparse.ArgumentParser) -> None: + """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).", + ) + parser.add_argument( + "--datadr", + default=None, + help="Raw-data folder, if it moved since the table was written.", + ) + parser.add_argument( + "--moco", + default=None, + help="Motion-correction folder (default: /motion_correction).", + ) + parser.add_argument( + "--device", + default="cpu", + help="'cpu' (default), 'auto', 'cuda' or 'cuda:N'.", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="Write layout files that exist again.", + ) + for name in ("paths", "trials"): + parser.add_argument( + f"--{name}", + type=lambda v: [int(x) for x in v.split(",") if x], + default=None, + help=f"One-based {name}, comma-separated (default: all).", + ) + + +def run_command(args: argparse.Namespace) -> int: + """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( + args.trial_table, + args.out, + datadr=args.datadr, + moco=args.moco, + device=args.device, + overwrite=args.overwrite, + paths=args.paths, + trials=args.trials, + ) + failed = [r for r in results if r["error"] is not None] + print( + f"giant export-f0-layout: {len(results) - len(failed)} of " + f"{len(results)} trials written or kept." + ) + for r in failed: + print(f" failed: {r['out']}: {r['error']}") + return 1 if failed else 0 diff --git a/src/giant_python/export/f0_mask.py b/src/giant_python/export/f0_mask.py index 2e74c868..13603eb2 100644 --- a/src/giant_python/export/f0_mask.py +++ b/src/giant_python/export/f0_mask.py @@ -1,287 +1,287 @@ -"""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 -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 - nearest 80 Hz frame and widened on both sides by - 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 - 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. - -The numbers were chosen on the GFP control 847983 with injected events -(GIAnT-Python export docs, f0_export.rst). -""" - -from __future__ import annotations - -from dataclasses import dataclass - -import numpy as np -from numpy.typing import ArrayLike -from scipy import ndimage, sparse - -SPOT_MODES = ("none", "seeds") - - -@dataclass(frozen=True) -class MaskRule: - """The activity mask's rule. - - Attributes - ---------- - k : float - 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 - Forward widening after each crossing, in decay constants of the - activity channel (2: 48 ms for iGluSnFR4f's 24 ms). - share_frames : int - 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'. - """ - - k: float = 3.0 - margin_px: float = 1.0 - widen_tau: float = 2.0 - share_frames: int = 6 - spots: str = "none" - - def check(self) -> None: - """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: - 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: - """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), - "activityMaskWidenTau": float(self.widen_tau), - "activityMaskShareFrames": int(self.share_frames), - "activityMaskSpots": self.spots, - } - - -def robust_sd(x: np.ndarray) -> float: - """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: - return np.nan - return 1.4826 * float(np.median(np.abs(x - np.median(x)))) - - -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: 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: - return np.zeros(x.size, np.int64) - i = np.clip(np.searchsorted(ds, x), 1, ds.size - 1) - left = x - ds[i - 1] < ds[i] - x - return np.where(left, i - 1, i).astype(np.int64) - - -def temporal_mask( - den: ArrayLike, - sigma: np.ndarray, - lines200: ArrayLike, - discard200: ArrayLike, - ds_lines: ArrayLike, - rule: MaskRule, - tau200: float, -) -> np.ndarray: - """Mask each source's 80 Hz frames, (sources, frames80) bool. - - Parameters - ---------- - den : ndarray (frames200, sources) - 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). - rule : MaskRule - tau200 : float - The activity channel's decay constant in 200 Hz frames (SILo's - 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 - T = np.asarray(ds_lines).size - out = np.zeros((n, T), bool) - if n == 0 or den.shape[0] == 0: - return out - L = int(round(rule.widen_tau * float(tau200))) - near = nearest_frames(ds_lines, lines200) - keep = ~np.asarray(discard200, bool) - share = np.ones(2 * int(rule.share_frames) + 1, bool) - sig = np.where(np.isfinite(sigma), sigma, np.inf) - i = np.arange(den.shape[0]) - for s in range(n): - above = (den[:, s] > rule.k * sig[s]) & keep - if not above.any(): - continue - if L > 0: # forward: any crossing in the last L frames - c = np.concatenate([[0], np.cumsum(above)]) - above = (c[i + 1] - c[np.maximum(0, i - L)]) > 0 - f = np.zeros(T, bool) - f[near[above]] = True - out[s] = ndimage.binary_dilation(f, share) if share.size > 1 else f - return out - - -def _disk(r: float) -> np.ndarray: - """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: sparse.spmatrix | None, - tm: np.ndarray | None, - shape: tuple, - crop: tuple, - rule: MaskRule, - spots_rc: np.ndarray | None = None, - n_frames: int = 0, -) -> np.ndarray: - """Build the trial's activity mask in the crop. - - (frames, rows, cols) uint8 (1: the loss is zeroed). - - Parameters - ---------- - H : sparse (pixels, sources) or None - The footprints in the trial frame (as the activity is placed). - tm : ndarray (sources, frames) or None - :func:`temporal_mask`. - shape : tuple - (rows, cols) of the trial frame. - crop : tuple - (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 - T = tm.shape[1] if tm is not None else int(n_frames) - out = np.zeros((T, r1 - r0, c1 - c0), np.uint8) - m = float(rule.margin_px) - se = _disk(m) if m > 0 else None - pad = int(np.ceil(m)) - if H is not None and tm is not None and tm.size: - Hc = H.tocsc() - for j in range(Hc.shape[1]): - fr = np.flatnonzero(tm[j]) - pix = Hc.indices[Hc.indptr[j] : Hc.indptr[j + 1]] - if fr.size == 0 or pix.size == 0: - continue - rr, cc = np.divmod(pix, C) - if se is not None: # dilate in the footprint's own box - a0, a1 = max(0, rr.min() - pad), min(R, rr.max() + pad + 1) - b0, b1 = max(0, cc.min() - pad), min(C, cc.max() + pad + 1) - box = np.zeros((a1 - a0, b1 - b0), bool) - box[rr - a0, cc - b0] = True - box = ndimage.binary_dilation(box, se) - rr, cc = np.nonzero(box) - 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 - 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) - for q in np.asarray(spots_rc, np.float64).reshape(-1, 2): - if np.all(np.isfinite(q)): - hit |= np.hypot(qr - q[0], qc - q[1]) <= m + 1.5 - out[:, hit] = 1 - return out +"""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 +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 + nearest 80 Hz frame and widened on both sides by + 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 + 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. + +The numbers were chosen on the GFP control 847983 with injected events +(GIAnT-Python export docs, f0_export.rst). +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from numpy.typing import ArrayLike +from scipy import ndimage, sparse + +SPOT_MODES = ("none", "seeds") + + +@dataclass(frozen=True) +class MaskRule: + """The activity mask's rule. + + Attributes + ---------- + k : float + 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 + Forward widening after each crossing, in decay constants of the + activity channel (2: 48 ms for iGluSnFR4f's 24 ms). + share_frames : int + 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'. + """ + + k: float = 3.0 + margin_px: float = 1.0 + widen_tau: float = 2.0 + share_frames: int = 6 + spots: str = "none" + + def check(self) -> None: + """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: + 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: + """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), + "activityMaskWidenTau": float(self.widen_tau), + "activityMaskShareFrames": int(self.share_frames), + "activityMaskSpots": self.spots, + } + + +def robust_sd(x: np.ndarray) -> float: + """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: + return np.nan + return 1.4826 * float(np.median(np.abs(x - np.median(x)))) + + +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: 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: + return np.zeros(x.size, np.int64) + i = np.clip(np.searchsorted(ds, x), 1, ds.size - 1) + left = x - ds[i - 1] < ds[i] - x + return np.where(left, i - 1, i).astype(np.int64) + + +def temporal_mask( + den: ArrayLike, + sigma: np.ndarray, + lines200: ArrayLike, + discard200: ArrayLike, + ds_lines: ArrayLike, + rule: MaskRule, + tau200: float, +) -> np.ndarray: + """Mask each source's 80 Hz frames, (sources, frames80) bool. + + Parameters + ---------- + den : ndarray (frames200, sources) + 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). + rule : MaskRule + tau200 : float + The activity channel's decay constant in 200 Hz frames (SILo's + 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 + T = np.asarray(ds_lines).size + out = np.zeros((n, T), bool) + if n == 0 or den.shape[0] == 0: + return out + L = int(round(rule.widen_tau * float(tau200))) + near = nearest_frames(ds_lines, lines200) + keep = ~np.asarray(discard200, bool) + share = np.ones(2 * int(rule.share_frames) + 1, bool) + sig = np.where(np.isfinite(sigma), sigma, np.inf) + i = np.arange(den.shape[0]) + for s in range(n): + above = (den[:, s] > rule.k * sig[s]) & keep + if not above.any(): + continue + if L > 0: # forward: any crossing in the last L frames + c = np.concatenate([[0], np.cumsum(above)]) + above = (c[i + 1] - c[np.maximum(0, i - L)]) > 0 + f = np.zeros(T, bool) + f[near[above]] = True + out[s] = ndimage.binary_dilation(f, share) if share.size > 1 else f + return out + + +def _disk(r: float) -> np.ndarray: + """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: sparse.spmatrix | None, + tm: np.ndarray | None, + shape: tuple, + crop: tuple, + rule: MaskRule, + spots_rc: np.ndarray | None = None, + n_frames: int = 0, +) -> np.ndarray: + """Build the trial's activity mask in the crop. + + (frames, rows, cols) uint8 (1: the loss is zeroed). + + Parameters + ---------- + H : sparse (pixels, sources) or None + The footprints in the trial frame (as the activity is placed). + tm : ndarray (sources, frames) or None + :func:`temporal_mask`. + shape : tuple + (rows, cols) of the trial frame. + crop : tuple + (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 + T = tm.shape[1] if tm is not None else int(n_frames) + out = np.zeros((T, r1 - r0, c1 - c0), np.uint8) + m = float(rule.margin_px) + se = _disk(m) if m > 0 else None + pad = int(np.ceil(m)) + if H is not None and tm is not None and tm.size: + Hc = H.tocsc() + for j in range(Hc.shape[1]): + fr = np.flatnonzero(tm[j]) + pix = Hc.indices[Hc.indptr[j] : Hc.indptr[j + 1]] + if fr.size == 0 or pix.size == 0: + continue + rr, cc = np.divmod(pix, C) + if se is not None: # dilate in the footprint's own box + a0, a1 = max(0, rr.min() - pad), min(R, rr.max() + pad + 1) + b0, b1 = max(0, cc.min() - pad), min(C, cc.max() + pad + 1) + box = np.zeros((a1 - a0, b1 - b0), bool) + box[rr - a0, cc - b0] = True + box = ndimage.binary_dilation(box, se) + rr, cc = np.nonzero(box) + 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 + 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) + for q in np.asarray(spots_rc, np.float64).reshape(-1, 2): + if np.all(np.isfinite(q)): + hit |= np.hypot(qr - q[0], qc - q[1]) <= m + 1.5 + out[:, hit] = 1 + return out diff --git a/src/giant_python/export/f0_qc.py b/src/giant_python/export/f0_qc.py index 67133a54..f5b8e3e4 100644 --- a/src/giant_python/export/f0_qc.py +++ b/src/giant_python/export/f0_qc.py @@ -1,449 +1,449 @@ -"""Quality values of an F0 training trial. - -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 -old and new exports line up. - -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). -""" - -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 - -HPF_WIDTH = 81 # frames of the running median the fits are high-passed by - - -def movmedian_omitnan(x: np.ndarray, width: int = HPF_WIDTH) -> np.ndarray: - """MATLAB movmedian(x, width, 2, 'omitnan') (endpoints shrink). - - 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 - out = np.empty_like(x) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) - for a in range(0, x.shape[0], 32): - blk = x[a : a + 32] - pad = np.full((blk.shape[0], h), np.nan) - blk = np.concatenate([pad, blk, pad], axis=1) - win = np.lib.stride_tricks.sliding_window_view(blk, width, axis=1) - out[a : a + 32] = np.nanmedian(win, axis=-1) - return out - - -def hpf(x: np.ndarray) -> np.ndarray: - """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. - - 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. - - 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: 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]): - a, b = H.indptr[s], H.indptr[s + 1] - if b > a: - pk[s] = H.indices[a + int(np.argmax(H.data[a:b]))] - return pk - - -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 - if not ok.any(): - return sl, r - A = np.asarray(H[pk[ok]] @ X) - yh, ah = hpf(Y[:, pk[ok]].T), hpf(A) - for i, s in enumerate(np.flatnonzero(ok)): - sl[s], r[s] = _slope(yh[i], ah[i]), _corr(yh[i], ah[i]) - return sl, r - - -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] - if not np.any(ah[np.isfinite(yh) & np.isfinite(ah)]): - return np.nan, np.nan - ok = np.isfinite(yh) & np.isfinite(ah) - if ok.sum() <= 100: - return np.nan, np.nan - return _slope(yh, ah), _corr(yh, ah) - - -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) - sr, sc = np.divmod(sup, shape[1]) - for s in np.flatnonzero(pk >= 0): - pr, pc = divmod(int(pk[s]), shape[1]) - idx = sup[np.hypot(sr - pr, sc - pc) <= radius] - sl[s], r[s] = _flux_fit(H, X, Y, idx) - return sl, r - - -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() - dr, dc = dr.ravel(), dc.ravel() - rho = np.full(pk.size, np.nan) - for s in np.flatnonzero(pk >= 0): - pr, pc = divmod(int(pk[s]), C) - rr, cc = pr + dr, pc + dc - inside = (d <= 3.5) & (rr >= 0) & (rr < R) & (cc >= 0) & (cc < C) - rr, cc, ds = rr[inside], cc[inside], d[inside] - ok = valid[rr, cc] - idx, ds = (rr * C + cc)[ok], ds[ok] - core, outer = idx[ds <= 1.5], idx[ds > 1.5] - if core.size < 5 or outer.size < 12: - continue - a = _flux_fit(H, X, Y, core)[0] - b = _flux_fit(H, X, Y, outer)[0] - if a > 0 and b > 0: - rho[s] = a / b - return rho - - -def _events(x: np.ndarray) -> np.ndarray: - """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: 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: - return np.nan, 0 - A = np.asarray(H[pk[ok]] @ X) - for i, s in enumerate(ok): - y = Y[:, pk[s]].astype(np.float64) - for e in _events(np.asarray(X[s], np.float64)): - wy = y[e - 8 : e + 17] - if np.isnan(wy).any(): - continue - wr = wy - A[i, e - 8 : e + 17] - eta_y += wy - wy[:6].mean() - eta_r += wr - wr[:6].mean() - n_ev += 1 - if n_ev == 0: - return np.nan, 0 - return float(eta_r[8:13].max() / eta_y[8:13].max()), n_ev - - -@dataclass -class RingEventRatios: - """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 - n_sources: int = 0 - n_events: int = 0 - n_artifact_sources: int = 0 - - -RING_RAD = 8 -RING_EDGE = 160 - - -def _ring_events(sel: np.ndarray, discard: np.ndarray) -> list: - """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) - T = sel.size - return [ - e - for e in range(RING_EDGE, T - RING_EDGE) - if sel[e] > thr - and sel[e] >= sel[e - 1] - and sel[e] > sel[e + 1] - and not discard[e - 8 : e + 17].any() - ] - - -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) - core = v & (dist <= 1.5) - if ring.sum() < 12 or core.sum() < 5: - return 0 - mr = np.asarray(movie[:, rows[ring], cols[ring]], np.float64) - mr[discard] = np.nan - sel = np.where(np.isnan(mr).any(1), np.nan, mr.mean(1)) - if np.isnan(sel).all(): - return 0 - ev = _ring_events(sel, discard) - if len(ev) < 3: - return 0 - flat = rows * valid.shape[1] + cols - Mb = np.asarray(movie[:, rows, cols], np.float64) - Ab = np.asarray(act_at(flat.ravel()), np.float64).reshape(Mb.shape) - for e in ev: - am = Mb[e - 1 : e + 2].mean(0) - Mb[e - 8 : e - 2].mean(0) - aa = Ab[e - 1 : e + 2].mean(0) - Ab[e - 8 : e - 2].mean(0) - okp = v & np.isfinite(am) - for i, (lo, hi) in enumerate(((0.0, 1.5), (1.5, 2.5))): - q = okp & (dist >= lo) & (dist < hi) - sums[0, i] += am[q].sum() - sums[1, i] += aa[q].sum() - return len(ev) - - -def ring_event_ratios( - movie: np.ndarray, - act_at: Callable[[np.ndarray], np.ndarray], - mean_act: np.ndarray, - valid: np.ndarray, - pr: np.ndarray, - pc: np.ndarray, - discard: np.ndarray, -) -> RingEventRatios: - """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). - mean_act : ndarray (rows, cols) - The activity's time-mean. - valid : ndarray of bool (rows, cols) - pr, pc : ndarray of int - The sources' peak pixels (zero-based; negative: none). - discard : ndarray of bool (frames,) - - Returns - ------- - RingEventRatios - As slap2_f0.ringqc.ring_event_ratios on the written arrays. - """ - R, C = valid.shape - discard = np.asarray(discard, bool) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) - mm = np.nanmean(movie, axis=0) - with np.errstate(invalid="ignore"): - bad = mean_act > 3 * np.maximum(mm, 1) # NaN compares False - dr, dc = np.mgrid[-RING_RAD : RING_RAD + 1, -RING_RAD : RING_RAD + 1] - dist = np.hypot(dr, dc) - 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): - continue - if not valid[r0, c0]: - continue - rows, cols = r0 + dr, c0 + dc - 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) - if n: - out.n_sources += 1 - out.n_events += n - if out.n_events: - out.core = float(sums[1, 0] / sums[0, 0]) - out.near = float(sums[1, 1] / sums[0, 1]) - return out +"""Quality values of an F0 training trial. + +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 +old and new exports line up. + +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). +""" + +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 + +HPF_WIDTH = 81 # frames of the running median the fits are high-passed by + + +def movmedian_omitnan(x: np.ndarray, width: int = HPF_WIDTH) -> np.ndarray: + """MATLAB movmedian(x, width, 2, 'omitnan') (endpoints shrink). + + 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 + out = np.empty_like(x) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + for a in range(0, x.shape[0], 32): + blk = x[a : a + 32] + pad = np.full((blk.shape[0], h), np.nan) + blk = np.concatenate([pad, blk, pad], axis=1) + win = np.lib.stride_tricks.sliding_window_view(blk, width, axis=1) + out[a : a + 32] = np.nanmedian(win, axis=-1) + return out + + +def hpf(x: np.ndarray) -> np.ndarray: + """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. + + 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. + + 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: 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]): + a, b = H.indptr[s], H.indptr[s + 1] + if b > a: + pk[s] = H.indices[a + int(np.argmax(H.data[a:b]))] + return pk + + +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 + if not ok.any(): + return sl, r + A = np.asarray(H[pk[ok]] @ X) + yh, ah = hpf(Y[:, pk[ok]].T), hpf(A) + for i, s in enumerate(np.flatnonzero(ok)): + sl[s], r[s] = _slope(yh[i], ah[i]), _corr(yh[i], ah[i]) + return sl, r + + +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] + if not np.any(ah[np.isfinite(yh) & np.isfinite(ah)]): + return np.nan, np.nan + ok = np.isfinite(yh) & np.isfinite(ah) + if ok.sum() <= 100: + return np.nan, np.nan + return _slope(yh, ah), _corr(yh, ah) + + +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) + sr, sc = np.divmod(sup, shape[1]) + for s in np.flatnonzero(pk >= 0): + pr, pc = divmod(int(pk[s]), shape[1]) + idx = sup[np.hypot(sr - pr, sc - pc) <= radius] + sl[s], r[s] = _flux_fit(H, X, Y, idx) + return sl, r + + +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() + dr, dc = dr.ravel(), dc.ravel() + rho = np.full(pk.size, np.nan) + for s in np.flatnonzero(pk >= 0): + pr, pc = divmod(int(pk[s]), C) + rr, cc = pr + dr, pc + dc + inside = (d <= 3.5) & (rr >= 0) & (rr < R) & (cc >= 0) & (cc < C) + rr, cc, ds = rr[inside], cc[inside], d[inside] + ok = valid[rr, cc] + idx, ds = (rr * C + cc)[ok], ds[ok] + core, outer = idx[ds <= 1.5], idx[ds > 1.5] + if core.size < 5 or outer.size < 12: + continue + a = _flux_fit(H, X, Y, core)[0] + b = _flux_fit(H, X, Y, outer)[0] + if a > 0 and b > 0: + rho[s] = a / b + return rho + + +def _events(x: np.ndarray) -> np.ndarray: + """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: 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: + return np.nan, 0 + A = np.asarray(H[pk[ok]] @ X) + for i, s in enumerate(ok): + y = Y[:, pk[s]].astype(np.float64) + for e in _events(np.asarray(X[s], np.float64)): + wy = y[e - 8 : e + 17] + if np.isnan(wy).any(): + continue + wr = wy - A[i, e - 8 : e + 17] + eta_y += wy - wy[:6].mean() + eta_r += wr - wr[:6].mean() + n_ev += 1 + if n_ev == 0: + return np.nan, 0 + return float(eta_r[8:13].max() / eta_y[8:13].max()), n_ev + + +@dataclass +class RingEventRatios: + """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 + n_sources: int = 0 + n_events: int = 0 + n_artifact_sources: int = 0 + + +RING_RAD = 8 +RING_EDGE = 160 + + +def _ring_events(sel: np.ndarray, discard: np.ndarray) -> list: + """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) + T = sel.size + return [ + e + for e in range(RING_EDGE, T - RING_EDGE) + if sel[e] > thr + and sel[e] >= sel[e - 1] + and sel[e] > sel[e + 1] + and not discard[e - 8 : e + 17].any() + ] + + +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) + core = v & (dist <= 1.5) + if ring.sum() < 12 or core.sum() < 5: + return 0 + mr = np.asarray(movie[:, rows[ring], cols[ring]], np.float64) + mr[discard] = np.nan + sel = np.where(np.isnan(mr).any(1), np.nan, mr.mean(1)) + if np.isnan(sel).all(): + return 0 + ev = _ring_events(sel, discard) + if len(ev) < 3: + return 0 + flat = rows * valid.shape[1] + cols + Mb = np.asarray(movie[:, rows, cols], np.float64) + Ab = np.asarray(act_at(flat.ravel()), np.float64).reshape(Mb.shape) + for e in ev: + am = Mb[e - 1 : e + 2].mean(0) - Mb[e - 8 : e - 2].mean(0) + aa = Ab[e - 1 : e + 2].mean(0) - Ab[e - 8 : e - 2].mean(0) + okp = v & np.isfinite(am) + for i, (lo, hi) in enumerate(((0.0, 1.5), (1.5, 2.5))): + q = okp & (dist >= lo) & (dist < hi) + sums[0, i] += am[q].sum() + sums[1, i] += aa[q].sum() + return len(ev) + + +def ring_event_ratios( + movie: np.ndarray, + act_at: Callable[[np.ndarray], np.ndarray], + mean_act: np.ndarray, + valid: np.ndarray, + pr: np.ndarray, + pc: np.ndarray, + discard: np.ndarray, +) -> RingEventRatios: + """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). + mean_act : ndarray (rows, cols) + The activity's time-mean. + valid : ndarray of bool (rows, cols) + pr, pc : ndarray of int + The sources' peak pixels (zero-based; negative: none). + discard : ndarray of bool (frames,) + + Returns + ------- + RingEventRatios + As slap2_f0.ringqc.ring_event_ratios on the written arrays. + """ + R, C = valid.shape + discard = np.asarray(discard, bool) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + mm = np.nanmean(movie, axis=0) + with np.errstate(invalid="ignore"): + bad = mean_act > 3 * np.maximum(mm, 1) # NaN compares False + dr, dc = np.mgrid[-RING_RAD : RING_RAD + 1, -RING_RAD : RING_RAD + 1] + dist = np.hypot(dr, dc) + 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): + continue + if not valid[r0, c0]: + continue + rows, cols = r0 + dr, c0 + dc + 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) + if n: + out.n_sources += 1 + out.n_events += n + if out.n_events: + out.core = float(sums[1, 0] / sums[0, 0]) + out.near = float(sums[1, 1] / sums[0, 1]) + return out diff --git a/src/giant_python/extraction/__init__.py b/src/giant_python/extraction/__init__.py index 0bb7f2fb..2bcf7df7 100644 --- a/src/giant_python/extraction/__init__.py +++ b/src/giant_python/extraction/__init__.py @@ -1 +1 @@ -"""Source-extraction backends; import a backend explicitly when needed.""" +"""Source-extraction backends; import a backend explicitly when needed.""" diff --git a/src/giant_python/extraction/band/__init__.py b/src/giant_python/extraction/band/__init__.py index 676f24e6..3e3bb12d 100644 --- a/src/giant_python/extraction/band/__init__.py +++ b/src/giant_python/extraction/band/__init__.py @@ -1 +1 @@ -"""Band-scan extraction kernels with no eager workflow or IO imports.""" +"""Band-scan extraction kernels with no eager workflow or IO imports.""" diff --git a/src/giant_python/extraction/band/activity.py b/src/giant_python/extraction/band/activity.py index 47e9a1f1..1f87b4bb 100644 --- a/src/giant_python/extraction/band/activity.py +++ b/src/giant_python/extraction/band/activity.py @@ -1,330 +1,330 @@ -"""Matched-filter activity, valid-column masking, and temporal smoothing.""" - -from __future__ import annotations - -import numpy as np -import torch -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]: - """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). - - 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)] - z_col_idxs = [torch.nonzero(m, as_tuple=False).squeeze(1) for m in z_masks] - z_remaps = [] - 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) - z_remaps.append(remap) - return z_masks, z_col_idxs, z_remaps - - -def _valid_sel_cols_for_motion( - motion_idx: int, - unique_motion_to_keep_yx: np.ndarray, - ref_d: np.ndarray, - ref_r: np.ndarray, - ref_c: np.ndarray, - sel_pix_idxs: np.ndarray, - num_fast_zs: int, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, - psf2d: np.ndarray, -) -> np.ndarray: - """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 - 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[ - ref_d, - ref_r + int(unique_motion_to_keep_yx[motion_idx, 0]), - ref_c + int(unique_motion_to_keep_yx[motion_idx, 1]), - ] = True - valid_pix_mask = ndimage.binary_dilation( - valid_pix_mask, - structure=np.ones((1, psf2d.shape[0], psf2d.shape[1]), dtype=bool), - ) - valid_pix_mask = ndimage.binary_erosion( - 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), - ) - valid_pix_idxs = np.flatnonzero(valid_pix_mask) - valid_lookup = np.zeros(num_fast_zs * plane_size, dtype=bool) - valid_lookup[valid_pix_idxs] = True - return valid_lookup[sel_pix_idxs] - - -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], - 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, - psf2d: np.ndarray, - verbose: bool = False, -) -> np.ndarray: - """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. - - 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). - 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`. - d_mats, d_mats_expanded : list of torch.Tensor - Per-plane base/expanded convolution matrices from - :func:`build_convolution_matrix`. - sel_pix_idxs : ndarray of int - Sorted flat selected-pixel indices. - ref_d, ref_r, ref_c : ndarray - Per-superpixel reference depth/row/column indices. - num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int - Grid geometry. - psf2d : ndarray - The (cropped) PSF for this DMD. - verbose : bool - Show a per-motion-bin progress bar when set. - - Returns - ------- - ndarray of shape (n_sel, n_frames), float32 - 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_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) - - for i in progress( - range(len(unique_motion_to_keep_yx)), - desc="Computing rho", - verbose=verbose, - ): - motion_frames = np.flatnonzero(mot_inds_yx == i) - if motion_frames.size == 0: - continue - - h_mot = h_mots[i].coalesce() - h_idxs = h_mot.indices() - h_vals = h_mot.values() - nrows, _ = h_mot.size() - residual_motion = residual[:, motion_frames].T - - valid_sel_cols = _valid_sel_cols_for_motion( - i, - unique_motion_to_keep_yx, - ref_d, - ref_r, - ref_c, - sel_pix_idxs, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - psf2d, - ) - - for z in range(num_fast_zs): - new_ncols = int(z_col_idxs[z].numel()) - if new_ncols == 0: - continue - - z_mask = z_masks[z] - keep_mask = z_mask[h_idxs[1]] - if keep_mask.sum().item() == 0: - # Unreachable defensive guard (mirrors the reference): a plane - # with selected pixels (new_ncols > 0) always has H columns in - # it, since both derive from the same in-plane PSF footprint. - continue - - remap = z_remaps[z] - new_rows = h_idxs[0, keep_mask] - new_cols = remap[h_idxs[1, keep_mask]] - new_idxs = torch.stack([new_rows, new_cols], dim=0) - new_vals = h_vals[keep_mask] - h_sub = torch.sparse_coo_tensor( - new_idxs, new_vals, (nrows, new_ncols), dtype=torch.float32 - ).coalesce() - - hd = torch.sparse.mm(h_sub, d_mats[z]) - hd = hd / torch.sum(hd, dim=0, keepdim=True) - # Center-surround matched filter. Both projections are - # 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_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 - # normalization above pins each column's *sum*, not its norm, so - # noise gain varies with where a column sits relative to the - # sparse superpixel reference-pixel lattice. Since the activity - # image accumulates rho^2 only at local maxima, that bias is - # amplified into a visible grid of bright reference pixels. - # Whitening also makes ``peak_th`` a true sigma threshold. - # To revert, delete the two lines below. - hd_norm = torch.linalg.norm(hd_diff, dim=0, keepdim=True) - hd_diff = hd_diff / hd_norm.clamp_min(1e-12) - - z_cols = z_col_idxs_np[z] - z_valid_mask = valid_sel_cols[z_cols] - if not np.any(z_valid_mask): - continue - z_valid_cols = z_cols[z_valid_mask] - local_valid_cols = remap[torch.from_numpy(z_valid_cols)].long() - - rho[np.ix_(z_valid_cols, motion_frames)] = ( - residual_motion @ hd_diff[:, local_valid_cols].numpy() - ).T - - return 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. - - rho is modified in place. Rows whose NaN fraction exceeds thresh - are set entirely to NaN. - - Parameters - ---------- - rho : ndarray of shape (n_sel, n_frames) - The rho response. - thresh : float - NaN-fraction threshold above which a row is dropped. - - Returns - ------- - ndarray of shape (n_sel,) - Per-row NaN fraction (before dropping). - """ - nan_ct = np.mean(np.isnan(rho), axis=1) - rho[nan_ct > thresh] = np.nan - return nan_ct - - -def decay_kernel_1d(decay_tau_s: float, align_hz: float) -> np.ndarray: - """Build the normalized causal exponential-decay smoothing kernel. - - Parameters - ---------- - decay_tau_s : float - Calcium-decay time constant, in seconds. - align_hz : float - Alignment/analysis rate, in Hz. - - Returns - ------- - ndarray - A 1-D kernel spanning 3 * tau frames, summing to 1. - """ - decay_tau_frames = decay_tau_s * align_hz - k1d = np.exp( - np.linspace( - -np.ceil(decay_tau_frames * 3), - 0, - int(np.ceil(decay_tau_frames * 3) + 1), - ) - / decay_tau_frames - ) - 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. - - 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. - - Parameters - ---------- - rho : ndarray of shape (n_sel, n_frames) - The rho response (NaN allowed). - k1d : ndarray - 1-D smoothing kernel from :func:`decay_kernel_1d`. - verbose : bool - Show a per-row-chunk progress bar when set. - - Returns - ------- - ndarray - The smoothed rho. - """ - k2d = np.expand_dims(k1d, 0) - n_time = rho.shape[1] - bytes_per_row = max(1, n_time) * np.dtype(np.float32).itemsize * 3 - row_chunk = max(64, min(4096, int(200_000_000 // bytes_per_row))) - - for r0 in progress( - range(0, rho.shape[0], row_chunk), - desc="Smoothing rho", - verbose=verbose, - ): - r1 = min(r0 + row_chunk, rho.shape[0]) - rc = rho[r0:r1].copy() - row_has_data = np.any(np.isfinite(rc), axis=1) - if not np.any(row_has_data): - rho[r0:r1] = rc - continue - - 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_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) - rho_num[~valid_den] = np.nan - rc[row_has_data] = rho_num - rho[r0:r1] = rc - - return rho +"""Matched-filter activity, valid-column masking, and temporal smoothing.""" + +from __future__ import annotations + +import numpy as np +import torch +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]: + """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). + + 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)] + z_col_idxs = [torch.nonzero(m, as_tuple=False).squeeze(1) for m in z_masks] + z_remaps = [] + 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) + z_remaps.append(remap) + return z_masks, z_col_idxs, z_remaps + + +def _valid_sel_cols_for_motion( + motion_idx: int, + unique_motion_to_keep_yx: np.ndarray, + ref_d: np.ndarray, + ref_r: np.ndarray, + ref_c: np.ndarray, + sel_pix_idxs: np.ndarray, + num_fast_zs: int, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, + psf2d: np.ndarray, +) -> np.ndarray: + """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 + 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[ + ref_d, + ref_r + int(unique_motion_to_keep_yx[motion_idx, 0]), + ref_c + int(unique_motion_to_keep_yx[motion_idx, 1]), + ] = True + valid_pix_mask = ndimage.binary_dilation( + valid_pix_mask, + structure=np.ones((1, psf2d.shape[0], psf2d.shape[1]), dtype=bool), + ) + valid_pix_mask = ndimage.binary_erosion( + 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), + ) + valid_pix_idxs = np.flatnonzero(valid_pix_mask) + valid_lookup = np.zeros(num_fast_zs * plane_size, dtype=bool) + valid_lookup[valid_pix_idxs] = True + return valid_lookup[sel_pix_idxs] + + +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], + 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, + psf2d: np.ndarray, + verbose: bool = False, +) -> np.ndarray: + """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. + + 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). + 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`. + d_mats, d_mats_expanded : list of torch.Tensor + Per-plane base/expanded convolution matrices from + :func:`build_convolution_matrix`. + sel_pix_idxs : ndarray of int + Sorted flat selected-pixel indices. + ref_d, ref_r, ref_c : ndarray + Per-superpixel reference depth/row/column indices. + num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int + Grid geometry. + psf2d : ndarray + The (cropped) PSF for this DMD. + verbose : bool + Show a per-motion-bin progress bar when set. + + Returns + ------- + ndarray of shape (n_sel, n_frames), float32 + 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_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) + + for i in progress( + range(len(unique_motion_to_keep_yx)), + desc="Computing rho", + verbose=verbose, + ): + motion_frames = np.flatnonzero(mot_inds_yx == i) + if motion_frames.size == 0: + continue + + h_mot = h_mots[i].coalesce() + h_idxs = h_mot.indices() + h_vals = h_mot.values() + nrows, _ = h_mot.size() + residual_motion = residual[:, motion_frames].T + + valid_sel_cols = _valid_sel_cols_for_motion( + i, + unique_motion_to_keep_yx, + ref_d, + ref_r, + ref_c, + sel_pix_idxs, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + psf2d, + ) + + for z in range(num_fast_zs): + new_ncols = int(z_col_idxs[z].numel()) + if new_ncols == 0: + continue + + z_mask = z_masks[z] + keep_mask = z_mask[h_idxs[1]] + if keep_mask.sum().item() == 0: + # Unreachable defensive guard (mirrors the reference): a plane + # with selected pixels (new_ncols > 0) always has H columns in + # it, since both derive from the same in-plane PSF footprint. + continue + + remap = z_remaps[z] + new_rows = h_idxs[0, keep_mask] + new_cols = remap[h_idxs[1, keep_mask]] + new_idxs = torch.stack([new_rows, new_cols], dim=0) + new_vals = h_vals[keep_mask] + h_sub = torch.sparse_coo_tensor( + new_idxs, new_vals, (nrows, new_ncols), dtype=torch.float32 + ).coalesce() + + hd = torch.sparse.mm(h_sub, d_mats[z]) + hd = hd / torch.sum(hd, dim=0, keepdim=True) + # Center-surround matched filter. Both projections are + # 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_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 + # normalization above pins each column's *sum*, not its norm, so + # noise gain varies with where a column sits relative to the + # sparse superpixel reference-pixel lattice. Since the activity + # image accumulates rho^2 only at local maxima, that bias is + # amplified into a visible grid of bright reference pixels. + # Whitening also makes ``peak_th`` a true sigma threshold. + # To revert, delete the two lines below. + hd_norm = torch.linalg.norm(hd_diff, dim=0, keepdim=True) + hd_diff = hd_diff / hd_norm.clamp_min(1e-12) + + z_cols = z_col_idxs_np[z] + z_valid_mask = valid_sel_cols[z_cols] + if not np.any(z_valid_mask): + continue + z_valid_cols = z_cols[z_valid_mask] + local_valid_cols = remap[torch.from_numpy(z_valid_cols)].long() + + rho[np.ix_(z_valid_cols, motion_frames)] = ( + residual_motion @ hd_diff[:, local_valid_cols].numpy() + ).T + + return 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. + + rho is modified in place. Rows whose NaN fraction exceeds thresh + are set entirely to NaN. + + Parameters + ---------- + rho : ndarray of shape (n_sel, n_frames) + The rho response. + thresh : float + NaN-fraction threshold above which a row is dropped. + + Returns + ------- + ndarray of shape (n_sel,) + Per-row NaN fraction (before dropping). + """ + nan_ct = np.mean(np.isnan(rho), axis=1) + rho[nan_ct > thresh] = np.nan + return nan_ct + + +def decay_kernel_1d(decay_tau_s: float, align_hz: float) -> np.ndarray: + """Build the normalized causal exponential-decay smoothing kernel. + + Parameters + ---------- + decay_tau_s : float + Calcium-decay time constant, in seconds. + align_hz : float + Alignment/analysis rate, in Hz. + + Returns + ------- + ndarray + A 1-D kernel spanning 3 * tau frames, summing to 1. + """ + decay_tau_frames = decay_tau_s * align_hz + k1d = np.exp( + np.linspace( + -np.ceil(decay_tau_frames * 3), + 0, + int(np.ceil(decay_tau_frames * 3) + 1), + ) + / decay_tau_frames + ) + 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. + + 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. + + Parameters + ---------- + rho : ndarray of shape (n_sel, n_frames) + The rho response (NaN allowed). + k1d : ndarray + 1-D smoothing kernel from :func:`decay_kernel_1d`. + verbose : bool + Show a per-row-chunk progress bar when set. + + Returns + ------- + ndarray + The smoothed rho. + """ + k2d = np.expand_dims(k1d, 0) + n_time = rho.shape[1] + bytes_per_row = max(1, n_time) * np.dtype(np.float32).itemsize * 3 + row_chunk = max(64, min(4096, int(200_000_000 // bytes_per_row))) + + for r0 in progress( + range(0, rho.shape[0], row_chunk), + desc="Smoothing rho", + verbose=verbose, + ): + r1 = min(r0 + row_chunk, rho.shape[0]) + rc = rho[r0:r1].copy() + row_has_data = np.any(np.isfinite(rc), axis=1) + if not np.any(row_has_data): + rho[r0:r1] = rc + continue + + 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_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) + rho_num[~valid_den] = np.nan + rc[row_has_data] = rho_num + rho[r0:r1] = rc + + return rho diff --git a/src/giant_python/extraction/band/annotation.py b/src/giant_python/extraction/band/annotation.py index e3570d6e..b62fc213 100644 --- a/src/giant_python/extraction/band/annotation.py +++ b/src/giant_python/extraction/band/annotation.py @@ -1,282 +1,282 @@ -"""Standalone band annotation and shared load/draw/headless orchestration. - -Raw persistence lives in io.annotations, pure geometry in band.rois, and -toolkit code in gui.roi_editor. No toolkit is loaded on the headless path. -""" - -from __future__ import annotations - -import os -import sys -from pathlib import Path - -import numpy as np - -from ...io.annotations import read_annotations_h5, save_annotations_h5 -from ...models.params import ( - AnnotationInput, - BandParamsInput, - ExecutionInput, - resolve_band_options, -) -from ...models.trial_table import TrialTable -from ...progress import log -from . import geometry as geo -from . import inputs -from .inputs import ( - compute_keep_trials, - load_alignment_data_h5, - load_trial_table, -) -from .rois import compute_user_roi_geometry, resolve_annotation_records - - -def first_valid_trial(keep_trials: np.ndarray, dmd_ix: int) -> int: - """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}") - return int(indexes[0]) - - -def motion_median_from_adata(a_data: dict) -> tuple: - """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"]))), - int(np.nanmedian(np.round(a_data["motionDSz"]))), - ) - - -def _stdin_is_tty() -> bool: - """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: 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"): - return False - return _stdin_is_tty() - - -def _empty_user_rois(n_dmds: int) -> dict: - """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}, - "user_roi_superpixels": {k: [] for k in keys}, - "user_roi_labels": {k: [] for k in keys}, - "roi_records": {k: [] for k in keys}, - "annotated": False, - } - - -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, {}, {}, {}, {} - try: - raw = read_annotations_h5(annotations_path) - except OSError as error: - print(f"Could not read {annotations_path}: {error}") - return False, {}, {}, {}, {} - return resolve_annotation_records(raw, n_dmds, user_roi_geo) - - -def resolve_user_rois( - annotation_dir: str | Path, - n_dmds: int, - user_roi_geo: dict, - *, - interactive: bool, - ref_files: dict | None = None, -) -> dict: - """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) - if skip: - return { - "user_roi_masks": masks, - "user_roi_superpixels": superpixels, - "user_roi_labels": labels, - "roi_records": records, - "annotated": True, - } - if not interactive: - raise RuntimeError( - "Annotations are enabled but no usable ROIs were found at " - f"{path!r}, and this process is not interactive. Run " - "`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) - - -def _draw_and_save_user_rois( - annotation_dir: str | Path, - n_dmds: int, - user_roi_geo: dict, - ref_files: dict | None, -) -> dict: - """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) - selection = run_user_roi_selection(user_roi_geo, n_dmds) - save_annotations_h5( - str(annotation_dir), - selection["roi_records"], - selection["user_roi_masks"], - n_dmds, - ref_files=ref_files, - ) - selection["annotated"] = True - return selection - - -def build_user_roi_geometry(trial_table: dict, lookup: dict) -> tuple: - """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"] - for dmd_ix in range(int(trial_table["n_dmds"])): - key = f"DMD{dmd_ix + 1}" - ref_stack, _, ref_file = inputs.load_reference_stack( - datadr, trial_table["ref_stack"], dmd_ix - ) - smi = geo.build_subsample_matrix_inds( - lookup["allSuperPixelIDs"][key], lookup["sparseMaskInds"][key] - ) - fvt = first_valid_trial(keep_trials, dmd_ix) - a_data = load_alignment_data_h5(trial_table["fn_adata"][dmd_ix, fvt]) - user_roi_geo[key] = compute_user_roi_geometry( - ref_stack, - lookup["fastZ2RefZ"][key], - smi, - motion_median_from_adata(a_data), - ) - ref_files[key] = ref_file - return user_roi_geo, ref_files - - -def annotate_band_rois( - input: str | Path | TrialTable, - params: BandParamsInput = None, - *, - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> str: - """Annotate a path or in-memory TrialTable; return annotations.h5's path. - - 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. - - 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) - trial_table = load_trial_table(input) - trial_table["keep_trials"] = compute_keep_trials( - trial_table["fn_adata"], trial_table["filename"], trial_table["datadr"] - ) - annotation_dir = trial_table["annotation_save_dr"] - lookup = inputs.load_lookup_table( - Path(trial_table["moco_save_dr"]) / "bandRegLookupTable.h5", - trial_table["n_dmds"], - ) - log( - f"Loading reference geometry for {trial_table['n_dmds']} DMD path(s)", - run.verbose, - ) - user_roi_geo, ref_files = build_user_roi_geometry(trial_table, lookup) - resolve_user_rois( - annotation_dir, - trial_table["n_dmds"], - user_roi_geo, - interactive=resolve_interactivity(policy.interactive), - ref_files=ref_files, - ) - out_path = os.path.join(str(annotation_dir), "annotations.h5") - log(f"Annotations at {out_path}", run.verbose) - return out_path +"""Standalone band annotation and shared load/draw/headless orchestration. + +Raw persistence lives in io.annotations, pure geometry in band.rois, and +toolkit code in gui.roi_editor. No toolkit is loaded on the headless path. +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import numpy as np + +from ...io.annotations import read_annotations_h5, save_annotations_h5 +from ...models.params import ( + AnnotationInput, + BandParamsInput, + ExecutionInput, + resolve_band_options, +) +from ...models.trial_table import TrialTable +from ...progress import log +from . import geometry as geo +from . import inputs +from .inputs import ( + compute_keep_trials, + load_alignment_data_h5, + load_trial_table, +) +from .rois import compute_user_roi_geometry, resolve_annotation_records + + +def first_valid_trial(keep_trials: np.ndarray, dmd_ix: int) -> int: + """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}") + return int(indexes[0]) + + +def motion_median_from_adata(a_data: dict) -> tuple: + """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"]))), + int(np.nanmedian(np.round(a_data["motionDSz"]))), + ) + + +def _stdin_is_tty() -> bool: + """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: 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"): + return False + return _stdin_is_tty() + + +def _empty_user_rois(n_dmds: int) -> dict: + """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}, + "user_roi_superpixels": {k: [] for k in keys}, + "user_roi_labels": {k: [] for k in keys}, + "roi_records": {k: [] for k in keys}, + "annotated": False, + } + + +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, {}, {}, {}, {} + try: + raw = read_annotations_h5(annotations_path) + except OSError as error: + print(f"Could not read {annotations_path}: {error}") + return False, {}, {}, {}, {} + return resolve_annotation_records(raw, n_dmds, user_roi_geo) + + +def resolve_user_rois( + annotation_dir: str | Path, + n_dmds: int, + user_roi_geo: dict, + *, + interactive: bool, + ref_files: dict | None = None, +) -> dict: + """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) + if skip: + return { + "user_roi_masks": masks, + "user_roi_superpixels": superpixels, + "user_roi_labels": labels, + "roi_records": records, + "annotated": True, + } + if not interactive: + raise RuntimeError( + "Annotations are enabled but no usable ROIs were found at " + f"{path!r}, and this process is not interactive. Run " + "`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) + + +def _draw_and_save_user_rois( + annotation_dir: str | Path, + n_dmds: int, + user_roi_geo: dict, + ref_files: dict | None, +) -> dict: + """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) + selection = run_user_roi_selection(user_roi_geo, n_dmds) + save_annotations_h5( + str(annotation_dir), + selection["roi_records"], + selection["user_roi_masks"], + n_dmds, + ref_files=ref_files, + ) + selection["annotated"] = True + return selection + + +def build_user_roi_geometry(trial_table: dict, lookup: dict) -> tuple: + """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"] + for dmd_ix in range(int(trial_table["n_dmds"])): + key = f"DMD{dmd_ix + 1}" + ref_stack, _, ref_file = inputs.load_reference_stack( + datadr, trial_table["ref_stack"], dmd_ix + ) + smi = geo.build_subsample_matrix_inds( + lookup["allSuperPixelIDs"][key], lookup["sparseMaskInds"][key] + ) + fvt = first_valid_trial(keep_trials, dmd_ix) + a_data = load_alignment_data_h5(trial_table["fn_adata"][dmd_ix, fvt]) + user_roi_geo[key] = compute_user_roi_geometry( + ref_stack, + lookup["fastZ2RefZ"][key], + smi, + motion_median_from_adata(a_data), + ) + ref_files[key] = ref_file + return user_roi_geo, ref_files + + +def annotate_band_rois( + input: str | Path | TrialTable, + params: BandParamsInput = None, + *, + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> str: + """Annotate a path or in-memory TrialTable; return annotations.h5's path. + + 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. + + 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) + trial_table = load_trial_table(input) + trial_table["keep_trials"] = compute_keep_trials( + trial_table["fn_adata"], trial_table["filename"], trial_table["datadr"] + ) + annotation_dir = trial_table["annotation_save_dr"] + lookup = inputs.load_lookup_table( + Path(trial_table["moco_save_dr"]) / "bandRegLookupTable.h5", + trial_table["n_dmds"], + ) + log( + f"Loading reference geometry for {trial_table['n_dmds']} DMD path(s)", + run.verbose, + ) + user_roi_geo, ref_files = build_user_roi_geometry(trial_table, lookup) + resolve_user_rois( + annotation_dir, + trial_table["n_dmds"], + user_roi_geo, + interactive=resolve_interactivity(policy.interactive), + ref_files=ref_files, + ) + out_path = os.path.join(str(annotation_dir), "annotations.h5") + log(f"Annotations at {out_path}", run.verbose) + return out_path diff --git a/src/giant_python/extraction/band/background.py b/src/giant_python/extraction/band/background.py index 1a66391f..6e70890c 100644 --- a/src/giant_python/extraction/band/background.py +++ b/src/giant_python/extraction/band/background.py @@ -1,499 +1,499 @@ -"""Band background interpolation, rolling baseline, and noise estimation.""" - -from __future__ import annotations - -import numpy as np -import pandas as pd -from numpy.typing import DTypeLike -from scipy.interpolate import CubicSpline - -try: - import bottleneck as bn -except ImportError: - bn = None - - -def _collect_interp_columns( - 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) - 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 = {} - single_points = [] - for c in cols: - c_int = int(c) - if c_int not in sel_idxs_by_col_all: - continue - data_ix = np.flatnonzero(s_c == c) - if data_ix.size == 1: - rr = int(s_r[data_ix[0]]) - col_sel = sel_idxs_by_col_all[c_int] - rr_match = col_sel[sel_rows[col_sel] == rr] - if rr_match.size > 0 and (r0 <= rr <= r1): - single_points.append((rr_match, int(data_ix[0]))) - continue - rows = s_r[data_ix] - order = rows.argsort(kind="mergesort") - rows_by_col[c_int] = rows[order] - idxs_by_col[c_int] = data_ix[order] - return rows_by_col, idxs_by_col, single_points - - -# Preserve scientific parity with the reference interpolation branches. -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 - strictly between reference rows use linear or natural-cubic interpolation; - those outside the sampled row range are left untouched (NaN). Cubic spline - weights depend only on row geometry, so they are computed once and applied - 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(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] - src_idx = idxs_by_col[c_int] - - pos = np.searchsorted(rows, target_rows, side="left") - in_bounds = pos < rows.size - exact = np.zeros_like(pos, dtype=bool) - exact[in_bounds] = rows[pos[in_bounds]] == target_rows[in_bounds] - - 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] - - lo = pos - 1 - hi = pos - interp_mask = (~exact) & (lo >= 0) & (hi < rows.size) - if not np.any(interp_mask): - continue - - interp_rows = np.flatnonzero(interp_mask) - lo_v = lo[interp_mask] - hi_v = hi[interp_mask] - row_lo = rows[lo_v].astype(dtype, copy=False) - row_hi = rows[hi_v].astype(dtype, copy=False) - denom = row_hi - row_lo - nonzero = denom != 0 - if not np.any(nonzero): - # Unreachable defensive guard (mirrors the reference): sorted - # distinct rows make searchsorted never straddle equal rows, so - # denom is always non-zero here. - continue - - interp_rows = interp_rows[nonzero] - lo_v = lo_v[nonzero] - 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] - - target_indices = col_sel_pix_idxs[interp_rows] - linear_frame_mask = np.ones(frames.size, dtype=bool) - has_cubic_geometry = rows.size >= 3 and np.all(np.diff(rows) > 0) - if method == "cubic" and has_cubic_geometry: - source_values = data[src_idx][:, frames] - 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) - origin = source_rows[0] - cache_key = ( - tuple(source_rows - origin), - tuple(target_interp_rows - origin), - np.dtype(dtype).str, - ) - spline_weights = ( - spline_weight_cache.get(cache_key) if spline_weight_cache is not None else None - ) - if spline_weights is None: - spline_weights = CubicSpline( - source_rows, - np.eye(rows.size, dtype=dtype), - axis=0, - bc_type="natural", - extrapolate=False, - )(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 - linear_frame_mask = ~complete_frames - - if not np.any(linear_frame_mask): - continue - linear_frames = frames[linear_frame_mask] - vals_lo = data[src_idx[lo_v]][:, linear_frames] - vals_hi = data[src_idx[hi_v]][:, linear_frames] - linear_values = (1.0 - alpha) * vals_lo + alpha * vals_hi - out[np.ix_(target_indices, linear_frames)] = linear_values - - -def build_interp_data( - data: np.ndarray, - ref_r: np.ndarray, - ref_c: np.ndarray, - sel_pixels_2d: np.ndarray, - unique_motion_to_keep_yx: np.ndarray, - mot_inds_yx: np.ndarray, - height: int = 800, - width: int = 1280, - dtype: DTypeLike = np.float32, - method: str = "cubic", -) -> 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 - motion) are linearly interpolated along rows, per column, onto the selected - pixels of the plane, filling one background estimate per selected pixel and - frame. Selected pixels outside the sampled row range remain NaN. - - Parameters - ---------- - data : ndarray of shape (n_ref, n_frames) - Reference-pixel traces for one plane. - 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. - 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). - 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 - a natural spline with precomputed geometry weights and falls back to - linear for columns with fewer than three samples or frames with missing - samples. - - Returns - ------- - out : ndarray of shape (n_sel, n_frames) - Interpolated background estimate (NaN where unsampled). - row_bounds : tuple of int - (r0, r1) inclusive row window. - col_bounds : tuple of int - (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(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()) - c0 = int(max(0, ref_c.min()) + unique_motion_to_keep_yx[:, 1].min()) - c1 = int(min(width, ref_c.max()) + unique_motion_to_keep_yx[:, 1].max()) - - out = np.full((sel_pixels_2d.shape[0], data.shape[1]), np.nan, dtype=dtype) - - 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} - - frames_by_motion = [ - np.flatnonzero(mot_inds_yx == idx) for idx in range(len(unique_motion_to_keep_yx)) - ] - spline_weight_cache = {} if method == "cubic" else None - - for m_idx, frames in enumerate(frames_by_motion): - if frames.size == 0: - continue - - s_r = ref_r + int(unique_motion_to_keep_yx[m_idx, 0]) - s_c = ref_c + int(unique_motion_to_keep_yx[m_idx, 1]) - - in_win = (s_r >= r0) & (s_r <= r1) & (s_c >= c0) & (s_c <= c1) - if not np.any(in_win): - continue - cols = np.unique(s_c[in_win]) - - rows_by_col, idxs_by_col, single_points = _collect_interp_columns( - cols, s_c, s_r, sel_idxs_by_col_all, sel_rows, r0, r1 - ) - _interp_columns( - out, - rows_by_col, - idxs_by_col, - sel_idxs_by_col_all, - sel_rows, - data, - frames, - dtype, - method, - spline_weight_cache, - ) - for rr_match, src_pos in single_points: - out[np.ix_(rr_match, frames)] = data[src_pos, frames] - - return out, (r0, r1), (c0, c1) - - -def baseline_window_frames(align_hz: float, baseline_window_s: float) -> int: - """Return the rolling-baseline window length in frames. - - Parameters - ---------- - align_hz : float - Alignment/analysis rate, in Hz. - baseline_window_s : float - Baseline window, in seconds. - - Returns - ------- - int - 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: - """Compute a NaN-aware rolling-median baseline of the interpolated data. - - Each frame's baseline is the median of its centered window, ignoring NaNs, - so windows with no valid samples stay NaN and edge windows are truncated to - the available samples. This is the fast moving-median analogue of the - former moving-mean baseline; the median is more robust to transient - activity spikes when estimating the background. - - 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 - and the result is sliced back to center each window on its frame. - - Parameters - ---------- - interp_data : ndarray of shape (n_sel, n_frames) - Interpolated background estimate (from :func:`build_interp_data`). - baseline_window : int - Rolling window length, in frames. - - Returns - ------- - ndarray - The rolling-median background estimate (NaN where no valid samples). - """ - n_frames = interp_data.shape[1] - window = int(min(max(baseline_window, 1), n_frames)) - - if bn is not None: - pad = window // 2 - if pad: - padded = np.concatenate( - [ - interp_data, - np.full( - (interp_data.shape[0], pad), - np.nan, - dtype=interp_data.dtype, - ), - ], - axis=1, - ) - else: - padded = interp_data - trailing = bn.move_median(padded, window=window, min_count=1, axis=1) - background = trailing[:, pad : pad + n_frames] - return background.astype(interp_data.dtype, copy=False) - - # 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) - .rolling(window=window, center=True, min_periods=1) - .median() - .to_numpy() - .T - ) - return background.astype(interp_data.dtype, copy=False) - - -def assemble_background( - interp_data_background: np.ndarray, - unique_motion_to_keep_yx: np.ndarray, - mot_inds_yx: np.ndarray, - sel_pix_idxs: np.ndarray, - ref_d: np.ndarray, - ref_r: np.ndarray, - ref_c: np.ndarray, - n_super_pixels: int, - n_frames: int, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, -) -> np.ndarray: - """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 - is copied onto that superpixel. - - Parameters - ---------- - interp_data_background : ndarray of shape (n_sel, n_frames) - Rolling-baseline background on the selected-pixel grid. - 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). - sel_pix_idxs : ndarray of int - Sorted flat selected-pixel indices. - ref_d, ref_r, ref_c : ndarray - Per-superpixel reference depth/row/column indices. - n_super_pixels, n_frames : int - Output shape. - dmd_pixels_per_column, dmd_pixels_per_row : int - Grid geometry. - - Returns - ------- - ndarray of shape (n_super_pixels, n_frames), float32 - Per-superpixel background (NaN where unmapped). - """ - plane_size = dmd_pixels_per_column * dmd_pixels_per_row - background = np.full((n_super_pixels, n_frames), np.nan, dtype=np.float32) - - for motion_idx in range(len(unique_motion_to_keep_yx)): - motion_frames = np.flatnonzero(mot_inds_yx == motion_idx) - d_r = int(unique_motion_to_keep_yx[motion_idx, 0]) - d_c = int(unique_motion_to_keep_yx[motion_idx, 1]) - s_d = ref_d - s_r = ref_r + d_r - s_c = ref_c + d_c - - shifted_indices = s_d * plane_size + s_r * dmd_pixels_per_row + s_c - - 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] - - 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) - ] - - return background - - -def fit_noise_variance_model( - low_res_data_norm: np.ndarray, - background: np.ndarray, - v_im: np.ndarray, - vif: float = 1.38, -) -> 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 - the first valid frames, then returns the predicted standard deviation for - every sample. - - Parameters - ---------- - low_res_data_norm : ndarray of shape (n_superpixels, n_frames) - Count-normalized channel-1 traces. - 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). - vif : float - Variance inflation factor. - - Returns - ------- - data_std : ndarray - Per-sample predicted standard deviation. - v_k : float - Fitted multiplicative variance coefficient. - v_b : float - Fitted additive variance floor. - """ - 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) - data_std = np.sqrt(np.clip(v_k * background * v_im, 0, None) + v_b) - return data_std, v_k, v_b - - -def compute_residual( - low_res_data_norm: np.ndarray, - background: np.ndarray, - data_std: np.ndarray, -) -> np.ndarray: - """Return the background-subtracted, noise-normalized residual. - - Parameters - ---------- - low_res_data_norm : ndarray - Count-normalized traces. - background : ndarray - Per-superpixel background estimate. - data_std : ndarray - Per-sample predicted standard deviation. - - Returns - ------- - ndarray - (low_res_data_norm - background) / data_std. - """ - return (low_res_data_norm - background) / data_std +"""Band background interpolation, rolling baseline, and noise estimation.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +from numpy.typing import DTypeLike +from scipy.interpolate import CubicSpline + +try: + import bottleneck as bn +except ImportError: + bn = None + + +def _collect_interp_columns( + 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) + 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 = {} + single_points = [] + for c in cols: + c_int = int(c) + if c_int not in sel_idxs_by_col_all: + continue + data_ix = np.flatnonzero(s_c == c) + if data_ix.size == 1: + rr = int(s_r[data_ix[0]]) + col_sel = sel_idxs_by_col_all[c_int] + rr_match = col_sel[sel_rows[col_sel] == rr] + if rr_match.size > 0 and (r0 <= rr <= r1): + single_points.append((rr_match, int(data_ix[0]))) + continue + rows = s_r[data_ix] + order = rows.argsort(kind="mergesort") + rows_by_col[c_int] = rows[order] + idxs_by_col[c_int] = data_ix[order] + return rows_by_col, idxs_by_col, single_points + + +# Preserve scientific parity with the reference interpolation branches. +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 + strictly between reference rows use linear or natural-cubic interpolation; + those outside the sampled row range are left untouched (NaN). Cubic spline + weights depend only on row geometry, so they are computed once and applied + 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(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] + src_idx = idxs_by_col[c_int] + + pos = np.searchsorted(rows, target_rows, side="left") + in_bounds = pos < rows.size + exact = np.zeros_like(pos, dtype=bool) + exact[in_bounds] = rows[pos[in_bounds]] == target_rows[in_bounds] + + 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] + + lo = pos - 1 + hi = pos + interp_mask = (~exact) & (lo >= 0) & (hi < rows.size) + if not np.any(interp_mask): + continue + + interp_rows = np.flatnonzero(interp_mask) + lo_v = lo[interp_mask] + hi_v = hi[interp_mask] + row_lo = rows[lo_v].astype(dtype, copy=False) + row_hi = rows[hi_v].astype(dtype, copy=False) + denom = row_hi - row_lo + nonzero = denom != 0 + if not np.any(nonzero): + # Unreachable defensive guard (mirrors the reference): sorted + # distinct rows make searchsorted never straddle equal rows, so + # denom is always non-zero here. + continue + + interp_rows = interp_rows[nonzero] + lo_v = lo_v[nonzero] + 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] + + target_indices = col_sel_pix_idxs[interp_rows] + linear_frame_mask = np.ones(frames.size, dtype=bool) + has_cubic_geometry = rows.size >= 3 and np.all(np.diff(rows) > 0) + if method == "cubic" and has_cubic_geometry: + source_values = data[src_idx][:, frames] + 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) + origin = source_rows[0] + cache_key = ( + tuple(source_rows - origin), + tuple(target_interp_rows - origin), + np.dtype(dtype).str, + ) + spline_weights = ( + spline_weight_cache.get(cache_key) if spline_weight_cache is not None else None + ) + if spline_weights is None: + spline_weights = CubicSpline( + source_rows, + np.eye(rows.size, dtype=dtype), + axis=0, + bc_type="natural", + extrapolate=False, + )(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 + linear_frame_mask = ~complete_frames + + if not np.any(linear_frame_mask): + continue + linear_frames = frames[linear_frame_mask] + vals_lo = data[src_idx[lo_v]][:, linear_frames] + vals_hi = data[src_idx[hi_v]][:, linear_frames] + linear_values = (1.0 - alpha) * vals_lo + alpha * vals_hi + out[np.ix_(target_indices, linear_frames)] = linear_values + + +def build_interp_data( + data: np.ndarray, + ref_r: np.ndarray, + ref_c: np.ndarray, + sel_pixels_2d: np.ndarray, + unique_motion_to_keep_yx: np.ndarray, + mot_inds_yx: np.ndarray, + height: int = 800, + width: int = 1280, + dtype: DTypeLike = np.float32, + method: str = "cubic", +) -> 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 + motion) are linearly interpolated along rows, per column, onto the selected + pixels of the plane, filling one background estimate per selected pixel and + frame. Selected pixels outside the sampled row range remain NaN. + + Parameters + ---------- + data : ndarray of shape (n_ref, n_frames) + Reference-pixel traces for one plane. + 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. + 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). + 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 + a natural spline with precomputed geometry weights and falls back to + linear for columns with fewer than three samples or frames with missing + samples. + + Returns + ------- + out : ndarray of shape (n_sel, n_frames) + Interpolated background estimate (NaN where unsampled). + row_bounds : tuple of int + (r0, r1) inclusive row window. + col_bounds : tuple of int + (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(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()) + c0 = int(max(0, ref_c.min()) + unique_motion_to_keep_yx[:, 1].min()) + c1 = int(min(width, ref_c.max()) + unique_motion_to_keep_yx[:, 1].max()) + + out = np.full((sel_pixels_2d.shape[0], data.shape[1]), np.nan, dtype=dtype) + + 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} + + frames_by_motion = [ + np.flatnonzero(mot_inds_yx == idx) for idx in range(len(unique_motion_to_keep_yx)) + ] + spline_weight_cache = {} if method == "cubic" else None + + for m_idx, frames in enumerate(frames_by_motion): + if frames.size == 0: + continue + + s_r = ref_r + int(unique_motion_to_keep_yx[m_idx, 0]) + s_c = ref_c + int(unique_motion_to_keep_yx[m_idx, 1]) + + in_win = (s_r >= r0) & (s_r <= r1) & (s_c >= c0) & (s_c <= c1) + if not np.any(in_win): + continue + cols = np.unique(s_c[in_win]) + + rows_by_col, idxs_by_col, single_points = _collect_interp_columns( + cols, s_c, s_r, sel_idxs_by_col_all, sel_rows, r0, r1 + ) + _interp_columns( + out, + rows_by_col, + idxs_by_col, + sel_idxs_by_col_all, + sel_rows, + data, + frames, + dtype, + method, + spline_weight_cache, + ) + for rr_match, src_pos in single_points: + out[np.ix_(rr_match, frames)] = data[src_pos, frames] + + return out, (r0, r1), (c0, c1) + + +def baseline_window_frames(align_hz: float, baseline_window_s: float) -> int: + """Return the rolling-baseline window length in frames. + + Parameters + ---------- + align_hz : float + Alignment/analysis rate, in Hz. + baseline_window_s : float + Baseline window, in seconds. + + Returns + ------- + int + 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: + """Compute a NaN-aware rolling-median baseline of the interpolated data. + + Each frame's baseline is the median of its centered window, ignoring NaNs, + so windows with no valid samples stay NaN and edge windows are truncated to + the available samples. This is the fast moving-median analogue of the + former moving-mean baseline; the median is more robust to transient + activity spikes when estimating the background. + + 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 + and the result is sliced back to center each window on its frame. + + Parameters + ---------- + interp_data : ndarray of shape (n_sel, n_frames) + Interpolated background estimate (from :func:`build_interp_data`). + baseline_window : int + Rolling window length, in frames. + + Returns + ------- + ndarray + The rolling-median background estimate (NaN where no valid samples). + """ + n_frames = interp_data.shape[1] + window = int(min(max(baseline_window, 1), n_frames)) + + if bn is not None: + pad = window // 2 + if pad: + padded = np.concatenate( + [ + interp_data, + np.full( + (interp_data.shape[0], pad), + np.nan, + dtype=interp_data.dtype, + ), + ], + axis=1, + ) + else: + padded = interp_data + trailing = bn.move_median(padded, window=window, min_count=1, axis=1) + background = trailing[:, pad : pad + n_frames] + return background.astype(interp_data.dtype, copy=False) + + # 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) + .rolling(window=window, center=True, min_periods=1) + .median() + .to_numpy() + .T + ) + return background.astype(interp_data.dtype, copy=False) + + +def assemble_background( + interp_data_background: np.ndarray, + unique_motion_to_keep_yx: np.ndarray, + mot_inds_yx: np.ndarray, + sel_pix_idxs: np.ndarray, + ref_d: np.ndarray, + ref_r: np.ndarray, + ref_c: np.ndarray, + n_super_pixels: int, + n_frames: int, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, +) -> np.ndarray: + """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 + is copied onto that superpixel. + + Parameters + ---------- + interp_data_background : ndarray of shape (n_sel, n_frames) + Rolling-baseline background on the selected-pixel grid. + 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). + sel_pix_idxs : ndarray of int + Sorted flat selected-pixel indices. + ref_d, ref_r, ref_c : ndarray + Per-superpixel reference depth/row/column indices. + n_super_pixels, n_frames : int + Output shape. + dmd_pixels_per_column, dmd_pixels_per_row : int + Grid geometry. + + Returns + ------- + ndarray of shape (n_super_pixels, n_frames), float32 + Per-superpixel background (NaN where unmapped). + """ + plane_size = dmd_pixels_per_column * dmd_pixels_per_row + background = np.full((n_super_pixels, n_frames), np.nan, dtype=np.float32) + + for motion_idx in range(len(unique_motion_to_keep_yx)): + motion_frames = np.flatnonzero(mot_inds_yx == motion_idx) + d_r = int(unique_motion_to_keep_yx[motion_idx, 0]) + d_c = int(unique_motion_to_keep_yx[motion_idx, 1]) + s_d = ref_d + s_r = ref_r + d_r + s_c = ref_c + d_c + + shifted_indices = s_d * plane_size + s_r * dmd_pixels_per_row + s_c + + 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] + + 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) + ] + + return background + + +def fit_noise_variance_model( + low_res_data_norm: np.ndarray, + background: np.ndarray, + v_im: np.ndarray, + vif: float = 1.38, +) -> 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 + the first valid frames, then returns the predicted standard deviation for + every sample. + + Parameters + ---------- + low_res_data_norm : ndarray of shape (n_superpixels, n_frames) + Count-normalized channel-1 traces. + 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). + vif : float + Variance inflation factor. + + Returns + ------- + data_std : ndarray + Per-sample predicted standard deviation. + v_k : float + Fitted multiplicative variance coefficient. + v_b : float + Fitted additive variance floor. + """ + 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) + data_std = np.sqrt(np.clip(v_k * background * v_im, 0, None) + v_b) + return data_std, v_k, v_b + + +def compute_residual( + low_res_data_norm: np.ndarray, + background: np.ndarray, + data_std: np.ndarray, +) -> np.ndarray: + """Return the background-subtracted, noise-normalized residual. + + Parameters + ---------- + low_res_data_norm : ndarray + Count-normalized traces. + background : ndarray + Per-superpixel background estimate. + data_std : ndarray + Per-sample predicted standard deviation. + + Returns + ------- + ndarray + (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 9c081ec3..71c07bb6 100644 --- a/src/giant_python/extraction/band/geometry.py +++ b/src/giant_python/extraction/band/geometry.py @@ -1,238 +1,238 @@ -"""Pure DMD pixel geometry, selected-pixel support and PSF padding/cropping. - -Loading belongs to band.inputs; sparse projection to band.operators. -""" - -from __future__ import annotations - -import numpy as np -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]: - """Map flat reference-pixel indices to DMD (depth, column, row) indices. - - Parameters - ---------- - ref_pixs : ndarray of int - Flat reference-pixel indices. - dmd_pixels_per_column, dmd_pixels_per_row : int - DMD geometry. - - Returns - ------- - ref_d, ref_c, ref_r : ndarray of int32 - Depth, column, and row indices. - """ - ref_pixs = np.asarray(ref_pixs, dtype=np.int64) - 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_r = np.mod(ref_pixs, npc).astype(np.int32) - return ref_d, ref_c, ref_r - - -def build_subsample_matrix_inds( - all_super_pixel_ids: np.ndarray, - sparse_mask_inds: np.ndarray, -) -> np.ndarray: - """Build the superpixel -> reference-pixel index map for one DMD. - - 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 - ---------- - 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. - - Returns - ------- - ndarray of shape (n_superpixels, 2), int32 - [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) - for sp in range(num_super_pixels): - inds = np.where(sparse_mask_inds[:, 1] == sp + 1)[0] - open_pixs = sparse_mask_inds[inds, 0] - 1 - ref_pix = open_pixs[int(np.floor(len(open_pixs) / 2))] - out[sp, 0] = ref_pix - out[sp, 1] = sp + 1 - return out - - -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. - - Returns - ------- - ndarray - The padded PSF of shape (height, width). - """ - ph, pw = psf2d.shape - pad_r = (height - ph) // 2 - pad_c = (width - pw) // 2 - return np.pad( - psf2d, - ((pad_r, pad_r), (pad_c, pad_c)), - constant_values=np.min(psf2d), - ) - - -def build_combined_psf(psfs: list) -> np.ndarray: - """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) - for i, p in enumerate(psfs): - combined[i] = _pad_to(p, height, width) - return combined - - -def threshold_and_crop_psf(psf2d: np.ndarray) -> np.ndarray: - """Zero values below max * exp(-3) and crop boundary zeros. - - Parameters - ---------- - psf2d : ndarray - A single-DMD PSF image. - - Returns - ------- - ndarray of float32 - The thresholded, tightly-cropped PSF. - """ - psf2d = psf2d.astype(np.float32, copy=True) - psf2d[psf2d < np.max(psf2d) * np.exp(-3)] = 0 - non_zero_rows = np.any(psf2d != 0, axis=1) - non_zero_cols = np.any(psf2d != 0, axis=0) - row_start, row_end = np.where(non_zero_rows)[0][[0, -1]] - col_start, col_end = np.where(non_zero_cols)[0][[0, -1]] - row_stop = row_end + 1 - col_stop = col_end + 1 - return psf2d[row_start:row_stop, col_start:col_stop] - - -def build_selected_pixel_mask( - unique_motion_to_keep_yx: 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, - psf2d: 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 - dilates in-plane by the PSF footprint. - - Parameters - ---------- - unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2) - Kept 2-D motion vectors. - ref_d, ref_r, ref_c : ndarray - Per-superpixel reference depth/row/column indices. - num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int - Grid geometry. - psf2d : ndarray - The (cropped) PSF for this DMD; its shape sets the dilation footprint. - - Returns - ------- - sel_pix_mask : ndarray of bool - (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) - for i in range(len(unique_motion_to_keep_yx)): - sel_pix_mask[ - ref_d, - ref_r + int(unique_motion_to_keep_yx[i, 0]), - ref_c + int(unique_motion_to_keep_yx[i, 1]), - ] = True - sel_pix_mask = ndimage.binary_dilation( - sel_pix_mask, - structure=np.ones((1, psf2d.shape[0], psf2d.shape[1]), dtype=bool), - ) - sel_pix_idxs = np.flatnonzero(sel_pix_mask) - return sel_pix_mask, sel_pix_idxs - - -def pixel_coords_from_idxs( - sel_pix_idxs: np.ndarray, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, -) -> np.ndarray: - """Convert flat selected-pixel indices to [z, row, col] coordinates. - - Parameters - ---------- - sel_pix_idxs : ndarray of int - Flattened selected-pixel indices. - dmd_pixels_per_column, dmd_pixels_per_row : int - Grid geometry. - - Returns - ------- - ndarray of shape (n_sel, 3), int32 - [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) - pixel_coords[:, 0] = sel_pix_idxs // plane_size - remainder = sel_pix_idxs % plane_size - pixel_coords[:, 1] = remainder // dmd_pixels_per_row - pixel_coords[:, 2] = remainder % dmd_pixels_per_row - return pixel_coords - - -def selected_pixels_2d_for_plane( - sel_pix_idxs: np.ndarray, - 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. - - Parameters - ---------- - sel_pix_idxs : ndarray of int - Flattened selected-pixel indices (all planes). - plane_z : int - The z-plane to select. - dmd_pixels_per_column, dmd_pixels_per_row : int - Grid geometry. - - Returns - ------- - z_idxs : ndarray - 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. - """ - 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, - ]) - return z_idxs, sel_pixels_2d +"""Pure DMD pixel geometry, selected-pixel support and PSF padding/cropping. + +Loading belongs to band.inputs; sparse projection to band.operators. +""" + +from __future__ import annotations + +import numpy as np +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]: + """Map flat reference-pixel indices to DMD (depth, column, row) indices. + + Parameters + ---------- + ref_pixs : ndarray of int + Flat reference-pixel indices. + dmd_pixels_per_column, dmd_pixels_per_row : int + DMD geometry. + + Returns + ------- + ref_d, ref_c, ref_r : ndarray of int32 + Depth, column, and row indices. + """ + ref_pixs = np.asarray(ref_pixs, dtype=np.int64) + 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_r = np.mod(ref_pixs, npc).astype(np.int32) + return ref_d, ref_c, ref_r + + +def build_subsample_matrix_inds( + all_super_pixel_ids: np.ndarray, + sparse_mask_inds: np.ndarray, +) -> np.ndarray: + """Build the superpixel -> reference-pixel index map for one DMD. + + 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 + ---------- + 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. + + Returns + ------- + ndarray of shape (n_superpixels, 2), int32 + [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) + for sp in range(num_super_pixels): + inds = np.where(sparse_mask_inds[:, 1] == sp + 1)[0] + open_pixs = sparse_mask_inds[inds, 0] - 1 + ref_pix = open_pixs[int(np.floor(len(open_pixs) / 2))] + out[sp, 0] = ref_pix + out[sp, 1] = sp + 1 + return out + + +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. + + Returns + ------- + ndarray + The padded PSF of shape (height, width). + """ + ph, pw = psf2d.shape + pad_r = (height - ph) // 2 + pad_c = (width - pw) // 2 + return np.pad( + psf2d, + ((pad_r, pad_r), (pad_c, pad_c)), + constant_values=np.min(psf2d), + ) + + +def build_combined_psf(psfs: list) -> np.ndarray: + """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) + for i, p in enumerate(psfs): + combined[i] = _pad_to(p, height, width) + return combined + + +def threshold_and_crop_psf(psf2d: np.ndarray) -> np.ndarray: + """Zero values below max * exp(-3) and crop boundary zeros. + + Parameters + ---------- + psf2d : ndarray + A single-DMD PSF image. + + Returns + ------- + ndarray of float32 + The thresholded, tightly-cropped PSF. + """ + psf2d = psf2d.astype(np.float32, copy=True) + psf2d[psf2d < np.max(psf2d) * np.exp(-3)] = 0 + non_zero_rows = np.any(psf2d != 0, axis=1) + non_zero_cols = np.any(psf2d != 0, axis=0) + row_start, row_end = np.where(non_zero_rows)[0][[0, -1]] + col_start, col_end = np.where(non_zero_cols)[0][[0, -1]] + row_stop = row_end + 1 + col_stop = col_end + 1 + return psf2d[row_start:row_stop, col_start:col_stop] + + +def build_selected_pixel_mask( + unique_motion_to_keep_yx: 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, + psf2d: 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 + dilates in-plane by the PSF footprint. + + Parameters + ---------- + unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2) + Kept 2-D motion vectors. + ref_d, ref_r, ref_c : ndarray + Per-superpixel reference depth/row/column indices. + num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int + Grid geometry. + psf2d : ndarray + The (cropped) PSF for this DMD; its shape sets the dilation footprint. + + Returns + ------- + sel_pix_mask : ndarray of bool + (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) + for i in range(len(unique_motion_to_keep_yx)): + sel_pix_mask[ + ref_d, + ref_r + int(unique_motion_to_keep_yx[i, 0]), + ref_c + int(unique_motion_to_keep_yx[i, 1]), + ] = True + sel_pix_mask = ndimage.binary_dilation( + sel_pix_mask, + structure=np.ones((1, psf2d.shape[0], psf2d.shape[1]), dtype=bool), + ) + sel_pix_idxs = np.flatnonzero(sel_pix_mask) + return sel_pix_mask, sel_pix_idxs + + +def pixel_coords_from_idxs( + sel_pix_idxs: np.ndarray, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, +) -> np.ndarray: + """Convert flat selected-pixel indices to [z, row, col] coordinates. + + Parameters + ---------- + sel_pix_idxs : ndarray of int + Flattened selected-pixel indices. + dmd_pixels_per_column, dmd_pixels_per_row : int + Grid geometry. + + Returns + ------- + ndarray of shape (n_sel, 3), int32 + [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) + pixel_coords[:, 0] = sel_pix_idxs // plane_size + remainder = sel_pix_idxs % plane_size + pixel_coords[:, 1] = remainder // dmd_pixels_per_row + pixel_coords[:, 2] = remainder % dmd_pixels_per_row + return pixel_coords + + +def selected_pixels_2d_for_plane( + sel_pix_idxs: np.ndarray, + 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. + + Parameters + ---------- + sel_pix_idxs : ndarray of int + Flattened selected-pixel indices (all planes). + plane_z : int + The z-plane to select. + dmd_pixels_per_column, dmd_pixels_per_row : int + Grid geometry. + + Returns + ------- + z_idxs : ndarray + 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. + """ + 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, + ]) + 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 fc449044..77506189 100644 --- a/src/giant_python/extraction/band/inputs.py +++ b/src/giant_python/extraction/band/inputs.py @@ -1,354 +1,354 @@ -"""Band runtime input preparation and displacement-to-offset normalization. - -Shared IO is faithful to saved displacement. Only this backend boundary -negates offline motion into the reference offsets used by band numerics. -Lookup/reference/PSF loading and asset discovery also belong at this boundary; -PSF padding and cropping delegate to pure geometry functions. -""" - -from __future__ import annotations - -import os -from importlib import resources -from pathlib import Path - -import numpy as np - -from ...io.hdf5 import load_struct_h5, to_serializable -from ...io.slap2 import load_alignment_data_h5 as read_alignment_data_h5 -from ...io.tiff import read_tiff -from ...models.trial_table import TrialTable -from .geometry import build_combined_psf, threshold_and_crop_psf - - -def load_lookup_table(path: str | Path, n_dmds: int) -> dict: - """Load the band-registration lookup table (bandRegLookupTable.h5). - - Parameters - ---------- - path : str or Path - Path to the lookup-table HDF5 file. - n_dmds : int - Number of DMD paths. - - Returns - ------- - dict - {"allSuperPixelIDs": {...}, "sparseMaskInds": {...}, - "fastZ2RefZ": {...}}, each an inner dict keyed DMD{N}. - - Raises - ------ - ValueError - If a requested DMD has no Path/DMD lookup group. - """ - lt = load_struct_h5(path) - all_super_pixel_ids = {} - sparse_mask_inds = {} - fastz_to_refz = {} - 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}") - 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) - return { - "allSuperPixelIDs": all_super_pixel_ids, - "sparseMaskInds": sparse_mask_inds, - "fastZ2RefZ": fastz_to_refz, - } - - -def _ref_stack_group(ref_stack: dict, dmd_ix: int) -> dict: - """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} or DMD{dmd_ix + 1}") - return group - - -def find_reference_file(datadr: str | Path, dmd_ix: int) -> str | None: - """Find the REFERENCE tif for a DMD under datadr (recursive glob). - - Parameters - ---------- - datadr : str or Path - Raw-data directory. - dmd_ix : int - 0-based DMD index. - - Returns - ------- - str or None - Path to the first matching REFERENCE tif, or None if none found. - """ - patterns = ( - f"**/*DMD{dmd_ix + 1}_CONFIG2-REFERENCE*", - f"**/*DMD{dmd_ix + 1}-REFERENCE*", - ) - for pattern in patterns: - matches = list(Path(datadr).glob(pattern)) - if matches: - return str(matches[0]) - return None - - -def load_reference_stack( - datadr: str | Path, - ref_stack_meta: dict, - dmd_ix: int, -) -> 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 - trial table's embedded ref_stack metadata. The raw counts are scaled by - 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. - 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 : ndarray - Channel indices for this DMD. - ref_file : str or None - The REFERENCE file used, or None. - """ - grp = _ref_stack_group(ref_stack_meta, dmd_ix) - channels = np.asarray(grp["channels"]).reshape(-1) - num_channels = len(channels) - - ref_file = find_reference_file(datadr, dmd_ix) - if ref_file is None: - return None, channels, None - - ref = read_tiff(ref_file) / 100 - ref = ref.reshape(-1, num_channels, ref.shape[1], ref.shape[2]) - ref = ref.transpose(1, 0, 2, 3) - return ref, channels, ref_file - - -def default_psf(dilation: int) -> np.ndarray: - """Load a bundled default PSF template (assets/psfs/dil-NN.tif). - - Parameters - ---------- - dilation : int - Dilation size selecting dil-{dilation:02d}.tif (e.g. 17). - - Returns - ------- - ndarray of float32 - The PSF template image. - """ - name = f"dil-{int(dilation):02d}.tif" - 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) - - -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. - - Parameters - ---------- - dilation : int - Dilation size selecting the bundled PSF template. - n_dmds : int - Number of DMD paths. - - Returns - ------- - dict - {"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)} - - -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 { - **data, - **{ - key: None if data[key] is None else -data[key] - for key in ("motionDSr", "motionDSc", "motionDSz") - }, - } - - -def _resolve_fn_adata(fn_adata: np.ndarray, moco_save_dr: str) -> np.ndarray: - """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)) - return out - - -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. - - 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 - motion_correction = tt.motion_correction or {} - if slap2 is None or "fn_adata" not in motion_correction: - raise ValueError( - "load_trial_table expects a registered SLAP2 band trial table " - "(slap2_info + motion_correction/fn_adata); " - f"got {str(path)!r}." - ) - datadr = str(tt.datadr) if tt.datadr is not None else "" - result_dr = str(tt.savedr) if tt.savedr is not None else "" - 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() - } - 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)) - n_dmds, n_trials = filenames.shape - return { - "trial_table": tt, - "source_path": tt.source_path, - "datadr": datadr, - "savedr": result_dr, - "moco_save_dr": moco_save_dr, - "annotation_save_dr": os.path.join(result_dr, "annotations"), - "src_extr_save_dr": os.path.join(result_dr, "source_extraction"), - "align_params": align_params, - "n_dmds": int(n_dmds), - "n_trials": int(n_trials), - "filename": filenames, - "first_line": first_line, - "last_line": last_line, - "fn_adata": _resolve_fn_adata(fn_adata, moco_save_dr), - "ref_stack": slap2.ref_stack or {}, - } - - -def compute_keep_trials( - fn_adata_abs: np.ndarray, - filename: np.ndarray, - datadr: str | Path, -) -> np.ndarray: - """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 - keep = np.ones((n_dmds, n_trials), dtype=bool) - for d in range(n_dmds): - for t in range(n_trials): - adata = fn_adata_abs[d, t] - src = filename[d, t] - src_path = os.path.join(str(datadr), str(src)) if src else "" - if ( - not adata - or not os.path.exists(str(adata)) - or not src - or not os.path.exists(src_path) - ): - keep[d, t] = False - return keep - - -def read_align_info( - fn_adata_abs: np.ndarray, - keep_trials: np.ndarray, - n_dmds: int, -) -> tuple: - """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 = {} - num_channels = None - for d in range(n_dmds): - valid = np.flatnonzero(keep_trials[d]) - if valid.size == 0: - continue - a_data = load_alignment_data_h5(fn_adata_abs[d, valid[0]]) - align_hz[f"DMD{d + 1}"] = a_data["alignHz"] - num_channels = a_data["numChannels"] - return align_hz, num_channels +"""Band runtime input preparation and displacement-to-offset normalization. + +Shared IO is faithful to saved displacement. Only this backend boundary +negates offline motion into the reference offsets used by band numerics. +Lookup/reference/PSF loading and asset discovery also belong at this boundary; +PSF padding and cropping delegate to pure geometry functions. +""" + +from __future__ import annotations + +import os +from importlib import resources +from pathlib import Path + +import numpy as np + +from ...io.hdf5 import load_struct_h5, to_serializable +from ...io.slap2 import load_alignment_data_h5 as read_alignment_data_h5 +from ...io.tiff import read_tiff +from ...models.trial_table import TrialTable +from .geometry import build_combined_psf, threshold_and_crop_psf + + +def load_lookup_table(path: str | Path, n_dmds: int) -> dict: + """Load the band-registration lookup table (bandRegLookupTable.h5). + + Parameters + ---------- + path : str or Path + Path to the lookup-table HDF5 file. + n_dmds : int + Number of DMD paths. + + Returns + ------- + dict + {"allSuperPixelIDs": {...}, "sparseMaskInds": {...}, + "fastZ2RefZ": {...}}, each an inner dict keyed DMD{N}. + + Raises + ------ + ValueError + If a requested DMD has no Path/DMD lookup group. + """ + lt = load_struct_h5(path) + all_super_pixel_ids = {} + sparse_mask_inds = {} + fastz_to_refz = {} + 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}") + 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) + return { + "allSuperPixelIDs": all_super_pixel_ids, + "sparseMaskInds": sparse_mask_inds, + "fastZ2RefZ": fastz_to_refz, + } + + +def _ref_stack_group(ref_stack: dict, dmd_ix: int) -> dict: + """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} or DMD{dmd_ix + 1}") + return group + + +def find_reference_file(datadr: str | Path, dmd_ix: int) -> str | None: + """Find the REFERENCE tif for a DMD under datadr (recursive glob). + + Parameters + ---------- + datadr : str or Path + Raw-data directory. + dmd_ix : int + 0-based DMD index. + + Returns + ------- + str or None + Path to the first matching REFERENCE tif, or None if none found. + """ + patterns = ( + f"**/*DMD{dmd_ix + 1}_CONFIG2-REFERENCE*", + f"**/*DMD{dmd_ix + 1}-REFERENCE*", + ) + for pattern in patterns: + matches = list(Path(datadr).glob(pattern)) + if matches: + return str(matches[0]) + return None + + +def load_reference_stack( + datadr: str | Path, + ref_stack_meta: dict, + dmd_ix: int, +) -> 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 + trial table's embedded ref_stack metadata. The raw counts are scaled by + 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. + 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 : ndarray + Channel indices for this DMD. + ref_file : str or None + The REFERENCE file used, or None. + """ + grp = _ref_stack_group(ref_stack_meta, dmd_ix) + channels = np.asarray(grp["channels"]).reshape(-1) + num_channels = len(channels) + + ref_file = find_reference_file(datadr, dmd_ix) + if ref_file is None: + return None, channels, None + + ref = read_tiff(ref_file) / 100 + ref = ref.reshape(-1, num_channels, ref.shape[1], ref.shape[2]) + ref = ref.transpose(1, 0, 2, 3) + return ref, channels, ref_file + + +def default_psf(dilation: int) -> np.ndarray: + """Load a bundled default PSF template (assets/psfs/dil-NN.tif). + + Parameters + ---------- + dilation : int + Dilation size selecting dil-{dilation:02d}.tif (e.g. 17). + + Returns + ------- + ndarray of float32 + The PSF template image. + """ + name = f"dil-{int(dilation):02d}.tif" + 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) + + +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. + + Parameters + ---------- + dilation : int + Dilation size selecting the bundled PSF template. + n_dmds : int + Number of DMD paths. + + Returns + ------- + dict + {"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)} + + +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 { + **data, + **{ + key: None if data[key] is None else -data[key] + for key in ("motionDSr", "motionDSc", "motionDSz") + }, + } + + +def _resolve_fn_adata(fn_adata: np.ndarray, moco_save_dr: str) -> np.ndarray: + """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)) + return out + + +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. + + 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 + motion_correction = tt.motion_correction or {} + if slap2 is None or "fn_adata" not in motion_correction: + raise ValueError( + "load_trial_table expects a registered SLAP2 band trial table " + "(slap2_info + motion_correction/fn_adata); " + f"got {str(path)!r}." + ) + datadr = str(tt.datadr) if tt.datadr is not None else "" + result_dr = str(tt.savedr) if tt.savedr is not None else "" + 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() + } + 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)) + n_dmds, n_trials = filenames.shape + return { + "trial_table": tt, + "source_path": tt.source_path, + "datadr": datadr, + "savedr": result_dr, + "moco_save_dr": moco_save_dr, + "annotation_save_dr": os.path.join(result_dr, "annotations"), + "src_extr_save_dr": os.path.join(result_dr, "source_extraction"), + "align_params": align_params, + "n_dmds": int(n_dmds), + "n_trials": int(n_trials), + "filename": filenames, + "first_line": first_line, + "last_line": last_line, + "fn_adata": _resolve_fn_adata(fn_adata, moco_save_dr), + "ref_stack": slap2.ref_stack or {}, + } + + +def compute_keep_trials( + fn_adata_abs: np.ndarray, + filename: np.ndarray, + datadr: str | Path, +) -> np.ndarray: + """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 + keep = np.ones((n_dmds, n_trials), dtype=bool) + for d in range(n_dmds): + for t in range(n_trials): + adata = fn_adata_abs[d, t] + src = filename[d, t] + src_path = os.path.join(str(datadr), str(src)) if src else "" + if ( + not adata + or not os.path.exists(str(adata)) + or not src + or not os.path.exists(src_path) + ): + keep[d, t] = False + return keep + + +def read_align_info( + fn_adata_abs: np.ndarray, + keep_trials: np.ndarray, + n_dmds: int, +) -> tuple: + """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 = {} + num_channels = None + for d in range(n_dmds): + valid = np.flatnonzero(keep_trials[d]) + if valid.size == 0: + continue + a_data = load_alignment_data_h5(fn_adata_abs[d, valid[0]]) + align_hz[f"DMD{d + 1}"] = a_data["alignHz"] + num_channels = a_data["numChannels"] + return align_hz, num_channels diff --git a/src/giant_python/extraction/band/localization.py b/src/giant_python/extraction/band/localization.py index 5ee7d515..10451c40 100644 --- a/src/giant_python/extraction/band/localization.py +++ b/src/giant_python/extraction/band/localization.py @@ -1,942 +1,942 @@ -"""Superpixel-space NMF source localization. - -Ported from the source-localization block of -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` -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. - -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`), -2. fits the parametric Gaussian profiles to those targets with Adam - (:func:`fit_gaussian_profiles`), -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. - -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 -unregularized QR temporal solve changes numerical results. The reference's -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 cast - -import numpy as np -import torch -from scipy.linalg import qr, solve_triangular - -from ...progress import progress -from .activity import smooth_rho - - -def sel_pix_gaussian_profile( - gaussian_params: torch.Tensor, pixel_coords_tensor: torch.Tensor -) -> torch.Tensor: - """Render normalized bivariate-Gaussian profiles over selected pixels. - - 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). - pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) - Selected-pixel [z, row, col] coordinates. - - Returns - ------- - torch.Tensor of shape (n_sel, N) - Column-normalized profiles; each source is confined to its own z-plane - and to within 3 sigma of its center. - """ - z_planes = gaussian_params[:, 0].unsqueeze(0) - y_means = gaussian_params[:, 1].unsqueeze(0) - x_means = gaussian_params[:, 2].unsqueeze(0) - y_sigmas = gaussian_params[:, 3].unsqueeze(0) - x_sigmas = gaussian_params[:, 4].unsqueeze(0) - corr_coef = torch.tanh(gaussian_params[:, 5].unsqueeze(0)) - - y_centered = pixel_coords_tensor[:, 1].unsqueeze(1) - y_means - x_centered = pixel_coords_tensor[:, 2].unsqueeze(1) - x_means - - z_score_y = y_centered / y_sigmas - z_score_x = x_centered / x_sigmas - - exponent = (-1 / (2 * (1 - corr_coef**2))) * ( - z_score_y**2 - 2 * corr_coef * z_score_x * z_score_y + z_score_x**2 - ) - profile = torch.exp(exponent) - profile = ( - profile - * ( - (torch.sqrt(z_score_y**2 + z_score_x**2) <= 3) - & (pixel_coords_tensor[:, 0].unsqueeze(1) == z_planes) - ).float() - ) - - return profile / torch.sum(profile, dim=0, keepdim=True) - - -def sel_pix_patch_profile( - patch_params: torch.Tensor, pixel_coords_tensor: torch.Tensor -) -> torch.Tensor: - """Render rectangular in-plane support patches over selected pixels. - - Parameters - ---------- - patch_params : torch.Tensor of shape (N, 5) - 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. - - Returns - ------- - torch.Tensor of bool, shape (n_sel, N) - True where a pixel is inside a source's patch (same z-plane, within the - radii). - """ - z_planes = patch_params[:, 0].unsqueeze(0) - y_means = patch_params[:, 1].unsqueeze(0) - x_means = patch_params[:, 2].unsqueeze(0) - y_radii = patch_params[:, 3].unsqueeze(0) - x_radii = patch_params[:, 4].unsqueeze(0) - - y_centered = pixel_coords_tensor[:, 1].unsqueeze(1) - y_means - x_centered = pixel_coords_tensor[:, 2].unsqueeze(1) - x_means - - return ( - (torch.abs(y_centered) < y_radii) - & (torch.abs(x_centered) < x_radii) - & (pixel_coords_tensor[:, 0].unsqueeze(1) == z_planes) - ) - - -def init_source_params(source_seeds: np.ndarray) -> torch.Tensor: - """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]. - - Returns - ------- - torch.Tensor of shape (N, 6) - The initial source parameters. - """ - n = source_seeds.shape[0] - return torch.cat( - [ - torch.tensor(source_seeds, dtype=torch.float32), - torch.ones(n, 2, dtype=torch.float32), - torch.zeros(n, 1, dtype=torch.float32), - ], - dim=1, - ) - - -def build_a_patches( - source_seeds: np.ndarray, - pixel_coords_tensor: torch.Tensor, - sel_pix_idxs: np.ndarray, - n_pixels: int, - d_xy: float, -) -> torch.Tensor: - """Build the per-source rectangular support mask over the full pixel grid. - - Parameters - ---------- - source_seeds : ndarray of shape (N, 3) - 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. - n_pixels : int - Total number of image pixels (z * rows * cols). - d_xy : float - Half-width of the square support patch, in pixels. - - Returns - ------- - torch.Tensor of bool, shape (n_pixels, N) - The support mask. - """ - n_sources = source_seeds.shape[0] - a_patches = torch.zeros((n_pixels, n_sources), dtype=torch.bool) - patch_params = torch.cat( - [ - torch.tensor(source_seeds, dtype=torch.float32), - d_xy * torch.ones(n_sources, 2, dtype=torch.float32), - ], - dim=1, - ) - 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], - a_patches: torch.Tensor, - sel_pix_idxs: np.ndarray, - n_motions: int, -) -> 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. - a_patches : torch.Tensor of bool, shape (n_pixels, N) - Support mask from :func:`build_a_patches`. - sel_pix_idxs : ndarray of int - Flat selected-pixel indices. - n_motions : int - Number of motion bins. - - Returns - ------- - list of torch.Tensor of bool - 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) - ] - - -def project_spatial_profiles( - source_params: torch.Tensor, - pixel_coords_tensor: torch.Tensor, - sel_pix_idxs: np.ndarray, - n_pixels: int, - a_patches: torch.Tensor, -) -> torch.Tensor: - """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. - - Parameters - ---------- - source_params : torch.Tensor of shape (N, 6) - Source parameters. - pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) - Selected-pixel coordinates. - sel_pix_idxs : ndarray of int - Flat selected-pixel indices. - n_pixels : int - Total number of image pixels. - a_patches : torch.Tensor of bool, shape (n_pixels, N) - Support mask. - - Returns - ------- - torch.Tensor of shape (n_pixels, N) - The normalized 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[~a_patches] = 0 - mass = torch.sum(a, dim=0, keepdim=True) - mass[mass <= 0] = 1 - a /= mass - return a - - -def _motion_frames(mot_inds_yx: np.ndarray, i: int) -> np.ndarray: - """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: - """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 - 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. - No normal equations or ridge regularization are used. - - 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 - 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. - 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() - phi = np.zeros((x.shape[1], data_motion.shape[1]), dtype=x_array.dtype) - if min(x.shape) == 0 or data_motion.shape[1] == 0: - return torch.from_numpy(phi.T) - - # SciPy rejects the entire RHS batch if even one frame is nonfinite. - # Preserve missing frames without contaminating the independent fits, - # including coefficients that would otherwise be zero for deficient X. - valid_frames = np.all(np.isfinite(data_array), axis=0) - phi[:, ~valid_frames] = np.nan - - q, r, piv = qr(x_array, mode="economic", pivoting=True) - diagonal = np.abs(np.diag(r)) - tolerance = max(x.shape) * np.finfo(x_array.dtype).eps * diagonal[0] - # Use a leading block: stop at the first numerically dependent column. - 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] - phi[np.ix_(piv[:rank], valid_frames)] = solve_triangular( - r[:rank, :rank], q[:, :rank].T @ finite_data - ) - return torch.from_numpy(phi.T) - - -def fit_phi_all_motions( - a: 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. - - Parameters - ---------- - a : torch.Tensor of shape (n_pixels, N) - Spatial profiles. - h_mots : list of torch.Tensor - 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). - n_motions : int - Number of motion bins. - phi_low_res : torch.Tensor of shape (n_frames, N) - Temporal weights, updated in place per motion bin and returned. - - Returns - ------- - torch.Tensor - phi_low_res with each motion's frames filled. - """ - for i in range(n_motions): - frames = _motion_frames(mot_inds_yx, i) - x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, :]) - phi_low_res[frames, :] = solve_phi_motion(x, data_for_nmf[:, frames]) - return phi_low_res - - -def multiplicative_nmf( - a: 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, - n_motions: int, - sparse_fac: float, - max_iters: int, - generator: torch.Generator | None = None, -) -> 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 - spatial - 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. - x_support_mots : list of torch.Tensor of bool - Per-motion superpixel support masks. - sel_pix_idxs : ndarray of int - Flat selected-pixel indices. - data_for_nmf : torch.Tensor of shape (n_superpixels, n_frames) - Residual data. - mot_inds_yx : ndarray of shape (n_frames,) - Per-frame motion-bin index. - n_motions : int - Number of motion bins. - sparse_fac : float - 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. - - Returns - ------- - list of torch.Tensor - Per-motion fitted superpixel spatial targets X_mots. - """ - 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. - i = cast(int, idx.item()) - frames = _motion_frames(mot_inds_yx, i) - - x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, :]) - x[~x_support_mots[i]] = 0 - x = x / torch.norm(x, dim=0, keepdim=True) - - phi = torch.clamp(solve_phi_motion(x, data_for_nmf[:, frames]), min=0) - - for iter_idx in range(max_iters): - numerator = x.T @ data_for_nmf[:, frames] - denominator = (x.T @ x) @ phi.T + 1e-10 - phi = torch.clamp(phi * (numerator / denominator).T, min=0) - - numerator = data_for_nmf[:, frames] @ phi - denominator = x @ (phi.T @ phi) + 1e-10 - x = torch.clamp(x * (numerator / denominator), min=0) - - x = x * x_support_mots[i].float() - - norms = torch.norm(x, dim=0, keepdim=True) - x = torch.where(norms > 0, x / norms, x) - phi = torch.where(norms > 0, phi * norms, phi) - - if iter_idx % 3 == 0: - x_max = torch.max(x, dim=0, keepdim=True)[0] - x = torch.where(x_max > 0, x / x_max, x) - x = torch.clamp(x, min=sparse_fac) - sparse_fac - norms = torch.norm(x, dim=0, keepdim=True) - x = torch.where(norms > 0, x / norms, x) - - x_mots[i] = x - # randperm visits every slot exactly once, including the empty case. - 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], - pixel_coords_tensor: torch.Tensor, - a_patches: torch.Tensor, - sel_pix_idxs: np.ndarray, - d_xy: float, - num_epochs: int, - n_motions: int, - learning_rate: float, - gd_tol: float, - generator: torch.Generator | None = None, -) -> torch.Tensor: - """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. - - Parameters - ---------- - source_params : torch.Tensor of shape (N, 6) - Current source parameters (z fixed; loc/scale/tilt optimized). - source_seeds : ndarray of shape (N, 3) - Peak seeds (for the location clamp bounds). - x_mots : list of torch.Tensor - Per-motion NMF spatial targets. - h_mots : list of torch.Tensor - Per-motion sparse H matrices. - pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) - Selected-pixel coordinates. - a_patches : torch.Tensor of bool - Support mask. - sel_pix_idxs : ndarray of int - Flat selected-pixel indices. - d_xy : float - Location clamp half-width. - num_epochs : int - Maximum optimization epochs (one motion each). - n_motions : int - Number of motion bins (epochs per round). - learning_rate : float - Base Adam learning rate (scaled per parameter group). - 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. - - Returns - ------- - torch.Tensor of shape (N, 6) - The updated source parameters. - """ - 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}, - ]) - - z_col = source_params[:, 0].unsqueeze(1) - loc_min = torch.from_numpy(source_seeds[:, 1:3] - 1.5).float() - loc_max = torch.from_numpy(source_seeds[:, 1:3] + 1.5).float() - - losses = [] - shuffled_indices = None - for epoch in range(num_epochs): - optimizer.zero_grad() - - a_step = sel_pix_gaussian_profile( - torch.cat([z_col, optim_loc, optim_scale, optim_tilt], dim=1), - pixel_coords_tensor, - ) - a_step = a_step * a_patches[sel_pix_idxs, :].float() - mass = torch.sum(a_step, dim=0, keepdim=True) - mass[mass <= 0] = 1 - a_step = a_step / mass - - if epoch % n_motions == 0: - shuffled_indices = torch.randperm(n_motions, generator=generator) - # Epoch zero initializes the permutation before any index is read. - i = cast( - int, - cast(torch.Tensor, shuffled_indices)[epoch % n_motions].item(), - ) - - x_step = torch.sparse.mm(h_mots[i], a_step) - norms = torch.norm(x_step, dim=0, keepdim=True) - x_step = torch.where(norms > 0, x_step / norms, x_step) - loss = torch.sum((x_step - x_mots[i]) ** 2) - - loss.backward() - optimizer.step() - - with torch.no_grad(): - optim_loc.clamp_(min=loc_min, max=loc_max) - optim_scale[:, 0].clamp_(min=0.3, max=2) - optim_scale[:, 1].clamp_(min=0.3, max=2) - - if epoch % n_motions == n_motions - 1: - total_loss = 0 - for i in range(n_motions): - x_step = torch.sparse.mm(h_mots[i], a_step) - norms = torch.norm(x_step, dim=0, keepdim=True) - x_step = torch.where(norms > 0, x_step / norms, x_step) - 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: - break - - return torch.cat( - [z_col, optim_loc.detach(), optim_scale.detach(), optim_tilt.detach()], - dim=1, - ) - - -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: 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], - 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 - ---------- - order : array-like of int - Source indices in the new order (a permutation for sorting, or a subset - for pruning). - source_params, source_seeds, a, a_patches, phi_low_res : array/tensor - Per-source state to reindex along the source axis. - x_support_mots : list of torch.Tensor - Per-motion support masks (reindexed along the source axis). - - Returns - ------- - tuple - 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, :] - a = a[:, order] - a_patches = a_patches[:, order] - x_support_mots = [support[:, order] for support in x_support_mots] - phi_low_res = phi_low_res[:, order] - return ( - source_params, - source_seeds, - a, - a_patches, - x_support_mots, - phi_low_res, - ) - - -def compute_source_snr( - a: torch.Tensor, - h_mots: list[torch.Tensor], - sel_pix_idxs: np.ndarray, - data_for_nmf: torch.Tensor, - phi_low_res: torch.Tensor, - mot_inds_yx: np.ndarray, - n_motions: int, - n_sources: int, -) -> torch.Tensor: - """Per-source low-resolution SNR (explained variance / residual variance). - - 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. - - Parameters - ---------- - a : torch.Tensor of shape (n_pixels, N) - Spatial profiles. - h_mots : list of torch.Tensor - 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) - Residual data. - phi_low_res : torch.Tensor of shape (n_frames, N) - Temporal weights. - mot_inds_yx : ndarray of shape (n_frames,) - Per-frame motion-bin index. - n_motions, n_sources : int - Number of motion bins / sources. - - Returns - ------- - torch.Tensor of shape (N,) - 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 - - var_exp = torch.zeros(n_sources, dtype=torch.float32) - var_residual = torch.zeros(n_sources, dtype=torch.float32) - for j in range(n_sources): - for i in range(n_motions): - frames = _motion_frames(mot_inds_yx, i) - x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, j].unsqueeze(1)) - contributing = (x > 0).nonzero()[:, 0] - var_exp[j] += torch.sum( - torch.sum( - x[contributing] * phi_low_res[frames, j].unsqueeze(-1).T, - dim=0, - ) - ** 2 - ) - var_residual[j] += torch.sum( - torch.sum(residual_recon[contributing][:, frames], dim=0) ** 2 - ) - # Ratio of accumulated squared signals, not a peak-amplitude SNR. - return var_exp / var_residual - - -def fit_sources( - source_seeds: np.ndarray, - residual: np.ndarray, - h_mots: list[torch.Tensor], - unique_motion_to_keep_yx: np.ndarray, - mot_inds_yx: np.ndarray, - sel_pix_idxs: np.ndarray, - pixel_coords: np.ndarray, - n_pixels: int, - d_xy: float, - sparse_fac: float, - outer_loop_iters: int = 10, - mult_nmf_max_iters: int = 10, - learning_rate: float = 0.01, - gd_tol: float = 1e-4, - verbose: bool = False, - *, - temporal_kernel: np.ndarray | None = None, - seed: int | None = None, -) -> dict: - """Localize sources by superpixel-space NMF + Gaussian-profile fitting. - - Parameters - ---------- - source_seeds : ndarray of shape (N, 3) - 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. - 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). - sel_pix_idxs : ndarray of int - Flat selected-pixel indices into the n_pixels grid. - pixel_coords : ndarray of shape (n_sel, 3) - Selected-pixel [z, row, col] coordinates. - n_pixels : int - Total number of image pixels. - d_xy : float - Support-patch half-width / location clamp radius. - sparse_fac : float - NMF sparsification floor. - outer_loop_iters : int - Number of outer NMF/fit iterations. - mult_nmf_max_iters : int - Multiplicative-update iterations per motion bin. - learning_rate : float - Base Adam learning rate. - gd_tol : float - Adam convergence tolerance. - 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 - motion binning, without compensating for motion differences. Leaves - 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. - Raises ValueError if no usable frames remain. If omitted, use the - 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 - the number of Adam epochs in one iteration does not shift the draws - 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. - - 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] - n_frames = residual.shape[1] - pixel_coords_tensor = torch.tensor(pixel_coords, dtype=torch.float32) - nmf_residual = residual.astype(np.float32, copy=False) - if temporal_kernel is not None: - # smooth_rho operates in place. Dropped frames must not contribute - # 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) - # 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") - 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]) - mot_inds_yx = filtered_motion_inds - h_mots = [h_mots[i] for i in kept_motions] - n_motions = len(h_mots) - data_for_nmf = torch.from_numpy(nmf_residual) - 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 = 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) - - for outer_loop_iter in progress( - range(outer_loop_iters), - desc="Localizing sources (NMF)", - verbose=verbose, - ): - generator = None - if seed is not None: - 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, - h_mots, - x_support_mots, - sel_pix_idxs, - data_for_nmf, - mot_inds_yx, - n_motions, - sparse_fac, - mult_nmf_max_iters, - generator, - ) - source_params = fit_gaussian_profiles( - source_params, - source_seeds, - x_mots, - h_mots, - pixel_coords_tensor, - a_patches, - sel_pix_idxs, - d_xy, - num_epochs, - n_motions, - learning_rate, - gd_tol, - generator, - ) - a = project_spatial_profiles( - source_params, - pixel_coords_tensor, - sel_pix_idxs, - n_pixels, - a_patches, - ) - phi_low_res = fit_phi_all_motions( - a, - h_mots, - sel_pix_idxs, - data_for_nmf, - mot_inds_yx, - n_motions, - phi_low_res, - ) - - order = variance_sortorder(phi_low_res, n_sources) - ( - source_params, - source_seeds, - a, - a_patches, - x_support_mots, - phi_low_res, - ) = reorder_sources( - order, - source_params, - source_seeds, - a, - a_patches, - x_support_mots, - phi_low_res, - ) - - if (outer_loop_iter + 1) % 4 == 3: - snr = compute_source_snr( - a, - h_mots, - sel_pix_idxs, - data_for_nmf, - phi_low_res, - mot_inds_yx, - n_motions, - n_sources, - ) - keep = (snr > 1 / 3).nonzero()[:, 0] - n_sources = keep.shape[0] - ( - source_params, - source_seeds, - a, - a_patches, - x_support_mots, - phi_low_res, - ) = reorder_sources( - keep, - source_params, - source_seeds, - a, - a_patches, - x_support_mots, - phi_low_res, - ) - - source_snr = compute_source_snr( - a, - h_mots, - sel_pix_idxs, - data_for_nmf, - phi_low_res, - mot_inds_yx, - n_motions, - n_sources, - ).numpy() - - return { - "A": a, - "phi_low_res": phi_low_res, - "source_params": source_params, - "source_seeds": source_seeds, - "source_snr": source_snr, - "n_sources": n_sources, - } +"""Superpixel-space NMF source localization. + +Ported from the source-localization block of +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` +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. + +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`), +2. fits the parametric Gaussian profiles to those targets with Adam + (:func:`fit_gaussian_profiles`), +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. + +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 +unregularized QR temporal solve changes numerical results. The reference's +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 cast + +import numpy as np +import torch +from scipy.linalg import qr, solve_triangular + +from ...progress import progress +from .activity import smooth_rho + + +def sel_pix_gaussian_profile( + gaussian_params: torch.Tensor, pixel_coords_tensor: torch.Tensor +) -> torch.Tensor: + """Render normalized bivariate-Gaussian profiles over selected pixels. + + 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). + pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) + Selected-pixel [z, row, col] coordinates. + + Returns + ------- + torch.Tensor of shape (n_sel, N) + Column-normalized profiles; each source is confined to its own z-plane + and to within 3 sigma of its center. + """ + z_planes = gaussian_params[:, 0].unsqueeze(0) + y_means = gaussian_params[:, 1].unsqueeze(0) + x_means = gaussian_params[:, 2].unsqueeze(0) + y_sigmas = gaussian_params[:, 3].unsqueeze(0) + x_sigmas = gaussian_params[:, 4].unsqueeze(0) + corr_coef = torch.tanh(gaussian_params[:, 5].unsqueeze(0)) + + y_centered = pixel_coords_tensor[:, 1].unsqueeze(1) - y_means + x_centered = pixel_coords_tensor[:, 2].unsqueeze(1) - x_means + + z_score_y = y_centered / y_sigmas + z_score_x = x_centered / x_sigmas + + exponent = (-1 / (2 * (1 - corr_coef**2))) * ( + z_score_y**2 - 2 * corr_coef * z_score_x * z_score_y + z_score_x**2 + ) + profile = torch.exp(exponent) + profile = ( + profile + * ( + (torch.sqrt(z_score_y**2 + z_score_x**2) <= 3) + & (pixel_coords_tensor[:, 0].unsqueeze(1) == z_planes) + ).float() + ) + + return profile / torch.sum(profile, dim=0, keepdim=True) + + +def sel_pix_patch_profile( + patch_params: torch.Tensor, pixel_coords_tensor: torch.Tensor +) -> torch.Tensor: + """Render rectangular in-plane support patches over selected pixels. + + Parameters + ---------- + patch_params : torch.Tensor of shape (N, 5) + 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. + + Returns + ------- + torch.Tensor of bool, shape (n_sel, N) + True where a pixel is inside a source's patch (same z-plane, within the + radii). + """ + z_planes = patch_params[:, 0].unsqueeze(0) + y_means = patch_params[:, 1].unsqueeze(0) + x_means = patch_params[:, 2].unsqueeze(0) + y_radii = patch_params[:, 3].unsqueeze(0) + x_radii = patch_params[:, 4].unsqueeze(0) + + y_centered = pixel_coords_tensor[:, 1].unsqueeze(1) - y_means + x_centered = pixel_coords_tensor[:, 2].unsqueeze(1) - x_means + + return ( + (torch.abs(y_centered) < y_radii) + & (torch.abs(x_centered) < x_radii) + & (pixel_coords_tensor[:, 0].unsqueeze(1) == z_planes) + ) + + +def init_source_params(source_seeds: np.ndarray) -> torch.Tensor: + """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]. + + Returns + ------- + torch.Tensor of shape (N, 6) + The initial source parameters. + """ + n = source_seeds.shape[0] + return torch.cat( + [ + torch.tensor(source_seeds, dtype=torch.float32), + torch.ones(n, 2, dtype=torch.float32), + torch.zeros(n, 1, dtype=torch.float32), + ], + dim=1, + ) + + +def build_a_patches( + source_seeds: np.ndarray, + pixel_coords_tensor: torch.Tensor, + sel_pix_idxs: np.ndarray, + n_pixels: int, + d_xy: float, +) -> torch.Tensor: + """Build the per-source rectangular support mask over the full pixel grid. + + Parameters + ---------- + source_seeds : ndarray of shape (N, 3) + 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. + n_pixels : int + Total number of image pixels (z * rows * cols). + d_xy : float + Half-width of the square support patch, in pixels. + + Returns + ------- + torch.Tensor of bool, shape (n_pixels, N) + The support mask. + """ + n_sources = source_seeds.shape[0] + a_patches = torch.zeros((n_pixels, n_sources), dtype=torch.bool) + patch_params = torch.cat( + [ + torch.tensor(source_seeds, dtype=torch.float32), + d_xy * torch.ones(n_sources, 2, dtype=torch.float32), + ], + dim=1, + ) + 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], + a_patches: torch.Tensor, + sel_pix_idxs: np.ndarray, + n_motions: int, +) -> 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. + a_patches : torch.Tensor of bool, shape (n_pixels, N) + Support mask from :func:`build_a_patches`. + sel_pix_idxs : ndarray of int + Flat selected-pixel indices. + n_motions : int + Number of motion bins. + + Returns + ------- + list of torch.Tensor of bool + 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) + ] + + +def project_spatial_profiles( + source_params: torch.Tensor, + pixel_coords_tensor: torch.Tensor, + sel_pix_idxs: np.ndarray, + n_pixels: int, + a_patches: torch.Tensor, +) -> torch.Tensor: + """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. + + Parameters + ---------- + source_params : torch.Tensor of shape (N, 6) + Source parameters. + pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) + Selected-pixel coordinates. + sel_pix_idxs : ndarray of int + Flat selected-pixel indices. + n_pixels : int + Total number of image pixels. + a_patches : torch.Tensor of bool, shape (n_pixels, N) + Support mask. + + Returns + ------- + torch.Tensor of shape (n_pixels, N) + The normalized 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[~a_patches] = 0 + mass = torch.sum(a, dim=0, keepdim=True) + mass[mass <= 0] = 1 + a /= mass + return a + + +def _motion_frames(mot_inds_yx: np.ndarray, i: int) -> np.ndarray: + """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: + """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 + 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. + No normal equations or ridge regularization are used. + + 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 + 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. + 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() + phi = np.zeros((x.shape[1], data_motion.shape[1]), dtype=x_array.dtype) + if min(x.shape) == 0 or data_motion.shape[1] == 0: + return torch.from_numpy(phi.T) + + # SciPy rejects the entire RHS batch if even one frame is nonfinite. + # Preserve missing frames without contaminating the independent fits, + # including coefficients that would otherwise be zero for deficient X. + valid_frames = np.all(np.isfinite(data_array), axis=0) + phi[:, ~valid_frames] = np.nan + + q, r, piv = qr(x_array, mode="economic", pivoting=True) + diagonal = np.abs(np.diag(r)) + tolerance = max(x.shape) * np.finfo(x_array.dtype).eps * diagonal[0] + # Use a leading block: stop at the first numerically dependent column. + 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] + phi[np.ix_(piv[:rank], valid_frames)] = solve_triangular( + r[:rank, :rank], q[:, :rank].T @ finite_data + ) + return torch.from_numpy(phi.T) + + +def fit_phi_all_motions( + a: 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. + + Parameters + ---------- + a : torch.Tensor of shape (n_pixels, N) + Spatial profiles. + h_mots : list of torch.Tensor + 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). + n_motions : int + Number of motion bins. + phi_low_res : torch.Tensor of shape (n_frames, N) + Temporal weights, updated in place per motion bin and returned. + + Returns + ------- + torch.Tensor + phi_low_res with each motion's frames filled. + """ + for i in range(n_motions): + frames = _motion_frames(mot_inds_yx, i) + x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, :]) + phi_low_res[frames, :] = solve_phi_motion(x, data_for_nmf[:, frames]) + return phi_low_res + + +def multiplicative_nmf( + a: 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, + n_motions: int, + sparse_fac: float, + max_iters: int, + generator: torch.Generator | None = None, +) -> 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 + spatial + 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. + x_support_mots : list of torch.Tensor of bool + Per-motion superpixel support masks. + sel_pix_idxs : ndarray of int + Flat selected-pixel indices. + data_for_nmf : torch.Tensor of shape (n_superpixels, n_frames) + Residual data. + mot_inds_yx : ndarray of shape (n_frames,) + Per-frame motion-bin index. + n_motions : int + Number of motion bins. + sparse_fac : float + 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. + + Returns + ------- + list of torch.Tensor + Per-motion fitted superpixel spatial targets X_mots. + """ + 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. + i = cast(int, idx.item()) + frames = _motion_frames(mot_inds_yx, i) + + x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, :]) + x[~x_support_mots[i]] = 0 + x = x / torch.norm(x, dim=0, keepdim=True) + + phi = torch.clamp(solve_phi_motion(x, data_for_nmf[:, frames]), min=0) + + for iter_idx in range(max_iters): + numerator = x.T @ data_for_nmf[:, frames] + denominator = (x.T @ x) @ phi.T + 1e-10 + phi = torch.clamp(phi * (numerator / denominator).T, min=0) + + numerator = data_for_nmf[:, frames] @ phi + denominator = x @ (phi.T @ phi) + 1e-10 + x = torch.clamp(x * (numerator / denominator), min=0) + + x = x * x_support_mots[i].float() + + norms = torch.norm(x, dim=0, keepdim=True) + x = torch.where(norms > 0, x / norms, x) + phi = torch.where(norms > 0, phi * norms, phi) + + if iter_idx % 3 == 0: + x_max = torch.max(x, dim=0, keepdim=True)[0] + x = torch.where(x_max > 0, x / x_max, x) + x = torch.clamp(x, min=sparse_fac) - sparse_fac + norms = torch.norm(x, dim=0, keepdim=True) + x = torch.where(norms > 0, x / norms, x) + + x_mots[i] = x + # randperm visits every slot exactly once, including the empty case. + 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], + pixel_coords_tensor: torch.Tensor, + a_patches: torch.Tensor, + sel_pix_idxs: np.ndarray, + d_xy: float, + num_epochs: int, + n_motions: int, + learning_rate: float, + gd_tol: float, + generator: torch.Generator | None = None, +) -> torch.Tensor: + """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. + + Parameters + ---------- + source_params : torch.Tensor of shape (N, 6) + Current source parameters (z fixed; loc/scale/tilt optimized). + source_seeds : ndarray of shape (N, 3) + Peak seeds (for the location clamp bounds). + x_mots : list of torch.Tensor + Per-motion NMF spatial targets. + h_mots : list of torch.Tensor + Per-motion sparse H matrices. + pixel_coords_tensor : torch.Tensor of shape (n_sel, 3) + Selected-pixel coordinates. + a_patches : torch.Tensor of bool + Support mask. + sel_pix_idxs : ndarray of int + Flat selected-pixel indices. + d_xy : float + Location clamp half-width. + num_epochs : int + Maximum optimization epochs (one motion each). + n_motions : int + Number of motion bins (epochs per round). + learning_rate : float + Base Adam learning rate (scaled per parameter group). + 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. + + Returns + ------- + torch.Tensor of shape (N, 6) + The updated source parameters. + """ + 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}, + ]) + + z_col = source_params[:, 0].unsqueeze(1) + loc_min = torch.from_numpy(source_seeds[:, 1:3] - 1.5).float() + loc_max = torch.from_numpy(source_seeds[:, 1:3] + 1.5).float() + + losses = [] + shuffled_indices = None + for epoch in range(num_epochs): + optimizer.zero_grad() + + a_step = sel_pix_gaussian_profile( + torch.cat([z_col, optim_loc, optim_scale, optim_tilt], dim=1), + pixel_coords_tensor, + ) + a_step = a_step * a_patches[sel_pix_idxs, :].float() + mass = torch.sum(a_step, dim=0, keepdim=True) + mass[mass <= 0] = 1 + a_step = a_step / mass + + if epoch % n_motions == 0: + shuffled_indices = torch.randperm(n_motions, generator=generator) + # Epoch zero initializes the permutation before any index is read. + i = cast( + int, + cast(torch.Tensor, shuffled_indices)[epoch % n_motions].item(), + ) + + x_step = torch.sparse.mm(h_mots[i], a_step) + norms = torch.norm(x_step, dim=0, keepdim=True) + x_step = torch.where(norms > 0, x_step / norms, x_step) + loss = torch.sum((x_step - x_mots[i]) ** 2) + + loss.backward() + optimizer.step() + + with torch.no_grad(): + optim_loc.clamp_(min=loc_min, max=loc_max) + optim_scale[:, 0].clamp_(min=0.3, max=2) + optim_scale[:, 1].clamp_(min=0.3, max=2) + + if epoch % n_motions == n_motions - 1: + total_loss = 0 + for i in range(n_motions): + x_step = torch.sparse.mm(h_mots[i], a_step) + norms = torch.norm(x_step, dim=0, keepdim=True) + x_step = torch.where(norms > 0, x_step / norms, x_step) + 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: + break + + return torch.cat( + [z_col, optim_loc.detach(), optim_scale.detach(), optim_tilt.detach()], + dim=1, + ) + + +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: 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], + 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 + ---------- + order : array-like of int + Source indices in the new order (a permutation for sorting, or a subset + for pruning). + source_params, source_seeds, a, a_patches, phi_low_res : array/tensor + Per-source state to reindex along the source axis. + x_support_mots : list of torch.Tensor + Per-motion support masks (reindexed along the source axis). + + Returns + ------- + tuple + 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, :] + a = a[:, order] + a_patches = a_patches[:, order] + x_support_mots = [support[:, order] for support in x_support_mots] + phi_low_res = phi_low_res[:, order] + return ( + source_params, + source_seeds, + a, + a_patches, + x_support_mots, + phi_low_res, + ) + + +def compute_source_snr( + a: torch.Tensor, + h_mots: list[torch.Tensor], + sel_pix_idxs: np.ndarray, + data_for_nmf: torch.Tensor, + phi_low_res: torch.Tensor, + mot_inds_yx: np.ndarray, + n_motions: int, + n_sources: int, +) -> torch.Tensor: + """Per-source low-resolution SNR (explained variance / residual variance). + + 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. + + Parameters + ---------- + a : torch.Tensor of shape (n_pixels, N) + Spatial profiles. + h_mots : list of torch.Tensor + 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) + Residual data. + phi_low_res : torch.Tensor of shape (n_frames, N) + Temporal weights. + mot_inds_yx : ndarray of shape (n_frames,) + Per-frame motion-bin index. + n_motions, n_sources : int + Number of motion bins / sources. + + Returns + ------- + torch.Tensor of shape (N,) + 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 + + var_exp = torch.zeros(n_sources, dtype=torch.float32) + var_residual = torch.zeros(n_sources, dtype=torch.float32) + for j in range(n_sources): + for i in range(n_motions): + frames = _motion_frames(mot_inds_yx, i) + x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, j].unsqueeze(1)) + contributing = (x > 0).nonzero()[:, 0] + var_exp[j] += torch.sum( + torch.sum( + x[contributing] * phi_low_res[frames, j].unsqueeze(-1).T, + dim=0, + ) + ** 2 + ) + var_residual[j] += torch.sum( + torch.sum(residual_recon[contributing][:, frames], dim=0) ** 2 + ) + # Ratio of accumulated squared signals, not a peak-amplitude SNR. + return var_exp / var_residual + + +def fit_sources( + source_seeds: np.ndarray, + residual: np.ndarray, + h_mots: list[torch.Tensor], + unique_motion_to_keep_yx: np.ndarray, + mot_inds_yx: np.ndarray, + sel_pix_idxs: np.ndarray, + pixel_coords: np.ndarray, + n_pixels: int, + d_xy: float, + sparse_fac: float, + outer_loop_iters: int = 10, + mult_nmf_max_iters: int = 10, + learning_rate: float = 0.01, + gd_tol: float = 1e-4, + verbose: bool = False, + *, + temporal_kernel: np.ndarray | None = None, + seed: int | None = None, +) -> dict: + """Localize sources by superpixel-space NMF + Gaussian-profile fitting. + + Parameters + ---------- + source_seeds : ndarray of shape (N, 3) + 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. + 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). + sel_pix_idxs : ndarray of int + Flat selected-pixel indices into the n_pixels grid. + pixel_coords : ndarray of shape (n_sel, 3) + Selected-pixel [z, row, col] coordinates. + n_pixels : int + Total number of image pixels. + d_xy : float + Support-patch half-width / location clamp radius. + sparse_fac : float + NMF sparsification floor. + outer_loop_iters : int + Number of outer NMF/fit iterations. + mult_nmf_max_iters : int + Multiplicative-update iterations per motion bin. + learning_rate : float + Base Adam learning rate. + gd_tol : float + Adam convergence tolerance. + 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 + motion binning, without compensating for motion differences. Leaves + 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. + Raises ValueError if no usable frames remain. If omitted, use the + 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 + the number of Adam epochs in one iteration does not shift the draws + 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. + + 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] + n_frames = residual.shape[1] + pixel_coords_tensor = torch.tensor(pixel_coords, dtype=torch.float32) + nmf_residual = residual.astype(np.float32, copy=False) + if temporal_kernel is not None: + # smooth_rho operates in place. Dropped frames must not contribute + # 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) + # 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") + 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]) + mot_inds_yx = filtered_motion_inds + h_mots = [h_mots[i] for i in kept_motions] + n_motions = len(h_mots) + data_for_nmf = torch.from_numpy(nmf_residual) + 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 = 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) + + for outer_loop_iter in progress( + range(outer_loop_iters), + desc="Localizing sources (NMF)", + verbose=verbose, + ): + generator = None + if seed is not None: + 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, + h_mots, + x_support_mots, + sel_pix_idxs, + data_for_nmf, + mot_inds_yx, + n_motions, + sparse_fac, + mult_nmf_max_iters, + generator, + ) + source_params = fit_gaussian_profiles( + source_params, + source_seeds, + x_mots, + h_mots, + pixel_coords_tensor, + a_patches, + sel_pix_idxs, + d_xy, + num_epochs, + n_motions, + learning_rate, + gd_tol, + generator, + ) + a = project_spatial_profiles( + source_params, + pixel_coords_tensor, + sel_pix_idxs, + n_pixels, + a_patches, + ) + phi_low_res = fit_phi_all_motions( + a, + h_mots, + sel_pix_idxs, + data_for_nmf, + mot_inds_yx, + n_motions, + phi_low_res, + ) + + order = variance_sortorder(phi_low_res, n_sources) + ( + source_params, + source_seeds, + a, + a_patches, + x_support_mots, + phi_low_res, + ) = reorder_sources( + order, + source_params, + source_seeds, + a, + a_patches, + x_support_mots, + phi_low_res, + ) + + if (outer_loop_iter + 1) % 4 == 3: + snr = compute_source_snr( + a, + h_mots, + sel_pix_idxs, + data_for_nmf, + phi_low_res, + mot_inds_yx, + n_motions, + n_sources, + ) + keep = (snr > 1 / 3).nonzero()[:, 0] + n_sources = keep.shape[0] + ( + source_params, + source_seeds, + a, + a_patches, + x_support_mots, + phi_low_res, + ) = reorder_sources( + keep, + source_params, + source_seeds, + a, + a_patches, + x_support_mots, + phi_low_res, + ) + + source_snr = compute_source_snr( + a, + h_mots, + sel_pix_idxs, + data_for_nmf, + phi_low_res, + mot_inds_yx, + n_motions, + n_sources, + ).numpy() + + return { + "A": a, + "phi_low_res": phi_low_res, + "source_params": source_params, + "source_seeds": source_seeds, + "source_snr": source_snr, + "n_sources": n_sources, + } diff --git a/src/giant_python/extraction/band/motion_binning.py b/src/giant_python/extraction/band/motion_binning.py index e16c8e42..cf461f04 100644 --- a/src/giant_python/extraction/band/motion_binning.py +++ b/src/giant_python/extraction/band/motion_binning.py @@ -1,102 +1,102 @@ -"""Rounded motion bins and low-resolution frame-selection policy.""" - -from __future__ import annotations - -import numpy as np - - -def bin_motion( - motion_r: np.ndarray, motion_c: np.ndarray, motion_z: np.ndarray -) -> tuple[np.ndarray, np.ndarray]: - """Group frames into unique rounded (row, col, z) motion bins. - - Parameters - ---------- - motion_r, motion_c, motion_z : ndarray - Per-frame downsampled motion in rows, columns, and z. - - Returns - ------- - unique_motion : ndarray of shape (n_bins, 3) - 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. - """ - unique_motion, mot_inds = np.unique( - np.round(np.stack((motion_r, motion_c, motion_z), axis=1)), - axis=0, - return_inverse=True, - ) - # np.unique's inverse is 1-D on numpy<2 and 2.1+, but 2-D on 2.0; flatten - # so downstream bincount/isin behave identically across versions. - return unique_motion, np.reshape(mot_inds, -1) - - -def select_motion_bins( - unique_motion: np.ndarray, - mot_inds: np.ndarray, - motion_z: np.ndarray, - z_tol: float = 1.5, - min_frames: int = 100, -) -> 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, - the remaining frames are treated as having no z motion. - - Parameters - ---------- - unique_motion : ndarray of shape (n_bins, 3) - Unique motion vectors from :func:`bin_motion`. - mot_inds : ndarray of shape (n_frames,) - Per-frame motion-bin indices. - motion_z : ndarray - Per-frame z motion (used for the median). - z_tol : float - Maximum absolute z deviation from the median, in microns. - min_frames : int - Minimum frame count (strictly greater) for a bin to be kept. - - Returns - ------- - mot_inds_to_keep : ndarray - 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) - 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 - - -def bin_motion_yx( - motion_r: np.ndarray, - motion_c: np.ndarray, - frames_to_keep: np.ndarray, -) -> tuple[np.ndarray, np.ndarray]: - """Bin kept frames into unique rounded (row, col) motion bins. - - Parameters - ---------- - 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. - - Returns - ------- - unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2) - 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 - 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) - mot_inds_yx[frames_to_keep] = np.reshape(inv, -1) - return unique_motion_to_keep_yx, mot_inds_yx +"""Rounded motion bins and low-resolution frame-selection policy.""" + +from __future__ import annotations + +import numpy as np + + +def bin_motion( + motion_r: np.ndarray, motion_c: np.ndarray, motion_z: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + """Group frames into unique rounded (row, col, z) motion bins. + + Parameters + ---------- + motion_r, motion_c, motion_z : ndarray + Per-frame downsampled motion in rows, columns, and z. + + Returns + ------- + unique_motion : ndarray of shape (n_bins, 3) + 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. + """ + unique_motion, mot_inds = np.unique( + np.round(np.stack((motion_r, motion_c, motion_z), axis=1)), + axis=0, + return_inverse=True, + ) + # np.unique's inverse is 1-D on numpy<2 and 2.1+, but 2-D on 2.0; flatten + # so downstream bincount/isin behave identically across versions. + return unique_motion, np.reshape(mot_inds, -1) + + +def select_motion_bins( + unique_motion: np.ndarray, + mot_inds: np.ndarray, + motion_z: np.ndarray, + z_tol: float = 1.5, + min_frames: int = 100, +) -> 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, + the remaining frames are treated as having no z motion. + + Parameters + ---------- + unique_motion : ndarray of shape (n_bins, 3) + Unique motion vectors from :func:`bin_motion`. + mot_inds : ndarray of shape (n_frames,) + Per-frame motion-bin indices. + motion_z : ndarray + Per-frame z motion (used for the median). + z_tol : float + Maximum absolute z deviation from the median, in microns. + min_frames : int + Minimum frame count (strictly greater) for a bin to be kept. + + Returns + ------- + mot_inds_to_keep : ndarray + 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) + 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 + + +def bin_motion_yx( + motion_r: np.ndarray, + motion_c: np.ndarray, + frames_to_keep: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Bin kept frames into unique rounded (row, col) motion bins. + + Parameters + ---------- + 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. + + Returns + ------- + unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2) + 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 + 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) + 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 43165fc0..387821e8 100644 --- a/src/giant_python/extraction/band/operators.py +++ b/src/giant_python/extraction/band/operators.py @@ -1,294 +1,294 @@ -"""PSF kernels and sparse/dense band projection operators.""" - -from __future__ import annotations - -from typing import Any, cast - -import numpy as np -import torch -from scipy.interpolate import RectBivariateSpline - -from .geometry import ref_pixs_to_drc - - -def expand_psf( - psf2d: np.ndarray, ex_fac: int = 2 -) -> 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_facx up-sampled cubic-spline interpolation - that keeps the center aligned. Localization constructs its center/surround - filter separately with :func:`gaussian_kernel_2d`. - - Parameters - ---------- - psf2d : ndarray - The (cropped) PSF for this DMD. - ex_fac : int - Expansion factor along each axis. - - Returns - ------- - psf_tensor : torch.Tensor - Sum-normalized PSF. - psf_center : tuple of int - (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. - """ - psf_arr = np.asarray(psf2d, dtype=np.float32) - psf_tensor = torch.from_numpy(psf_arr).float() - psf_tensor = psf_tensor / torch.sum(psf_tensor) - psf_shape = psf_arr.shape - psf_center = (psf_shape[0] // 2, psf_shape[1] // 2) - - 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()) - psf_tensor_expanded = torch.from_numpy( - interp_spline(expanded_y.numpy(), expanded_x.numpy()) - ).float() - psf_tensor_expanded = psf_tensor_expanded / torch.sum(psf_tensor_expanded) - psf_shape_expanded = psf_tensor_expanded.shape - psf_center_expanded = ( - psf_shape_expanded[0] // 2, - psf_shape_expanded[1] // 2, - ) - 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: - """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 - 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. - - Parameters - ---------- - 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). - scale_x : float - Spatial shrink factor along the column (x) axis (< 1 shrinks, - 1 is a no-op). - - Returns - ------- - ndarray of shape psf2d.shape, float32 - The shrunk, sum-normalized PSF. - """ - psf_arr = np.asarray(psf2d, dtype=np.float32) - psf_shape = psf_arr.shape - center_y = (psf_shape[0] - 1) / 2 - center_x = (psf_shape[1] - 1) / 2 - orig_y = np.arange(psf_shape[0], dtype=np.float64) - center_y - orig_x = np.arange(psf_shape[1], dtype=np.float64) - center_x - interp_spline = RectBivariateSpline(orig_y, orig_x, psf_arr) - shrunk = interp_spline(orig_y / scale_y, orig_x / scale_x) - shrunk = np.clip(shrunk, 0.0, None).astype(np.float32) - total = shrunk.sum() - if total > 0: - shrunk = shrunk / total - return shrunk - - -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 - with an isotropic center/surround pair. The subtraction itself still - happens in :func:`compute_rho`, after per-column normalization. - - Parameters - ---------- - sigma : float - Gaussian standard deviation, in pixels. - truncate : float - Kernel half-width, in standard deviations. Truncation lowers the - realized standard deviation slightly, so the default is generous. - - Returns - ------- - kernel : torch.Tensor - Sum-normalized (2 * radius + 1, 2 * radius + 1) kernel. - center : tuple of int - (row, col) center index of kernel. - """ - radius = int(np.ceil(truncate * sigma)) - coords = np.arange(-radius, radius + 1, dtype=np.float64) - g_1d = np.exp(-(coords**2) / (2.0 * sigma**2)) - kernel = np.outer(g_1d, g_1d).astype(np.float32) - kernel /= kernel.sum() - return torch.from_numpy(kernel), (radius, radius) - - -def build_convolution_matrix( - sel_pixels_2d: np.ndarray, - psf_tensor: torch.Tensor, - 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. - - Parameters - ---------- - sel_pixels_2d : ndarray of shape (n_plane, 2) - 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. - - Returns - ------- - torch.Tensor - Dense (n_plane, n_plane) convolution matrix. - """ - n = sel_pixels_2d.shape[0] - if n == 0: - return torch.zeros((0, 0), dtype=torch.float32) - src_rows = sel_pixels_2d[:, 0][np.newaxis, :] - src_cols = sel_pixels_2d[:, 1][np.newaxis, :] - tgt_rows = sel_pixels_2d[:, 0][:, np.newaxis] - tgt_cols = sel_pixels_2d[:, 1][:, np.newaxis] - rel_rows = tgt_rows - src_rows + psf_center[0] - rel_cols = tgt_cols - src_cols + psf_center[1] - 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]) - ) - out = np.zeros((n, n), dtype=np.float32) - out[valid_mask] = psf_np[rel_rows[valid_mask], rel_cols[valid_mask]] - return torch.from_numpy(out) - - -def build_motion_h_matrices( - sparse_h_inds: np.ndarray, - sparse_h_vals: np.ndarray, - unique_motion_to_keep_yx: np.ndarray, - 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. - - 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). - sparse_h_vals : ndarray of shape (nnz,) - 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). - 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. - """ - n_mot = len(unique_motion_to_keep_yx) - 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) - 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): - shifted_cols = base_sparse_cols + pix_shift - shifted_inds[1] = np.searchsorted(sel_pix_idxs, shifted_cols) - # PyTorch accepts NumPy COO arrays despite its narrower stubs. - h_mots[i] = torch.sparse_coo_tensor( - cast(Any, shifted_inds), - cast(Any, sparse_h_vals), - (num_super_pixels, sel_pix_idxs.shape[0]), - dtype=torch.float32, - ) - # Every slot is populated by the corresponding motion shift above. - return cast(list[torch.Tensor], h_mots) - - -def build_sparse_h( - subsample_matrix_inds: np.ndarray, - 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). - - 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. - psf2d : ndarray - The (thresholded/cropped) PSF for this DMD. - dmd_pixels_per_column, dmd_pixels_per_row : int - DMD plane geometry. - - Returns - ------- - sparse_h_inds : ndarray of shape (2, nnz), int32 - Row (superpixel) / column (image-pixel) indices of non-zero entries. - sparse_h_vals : ndarray of shape (nnz,), float32 - The corresponding PSF weights. - """ - ref_d, ref_c, ref_r = ref_pixs_to_drc( - subsample_matrix_inds[:, 0], dmd_pixels_per_column, dmd_pixels_per_row - ) - psf2d = np.asarray(psf2d, dtype=np.float32) - psf_h, psf_w = psf2d.shape - filter_size = psf_h * psf_w - plane_size = dmd_pixels_per_column * dmd_pixels_per_row - num_super_pixels = subsample_matrix_inds.shape[0] - - 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() - 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[0] = np.repeat(subsample_matrix_inds[:, 1] - 1, filter_size) - for sp in range(num_super_pixels): - start = sp * filter_size - end = (sp + 1) * filter_size - rows = ref_r[sp] + row_offsets_flat - cols = ref_c[sp] + col_offsets_flat - sparse_h_inds[1, start:end] = ( - ref_d[sp] * plane_size + rows * dmd_pixels_per_row + cols - ).astype(np.int32, copy=False) - sparse_h_vals[start:end] = psf_vals_flat - - non_zero_mask = sparse_h_vals != 0 - return sparse_h_inds[:, non_zero_mask], sparse_h_vals[non_zero_mask] +"""PSF kernels and sparse/dense band projection operators.""" + +from __future__ import annotations + +from typing import Any, cast + +import numpy as np +import torch +from scipy.interpolate import RectBivariateSpline + +from .geometry import ref_pixs_to_drc + + +def expand_psf( + psf2d: np.ndarray, ex_fac: int = 2 +) -> 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_facx up-sampled cubic-spline interpolation + that keeps the center aligned. Localization constructs its center/surround + filter separately with :func:`gaussian_kernel_2d`. + + Parameters + ---------- + psf2d : ndarray + The (cropped) PSF for this DMD. + ex_fac : int + Expansion factor along each axis. + + Returns + ------- + psf_tensor : torch.Tensor + Sum-normalized PSF. + psf_center : tuple of int + (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. + """ + psf_arr = np.asarray(psf2d, dtype=np.float32) + psf_tensor = torch.from_numpy(psf_arr).float() + psf_tensor = psf_tensor / torch.sum(psf_tensor) + psf_shape = psf_arr.shape + psf_center = (psf_shape[0] // 2, psf_shape[1] // 2) + + 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()) + psf_tensor_expanded = torch.from_numpy( + interp_spline(expanded_y.numpy(), expanded_x.numpy()) + ).float() + psf_tensor_expanded = psf_tensor_expanded / torch.sum(psf_tensor_expanded) + psf_shape_expanded = psf_tensor_expanded.shape + psf_center_expanded = ( + psf_shape_expanded[0] // 2, + psf_shape_expanded[1] // 2, + ) + 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: + """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 + 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. + + Parameters + ---------- + 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). + scale_x : float + Spatial shrink factor along the column (x) axis (< 1 shrinks, + 1 is a no-op). + + Returns + ------- + ndarray of shape psf2d.shape, float32 + The shrunk, sum-normalized PSF. + """ + psf_arr = np.asarray(psf2d, dtype=np.float32) + psf_shape = psf_arr.shape + center_y = (psf_shape[0] - 1) / 2 + center_x = (psf_shape[1] - 1) / 2 + orig_y = np.arange(psf_shape[0], dtype=np.float64) - center_y + orig_x = np.arange(psf_shape[1], dtype=np.float64) - center_x + interp_spline = RectBivariateSpline(orig_y, orig_x, psf_arr) + shrunk = interp_spline(orig_y / scale_y, orig_x / scale_x) + shrunk = np.clip(shrunk, 0.0, None).astype(np.float32) + total = shrunk.sum() + if total > 0: + shrunk = shrunk / total + return shrunk + + +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 + with an isotropic center/surround pair. The subtraction itself still + happens in :func:`compute_rho`, after per-column normalization. + + Parameters + ---------- + sigma : float + Gaussian standard deviation, in pixels. + truncate : float + Kernel half-width, in standard deviations. Truncation lowers the + realized standard deviation slightly, so the default is generous. + + Returns + ------- + kernel : torch.Tensor + Sum-normalized (2 * radius + 1, 2 * radius + 1) kernel. + center : tuple of int + (row, col) center index of kernel. + """ + radius = int(np.ceil(truncate * sigma)) + coords = np.arange(-radius, radius + 1, dtype=np.float64) + g_1d = np.exp(-(coords**2) / (2.0 * sigma**2)) + kernel = np.outer(g_1d, g_1d).astype(np.float32) + kernel /= kernel.sum() + return torch.from_numpy(kernel), (radius, radius) + + +def build_convolution_matrix( + sel_pixels_2d: np.ndarray, + psf_tensor: torch.Tensor, + 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. + + Parameters + ---------- + sel_pixels_2d : ndarray of shape (n_plane, 2) + 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. + + Returns + ------- + torch.Tensor + Dense (n_plane, n_plane) convolution matrix. + """ + n = sel_pixels_2d.shape[0] + if n == 0: + return torch.zeros((0, 0), dtype=torch.float32) + src_rows = sel_pixels_2d[:, 0][np.newaxis, :] + src_cols = sel_pixels_2d[:, 1][np.newaxis, :] + tgt_rows = sel_pixels_2d[:, 0][:, np.newaxis] + tgt_cols = sel_pixels_2d[:, 1][:, np.newaxis] + rel_rows = tgt_rows - src_rows + psf_center[0] + rel_cols = tgt_cols - src_cols + psf_center[1] + 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]) + ) + out = np.zeros((n, n), dtype=np.float32) + out[valid_mask] = psf_np[rel_rows[valid_mask], rel_cols[valid_mask]] + return torch.from_numpy(out) + + +def build_motion_h_matrices( + sparse_h_inds: np.ndarray, + sparse_h_vals: np.ndarray, + unique_motion_to_keep_yx: np.ndarray, + 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. + + 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). + sparse_h_vals : ndarray of shape (nnz,) + 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). + 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. + """ + n_mot = len(unique_motion_to_keep_yx) + 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) + 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): + shifted_cols = base_sparse_cols + pix_shift + shifted_inds[1] = np.searchsorted(sel_pix_idxs, shifted_cols) + # PyTorch accepts NumPy COO arrays despite its narrower stubs. + h_mots[i] = torch.sparse_coo_tensor( + cast(Any, shifted_inds), + cast(Any, sparse_h_vals), + (num_super_pixels, sel_pix_idxs.shape[0]), + dtype=torch.float32, + ) + # Every slot is populated by the corresponding motion shift above. + return cast(list[torch.Tensor], h_mots) + + +def build_sparse_h( + subsample_matrix_inds: np.ndarray, + 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). + + 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. + psf2d : ndarray + The (thresholded/cropped) PSF for this DMD. + dmd_pixels_per_column, dmd_pixels_per_row : int + DMD plane geometry. + + Returns + ------- + sparse_h_inds : ndarray of shape (2, nnz), int32 + Row (superpixel) / column (image-pixel) indices of non-zero entries. + sparse_h_vals : ndarray of shape (nnz,), float32 + The corresponding PSF weights. + """ + ref_d, ref_c, ref_r = ref_pixs_to_drc( + subsample_matrix_inds[:, 0], dmd_pixels_per_column, dmd_pixels_per_row + ) + psf2d = np.asarray(psf2d, dtype=np.float32) + psf_h, psf_w = psf2d.shape + filter_size = psf_h * psf_w + plane_size = dmd_pixels_per_column * dmd_pixels_per_row + num_super_pixels = subsample_matrix_inds.shape[0] + + 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() + 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[0] = np.repeat(subsample_matrix_inds[:, 1] - 1, filter_size) + for sp in range(num_super_pixels): + start = sp * filter_size + end = (sp + 1) * filter_size + rows = ref_r[sp] + row_offsets_flat + cols = ref_c[sp] + col_offsets_flat + sparse_h_inds[1, start:end] = ( + ref_d[sp] * plane_size + rows * dmd_pixels_per_row + cols + ).astype(np.int32, copy=False) + sparse_h_vals[start:end] = psf_vals_flat + + non_zero_mask = sparse_h_vals != 0 + return sparse_h_inds[:, non_zero_mask], sparse_h_vals[non_zero_mask] diff --git a/src/giant_python/extraction/band/result_assembly.py b/src/giant_python/extraction/band/result_assembly.py index 8b97ba89..c6ff82c2 100644 --- a/src/giant_python/extraction/band/result_assembly.py +++ b/src/giant_python/extraction/band/result_assembly.py @@ -1,211 +1,211 @@ -"""Canonical band numerical output assembly; persistence belongs to shared IO. - -Internal reference offsets become MATLAB displacement once here. -""" - -from __future__ import annotations - -from dataclasses import dataclass - -import numpy as np -from torch import Tensor - -from ...models.experiment_summary import ( - FrameInfo, - PathSummary, - Source, - UserRoi, - Visualizations, -) -from ...numerics.baseline import assemble_dff -from .types import TrialTraceResult - - -@dataclass -class PathResult: - """One path's numerical outputs, geometry, and assembly window lengths. - - 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. - No tensor copies or numerical normalization occur in this container. - """ - - a: Tensor - source_params: Tensor - source_snr: np.ndarray - act_im: np.ndarray - mean_im: np.ndarray - act_im_peaks: np.ndarray - trace_results: list[TrialTraceResult] - z_depths: np.ndarray - num_fast_zs: int - dmd_pixels_per_column: int - dmd_pixels_per_row: int - num_channels: int - denoise_window: int - baseline_window: int - draw_user_rois: bool = False - 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. - - 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: 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 ( - user_rois["user_roi_masks"].get(key), - user_rois["user_roi_labels"].get(key), - user_rois["user_roi_superpixels"].get(key, []), - ) - - -def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary: - """Concatenate trials and assemble dF/F with unchanged numerical ordering. - - 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], - axis=0, - ) - 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 - ) - coords = pr.source_params[:, :3].numpy() - df_channels = _with_nan_channel(d_f, pr.num_channels) - # Keep the fitted convolution trace itself, not a second - # baseline-subtracted version: otherwise it would no longer correspond - # to the fitted events. - # 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)) - 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], - axis=0, - ) - denoised_channels = _with_nan_channel(denoised, pr.num_channels) - event_channels = _with_nan_channel(events, pr.num_channels) - f0_channels = _with_nan_channel(f0, pr.num_channels) - snr = pr.source_snr.reshape(-1, 1) - sources = [ - Source( - profile=profiles[j], - coords=coords[j], - df_ls=df_channels[j], - df_denoised=denoised_channels[j], - events=event_channels[j], - f0=f0_channels[j], - snr=snr[j, 0], - ) - 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), - 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), - ) - annotation_enabled = False - user_rois = [] - empty_roi_arrays = {} - if pr.draw_user_rois and pr.soma_masks is not None: - annotation_enabled = True - masks = ( - np.stack([np.asarray(m, dtype=bool) for m in pr.soma_masks]) - 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) - labels = np.asarray(pr.soma_labels, dtype=object).reshape(-1) - user_rois = [ - UserRoi( - label=str(label), - mask=masks[j] if j < masks.shape[0] else None, - f=fluorescence[j] if j < fluorescence.shape[0] else None, - ) - for j, label in enumerate(labels) - ] - if not user_rois: - empty_roi_arrays = {"mask": masks, "F": fluorescence} - return PathSummary( - path_index=path_index, - sources=sources, - user_rois=user_rois, - visualizations=Visualizations( - act_im=pr.act_im, mean_im=pr.mean_im, act_im_peaks=pr.act_im_peaks - ), - frame_info=frame_info, - global_f=np.concatenate([r.global_f for r in results], axis=0).T, - z_depths=pr.z_depths, - annotation_enabled=annotation_enabled, - _empty_source_arrays=( - {} - if sources - else { - "profiles": profiles, - "coords": coords, - "dF_ls": df_channels, - "dF_denoised": denoised_channels, - "events": event_channels, - "F0": f0_channels, - "SNR": snr, - } - ), - _empty_roi_arrays=empty_roi_arrays, - ) +"""Canonical band numerical output assembly; persistence belongs to shared IO. + +Internal reference offsets become MATLAB displacement once here. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from torch import Tensor + +from ...models.experiment_summary import ( + FrameInfo, + PathSummary, + Source, + UserRoi, + Visualizations, +) +from ...numerics.baseline import assemble_dff +from .types import TrialTraceResult + + +@dataclass +class PathResult: + """One path's numerical outputs, geometry, and assembly window lengths. + + 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. + No tensor copies or numerical normalization occur in this container. + """ + + a: Tensor + source_params: Tensor + source_snr: np.ndarray + act_im: np.ndarray + mean_im: np.ndarray + act_im_peaks: np.ndarray + trace_results: list[TrialTraceResult] + z_depths: np.ndarray + num_fast_zs: int + dmd_pixels_per_column: int + dmd_pixels_per_row: int + num_channels: int + denoise_window: int + baseline_window: int + draw_user_rois: bool = False + 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. + + 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: 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 ( + user_rois["user_roi_masks"].get(key), + user_rois["user_roi_labels"].get(key), + user_rois["user_roi_superpixels"].get(key, []), + ) + + +def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary: + """Concatenate trials and assemble dF/F with unchanged numerical ordering. + + 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], + axis=0, + ) + 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 + ) + coords = pr.source_params[:, :3].numpy() + df_channels = _with_nan_channel(d_f, pr.num_channels) + # Keep the fitted convolution trace itself, not a second + # baseline-subtracted version: otherwise it would no longer correspond + # to the fitted events. + # 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)) + 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], + axis=0, + ) + denoised_channels = _with_nan_channel(denoised, pr.num_channels) + event_channels = _with_nan_channel(events, pr.num_channels) + f0_channels = _with_nan_channel(f0, pr.num_channels) + snr = pr.source_snr.reshape(-1, 1) + sources = [ + Source( + profile=profiles[j], + coords=coords[j], + df_ls=df_channels[j], + df_denoised=denoised_channels[j], + events=event_channels[j], + f0=f0_channels[j], + snr=snr[j, 0], + ) + 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), + 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), + ) + annotation_enabled = False + user_rois = [] + empty_roi_arrays = {} + if pr.draw_user_rois and pr.soma_masks is not None: + annotation_enabled = True + masks = ( + np.stack([np.asarray(m, dtype=bool) for m in pr.soma_masks]) + 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) + labels = np.asarray(pr.soma_labels, dtype=object).reshape(-1) + user_rois = [ + UserRoi( + label=str(label), + mask=masks[j] if j < masks.shape[0] else None, + f=fluorescence[j] if j < fluorescence.shape[0] else None, + ) + for j, label in enumerate(labels) + ] + if not user_rois: + empty_roi_arrays = {"mask": masks, "F": fluorescence} + return PathSummary( + path_index=path_index, + sources=sources, + user_rois=user_rois, + visualizations=Visualizations( + act_im=pr.act_im, mean_im=pr.mean_im, act_im_peaks=pr.act_im_peaks + ), + frame_info=frame_info, + global_f=np.concatenate([r.global_f for r in results], axis=0).T, + z_depths=pr.z_depths, + annotation_enabled=annotation_enabled, + _empty_source_arrays=( + {} + if sources + else { + "profiles": profiles, + "coords": coords, + "dF_ls": df_channels, + "dF_denoised": denoised_channels, + "events": event_channels, + "F0": f0_channels, + "SNR": snr, + } + ), + _empty_roi_arrays=empty_roi_arrays, + ) diff --git a/src/giant_python/extraction/band/rois.py b/src/giant_python/extraction/band/rois.py index cf1c3e0f..249b047d 100644 --- a/src/giant_python/extraction/band/rois.py +++ b/src/giant_python/extraction/band/rois.py @@ -1,196 +1,196 @@ -"""Pure band ROI geometry, annotation validation, and superpixel mapping.""" - -import numpy as np - - -def user_roi_superpixel_lists_from_masks( - roi_masks: list, - sp_fastz: np.ndarray, - sp_rows: np.ndarray, - sp_cols: np.ndarray, -) -> list: - """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( - ref: np.ndarray, - fastz_to_refz: np.ndarray, - subsample_matrix_inds: np.ndarray, - motion_median: tuple, -) -> dict: - """Prepare reference display and mask geometry with internal band offsets. - - 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] - yx_shape = (ref.shape[2], ref.shape[3]) - plane = yx_shape[0] * yx_shape[1] - ch_means = [np.nanmean(ref[c]) for c in range(ref.shape[0])] - best_ch = int(np.argmax(ch_means)) if len(ch_means) > 0 else 0 - z_map = np.array(fastz_to_refz + avg_motion_z).reshape(-1) - 1 - num_fast_z = z_map.shape[0] - ref_pix = subsample_matrix_inds[:, 0] - sp_fastz = ref_pix // plane - sp_cols = avg_motion_c + (ref_pix - sp_fastz * plane) // yx_shape[0] - sp_rows = avg_motion_r + ref_pix % yx_shape[0] - sp_mask = np.zeros((num_fast_z, *yx_shape), dtype=bool) - valid = ( - (sp_rows >= 0) - & (sp_rows < yx_shape[0]) - & (sp_cols >= 0) - & (sp_cols < yx_shape[1]) - & (sp_fastz >= 0) - & (sp_fastz < num_fast_z) - ) - if np.any(valid): - sp_mask[sp_fastz[valid], sp_rows[valid], sp_cols[valid]] = True - return { - "ref": ref, - "num_ref_z": num_ref_z, - "yx_shape": yx_shape, - "best_ch": best_ch, - "z_map": z_map, - "num_fast_z": num_fast_z, - "sp_fastz": sp_fastz, - "sp_rows": sp_rows, - "sp_cols": sp_cols, - "sp_mask": sp_mask, - } - - -def _empty_path_selection(dmd_key: str, out: dict) -> None: - """Record a neutral selection for one invalid/missing path.""" - for values in out.values(): - values[dmd_key] = [] - - -def _read_roi_records(grp: dict, expected: tuple) -> tuple: - """Validate decoded ROI records against the current band mask geometry. - - 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 = [], [], [] - for i in range(n_rois): - record = grp.get(f"roi_{i:03d}") - if record is None: - continue - 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"]) - if mask.shape != expected: - return roi_masks, labels, recs, True - roi_masks.append(mask > 0) - else: - roi_masks.append(np.zeros(expected, dtype=bool)) - labels.append(label) - rec: dict[str, str | np.ndarray] = {"type": roi_type, "label": label} - if "position" in record: - rec["position"] = np.asarray(record["position"]) - recs.append(rec) - 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. - - 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] - expected = (geo["num_fast_z"], geo["yx_shape"][0], geo["yx_shape"][1]) - group = raw.get(path_key) - if group is None: - _empty_path_selection(key, out) - return False - masks, labels, records, bad_shape = _read_roi_records(group, expected) - if bad_shape: - print( - f"annotations.h5: {path_key} ROI mask shape mismatch " - f"(expected {expected}); treating this path as no selection." - ) - _empty_path_selection(key, out) - return False - out["user_roi_masks"][key] = masks - out["user_roi_superpixels"][key] = user_roi_superpixel_lists_from_masks( - masks, geo["sp_fastz"], geo["sp_rows"], geo["sp_cols"] - ) - 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") - 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. - - 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": {}, - "user_roi_labels": {}, - "roi_records": {}, - } - any_valid = False - for dmd_ix in range(n_dmds): - if _load_one_path(raw, dmd_ix, user_roi_geo, out): - any_valid = True - if not any_valid: - return False, {}, {}, {}, {} - return ( - True, - out["user_roi_masks"], - out["user_roi_superpixels"], - out["user_roi_labels"], - out["roi_records"], - ) +"""Pure band ROI geometry, annotation validation, and superpixel mapping.""" + +import numpy as np + + +def user_roi_superpixel_lists_from_masks( + roi_masks: list, + sp_fastz: np.ndarray, + sp_rows: np.ndarray, + sp_cols: np.ndarray, +) -> list: + """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( + ref: np.ndarray, + fastz_to_refz: np.ndarray, + subsample_matrix_inds: np.ndarray, + motion_median: tuple, +) -> dict: + """Prepare reference display and mask geometry with internal band offsets. + + 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] + yx_shape = (ref.shape[2], ref.shape[3]) + plane = yx_shape[0] * yx_shape[1] + ch_means = [np.nanmean(ref[c]) for c in range(ref.shape[0])] + best_ch = int(np.argmax(ch_means)) if len(ch_means) > 0 else 0 + z_map = np.array(fastz_to_refz + avg_motion_z).reshape(-1) - 1 + num_fast_z = z_map.shape[0] + ref_pix = subsample_matrix_inds[:, 0] + sp_fastz = ref_pix // plane + sp_cols = avg_motion_c + (ref_pix - sp_fastz * plane) // yx_shape[0] + sp_rows = avg_motion_r + ref_pix % yx_shape[0] + sp_mask = np.zeros((num_fast_z, *yx_shape), dtype=bool) + valid = ( + (sp_rows >= 0) + & (sp_rows < yx_shape[0]) + & (sp_cols >= 0) + & (sp_cols < yx_shape[1]) + & (sp_fastz >= 0) + & (sp_fastz < num_fast_z) + ) + if np.any(valid): + sp_mask[sp_fastz[valid], sp_rows[valid], sp_cols[valid]] = True + return { + "ref": ref, + "num_ref_z": num_ref_z, + "yx_shape": yx_shape, + "best_ch": best_ch, + "z_map": z_map, + "num_fast_z": num_fast_z, + "sp_fastz": sp_fastz, + "sp_rows": sp_rows, + "sp_cols": sp_cols, + "sp_mask": sp_mask, + } + + +def _empty_path_selection(dmd_key: str, out: dict) -> None: + """Record a neutral selection for one invalid/missing path.""" + for values in out.values(): + values[dmd_key] = [] + + +def _read_roi_records(grp: dict, expected: tuple) -> tuple: + """Validate decoded ROI records against the current band mask geometry. + + 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 = [], [], [] + for i in range(n_rois): + record = grp.get(f"roi_{i:03d}") + if record is None: + continue + 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"]) + if mask.shape != expected: + return roi_masks, labels, recs, True + roi_masks.append(mask > 0) + else: + roi_masks.append(np.zeros(expected, dtype=bool)) + labels.append(label) + rec: dict[str, str | np.ndarray] = {"type": roi_type, "label": label} + if "position" in record: + rec["position"] = np.asarray(record["position"]) + recs.append(rec) + 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. + + 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] + expected = (geo["num_fast_z"], geo["yx_shape"][0], geo["yx_shape"][1]) + group = raw.get(path_key) + if group is None: + _empty_path_selection(key, out) + return False + masks, labels, records, bad_shape = _read_roi_records(group, expected) + if bad_shape: + print( + f"annotations.h5: {path_key} ROI mask shape mismatch " + f"(expected {expected}); treating this path as no selection." + ) + _empty_path_selection(key, out) + return False + out["user_roi_masks"][key] = masks + out["user_roi_superpixels"][key] = user_roi_superpixel_lists_from_masks( + masks, geo["sp_fastz"], geo["sp_rows"], geo["sp_cols"] + ) + 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") + 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. + + 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": {}, + "user_roi_labels": {}, + "roi_records": {}, + } + any_valid = False + for dmd_ix in range(n_dmds): + if _load_one_path(raw, dmd_ix, user_roi_geo, out): + any_valid = True + if not any_valid: + return False, {}, {}, {}, {} + return ( + True, + out["user_roi_masks"], + out["user_roi_superpixels"], + out["user_roi_labels"], + out["roi_records"], + ) diff --git a/src/giant_python/extraction/band/summary_images.py b/src/giant_python/extraction/band/summary_images.py index b9a35675..14da2bdb 100644 --- a/src/giant_python/extraction/band/summary_images.py +++ b/src/giant_python/extraction/band/summary_images.py @@ -1,641 +1,641 @@ -"""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: - -* :func:`compute_mean_image` (ref 1913-1918) scatters the kept-frame mean - 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 - image that Phase-5 peak detection localizes sources in. - -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 -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 -from numpy.typing import NDArray -from scipy import ndimage - -from ...numerics.morphology import fast_dilation -from ...progress import progress - - -def compute_mean_image( - low_res_data_norm: np.ndarray, - unique_motion: np.ndarray, - mot_inds: np.ndarray, - frames_to_keep: 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, - num_channels: int, - low_res_data2_norm: np.ndarray | None = None, -) -> np.ndarray: - """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). - - Parameters - ---------- - low_res_data_norm : ndarray of shape (n_superpixels, n_frames) - Count-normalized channel-1 low-res traces. - unique_motion : ndarray of shape (n_bins, 3) - Unique motion vectors from - :func:`giant_python.extraction.band.motion_binning.bin_motion`. - mot_inds : ndarray - Per-frame motion-bin indices (used to pick the most common bin). - frames_to_keep : ndarray of bool - Frames contributing to the mean. - ref_d, ref_r, ref_c : ndarray - Per-superpixel reference depth/row/column indices. - num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int - Output grid geometry. - 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). - - Returns - ------- - ndarray of float32 - 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), - np.nan, - dtype=np.float32, - ) - 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) - 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( - cast(np.ndarray, low_res_data2_norm)[:, frames_to_keep], axis=1 - ) - return mean_im - - -def accumulate_activity_image( - rho: np.ndarray, - sel_pix_idxs: np.ndarray, - num_fast_zs: int, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, - batch_size: int = 1000, - verbose: bool = False, -) -> np.ndarray: - """Accumulate squared spatio-temporal local maxima of rho. - - 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. - - Parameters - ---------- - rho : ndarray of shape (n_sel, n_frames) - Smoothed rho response (NaN allowed). - sel_pix_idxs : ndarray of int - Flattened selected-pixel indices into the spatial grid. - 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). - 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). - """ - n_frames = rho.shape[1] - batch_size = min(batch_size, n_frames) - num_batches = int(np.ceil(n_frames / batch_size)) - - spatial_coords = np.unravel_index( - sel_pix_idxs, (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row) - ) - depth_indices = spatial_coords[0][None, :].astype(np.intp, copy=False) - row_indices = spatial_coords[1][None, :].astype(np.intp, copy=False) - col_indices = spatial_coords[2][None, :].astype(np.intp, copy=False) - - dilation_struct = np.ones((3, 3), dtype=np.uint8) - act_im = np.zeros( - (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), - dtype=np.float32, - ) - temporal_pad = 1 - - # Crop to a padded ROI containing all selected pixels; all-NaN regions - # outside it can never produce a local maximum. - row_min = int(np.min(row_indices)) - row_max = int(np.max(row_indices)) - col_min = int(np.min(col_indices)) - col_max = int(np.max(col_indices)) - row_start = max(0, row_min - 1) - row_stop = min(dmd_pixels_per_column, row_max + 2) - col_start = max(0, col_min - 1) - col_stop = min(dmd_pixels_per_row, col_max + 2) - roi_h = row_stop - row_start - roi_w = col_stop - col_start - - row_indices_roi = (row_indices - row_start).astype(np.intp, copy=False) - 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) - nan_mask = np.empty_like(batch_rho, dtype=bool) - interior_shape = ( - max(prealloc_size - 2, 0), - num_fast_zs, - max(roi_h - 2, 0), - max(roi_w - 2, 0), - ) - local_maxima_core = np.empty(interior_shape, dtype=bool) - compare_tmp_core = np.empty(interior_shape, dtype=bool) - 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): - batch_start = batch_idx * batch_size - batch_end = min(batch_start + batch_size, n_frames) - padded_start = max(0, batch_start - temporal_pad) - padded_end = min(n_frames, batch_end + temporal_pad) - curr_size = padded_end - padded_start - - br = batch_rho[:curr_size] - nm = nan_mask[:curr_size] - - br.fill(0) - 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[nm] = 0 - core_t = curr_size - 2 - if core_t <= 0: - continue - - dilated_nan_mask = fast_dilation(nm, dilation_struct) - - center = br[1:-1, :, 1:-1, 1:-1] - lmc = local_maxima_core[:core_t] - ctmp = compare_tmp_core[:core_t] - b3c = batch_rho_pow2_core[:core_t] - - np.greater(center, br[:-2, :, 1:-1, 1:-1], out=lmc) - np.greater(center, br[2:, :, 1:-1, 1:-1], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - np.greater(center, br[1:-1, :, :-2, 1:-1], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - np.greater(center, br[1:-1, :, 2:, 1:-1], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - np.greater(center, br[1:-1, :, 1:-1, :-2], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - np.greater(center, br[1:-1, :, 1:-1, 2:], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - np.logical_not(dilated_nan_mask[1:-1, :, 1:-1, 1:-1], out=ctmp) - np.logical_and(lmc, ctmp, out=lmc) - - np.multiply(center, center, out=b3c) - 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) - - return act_im - - -def finalize_activity_image( - act_im: np.ndarray, - sel_pix_idxs: np.ndarray, - nan_ct: np.ndarray, - ref_r: np.ndarray | None = None, - ref_c: np.ndarray | None = None, - ref_d: np.ndarray | None = None, - phase_window_height: int = 7, - phase_window_width: int = 11, - phase_tolerance: float = 0.0, - phase_min_samples: int = 5, -) -> 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 - 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 - in the original activity units. With geometry, neighborhoods - 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 - centered vertical window in their own column crosses invalid/nonfinite - input or an image boundary. This overrides undefined medians at these - edges without changing the filter samples. - Horizontal window clipping alone does not trigger this suppression. - - Parameters - ---------- - 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. - nan_ct : ndarray of shape (n_sel,) - Per-selected-pixel rho NaN fraction from - :func:`giant_python.extraction.band.activity.mask_high_nan_rho`. - ref_r, ref_c : ndarray, optional - Reference-center row and column for each superpixel, expressed in - the activity-image coordinate frame. The pipeline shifts these by - the dominant retained motion bin as an approximation for the - multi-motion image. Multiple bands can occupy the same column. - ref_d : ndarray, optional - Depth of each reference center. Required with geometry for multi-plane - images; omitted centers belong to plane zero in single-plane images. - phase_window_height, phase_window_width : int - Positive odd spatial window dimensions for phase matching (7x11). - phase_tolerance : float - Maximum signed-phase difference, in row pixels (default 0, exact - equality). Midpoint ties choose the smaller reference row. - phase_min_samples : int - Minimum finite phase-matched samples for first-pass medians - (default 5); smaller neighborhoods use the full-window fallback. - - Returns - ------- - ndarray - Median-subtracted activity in original units, NaN outside valid - support or where the median is undefined. Valid vertical support-edge - pixels are zero. - """ - 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 - act_im[nan_mask] = np.nan - - if ref_r is not None and ref_c is not None: - med_act_im = phase_matched_nanmedian( - act_im, - np.flatnonzero(~nan_mask), - ref_r, - ref_c, - ref_d=ref_d, - height=phase_window_height, - width=phase_window_width, - phase_tolerance=phase_tolerance, - min_samples=phase_min_samples, - ) - else: - 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 - # With no output override, ndimage preserves the boolean input dtype. - vertical_interior = cast( - NDArray[np.bool_], - ndimage.minimum_filter1d( - valid_input, - size=window_height, - axis=1, - mode="constant", - cval=0, - ), - ) - vertical_edge = valid_input & ~vertical_interior - act_im = act_im - med_act_im - act_im[nan_mask] = np.nan - act_im[vertical_edge] = 0 - return act_im - - -# Preserve scientific parity of phase assignment and frozen fallback passes. -def phase_matched_nanmedian( - image: np.ndarray, - valid_pix_idxs: np.ndarray, - ref_r: np.ndarray, - ref_c: np.ndarray, - ref_d: np.ndarray | None = None, - height: int = 7, - width: int = 11, - phase_tolerance: float = 0.0, - min_samples: int = 5, - chunk_size: int = 4096, -) -> np.ndarray: - """Local median conditioned on signed reference-band phase. - - 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 - different curvature. Reference coordinates must already include motion. - - All nearest-center assignments are retained; exact distance ties choose - the smaller reference row. Duplicate centers are deduplicated; exact - 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. - - 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 - 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. - This is a phase-conditioned spatial background, not a - reconstruction or separation of contributions at physical crossings. - - 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)") - for name, value in (("height", height), ("width", width)): - 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), - ("chunk_size", chunk_size), - ): - if not isinstance(value, (int, np.integer)) or value < 1: - raise ValueError(f"{name} must be a positive integer") - if not np.isfinite(phase_tolerance) or phase_tolerance < 0: - raise ValueError("phase_tolerance must be finite and nonnegative") - - ref_r = np.asarray(ref_r, dtype=float).reshape(-1) - ref_c = np.asarray(ref_c).reshape(-1) - if not ref_r.size or ref_r.size != ref_c.size: - raise ValueError("ref_r and ref_c must be non-empty and equally sized") - if not np.all(np.isfinite(ref_r)): - raise ValueError("reference rows must be finite") - if ref_d is None: - if image.shape[0] != 1: - raise ValueError("ref_d is required for multi-plane images") - ref_d = np.zeros(ref_r.size, dtype=np.intp) - else: - ref_d = np.asarray(ref_d).reshape(-1) - 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") - 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 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)) - if not selected.size: - return result - - nz, nr, nc = image.shape - in_bounds = (ref_d >= 0) & (ref_d < nz) & (ref_c >= 0) & (ref_c < nc) - # 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]): - 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] - phase = np.full(selected.size, np.nan) - for start, stop in itertools.pairwise(boundaries): - positions = order[start:stop] - centers = references.get(int(keys[positions[0]])) - if centers is None: - continue - centers = np.unique(centers) - pixel_rows = rows[positions] - insertion = np.searchsorted(centers, pixel_rows) - 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]), - left, - right, - ) - phase[positions] = pixel_rows - centers[nearest] - - # Lookup both support membership and phase using sorted selected indices; - # finite unselected image pixels must never enter the sample population. - row_offsets, col_offsets = np.meshgrid( - np.arange(-(height // 2), height // 2 + 1), - np.arange(-(width // 2), width // 2 + 1), - indexing="ij", - ) - row_offsets, col_offsets = row_offsets.ravel(), col_offsets.ravel() - values = image.ravel()[selected] - outputs = np.flatnonzero(np.isfinite(phase) & np.isfinite(values)) - - 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) - 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) - ) - 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) - medians = np.nanmedian(samples, axis=1) - flat = selected[positions[enough]] - result.ravel()[flat] = medians - - # Advanced indexing freezes first-pass values: fallback estimates must - # not propagate or depend on chunk size / iteration order. - first_medians = result.ravel()[selected] - missing = outputs[~np.isfinite(first_medians[outputs])] - for positions, lookup, support in windows(missing): - accept = support & np.isfinite(first_medians[lookup]) - counts = np.count_nonzero(accept, axis=1) - enough = counts > 0 - # Equivalent to nanmean, without empty-window warnings. - totals = np.sum( - np.where(accept, first_medians[lookup], 0), - axis=1, - dtype=np.float64, - ) - result.ravel()[selected[positions[enough]]] = totals[enough] / counts[enough] - return result - - -def snake_aligned_nanmedian( - image: np.ndarray, - valid_pix_idxs: np.ndarray, - ref_r: np.ndarray, - ref_c: np.ndarray, - height: int = 5, - width: int = 11, - chunk_size: int = 100_000, -) -> np.ndarray: - """Return local medians along the band trajectory. - - The parallel snakes have the same trajectory and differ by a nearly fixed - 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. - Work is restricted to valid pixels and chunked to bound temporary memory. - 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") - - ref_r = np.asarray(ref_r).reshape(-1) - ref_c = np.asarray(ref_c).reshape(-1).astype(np.intp, copy=False) - if ref_r.size == 0 or ref_r.size != ref_c.size: - raise ValueError("ref_r and ref_c must be non-empty and equally sized") - - n_rows, n_cols = image.shape[-2:] - in_bounds = (ref_c >= 0) & (ref_c < n_cols) - columns = np.unique(ref_c[in_bounds]) - if columns.size == 0: - 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) - snake_spacing = ( - 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] - run_stops = np.r_[run_starts[1:], columns.size] - center_rows = np.array([rows[0] for rows in rows_by_column], dtype=float) - segment_at_reference = np.empty(columns.size, dtype=np.intp) - 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]] - 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 - - 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), - 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)) - col_offsets = np.arange(-(width // 2), width // 2 + 1) - row_offsets = np.arange(-(height // 2), height // 2 + 1) - - for start in range(0, len(valid_pix_idxs), chunk_size): - flat = valid_pix_idxs[start : start + chunk_size] - depths, rows, cols = np.unravel_index(flat, image.shape) - 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) - 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) - samples = np.full(sample_rows.shape, np.nan, dtype=result.dtype) - 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 +"""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: + +* :func:`compute_mean_image` (ref 1913-1918) scatters the kept-frame mean + 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 + image that Phase-5 peak detection localizes sources in. + +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 +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 +from numpy.typing import NDArray +from scipy import ndimage + +from ...numerics.morphology import fast_dilation +from ...progress import progress + + +def compute_mean_image( + low_res_data_norm: np.ndarray, + unique_motion: np.ndarray, + mot_inds: np.ndarray, + frames_to_keep: 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, + num_channels: int, + low_res_data2_norm: np.ndarray | None = None, +) -> np.ndarray: + """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). + + Parameters + ---------- + low_res_data_norm : ndarray of shape (n_superpixels, n_frames) + Count-normalized channel-1 low-res traces. + unique_motion : ndarray of shape (n_bins, 3) + Unique motion vectors from + :func:`giant_python.extraction.band.motion_binning.bin_motion`. + mot_inds : ndarray + Per-frame motion-bin indices (used to pick the most common bin). + frames_to_keep : ndarray of bool + Frames contributing to the mean. + ref_d, ref_r, ref_c : ndarray + Per-superpixel reference depth/row/column indices. + num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int + Output grid geometry. + 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). + + Returns + ------- + ndarray of float32 + 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), + np.nan, + dtype=np.float32, + ) + 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) + 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( + cast(np.ndarray, low_res_data2_norm)[:, frames_to_keep], axis=1 + ) + return mean_im + + +def accumulate_activity_image( + rho: np.ndarray, + sel_pix_idxs: np.ndarray, + num_fast_zs: int, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, + batch_size: int = 1000, + verbose: bool = False, +) -> np.ndarray: + """Accumulate squared spatio-temporal local maxima of rho. + + 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. + + Parameters + ---------- + rho : ndarray of shape (n_sel, n_frames) + Smoothed rho response (NaN allowed). + sel_pix_idxs : ndarray of int + Flattened selected-pixel indices into the spatial grid. + 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). + 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). + """ + n_frames = rho.shape[1] + batch_size = min(batch_size, n_frames) + num_batches = int(np.ceil(n_frames / batch_size)) + + spatial_coords = np.unravel_index( + sel_pix_idxs, (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row) + ) + depth_indices = spatial_coords[0][None, :].astype(np.intp, copy=False) + row_indices = spatial_coords[1][None, :].astype(np.intp, copy=False) + col_indices = spatial_coords[2][None, :].astype(np.intp, copy=False) + + dilation_struct = np.ones((3, 3), dtype=np.uint8) + act_im = np.zeros( + (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), + dtype=np.float32, + ) + temporal_pad = 1 + + # Crop to a padded ROI containing all selected pixels; all-NaN regions + # outside it can never produce a local maximum. + row_min = int(np.min(row_indices)) + row_max = int(np.max(row_indices)) + col_min = int(np.min(col_indices)) + col_max = int(np.max(col_indices)) + row_start = max(0, row_min - 1) + row_stop = min(dmd_pixels_per_column, row_max + 2) + col_start = max(0, col_min - 1) + col_stop = min(dmd_pixels_per_row, col_max + 2) + roi_h = row_stop - row_start + roi_w = col_stop - col_start + + row_indices_roi = (row_indices - row_start).astype(np.intp, copy=False) + 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) + nan_mask = np.empty_like(batch_rho, dtype=bool) + interior_shape = ( + max(prealloc_size - 2, 0), + num_fast_zs, + max(roi_h - 2, 0), + max(roi_w - 2, 0), + ) + local_maxima_core = np.empty(interior_shape, dtype=bool) + compare_tmp_core = np.empty(interior_shape, dtype=bool) + 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): + batch_start = batch_idx * batch_size + batch_end = min(batch_start + batch_size, n_frames) + padded_start = max(0, batch_start - temporal_pad) + padded_end = min(n_frames, batch_end + temporal_pad) + curr_size = padded_end - padded_start + + br = batch_rho[:curr_size] + nm = nan_mask[:curr_size] + + br.fill(0) + 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[nm] = 0 + core_t = curr_size - 2 + if core_t <= 0: + continue + + dilated_nan_mask = fast_dilation(nm, dilation_struct) + + center = br[1:-1, :, 1:-1, 1:-1] + lmc = local_maxima_core[:core_t] + ctmp = compare_tmp_core[:core_t] + b3c = batch_rho_pow2_core[:core_t] + + np.greater(center, br[:-2, :, 1:-1, 1:-1], out=lmc) + np.greater(center, br[2:, :, 1:-1, 1:-1], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + np.greater(center, br[1:-1, :, :-2, 1:-1], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + np.greater(center, br[1:-1, :, 2:, 1:-1], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + np.greater(center, br[1:-1, :, 1:-1, :-2], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + np.greater(center, br[1:-1, :, 1:-1, 2:], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + np.logical_not(dilated_nan_mask[1:-1, :, 1:-1, 1:-1], out=ctmp) + np.logical_and(lmc, ctmp, out=lmc) + + np.multiply(center, center, out=b3c) + 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) + + return act_im + + +def finalize_activity_image( + act_im: np.ndarray, + sel_pix_idxs: np.ndarray, + nan_ct: np.ndarray, + ref_r: np.ndarray | None = None, + ref_c: np.ndarray | None = None, + ref_d: np.ndarray | None = None, + phase_window_height: int = 7, + phase_window_width: int = 11, + phase_tolerance: float = 0.0, + phase_min_samples: int = 5, +) -> 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 + 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 + in the original activity units. With geometry, neighborhoods + 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 + centered vertical window in their own column crosses invalid/nonfinite + input or an image boundary. This overrides undefined medians at these + edges without changing the filter samples. + Horizontal window clipping alone does not trigger this suppression. + + Parameters + ---------- + 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. + nan_ct : ndarray of shape (n_sel,) + Per-selected-pixel rho NaN fraction from + :func:`giant_python.extraction.band.activity.mask_high_nan_rho`. + ref_r, ref_c : ndarray, optional + Reference-center row and column for each superpixel, expressed in + the activity-image coordinate frame. The pipeline shifts these by + the dominant retained motion bin as an approximation for the + multi-motion image. Multiple bands can occupy the same column. + ref_d : ndarray, optional + Depth of each reference center. Required with geometry for multi-plane + images; omitted centers belong to plane zero in single-plane images. + phase_window_height, phase_window_width : int + Positive odd spatial window dimensions for phase matching (7x11). + phase_tolerance : float + Maximum signed-phase difference, in row pixels (default 0, exact + equality). Midpoint ties choose the smaller reference row. + phase_min_samples : int + Minimum finite phase-matched samples for first-pass medians + (default 5); smaller neighborhoods use the full-window fallback. + + Returns + ------- + ndarray + Median-subtracted activity in original units, NaN outside valid + support or where the median is undefined. Valid vertical support-edge + pixels are zero. + """ + 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 + act_im[nan_mask] = np.nan + + if ref_r is not None and ref_c is not None: + med_act_im = phase_matched_nanmedian( + act_im, + np.flatnonzero(~nan_mask), + ref_r, + ref_c, + ref_d=ref_d, + height=phase_window_height, + width=phase_window_width, + phase_tolerance=phase_tolerance, + min_samples=phase_min_samples, + ) + else: + 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 + # With no output override, ndimage preserves the boolean input dtype. + vertical_interior = cast( + NDArray[np.bool_], + ndimage.minimum_filter1d( + valid_input, + size=window_height, + axis=1, + mode="constant", + cval=0, + ), + ) + vertical_edge = valid_input & ~vertical_interior + act_im = act_im - med_act_im + act_im[nan_mask] = np.nan + act_im[vertical_edge] = 0 + return act_im + + +# Preserve scientific parity of phase assignment and frozen fallback passes. +def phase_matched_nanmedian( + image: np.ndarray, + valid_pix_idxs: np.ndarray, + ref_r: np.ndarray, + ref_c: np.ndarray, + ref_d: np.ndarray | None = None, + height: int = 7, + width: int = 11, + phase_tolerance: float = 0.0, + min_samples: int = 5, + chunk_size: int = 4096, +) -> np.ndarray: + """Local median conditioned on signed reference-band phase. + + 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 + different curvature. Reference coordinates must already include motion. + + All nearest-center assignments are retained; exact distance ties choose + the smaller reference row. Duplicate centers are deduplicated; exact + 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. + + 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 + 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. + This is a phase-conditioned spatial background, not a + reconstruction or separation of contributions at physical crossings. + + 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)") + for name, value in (("height", height), ("width", width)): + 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), + ("chunk_size", chunk_size), + ): + if not isinstance(value, (int, np.integer)) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not np.isfinite(phase_tolerance) or phase_tolerance < 0: + raise ValueError("phase_tolerance must be finite and nonnegative") + + ref_r = np.asarray(ref_r, dtype=float).reshape(-1) + ref_c = np.asarray(ref_c).reshape(-1) + if not ref_r.size or ref_r.size != ref_c.size: + raise ValueError("ref_r and ref_c must be non-empty and equally sized") + if not np.all(np.isfinite(ref_r)): + raise ValueError("reference rows must be finite") + if ref_d is None: + if image.shape[0] != 1: + raise ValueError("ref_d is required for multi-plane images") + ref_d = np.zeros(ref_r.size, dtype=np.intp) + else: + ref_d = np.asarray(ref_d).reshape(-1) + 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") + 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 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)) + if not selected.size: + return result + + nz, nr, nc = image.shape + in_bounds = (ref_d >= 0) & (ref_d < nz) & (ref_c >= 0) & (ref_c < nc) + # 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]): + 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] + phase = np.full(selected.size, np.nan) + for start, stop in itertools.pairwise(boundaries): + positions = order[start:stop] + centers = references.get(int(keys[positions[0]])) + if centers is None: + continue + centers = np.unique(centers) + pixel_rows = rows[positions] + insertion = np.searchsorted(centers, pixel_rows) + 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]), + left, + right, + ) + phase[positions] = pixel_rows - centers[nearest] + + # Lookup both support membership and phase using sorted selected indices; + # finite unselected image pixels must never enter the sample population. + row_offsets, col_offsets = np.meshgrid( + np.arange(-(height // 2), height // 2 + 1), + np.arange(-(width // 2), width // 2 + 1), + indexing="ij", + ) + row_offsets, col_offsets = row_offsets.ravel(), col_offsets.ravel() + values = image.ravel()[selected] + outputs = np.flatnonzero(np.isfinite(phase) & np.isfinite(values)) + + 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) + 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) + ) + 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) + medians = np.nanmedian(samples, axis=1) + flat = selected[positions[enough]] + result.ravel()[flat] = medians + + # Advanced indexing freezes first-pass values: fallback estimates must + # not propagate or depend on chunk size / iteration order. + first_medians = result.ravel()[selected] + missing = outputs[~np.isfinite(first_medians[outputs])] + for positions, lookup, support in windows(missing): + accept = support & np.isfinite(first_medians[lookup]) + counts = np.count_nonzero(accept, axis=1) + enough = counts > 0 + # Equivalent to nanmean, without empty-window warnings. + totals = np.sum( + np.where(accept, first_medians[lookup], 0), + axis=1, + dtype=np.float64, + ) + result.ravel()[selected[positions[enough]]] = totals[enough] / counts[enough] + return result + + +def snake_aligned_nanmedian( + image: np.ndarray, + valid_pix_idxs: np.ndarray, + ref_r: np.ndarray, + ref_c: np.ndarray, + height: int = 5, + width: int = 11, + chunk_size: int = 100_000, +) -> np.ndarray: + """Return local medians along the band trajectory. + + The parallel snakes have the same trajectory and differ by a nearly fixed + 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. + Work is restricted to valid pixels and chunked to bound temporary memory. + 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") + + ref_r = np.asarray(ref_r).reshape(-1) + ref_c = np.asarray(ref_c).reshape(-1).astype(np.intp, copy=False) + if ref_r.size == 0 or ref_r.size != ref_c.size: + raise ValueError("ref_r and ref_c must be non-empty and equally sized") + + n_rows, n_cols = image.shape[-2:] + in_bounds = (ref_c >= 0) & (ref_c < n_cols) + columns = np.unique(ref_c[in_bounds]) + if columns.size == 0: + 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) + snake_spacing = ( + 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] + run_stops = np.r_[run_starts[1:], columns.size] + center_rows = np.array([rows[0] for rows in rows_by_column], dtype=float) + segment_at_reference = np.empty(columns.size, dtype=np.intp) + 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]] + 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 + + 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), + 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)) + col_offsets = np.arange(-(width // 2), width // 2 + 1) + row_offsets = np.arange(-(height // 2), height // 2 + 1) + + for start in range(0, len(valid_pix_idxs), chunk_size): + flat = valid_pix_idxs[start : start + chunk_size] + depths, rows, cols = np.unravel_index(flat, image.shape) + 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) + 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) + samples = np.full(sample_rows.shape, np.nan, dtype=result.dtype) + 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 a7c82580..559a83b1 100644 --- a/src/giant_python/extraction/band/traces.py +++ b/src/giant_python/extraction/band/traces.py @@ -1,812 +1,812 @@ -"""High-resolution per-trial trace extraction. - -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 -backprojection of each projected profile onto the background, and a -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 -always calculates both least-squares and transient traces. It also computes the -global and per-user-ROI fluorescence. - -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 -backprojection after the original fields. -""" - -from __future__ import annotations - -from typing import cast - -import numpy as np -import torch - -from ...numerics.interpolation import nearest_interp -from .geometry import build_selected_pixel_mask, ref_pixs_to_drc -from .localization import solve_phi_motion -from .operators import build_motion_h_matrices -from .transient import TransientOptions, fit_transient_traces -from .trial_data import read_band_trial_data -from .types import 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). - num_channels : int - Number of acquisition channels. - n_soma : int - Number of user/soma ROIs. - - Returns - ------- - tuple - Same record as :func:`compute_high_res_traces`, with zero - frames. - """ - return TrialTraceResult( - np.full((0, n_sources), np.nan, dtype=np.float32), - np.full((0, n_sources), np.nan, dtype=np.float32), - np.full((0,), np.nan), - np.full((0,), np.nan), - np.full((0, num_channels), np.nan, dtype=np.float32), - (np.full((0,), np.nan), np.full((0,), np.nan), np.full((0,), np.nan)), - ( - np.full((0,), 0, dtype=np.int16), - np.full((0,), 0, dtype=np.int16), - np.full((0,), 0, dtype=np.int16), - ), - np.full((0, n_soma, num_channels), np.nan, dtype=np.float32), - np.full((0, n_sources), np.nan, dtype=np.float32), - np.full((0, n_sources), np.nan, dtype=np.float32), - np.full((0, n_sources), np.nan, dtype=np.float32), - ) - - -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 - nearest-neighbor interpolation. - - Parameters - ---------- - frames : ndarray - The trial's high-res downsample frame line positions. - a_data : dict - 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). - """ - 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]) - ]) - 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"]) - return ( - motion_r, - motion_c, - motion_z, - background, - online_y, - online_x, - online_z, - ) - - -def _bin_trial_motion( - motion_r: np.ndarray, - motion_c: np.ndarray, - motion_z: np.ndarray, - median_z: float, - 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]: - """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) - motion bins; each retained low-res bin is matched to its trial bin so the - same PSF geometry is reused. - - Parameters - ---------- - motion_r, motion_c, motion_z : ndarray - Per-frame interpolated motion. - median_z : float - Median z across the recording (from the low-res pass). - unique_motion_ds : ndarray of shape (n_ds_bins, 2+) - The low-res kept 2-D motion vectors. - mot_inds_to_keep_ds : ndarray - Indices of the low-res bins to keep. - z_tol : float, optional - Maximum absolute rounded z offset from the median, in um (default 1.5). - - Returns - ------- - 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). - mot_inds_to_keep : ndarray - Trial-bin indices matching a kept low-res bin. - frames_to_keep : ndarray of bool - Frames belonging to a matched bin. - """ - unique_motion3, mot_inds = np.unique( - np.round(np.stack((motion_r, motion_c, motion_z), axis=1)), - axis=0, - return_inverse=True, - ) - mot_inds = np.reshape(mot_inds, -1) - frames_to_keep = np.isin( - mot_inds, - np.flatnonzero(np.abs(unique_motion3[:, 2] - median_z) <= z_tol), - ) - - 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, :]) - unique_motion, inv = np.unique(stacked, axis=0, return_inverse=True) - mot_inds[frames_to_keep] = np.reshape(inv, -1) - - mot_inds_to_keep = -1 * np.ones_like(mot_inds_to_keep_ds, dtype=np.int64) - for i, motion_idx_ds in enumerate(mot_inds_to_keep_ds): - matches = np.flatnonzero( - np.all( - unique_motion[:, :2] == unique_motion_ds[motion_idx_ds, :2], - axis=1, - ) - ) - if len(matches) > 0: - mot_inds_to_keep[i] = matches[0] - mot_inds_to_keep = mot_inds_to_keep[mot_inds_to_keep != -1] - - frames_to_keep = np.isin(mot_inds, mot_inds_to_keep) - return unique_motion, mot_inds, mot_inds_to_keep, frames_to_keep - - -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 - 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")) - return (weights.T @ data).T - - -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 - 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: 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") - if not isinstance(transient_options, TransientOptions): - raise TypeError("transient_options must be TransientOptions or None") - from ...models.params import _positive - - _positive("analyze_hz", analyze_hz) - - -def _solve_trial_phi_f0( - data: np.ndarray, - background: np.ndarray, - unique_motion: np.ndarray, - mot_inds: np.ndarray, - mot_inds_to_keep: np.ndarray, - sparse_h_inds: np.ndarray, - sparse_h_vals: np.ndarray, - sel_pix_idxs: np.ndarray, - a_final: torch.Tensor, - num_super_pixels: int, - dmd_pixels_per_row: int, - simple_trace_extraction: bool = False, - *, - 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 - weights (from the background-subtracted residual), and backprojects the - profiles onto the background (F0) and onto the fit residual - data - background - x @ phi. - - Parameters - ---------- - data : ndarray of shape (n_superpixels, n_frames) - Count-normalized activity. - background : ndarray of shape (n_superpixels, n_frames) - Interpolated background. - unique_motion : ndarray of shape (n_bins, 2) - Trial 2-D motion bins. - mot_inds : ndarray of shape (n_frames,) - Per-frame trial-bin index. - 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). - 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). - dmd_pixels_per_row : int - Grid geometry (column-shift stride). - simple_trace_extraction : bool, optional - Use normalized profile-intensity weighted averages for both dF and F0 - instead of least-squares dF and backprojected F0, with a zero - residual term (default False). - transient_options : TransientOptions or None - Add benchmark-style constrained dF, keeping separate QR dF and - backprojected F0. Mutually - exclusive with simple extraction. A failed fit raises RuntimeError. - analyze_hz : float or None - Nominal grid rate, required for transient fitting; line indices are - not seconds. Missing frames must retain their positions in the grid. - return_transient : bool - Also return denoised dF, events and the residual backprojection after - phi and f0. Missing-frame events are NaN; the initial state is not - counted as a new event. - - Returns - ------- - phi, f0 : torch.Tensor of shape (n_frames, n_sources) - Per-source dF and background backprojection (NaN where no motion bin - applies, where input frames contain nonfinite samples, or where - 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). - - Raises - ------ - RuntimeError - If the transient fit does not converge. - """ - _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")) - residual = data - background - - # One shifted superpixel<-pixel H per trial motion bin (same builder the - # NMF pass uses); only the matched bins are solved below. - h_mots = build_motion_h_matrices( - sparse_h_inds, - sparse_h_vals, - unique_motion, - sel_pix_idxs, - num_super_pixels, - dmd_pixels_per_row, - ) - - 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)) - 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)) - if simple_trace_extraction: - f0[motion_frames, :] = extract(x, background_frames) - else: - f0[motion_frames, :] = _backproject(x, background_frames) - f_residual[motion_frames, :] = _backproject( - x, residual_frames - x @ phi[motion_frames, :].T - ) - - if transient_options is not None and n_sources: - residual32 = residual.astype(np.float32) - valid = np.isin(mot_inds, mot_inds_to_keep) - valid &= np.all(np.isfinite(residual32), axis=0) - # Preserve the empty/all-invalid behavior of the existing extractor. - if np.any(valid): - result = fit_transient_traces( - residual32, - designs, - mot_inds, - valid, - analyze_hz, - options=transient_options, - ) - if not result.metadata["converged"]: - raise RuntimeError( - "Convolution trace extraction did not converge: " - f"{result.metadata['message']}. Increase trace_max_iter " - "or inspect the fit with fit_transient_traces()." - ) - denoised = torch.from_numpy(result.d_f.astype(np.float32)) - events = torch.from_numpy(result.events.astype(np.float32)) - events[~valid] = float("nan") - - if return_transient: - return phi, f0, denoised, events, f_residual - return phi, f0 - - -def _compute_global_f( - data: np.ndarray, - data2: np.ndarray | None, - frames_to_keep: np.ndarray, - num_channels: int, -) -> np.ndarray: - """Sum fluorescence over all superpixels per channel and frame. - - Parameters - ---------- - data : ndarray of shape (n_superpixels, n_frames) - Channel-1 activity. - data2 : ndarray or None - Channel-2 activity (used when num_channels >= 2). - frames_to_keep : ndarray of bool - Dropped frames are set to NaN. - num_channels : int - Number of acquisition channels. - - Returns - ------- - ndarray of shape (n_frames, num_channels) - Global fluorescence. - """ - channel_sums = [np.sum(data, axis=0)] - if num_channels >= 2: - # Two-channel acquisitions supply data2; do not coerce/copy it. - channel_sums.append(np.sum(cast(np.ndarray, data2), axis=0)) - global_f = np.stack(channel_sums, axis=-1) - global_f[~frames_to_keep, :] = np.nan - return global_f - - -def _compute_f_soma( - data: np.ndarray, - data2: np.ndarray | None, - soma_sps: list[np.ndarray], - frames_to_keep: np.ndarray, - num_channels: int, -) -> np.ndarray: - """Sum fluorescence over each user-ROI's superpixels per channel. - - Parameters - ---------- - data : ndarray of shape (n_superpixels, n_frames) - Channel-1 activity. - data2 : ndarray or None - Channel-2 activity (used when num_channels >= 2). - soma_sps : list of ndarray - Per-ROI superpixel index arrays. - frames_to_keep : ndarray of bool - Dropped frames are set to NaN. - num_channels : int - Number of acquisition channels. - - Returns - ------- - ndarray of shape (n_frames, n_rois, num_channels) - Per-ROI fluorescence. - """ - n_frames = data.shape[1] - 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[~frames_to_keep, :, :] = np.nan - return f_soma - - -def compute_high_res_traces( - data: np.ndarray, - data2: np.ndarray | None, - background_ds: np.ndarray, - frames: np.ndarray, - a_data: dict, - subsample_matrix_inds: np.ndarray, - sparse_h_inds: np.ndarray, - sparse_h_vals: np.ndarray, - a_final: torch.Tensor, - unique_motion_ds: np.ndarray, - mot_inds_to_keep_ds: np.ndarray, - median_z: float, - psf2d: np.ndarray, - num_super_pixels: int, - num_fast_zs: int, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, - num_channels: int, - soma_sps: list[np.ndarray], - z_tol: float = 1.5, - simple_trace_extraction: bool = False, - *, - transient_options: TransientOptions | None = None, - analyze_hz: float | None = None, -) -> TrialTraceResult: - """Compute one trial's high-res source traces from loaded arrays. - - Parameters - ---------- - data : ndarray of shape (n_superpixels, n_frames) - Count-normalized channel-1 activity. - data2 : ndarray or None - Count-normalized channel-2 activity. - background_ds : ndarray of shape (n_superpixels, n_ds) - Per-superpixel low-res background for this trial. - frames : ndarray - The trial's downsample frame line positions. - a_data : dict - Alignment data for this trial. - subsample_matrix_inds : ndarray - Superpixel reference-pixel map (from geometry). - sparse_h_inds, sparse_h_vals : ndarray - Base sparse H. - a_final : torch.Tensor of shape (n_pixels, n_sources) - Fixed source spatial profiles. - unique_motion_ds : ndarray - Low-res kept 2-D motion vectors. - mot_inds_to_keep_ds : ndarray - Indices of the low-res bins to keep. - median_z : float - Median z (from the low-res pass). - psf2d : ndarray - The (cropped) PSF for this DMD. - num_super_pixels, num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row \ -: int - Geometry. - num_channels : int - Number of acquisition channels. - soma_sps : list of ndarray - Per-ROI superpixel index arrays. - z_tol : float, optional - Maximum absolute rounded z offset from the median, in um (default 1.5). - simple_trace_extraction : bool, optional - Average superpixels weighted by normalized source profiles instead - of least-squares fitting dF and backprojecting F0; the residual term - is zero (default False). - transient_options : TransientOptions or None - Add constrained dF and events, retaining QR dF, backprojected F0 and - auxiliary data. - Fits nonnegative sparse events plus an unpenalized initial state. - Public dF retains missing-frame NaNs; nonconvergence raises - RuntimeError. - analyze_hz : float or None - Required nominal rate for transient fitting on the uniform full grid. - Acquisition averaging is approximated, not explicitly modeled. - - Returns - ------- - 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. - - 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) - if frame_grid.ndim != 1 or not np.all(np.isfinite(frame_grid)): - raise ValueError("frames must be a finite chronological vector") - # Reader ceil-rounds line positions, so nominally uniform samples - # 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") - ( - motion_r, - motion_c, - motion_z, - background, - online_y, - online_x, - online_z, - ) = _interp_trial_alignment(frames, a_data, background_ds) - - ( - unique_motion, - mot_inds, - mot_inds_to_keep, - frames_to_keep, - ) = _bin_trial_motion( - motion_r, - motion_c, - motion_z, - median_z, - unique_motion_ds, - mot_inds_to_keep_ds, - z_tol=z_tol, - ) - - ref_d, ref_c, ref_r = ref_pixs_to_drc( - subsample_matrix_inds[:, 0], dmd_pixels_per_column, dmd_pixels_per_row - ) - _, sel_pix_idxs = build_selected_pixel_mask( - unique_motion, - ref_d, - ref_r, - ref_c, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - psf2d, - ) - - phi, f0, denoised, events, f_residual = _solve_trial_phi_f0( - data, - background, - unique_motion, - mot_inds, - mot_inds_to_keep, - sparse_h_inds, - sparse_h_vals, - sel_pix_idxs, - a_final, - num_super_pixels, - dmd_pixels_per_row, - simple_trace_extraction=simple_trace_extraction, - transient_options=transient_options, - analyze_hz=analyze_hz, - return_transient=True, - ) - - 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) - - return TrialTraceResult( - phi.numpy(), - f0.numpy(), - frames, - sel_pix_idxs, - global_f, - (motion_r, motion_c, motion_z), - (online_y, online_x, online_z), - f_soma, - denoised.numpy(), - events.numpy(), - f_residual.numpy(), - ) - - -def _load_high_res_trial_data( - trial_ix: int, - dmd_ix: int, - samp_freq: float, - super_pixel_ids: np.ndarray, - 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. - """ - # The reader returns None only for skipped trials; keep_trial is True. - result = cast( - dict, - read_band_trial_data( - trial_ix, - True, - dmd_ix, - samp_freq, - super_pixel_ids, - datadr, - trial_table, - num_channels, - all_channels=True, - ), - ) - data = result["data"] / result["data_count"] - data2 = None - if num_channels >= 2: - data2 = result["data2"] / result["data_count2"] - return data, data2, result["alignment"], result["ds_frames"] - - -def get_high_res_traces( - trial_info: tuple, - dmd_ix: int, - samp_freq: float, - super_pixel_ids: np.ndarray, - datadr: str, - trial_table: dict, - subsample_matrix_inds: np.ndarray, - sparse_h_inds: np.ndarray, - sparse_h_vals: np.ndarray, - a_final: np.ndarray | torch.Tensor, - unique_motion_ds: np.ndarray, - mot_inds_to_keep_ds: np.ndarray, - median_z: float, - psf2d: np.ndarray, - num_super_pixels: int, - num_fast_zs: int, - dmd_pixels_per_column: int, - dmd_pixels_per_row: int, - num_channels: int, - soma_sps: list[np.ndarray], - z_tol: float = 1.5, - simple_trace_extraction: bool = False, - *, - 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 - :func:`compute_high_res_traces`. - - Parameters - ---------- - trial_info : tuple - (trial_ix, keep_trial, background_ds) for this trial. - dmd_ix : int - 0-based DMD index. - samp_freq : float - Analysis sample rate, in Hz. - super_pixel_ids : ndarray - Superpixel id lookup for this DMD. - datadr : str - Raw-data directory. - trial_table : dict - Normalized trial table. - subsample_matrix_inds, sparse_h_inds, sparse_h_vals : ndarray - Geometry / sparse H. - a_final : ndarray or torch.Tensor - 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 - Median z (from the low-res pass). - psf2d : ndarray - The (cropped) PSF for this DMD. - num_super_pixels, num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row \ -: int - Geometry. - num_channels : int - Number of acquisition channels. - soma_sps : list of ndarray - Per-ROI superpixel index arrays. - z_tol : float, optional - Maximum absolute rounded z offset from the median, in um (default 1.5). - simple_trace_extraction : bool, optional - Average superpixels weighted by normalized source profiles instead - of least-squares fitting dF and backprojecting F0; the residual term - is zero (default False). - transient_options : TransientOptions or None - Add constrained dF/events alongside QR dF, backprojected F0 and - unchanged profiles. - The reader's samp_freq supplies the nominal convolution rate. - - Returns - ------- - tuple - The named result of :func:`compute_high_res_traces` (empty for - skipped trials). - """ - trial_ix, keep_trial, background_ds = trial_info - - if not isinstance(a_final, torch.Tensor): - a_final = torch.tensor(a_final, dtype=torch.float32) - n_sources = a_final.shape[1] - - if not keep_trial: - return _empty_trace_result(n_sources, num_channels, len(soma_sps)) - - data, data2, a_data, frames = _load_high_res_trial_data( - trial_ix, - dmd_ix, - samp_freq, - super_pixel_ids, - datadr, - trial_table, - num_channels, - ) - - return compute_high_res_traces( - data, - data2, - background_ds, - frames, - a_data, - subsample_matrix_inds, - sparse_h_inds, - sparse_h_vals, - a_final, - unique_motion_ds, - mot_inds_to_keep_ds, - median_z, - psf2d, - num_super_pixels, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - num_channels, - soma_sps, - z_tol=z_tol, - simple_trace_extraction=simple_trace_extraction, - transient_options=transient_options, - analyze_hz=samp_freq, - ) +"""High-resolution per-trial trace extraction. + +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 +backprojection of each projected profile onto the background, and a +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 +always calculates both least-squares and transient traces. It also computes the +global and per-user-ROI fluorescence. + +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 +backprojection after the original fields. +""" + +from __future__ import annotations + +from typing import cast + +import numpy as np +import torch + +from ...numerics.interpolation import nearest_interp +from .geometry import build_selected_pixel_mask, ref_pixs_to_drc +from .localization import solve_phi_motion +from .operators import build_motion_h_matrices +from .transient import TransientOptions, fit_transient_traces +from .trial_data import read_band_trial_data +from .types import 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). + num_channels : int + Number of acquisition channels. + n_soma : int + Number of user/soma ROIs. + + Returns + ------- + tuple + Same record as :func:`compute_high_res_traces`, with zero + frames. + """ + return TrialTraceResult( + np.full((0, n_sources), np.nan, dtype=np.float32), + np.full((0, n_sources), np.nan, dtype=np.float32), + np.full((0,), np.nan), + np.full((0,), np.nan), + np.full((0, num_channels), np.nan, dtype=np.float32), + (np.full((0,), np.nan), np.full((0,), np.nan), np.full((0,), np.nan)), + ( + np.full((0,), 0, dtype=np.int16), + np.full((0,), 0, dtype=np.int16), + np.full((0,), 0, dtype=np.int16), + ), + np.full((0, n_soma, num_channels), np.nan, dtype=np.float32), + np.full((0, n_sources), np.nan, dtype=np.float32), + np.full((0, n_sources), np.nan, dtype=np.float32), + np.full((0, n_sources), np.nan, dtype=np.float32), + ) + + +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 + nearest-neighbor interpolation. + + Parameters + ---------- + frames : ndarray + The trial's high-res downsample frame line positions. + a_data : dict + 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). + """ + 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]) + ]) + 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"]) + return ( + motion_r, + motion_c, + motion_z, + background, + online_y, + online_x, + online_z, + ) + + +def _bin_trial_motion( + motion_r: np.ndarray, + motion_c: np.ndarray, + motion_z: np.ndarray, + median_z: float, + 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]: + """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) + motion bins; each retained low-res bin is matched to its trial bin so the + same PSF geometry is reused. + + Parameters + ---------- + motion_r, motion_c, motion_z : ndarray + Per-frame interpolated motion. + median_z : float + Median z across the recording (from the low-res pass). + unique_motion_ds : ndarray of shape (n_ds_bins, 2+) + The low-res kept 2-D motion vectors. + mot_inds_to_keep_ds : ndarray + Indices of the low-res bins to keep. + z_tol : float, optional + Maximum absolute rounded z offset from the median, in um (default 1.5). + + Returns + ------- + 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). + mot_inds_to_keep : ndarray + Trial-bin indices matching a kept low-res bin. + frames_to_keep : ndarray of bool + Frames belonging to a matched bin. + """ + unique_motion3, mot_inds = np.unique( + np.round(np.stack((motion_r, motion_c, motion_z), axis=1)), + axis=0, + return_inverse=True, + ) + mot_inds = np.reshape(mot_inds, -1) + frames_to_keep = np.isin( + mot_inds, + np.flatnonzero(np.abs(unique_motion3[:, 2] - median_z) <= z_tol), + ) + + 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, :]) + unique_motion, inv = np.unique(stacked, axis=0, return_inverse=True) + mot_inds[frames_to_keep] = np.reshape(inv, -1) + + mot_inds_to_keep = -1 * np.ones_like(mot_inds_to_keep_ds, dtype=np.int64) + for i, motion_idx_ds in enumerate(mot_inds_to_keep_ds): + matches = np.flatnonzero( + np.all( + unique_motion[:, :2] == unique_motion_ds[motion_idx_ds, :2], + axis=1, + ) + ) + if len(matches) > 0: + mot_inds_to_keep[i] = matches[0] + mot_inds_to_keep = mot_inds_to_keep[mot_inds_to_keep != -1] + + frames_to_keep = np.isin(mot_inds, mot_inds_to_keep) + return unique_motion, mot_inds, mot_inds_to_keep, frames_to_keep + + +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 + 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")) + return (weights.T @ data).T + + +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 + 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: 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") + if not isinstance(transient_options, TransientOptions): + raise TypeError("transient_options must be TransientOptions or None") + from ...models.params import _positive + + _positive("analyze_hz", analyze_hz) + + +def _solve_trial_phi_f0( + data: np.ndarray, + background: np.ndarray, + unique_motion: np.ndarray, + mot_inds: np.ndarray, + mot_inds_to_keep: np.ndarray, + sparse_h_inds: np.ndarray, + sparse_h_vals: np.ndarray, + sel_pix_idxs: np.ndarray, + a_final: torch.Tensor, + num_super_pixels: int, + dmd_pixels_per_row: int, + simple_trace_extraction: bool = False, + *, + 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 + weights (from the background-subtracted residual), and backprojects the + profiles onto the background (F0) and onto the fit residual + data - background - x @ phi. + + Parameters + ---------- + data : ndarray of shape (n_superpixels, n_frames) + Count-normalized activity. + background : ndarray of shape (n_superpixels, n_frames) + Interpolated background. + unique_motion : ndarray of shape (n_bins, 2) + Trial 2-D motion bins. + mot_inds : ndarray of shape (n_frames,) + Per-frame trial-bin index. + 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). + 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). + dmd_pixels_per_row : int + Grid geometry (column-shift stride). + simple_trace_extraction : bool, optional + Use normalized profile-intensity weighted averages for both dF and F0 + instead of least-squares dF and backprojected F0, with a zero + residual term (default False). + transient_options : TransientOptions or None + Add benchmark-style constrained dF, keeping separate QR dF and + backprojected F0. Mutually + exclusive with simple extraction. A failed fit raises RuntimeError. + analyze_hz : float or None + Nominal grid rate, required for transient fitting; line indices are + not seconds. Missing frames must retain their positions in the grid. + return_transient : bool + Also return denoised dF, events and the residual backprojection after + phi and f0. Missing-frame events are NaN; the initial state is not + counted as a new event. + + Returns + ------- + phi, f0 : torch.Tensor of shape (n_frames, n_sources) + Per-source dF and background backprojection (NaN where no motion bin + applies, where input frames contain nonfinite samples, or where + 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). + + Raises + ------ + RuntimeError + If the transient fit does not converge. + """ + _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")) + residual = data - background + + # One shifted superpixel<-pixel H per trial motion bin (same builder the + # NMF pass uses); only the matched bins are solved below. + h_mots = build_motion_h_matrices( + sparse_h_inds, + sparse_h_vals, + unique_motion, + sel_pix_idxs, + num_super_pixels, + dmd_pixels_per_row, + ) + + 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)) + 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)) + if simple_trace_extraction: + f0[motion_frames, :] = extract(x, background_frames) + else: + f0[motion_frames, :] = _backproject(x, background_frames) + f_residual[motion_frames, :] = _backproject( + x, residual_frames - x @ phi[motion_frames, :].T + ) + + if transient_options is not None and n_sources: + residual32 = residual.astype(np.float32) + valid = np.isin(mot_inds, mot_inds_to_keep) + valid &= np.all(np.isfinite(residual32), axis=0) + # Preserve the empty/all-invalid behavior of the existing extractor. + if np.any(valid): + result = fit_transient_traces( + residual32, + designs, + mot_inds, + valid, + analyze_hz, + options=transient_options, + ) + if not result.metadata["converged"]: + raise RuntimeError( + "Convolution trace extraction did not converge: " + f"{result.metadata['message']}. Increase trace_max_iter " + "or inspect the fit with fit_transient_traces()." + ) + denoised = torch.from_numpy(result.d_f.astype(np.float32)) + events = torch.from_numpy(result.events.astype(np.float32)) + events[~valid] = float("nan") + + if return_transient: + return phi, f0, denoised, events, f_residual + return phi, f0 + + +def _compute_global_f( + data: np.ndarray, + data2: np.ndarray | None, + frames_to_keep: np.ndarray, + num_channels: int, +) -> np.ndarray: + """Sum fluorescence over all superpixels per channel and frame. + + Parameters + ---------- + data : ndarray of shape (n_superpixels, n_frames) + Channel-1 activity. + data2 : ndarray or None + Channel-2 activity (used when num_channels >= 2). + frames_to_keep : ndarray of bool + Dropped frames are set to NaN. + num_channels : int + Number of acquisition channels. + + Returns + ------- + ndarray of shape (n_frames, num_channels) + Global fluorescence. + """ + channel_sums = [np.sum(data, axis=0)] + if num_channels >= 2: + # Two-channel acquisitions supply data2; do not coerce/copy it. + channel_sums.append(np.sum(cast(np.ndarray, data2), axis=0)) + global_f = np.stack(channel_sums, axis=-1) + global_f[~frames_to_keep, :] = np.nan + return global_f + + +def _compute_f_soma( + data: np.ndarray, + data2: np.ndarray | None, + soma_sps: list[np.ndarray], + frames_to_keep: np.ndarray, + num_channels: int, +) -> np.ndarray: + """Sum fluorescence over each user-ROI's superpixels per channel. + + Parameters + ---------- + data : ndarray of shape (n_superpixels, n_frames) + Channel-1 activity. + data2 : ndarray or None + Channel-2 activity (used when num_channels >= 2). + soma_sps : list of ndarray + Per-ROI superpixel index arrays. + frames_to_keep : ndarray of bool + Dropped frames are set to NaN. + num_channels : int + Number of acquisition channels. + + Returns + ------- + ndarray of shape (n_frames, n_rois, num_channels) + Per-ROI fluorescence. + """ + n_frames = data.shape[1] + 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[~frames_to_keep, :, :] = np.nan + return f_soma + + +def compute_high_res_traces( + data: np.ndarray, + data2: np.ndarray | None, + background_ds: np.ndarray, + frames: np.ndarray, + a_data: dict, + subsample_matrix_inds: np.ndarray, + sparse_h_inds: np.ndarray, + sparse_h_vals: np.ndarray, + a_final: torch.Tensor, + unique_motion_ds: np.ndarray, + mot_inds_to_keep_ds: np.ndarray, + median_z: float, + psf2d: np.ndarray, + num_super_pixels: int, + num_fast_zs: int, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, + num_channels: int, + soma_sps: list[np.ndarray], + z_tol: float = 1.5, + simple_trace_extraction: bool = False, + *, + transient_options: TransientOptions | None = None, + analyze_hz: float | None = None, +) -> TrialTraceResult: + """Compute one trial's high-res source traces from loaded arrays. + + Parameters + ---------- + data : ndarray of shape (n_superpixels, n_frames) + Count-normalized channel-1 activity. + data2 : ndarray or None + Count-normalized channel-2 activity. + background_ds : ndarray of shape (n_superpixels, n_ds) + Per-superpixel low-res background for this trial. + frames : ndarray + The trial's downsample frame line positions. + a_data : dict + Alignment data for this trial. + subsample_matrix_inds : ndarray + Superpixel reference-pixel map (from geometry). + sparse_h_inds, sparse_h_vals : ndarray + Base sparse H. + a_final : torch.Tensor of shape (n_pixels, n_sources) + Fixed source spatial profiles. + unique_motion_ds : ndarray + Low-res kept 2-D motion vectors. + mot_inds_to_keep_ds : ndarray + Indices of the low-res bins to keep. + median_z : float + Median z (from the low-res pass). + psf2d : ndarray + The (cropped) PSF for this DMD. + num_super_pixels, num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row \ +: int + Geometry. + num_channels : int + Number of acquisition channels. + soma_sps : list of ndarray + Per-ROI superpixel index arrays. + z_tol : float, optional + Maximum absolute rounded z offset from the median, in um (default 1.5). + simple_trace_extraction : bool, optional + Average superpixels weighted by normalized source profiles instead + of least-squares fitting dF and backprojecting F0; the residual term + is zero (default False). + transient_options : TransientOptions or None + Add constrained dF and events, retaining QR dF, backprojected F0 and + auxiliary data. + Fits nonnegative sparse events plus an unpenalized initial state. + Public dF retains missing-frame NaNs; nonconvergence raises + RuntimeError. + analyze_hz : float or None + Required nominal rate for transient fitting on the uniform full grid. + Acquisition averaging is approximated, not explicitly modeled. + + Returns + ------- + 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. + + 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) + if frame_grid.ndim != 1 or not np.all(np.isfinite(frame_grid)): + raise ValueError("frames must be a finite chronological vector") + # Reader ceil-rounds line positions, so nominally uniform samples + # 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") + ( + motion_r, + motion_c, + motion_z, + background, + online_y, + online_x, + online_z, + ) = _interp_trial_alignment(frames, a_data, background_ds) + + ( + unique_motion, + mot_inds, + mot_inds_to_keep, + frames_to_keep, + ) = _bin_trial_motion( + motion_r, + motion_c, + motion_z, + median_z, + unique_motion_ds, + mot_inds_to_keep_ds, + z_tol=z_tol, + ) + + ref_d, ref_c, ref_r = ref_pixs_to_drc( + subsample_matrix_inds[:, 0], dmd_pixels_per_column, dmd_pixels_per_row + ) + _, sel_pix_idxs = build_selected_pixel_mask( + unique_motion, + ref_d, + ref_r, + ref_c, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + psf2d, + ) + + phi, f0, denoised, events, f_residual = _solve_trial_phi_f0( + data, + background, + unique_motion, + mot_inds, + mot_inds_to_keep, + sparse_h_inds, + sparse_h_vals, + sel_pix_idxs, + a_final, + num_super_pixels, + dmd_pixels_per_row, + simple_trace_extraction=simple_trace_extraction, + transient_options=transient_options, + analyze_hz=analyze_hz, + return_transient=True, + ) + + 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) + + return TrialTraceResult( + phi.numpy(), + f0.numpy(), + frames, + sel_pix_idxs, + global_f, + (motion_r, motion_c, motion_z), + (online_y, online_x, online_z), + f_soma, + denoised.numpy(), + events.numpy(), + f_residual.numpy(), + ) + + +def _load_high_res_trial_data( + trial_ix: int, + dmd_ix: int, + samp_freq: float, + super_pixel_ids: np.ndarray, + 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. + """ + # The reader returns None only for skipped trials; keep_trial is True. + result = cast( + dict, + read_band_trial_data( + trial_ix, + True, + dmd_ix, + samp_freq, + super_pixel_ids, + datadr, + trial_table, + num_channels, + all_channels=True, + ), + ) + data = result["data"] / result["data_count"] + data2 = None + if num_channels >= 2: + data2 = result["data2"] / result["data_count2"] + return data, data2, result["alignment"], result["ds_frames"] + + +def get_high_res_traces( + trial_info: tuple, + dmd_ix: int, + samp_freq: float, + super_pixel_ids: np.ndarray, + datadr: str, + trial_table: dict, + subsample_matrix_inds: np.ndarray, + sparse_h_inds: np.ndarray, + sparse_h_vals: np.ndarray, + a_final: np.ndarray | torch.Tensor, + unique_motion_ds: np.ndarray, + mot_inds_to_keep_ds: np.ndarray, + median_z: float, + psf2d: np.ndarray, + num_super_pixels: int, + num_fast_zs: int, + dmd_pixels_per_column: int, + dmd_pixels_per_row: int, + num_channels: int, + soma_sps: list[np.ndarray], + z_tol: float = 1.5, + simple_trace_extraction: bool = False, + *, + 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 + :func:`compute_high_res_traces`. + + Parameters + ---------- + trial_info : tuple + (trial_ix, keep_trial, background_ds) for this trial. + dmd_ix : int + 0-based DMD index. + samp_freq : float + Analysis sample rate, in Hz. + super_pixel_ids : ndarray + Superpixel id lookup for this DMD. + datadr : str + Raw-data directory. + trial_table : dict + Normalized trial table. + subsample_matrix_inds, sparse_h_inds, sparse_h_vals : ndarray + Geometry / sparse H. + a_final : ndarray or torch.Tensor + 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 + Median z (from the low-res pass). + psf2d : ndarray + The (cropped) PSF for this DMD. + num_super_pixels, num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row \ +: int + Geometry. + num_channels : int + Number of acquisition channels. + soma_sps : list of ndarray + Per-ROI superpixel index arrays. + z_tol : float, optional + Maximum absolute rounded z offset from the median, in um (default 1.5). + simple_trace_extraction : bool, optional + Average superpixels weighted by normalized source profiles instead + of least-squares fitting dF and backprojecting F0; the residual term + is zero (default False). + transient_options : TransientOptions or None + Add constrained dF/events alongside QR dF, backprojected F0 and + unchanged profiles. + The reader's samp_freq supplies the nominal convolution rate. + + Returns + ------- + tuple + The named result of :func:`compute_high_res_traces` (empty for + skipped trials). + """ + trial_ix, keep_trial, background_ds = trial_info + + if not isinstance(a_final, torch.Tensor): + a_final = torch.tensor(a_final, dtype=torch.float32) + n_sources = a_final.shape[1] + + if not keep_trial: + return _empty_trace_result(n_sources, num_channels, len(soma_sps)) + + data, data2, a_data, frames = _load_high_res_trial_data( + trial_ix, + dmd_ix, + samp_freq, + super_pixel_ids, + datadr, + trial_table, + num_channels, + ) + + return compute_high_res_traces( + data, + data2, + background_ds, + frames, + a_data, + subsample_matrix_inds, + sparse_h_inds, + sparse_h_vals, + a_final, + unique_motion_ds, + mot_inds_to_keep_ds, + median_z, + psf2d, + num_super_pixels, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + num_channels, + soma_sps, + z_tol=z_tol, + simple_trace_extraction=simple_trace_extraction, + transient_options=transient_options, + analyze_hz=samp_freq, + ) diff --git a/src/giant_python/extraction/band/transient.py b/src/giant_python/extraction/band/transient.py index 64383b5f..27ae515a 100644 --- a/src/giant_python/extraction/band/transient.py +++ b/src/giant_python/extraction/band/transient.py @@ -1,394 +1,394 @@ -"""Fixed-profile, output-grid sparse transient fitting. - -Port of the standalone trace benchmark, not a localization/NMF solver. -Fits 0.5 * ||r - X K s||^2 + beta * sum(s[1:]), s >= 0, using -float64 sufficient statistics and bounded L-BFGS-B. The first coefficient -is an unpenalized initial state. Trials must be solved independently. -Reader averaging is not modeled exactly; events are not spike times. -""" - -import warnings -from dataclasses import dataclass - -import numpy as np -import numpy.typing as npt -from scipy.optimize import minimize -from scipy.signal import fftconvolve, lfilter - -from ...models.params import _nonnegative, _positive - - -@dataclass(frozen=True) -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. - """ - - tau_s: float = 0.15 - beta_fraction: float = 0.01 - beta: float | None = None - max_iter: int = 500 - tolerance: float = 1e-7 - debias: bool = False - event_threshold: float = 1e-6 - - 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) - _nonnegative("beta_fraction", self.beta_fraction) - _nonnegative("event_threshold", self.event_threshold) - if self.beta is not None: - _nonnegative("beta", self.beta) - if not isinstance(self.debias, bool): - raise ValueError("debias must be a bool") - - -@dataclass -class TransientResult: - """Trace, latent predictions/events, and convergence diagnostics.""" - - d_f: np.ndarray - metadata: dict - events: np.ndarray - initial_state: np.ndarray - model_trace: np.ndarray - - -class TransientOperator: - """Causal convolution and exact adjoint without a dense temporal matrix.""" - - 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) - if self.kernel is not None and ( - self.kernel.ndim != 1 - or not self.kernel.size - or not np.all(np.isfinite(self.kernel)) - or np.any(self.kernel < 0) - or self.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. - - 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)] - - 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: 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(): - ix = groups[motion] - fit = trace[ix] - gt = fit @ gram - value += np.sum(fit * (0.5 * gt - rhs.T)) - gradient[ix] = gt - rhs.T - return float(value), gradient - - -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() - if residual.ndim != 2: - 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") - if not designs: - raise ValueError("Transient fitting requires projected profiles") - arrays = {m: np.asarray(x) for m, x in designs.items()} - first = next(iter(arrays.values())) - if first.ndim != 2: - raise ValueError("designs must have shape (superpixels, sources)") - 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") - 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") - groups, normal = {}, {} - for motion, x in arrays.items(): - ix = np.flatnonzero(valid & (motion_indices == motion)) - if ix.size: - xd = x.astype(np.float64) - groups[motion] = ix - normal[motion] = ( - xd.T @ xd, - xd.T @ residual[:, ix].astype(np.float64), - ) - return (n_frames, n_sources), valid, groups, normal - - -def fit_transient_traces( - residual: npt.ArrayLike, - designs: dict[int, np.ndarray], - motion_indices: npt.ArrayLike, - valid: npt.ArrayLike, - analyze_hz: float, - *, - 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. - 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. - - 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): - raise TypeError("options must be TransientOptions or None") - op = TransientOperator(analyze_hz, options.tau_s, kernel) - shape, valid, groups, normal = _prepare_transient_system( - residual, designs, motion_indices, valid - ) - rhs_trace = np.zeros(shape) - for motion, (_, rhs) in normal.items(): - rhs_trace[groups[motion]] = rhs.T - 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 - ) - diagonals = np.concatenate([np.diag(g) for g, _ in normal.values()]) - positive = diagonals[diagonals > 0] - if not positive.size: - raise ValueError("No observable profile support") - gram_scale = float(np.max(positive)) - amplitude_scale = max(float(np.max(np.abs(rhs_trace))) / gram_scale, 1e-12) - objective_scale = gram_scale * amplitude_scale**2 - - 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) - gradient = op.adjoint(trace_gradient).copy() - value += event_penalty * coefficients[1:].sum() - gradient[1:] += event_penalty - return ( - value / objective_scale, - (gradient * amplitude_scale / objective_scale).ravel(), - ) - - optimizer_options = { - "maxiter": options.max_iter, - "ftol": options.tolerance, - "gtol": options.tolerance, - "maxls": 40, - "maxcor": 10, - } - result = minimize( - objective, - np.zeros(np.prod(shape)), - method="L-BFGS-B", - jac=True, - bounds=[(0.0, None)] * int(np.prod(shape)), - options=optimizer_options, - ) - selection = { - "converged": bool(result.success), - "iterations": int(result.nit), - "message": str(result.message), - "objective_without_data_constant": float(result.fun * objective_scale), - } - debias_info = { - "requested": options.debias, - "performed": False, - "event_threshold": float(options.event_threshold), - } - if options.debias and result.success: - 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: 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) - return value, gradient[free] - - refit = minimize( - restricted_objective, - result.x[free], - method="L-BFGS-B", - jac=True, - bounds=[(0.0, None)] * len(free), - options=optimizer_options, - ) - full = np.zeros(np.prod(shape)) - full[free] = refit.x - refit.x = full - result = refit - debias_info.update( - performed=True, - converged=bool(refit.success), - iterations=int(refit.nit), - message=str(refit.message), - ) - elif options.debias: - debias_info["skip_reason"] = "Support-selection fit did not converge" - coefficients = result.x.reshape(shape) * amplitude_scale - model_trace = op.forward(coefficients) - phi = model_trace.copy() - phi[~valid] = np.nan - events = coefficients.copy() - initial = events[0].copy() - events[0] = 0 - converged = bool( - result.success and np.isfinite(result.fun) and np.all(np.isfinite(model_trace)) - ) - if not converged: - warnings.warn( - f"Transient solver did not converge: {result.message}", - RuntimeWarning, - stacklevel=2, - ) - return TransientResult( - phi, - { - "method": "transient", - "tau_s": options.tau_s, - "beta": penalty, - "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"), - "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), - }, - events, - initial, - model_trace, - ) +"""Fixed-profile, output-grid sparse transient fitting. + +Port of the standalone trace benchmark, not a localization/NMF solver. +Fits 0.5 * ||r - X K s||^2 + beta * sum(s[1:]), s >= 0, using +float64 sufficient statistics and bounded L-BFGS-B. The first coefficient +is an unpenalized initial state. Trials must be solved independently. +Reader averaging is not modeled exactly; events are not spike times. +""" + +import warnings +from dataclasses import dataclass + +import numpy as np +import numpy.typing as npt +from scipy.optimize import minimize +from scipy.signal import fftconvolve, lfilter + +from ...models.params import _nonnegative, _positive + + +@dataclass(frozen=True) +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. + """ + + tau_s: float = 0.15 + beta_fraction: float = 0.01 + beta: float | None = None + max_iter: int = 500 + tolerance: float = 1e-7 + debias: bool = False + event_threshold: float = 1e-6 + + 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) + _nonnegative("beta_fraction", self.beta_fraction) + _nonnegative("event_threshold", self.event_threshold) + if self.beta is not None: + _nonnegative("beta", self.beta) + if not isinstance(self.debias, bool): + raise ValueError("debias must be a bool") + + +@dataclass +class TransientResult: + """Trace, latent predictions/events, and convergence diagnostics.""" + + d_f: np.ndarray + metadata: dict + events: np.ndarray + initial_state: np.ndarray + model_trace: np.ndarray + + +class TransientOperator: + """Causal convolution and exact adjoint without a dense temporal matrix.""" + + 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) + if self.kernel is not None and ( + self.kernel.ndim != 1 + or not self.kernel.size + or not np.all(np.isfinite(self.kernel)) + or np.any(self.kernel < 0) + or self.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. + + 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)] + + 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: 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(): + ix = groups[motion] + fit = trace[ix] + gt = fit @ gram + value += np.sum(fit * (0.5 * gt - rhs.T)) + gradient[ix] = gt - rhs.T + return float(value), gradient + + +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() + if residual.ndim != 2: + 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") + if not designs: + raise ValueError("Transient fitting requires projected profiles") + arrays = {m: np.asarray(x) for m, x in designs.items()} + first = next(iter(arrays.values())) + if first.ndim != 2: + raise ValueError("designs must have shape (superpixels, sources)") + 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") + 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") + groups, normal = {}, {} + for motion, x in arrays.items(): + ix = np.flatnonzero(valid & (motion_indices == motion)) + if ix.size: + xd = x.astype(np.float64) + groups[motion] = ix + normal[motion] = ( + xd.T @ xd, + xd.T @ residual[:, ix].astype(np.float64), + ) + return (n_frames, n_sources), valid, groups, normal + + +def fit_transient_traces( + residual: npt.ArrayLike, + designs: dict[int, np.ndarray], + motion_indices: npt.ArrayLike, + valid: npt.ArrayLike, + analyze_hz: float, + *, + 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. + 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. + + 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): + raise TypeError("options must be TransientOptions or None") + op = TransientOperator(analyze_hz, options.tau_s, kernel) + shape, valid, groups, normal = _prepare_transient_system( + residual, designs, motion_indices, valid + ) + rhs_trace = np.zeros(shape) + for motion, (_, rhs) in normal.items(): + rhs_trace[groups[motion]] = rhs.T + 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 + ) + diagonals = np.concatenate([np.diag(g) for g, _ in normal.values()]) + positive = diagonals[diagonals > 0] + if not positive.size: + raise ValueError("No observable profile support") + gram_scale = float(np.max(positive)) + amplitude_scale = max(float(np.max(np.abs(rhs_trace))) / gram_scale, 1e-12) + objective_scale = gram_scale * amplitude_scale**2 + + 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) + gradient = op.adjoint(trace_gradient).copy() + value += event_penalty * coefficients[1:].sum() + gradient[1:] += event_penalty + return ( + value / objective_scale, + (gradient * amplitude_scale / objective_scale).ravel(), + ) + + optimizer_options = { + "maxiter": options.max_iter, + "ftol": options.tolerance, + "gtol": options.tolerance, + "maxls": 40, + "maxcor": 10, + } + result = minimize( + objective, + np.zeros(np.prod(shape)), + method="L-BFGS-B", + jac=True, + bounds=[(0.0, None)] * int(np.prod(shape)), + options=optimizer_options, + ) + selection = { + "converged": bool(result.success), + "iterations": int(result.nit), + "message": str(result.message), + "objective_without_data_constant": float(result.fun * objective_scale), + } + debias_info = { + "requested": options.debias, + "performed": False, + "event_threshold": float(options.event_threshold), + } + if options.debias and result.success: + 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: 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) + return value, gradient[free] + + refit = minimize( + restricted_objective, + result.x[free], + method="L-BFGS-B", + jac=True, + bounds=[(0.0, None)] * len(free), + options=optimizer_options, + ) + full = np.zeros(np.prod(shape)) + full[free] = refit.x + refit.x = full + result = refit + debias_info.update( + performed=True, + converged=bool(refit.success), + iterations=int(refit.nit), + message=str(refit.message), + ) + elif options.debias: + debias_info["skip_reason"] = "Support-selection fit did not converge" + coefficients = result.x.reshape(shape) * amplitude_scale + model_trace = op.forward(coefficients) + phi = model_trace.copy() + phi[~valid] = np.nan + events = coefficients.copy() + initial = events[0].copy() + events[0] = 0 + converged = bool( + result.success and np.isfinite(result.fun) and np.all(np.isfinite(model_trace)) + ) + if not converged: + warnings.warn( + f"Transient solver did not converge: {result.message}", + RuntimeWarning, + stacklevel=2, + ) + return TransientResult( + phi, + { + "method": "transient", + "tau_s": options.tau_s, + "beta": penalty, + "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"), + "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), + }, + events, + initial, + model_trace, + ) diff --git a/src/giant_python/extraction/band/trial_data.py b/src/giant_python/extraction/band/trial_data.py index a065c7b2..7b589cea 100644 --- a/src/giant_python/extraction/band/trial_data.py +++ b/src/giant_python/extraction/band/trial_data.py @@ -1,343 +1,343 @@ -"""Read low-resolution superpixel activity for band-scan trials. - -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 -unchanged. Shared interpolation and morphology utilities live in -:mod:`giant_python.numerics`. -""" - -from __future__ import annotations - -import os - -import numpy as np - -from ...io.slap2 import Slap2Reader, open_slap2_file -from .inputs import load_alignment_data_h5 - -__all__ = [ - "accumulate_superpixel_data", - "assemble_lowres_data", - "compute_ds_frames", - "load_lowres_data", - "read_band_trial_data", - "save_lowres_data", -] - - -def compute_ds_frames(first_line: float, last_line: float, dt: float) -> np.ndarray: - """Return the downsampled-frame line grid for one trial. - - Parameters - ---------- - first_line, last_line : float - First/last acquisition line (1-based, inclusive). - dt : float - Downsample step, in lines (1 / samp_freq / line_period_s). - - Returns - ------- - ndarray - 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 -) -> 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 = [ - np.arange( - max(1, np.floor(f - dt_read)), - min(np.ceil(f + dt_read), max_line) + 1, - ) - 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] - return time_windows, line_indices, cycle_indices - - -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))} - return all_lines, all_cycles, mapping - - -def _accumulate_line( - acc: dict, - line_data: np.ndarray, - positions: np.ndarray, - z_idx: np.ndarray, - super_pixel_ids: np.ndarray, - weight: float, - ds_ix: int, -) -> None: - """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] - 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: - acc["data2"][matching_indices, ds_ix] += line_data[matched, 1] * weight - acc["data_count2"][matching_indices, ds_ix] += weight - - -def accumulate_superpixel_data( - data_file: Slap2Reader, - ds_frames: np.ndarray, - dt: float, - super_pixel_ids: np.ndarray, - num_channels: int, - all_channels: bool, -) -> dict: - """Accumulate weighted per-superpixel activity over the DS-frame grid. - - 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. - - Parameters - ---------- - data_file : object - 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). - num_channels : int - Number of acquisition channels. - all_channels : bool - 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. - """ - lines_per_cycle = data_file.header["linesPerCycle"] - n_ds = len(ds_frames) - num_sp = super_pixel_ids.shape[0] - sp_flat = np.asarray(super_pixel_ids).reshape(-1) - read_second = all_channels and num_channels >= 2 - - 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) - - 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), - } - - for ds_ix in range(n_ds): - weights = np.exp(-np.abs(ds_frames[ds_ix] - time_windows[ds_ix]) / dt) - frame_lines = line_indices[ds_ix] - frame_cycles = cycle_indices[ds_ix] - for i, li in enumerate(frame_lines): - line_idx = int(li) - if data_file.lineDataNumElements[line_idx - 1] == 0: - continue - cache_idx = mapping[(line_idx, int(frame_cycles[i]))] - _accumulate_line( - acc, - all_line_data[cache_idx], - data_file.lineSuperPixelIDs[line_idx - 1], - data_file.lineFastZIdxs[line_idx - 1], - sp_flat, - weights[i], - ds_ix, - ) - return acc - - -def read_band_trial_data( - trial_ix: int, - keep_trial: bool, - dmd_ix: int, - samp_freq: float, - super_pixel_ids: np.ndarray, - datadr: str, - trial_table: dict, - num_channels: int, - all_channels: bool = True, -) -> 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 - scaling. - - Parameters - ---------- - trial_ix : int - Trial index into trial_table columns. - keep_trial : bool - When False, the trial is skipped and None is returned. - dmd_ix : int - 0-based DMD index into trial_table rows. - samp_freq : float - Analysis/alignment sample rate, in Hz. - super_pixel_ids : ndarray - Superpixel id lookup for this DMD. - datadr : str - Raw-data directory holding the SLAP2 files. - trial_table : dict - Normalized trial table (filename, first_line, last_line, - fn_adata). - num_channels : int - Number of acquisition channels. - all_channels : bool - Read all channels (default) vs channel 1 only. - - Returns - ------- - dict or None - {"data", "data_count", "alignment", "ds_frames", "data2", - "data_count2"} for kept trials, else None. - """ - if not keep_trial: - return None - - source_fn = trial_table["filename"][dmd_ix, trial_ix] - first_line = trial_table["first_line"][dmd_ix, trial_ix] - last_line = trial_table["last_line"][dmd_ix, trial_ix] - - data_file = open_slap2_file(os.path.join(datadr, source_fn)) - dt = 1.0 / samp_freq / data_file.metaData.linePeriod_s - ds_frames = compute_ds_frames(first_line, last_line, dt) - - 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]) - - data2 = acc["data2"] - return { - "data": acc["data"] / 100.0, - "data_count": acc["data_count"], - "alignment": alignment, - "ds_frames": ds_frames, - "data2": None if data2 is None else data2 / 100.0, - "data_count2": acc["data_count2"], - } - - -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. - - Parameters - ---------- - results : list - 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). - """ - 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), - "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) - return arrays - - -def save_lowres_data(path: str, arrays: dict) -> None: - """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. - - Parameters - ---------- - path : str - Path to the lowres_data_DMD{N}.npz cache. - num_channels : int - Number of acquisition channels (>= 2 also loads the second channel). - - Returns - ------- - dict - The cached low-res arrays. - """ - keys = [ - "lowResData", - "lowResDataCt", - "lowResMotionR", - "lowResMotionC", - "lowResMotionZ", - "lowResTrialID", - ] - if num_channels >= 2: - keys += ["lowResData2", "lowResDataCt2"] - with np.load(path) as data_arrays: - return {k: data_arrays[k] for k in keys} +"""Read low-resolution superpixel activity for band-scan trials. + +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 +unchanged. Shared interpolation and morphology utilities live in +:mod:`giant_python.numerics`. +""" + +from __future__ import annotations + +import os + +import numpy as np + +from ...io.slap2 import Slap2Reader, open_slap2_file +from .inputs import load_alignment_data_h5 + +__all__ = [ + "accumulate_superpixel_data", + "assemble_lowres_data", + "compute_ds_frames", + "load_lowres_data", + "read_band_trial_data", + "save_lowres_data", +] + + +def compute_ds_frames(first_line: float, last_line: float, dt: float) -> np.ndarray: + """Return the downsampled-frame line grid for one trial. + + Parameters + ---------- + first_line, last_line : float + First/last acquisition line (1-based, inclusive). + dt : float + Downsample step, in lines (1 / samp_freq / line_period_s). + + Returns + ------- + ndarray + 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 +) -> 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 = [ + np.arange( + max(1, np.floor(f - dt_read)), + min(np.ceil(f + dt_read), max_line) + 1, + ) + 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] + return time_windows, line_indices, cycle_indices + + +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))} + return all_lines, all_cycles, mapping + + +def _accumulate_line( + acc: dict, + line_data: np.ndarray, + positions: np.ndarray, + z_idx: np.ndarray, + super_pixel_ids: np.ndarray, + weight: float, + ds_ix: int, +) -> None: + """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] + 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: + acc["data2"][matching_indices, ds_ix] += line_data[matched, 1] * weight + acc["data_count2"][matching_indices, ds_ix] += weight + + +def accumulate_superpixel_data( + data_file: Slap2Reader, + ds_frames: np.ndarray, + dt: float, + super_pixel_ids: np.ndarray, + num_channels: int, + all_channels: bool, +) -> dict: + """Accumulate weighted per-superpixel activity over the DS-frame grid. + + 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. + + Parameters + ---------- + data_file : object + 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). + num_channels : int + Number of acquisition channels. + all_channels : bool + 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. + """ + lines_per_cycle = data_file.header["linesPerCycle"] + n_ds = len(ds_frames) + num_sp = super_pixel_ids.shape[0] + sp_flat = np.asarray(super_pixel_ids).reshape(-1) + read_second = all_channels and num_channels >= 2 + + 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) + + 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), + } + + for ds_ix in range(n_ds): + weights = np.exp(-np.abs(ds_frames[ds_ix] - time_windows[ds_ix]) / dt) + frame_lines = line_indices[ds_ix] + frame_cycles = cycle_indices[ds_ix] + for i, li in enumerate(frame_lines): + line_idx = int(li) + if data_file.lineDataNumElements[line_idx - 1] == 0: + continue + cache_idx = mapping[(line_idx, int(frame_cycles[i]))] + _accumulate_line( + acc, + all_line_data[cache_idx], + data_file.lineSuperPixelIDs[line_idx - 1], + data_file.lineFastZIdxs[line_idx - 1], + sp_flat, + weights[i], + ds_ix, + ) + return acc + + +def read_band_trial_data( + trial_ix: int, + keep_trial: bool, + dmd_ix: int, + samp_freq: float, + super_pixel_ids: np.ndarray, + datadr: str, + trial_table: dict, + num_channels: int, + all_channels: bool = True, +) -> 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 + scaling. + + Parameters + ---------- + trial_ix : int + Trial index into trial_table columns. + keep_trial : bool + When False, the trial is skipped and None is returned. + dmd_ix : int + 0-based DMD index into trial_table rows. + samp_freq : float + Analysis/alignment sample rate, in Hz. + super_pixel_ids : ndarray + Superpixel id lookup for this DMD. + datadr : str + Raw-data directory holding the SLAP2 files. + trial_table : dict + Normalized trial table (filename, first_line, last_line, + fn_adata). + num_channels : int + Number of acquisition channels. + all_channels : bool + Read all channels (default) vs channel 1 only. + + Returns + ------- + dict or None + {"data", "data_count", "alignment", "ds_frames", "data2", + "data_count2"} for kept trials, else None. + """ + if not keep_trial: + return None + + source_fn = trial_table["filename"][dmd_ix, trial_ix] + first_line = trial_table["first_line"][dmd_ix, trial_ix] + last_line = trial_table["last_line"][dmd_ix, trial_ix] + + data_file = open_slap2_file(os.path.join(datadr, source_fn)) + dt = 1.0 / samp_freq / data_file.metaData.linePeriod_s + ds_frames = compute_ds_frames(first_line, last_line, dt) + + 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]) + + data2 = acc["data2"] + return { + "data": acc["data"] / 100.0, + "data_count": acc["data_count"], + "alignment": alignment, + "ds_frames": ds_frames, + "data2": None if data2 is None else data2 / 100.0, + "data_count2": acc["data_count2"], + } + + +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. + + Parameters + ---------- + results : list + 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). + """ + 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), + "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) + return arrays + + +def save_lowres_data(path: str, arrays: dict) -> None: + """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. + + Parameters + ---------- + path : str + Path to the lowres_data_DMD{N}.npz cache. + num_channels : int + Number of acquisition channels (>= 2 also loads the second channel). + + Returns + ------- + dict + The cached low-res arrays. + """ + keys = [ + "lowResData", + "lowResDataCt", + "lowResMotionR", + "lowResMotionC", + "lowResMotionZ", + "lowResTrialID", + ] + if num_channels >= 2: + keys += ["lowResData2", "lowResDataCt2"] + with np.load(path) as data_arrays: + return {k: data_arrays[k] for k in keys} diff --git a/src/giant_python/extraction/band/types.py b/src/giant_python/extraction/band/types.py index aabb03ac..35137488 100644 --- a/src/giant_python/extraction/band/types.py +++ b/src/giant_python/extraction/band/types.py @@ -1,42 +1,42 @@ -"""Small runtime records used by band extraction, without copying arrays.""" - -from dataclasses import dataclass -from typing import NamedTuple - -import numpy as np - - -class TrialTraceResult(NamedTuple): - """One trial's named traces in a compact, immutable record. - - Source arrays are (frames, sources); global fluorescence is - (frames, channels) and ROI fluorescence is (frames, ROIs, channels). - 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 - eight-argument construction, but the record now has eleven fields. - """ - - d_f: np.ndarray - f0_ls: np.ndarray - frame_line_idxs: np.ndarray - selected_pixels: np.ndarray - global_f: np.ndarray - reference_offsets: tuple[np.ndarray, np.ndarray, np.ndarray] - online_shifts: tuple[np.ndarray, np.ndarray, np.ndarray] - user_roi_f: np.ndarray - d_f_denoised: np.ndarray | None = None - events: np.ndarray | None = None - f_residual: np.ndarray | None = None - - -@dataclass(frozen=True) -class ResolvedAcquisition: - """Acquisition metadata resolved once without mutating science options.""" - - num_channels: int - align_hz: dict[str, float] +"""Small runtime records used by band extraction, without copying arrays.""" + +from dataclasses import dataclass +from typing import NamedTuple + +import numpy as np + + +class TrialTraceResult(NamedTuple): + """One trial's named traces in a compact, immutable record. + + Source arrays are (frames, sources); global fluorescence is + (frames, channels) and ROI fluorescence is (frames, ROIs, channels). + 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 + eight-argument construction, but the record now has eleven fields. + """ + + d_f: np.ndarray + f0_ls: np.ndarray + frame_line_idxs: np.ndarray + selected_pixels: np.ndarray + global_f: np.ndarray + reference_offsets: tuple[np.ndarray, np.ndarray, np.ndarray] + online_shifts: tuple[np.ndarray, np.ndarray, np.ndarray] + user_roi_f: np.ndarray + d_f_denoised: np.ndarray | None = None + events: np.ndarray | None = None + f_residual: np.ndarray | None = None + + +@dataclass(frozen=True) +class ResolvedAcquisition: + """Acquisition metadata resolved once without mutating science options.""" + + num_channels: int + align_hz: dict[str, float] diff --git a/src/giant_python/extraction/band/workflow.py b/src/giant_python/extraction/band/workflow.py index a5a102e1..6ca6317f 100644 --- a/src/giant_python/extraction/band/workflow.py +++ b/src/giant_python/extraction/band/workflow.py @@ -1,640 +1,640 @@ -"""Canonical band extraction driver, from prepared inputs to eager results. - -Numerical ordering follows the original BandSILo driver. Acquisition metadata, -execution policy and annotations are separate from scientific configuration; -result assembly and persistence belong to their canonical owners. -""" - -from __future__ import annotations - -from pathlib import Path - -import numpy as np -from torch import Tensor - -from ...io.experiment_summary import write_summary -from ...io.hdf5 import to_serializable -from ...models.experiment_summary import ExperimentSummary, PathSummary -from ...models.params import ( - AnnotationInput, - AnnotationOptions, - BandParamsInput, - BandSiloParams, - ExecutionInput, - ExecutionOptions, - resolve_band_options, -) -from ...models.trial_table import TrialTable -from ...numerics.peaks import get_act_im_peaks -from ...parallel import map_trials -from ...progress import log, progress -from . import activity, inputs, motion_binning, operators -from . import background as bg -from . import geometry as geo -from . import summary_images as si -from . import trial_data as td -from .annotation import ( - build_user_roi_geometry, - resolve_interactivity, - resolve_user_rois, -) -from .inputs import compute_keep_trials, load_trial_table, read_align_info -from .localization import fit_sources -from .result_assembly import ( - PathResult, - _dmd_user_rois, - assemble_path_summary, -) -from .traces import get_high_res_traces -from .types import ResolvedAcquisition, TrialTraceResult - - -def _resolve_session_user_rois( - result_dr: str, - trial_table: dict, - lookup: dict, - annotations: AnnotationOptions, -) -> 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) - return resolve_user_rois( - Path(result_dr) / "annotations", - trial_table["n_dmds"], - user_roi_geo, - interactive=resolve_interactivity(annotations.interactive), - ref_files=ref_files, - ) - - -def extract_band_sources( - input: str | Path | TrialTable, - params: BandParamsInput = None, - *, - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> ExperimentSummary: - """Extract all paths from an exact filename or an already loaded table. - - Loaded models are prepared directly, without inferring or reopening a - 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) - trial_table = load_trial_table(input) - result_dr = str(trial_table["savedr"]) - src_extr_dr = Path(result_dr) / "source_extraction" - src_extr_dr.mkdir(parents=True, exist_ok=True) - output_path = src_extr_dr / "experiment_summary.h5" - - lookup = inputs.load_lookup_table( - Path(result_dr) / "motion_correction" / "bandRegLookupTable.h5", - trial_table["n_dmds"], - ) - psf = inputs.load_psf(params.psf_dilation, trial_table["n_dmds"]) - trial_table["keep_trials"] = compute_keep_trials( - trial_table["fn_adata"], trial_table["filename"], trial_table["datadr"] - ) - align_hz, num_channels = read_align_info( - trial_table["fn_adata"], - trial_table["keep_trials"], - trial_table["n_dmds"], - ) - if num_channels is None: - raise ValueError( - "num_channels could not be determined from the alignment data " - "(no kept trials?); provide acquisition metadata for a kept trial." - ) - acquisition = ResolvedAcquisition(num_channels, align_hz) - user_rois = _resolve_session_user_rois(result_dr, trial_table, lookup, roi) - - n_dmds = trial_table["n_dmds"] - log(f"Extracting sources for {n_dmds} DMD path(s)", run.verbose) - paths: list[PathSummary] = [] - for dmd_ix in range(n_dmds): - paths.append( - assemble_path_summary( - _process_dmd( - dmd_ix, - trial_table, - params, - lookup, - psf, - user_rois, - acquisition=acquisition, - execution=run, - annotations=roi, - ), - path_index=dmd_ix, - ) - ) - - 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) - return summary - - -def _params_dict( - params: BandSiloParams, - acquisition: ResolvedAcquisition, - annotations: AnnotationOptions, -) -> dict: - """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, - "denoiseWindow_s": params.denoise_window_s, - "baselineWindow_s": params.baseline_window_s, - "backgroundInterpolation": "cubic", - "decayTau_s": params.decay_tau_s, - "dXY": params.d_xy, - "sparse_fac": params.sparse_fac, - "vif": params.vif, - "peakth": params.peakth, - "peak_buffer": params.peak_buffer, - "trace_beta_fraction": params.trace_beta_fraction, - "trace_max_iter": params.trace_max_iter, - "trace_tolerance": params.trace_tolerance, - "trace_debias": params.trace_debias, - "trace_event_threshold": params.trace_event_threshold, - "random_seed": params.random_seed, - "draw_user_rois": annotations.enabled, - } - - -def _process_dmd( - dmd_ix: int, - trial_table: dict, - params: BandSiloParams, - lookup: dict, - psf: dict, - user_rois: dict | None = None, - *, - acquisition: ResolvedAcquisition, - execution: ExecutionOptions, - annotations: AnnotationOptions, -) -> PathResult: - """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) - datadr = str(trial_table["datadr"]) - n_trials = trial_table["filename"].shape[1] - if execution.max_trials is not None: - n_trials = min(n_trials, execution.max_trials) - log(f"Debug: limiting to first {n_trials} trial(s)", execution.verbose) - num_channels = acquisition.num_channels - 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) - 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) - fastz_to_refz = lookup["fastZ2RefZ"][key] - num_fast_zs = fastz_to_refz.shape[0] - all_sp_ids = lookup["allSuperPixelIDs"][key] - 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]) - 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) - - 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]), - dmd_ix, - align_hz, - all_sp_ids, - datadr, - trial_table, - num_channels, - ) - - low = td.assemble_lowres_data( - map_trials( - _read, - range(n_trials), - execution.max_workers, - desc=f"{key} reading trials" if execution.verbose else None, - ), - num_channels, - ) - 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 - unique_motion, mot_inds = motion_binning.bin_motion( - low["lowResMotionR"], low["lowResMotionC"], low["lowResMotionZ"] - ) - median_z = np.median(low["lowResMotionZ"]) - _, frames_to_keep = motion_binning.select_motion_bins( - unique_motion, mot_inds, low["lowResMotionZ"], z_tol=params.z_tol - ) - mean_im = si.compute_mean_image( - low_res_data_norm, - unique_motion, - mot_inds, - frames_to_keep, - ref_d, - ref_r, - ref_c, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - num_channels, - low2, - ) - umyx, mot_inds_yx = motion_binning.bin_motion_yx( - low["lowResMotionR"], low["lowResMotionC"], frames_to_keep - ) - _, sel_pix_idxs = geo.build_selected_pixel_mask( - umyx, - ref_d, - ref_r, - ref_c, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - psf2d, - ) - pixel_coords = geo.pixel_coords_from_idxs( - sel_pix_idxs, dmd_pixels_per_column, dmd_pixels_per_row - ) - background = _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, - execution=execution, - ) - 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, - 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, - execution=execution, - exclusion_mask=( - np.logical_or.reduce(soma_masks) - if soma_masks is not None and len(soma_masks) > 0 - else None - ), - ) - - # Trace-only options: never passed to localization or its QR solver. - from .transient import TransientOptions - - transient_options = TransientOptions( - tau_s=params.decay_tau_s, - beta_fraction=params.trace_beta_fraction, - max_iter=params.trace_max_iter, - tolerance=params.trace_tolerance, - debias=params.trace_debias, - event_threshold=params.trace_event_threshold, - ) - - 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, - bool(keep_trials[dmd_ix, trial_ix]), - background[:, low["lowResTrialID"] == trial_ix], - ), - dmd_ix, - params.analyze_hz, - all_sp_ids, - datadr, - trial_table, - smi, - sparse_h_inds, - sparse_h_vals, - a, - umyx, - np.arange(umyx.shape[0]), - median_z, - psf2d, - num_super_pixels, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - num_channels, - soma_sps, - z_tol=params.z_tol, - transient_options=transient_options, - ) - - trace_results = map_trials( - _traces, - range(n_trials), - execution.max_workers, - desc=f"{key} extracting traces" if execution.verbose else None, - ) - trace_results = [r for r in trace_results if r.d_f.shape[0] > 0] - return PathResult( - a=a, - source_params=source_params, - source_snr=source_snr, - act_im=act_im, - mean_im=mean_im, - act_im_peaks=act_im_peaks, - trace_results=trace_results, - z_depths=fastz_to_refz, - num_fast_zs=num_fast_zs, - 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)), - draw_user_rois=annotations.enabled, - soma_masks=soma_masks, - soma_labels=soma_labels, - yx_shape=yx_shape, - ) - - -def _estimate_background( - 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: 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( - (sel_pix_idxs.shape[0], low_res_data_norm.shape[1]), - np.nan, - dtype=np.float32, - ) - for z in progress( - range(num_fast_zs), - desc="Interpolating planes", - verbose=execution.verbose, - ): - z_idxs, sel_2d = geo.selected_pixels_2d_for_plane( - sel_pix_idxs, z, dmd_pixels_per_column, dmd_pixels_per_row - ) - if z_idxs.size == 0: - continue - ref_z = np.flatnonzero(ref_d == z) - interp_data[z_idxs], _, _ = bg.build_interp_data( - low_res_data_norm[ref_z], - ref_r[ref_z], - ref_c[ref_z], - sel_2d, - umyx, - 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) - return bg.assemble_background( - interp_background, - umyx, - mot_inds_yx, - sel_pix_idxs, - ref_d, - ref_r, - ref_c, - low_res_data_norm.shape[0], - low_res_data_norm.shape[1], - dmd_pixels_per_column, - dmd_pixels_per_row, - ) - - -def _localize( - 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: 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( - sparse_h_inds, - sparse_h_vals, - umyx, - sel_pix_idxs, - num_super_pixels, - dmd_pixels_per_row, - ) - # compute_rho normalizes center/surround columns separately. The PSF still - # 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) - d_mats, d_mats_exp = [], [] - for z in progress( - range(num_fast_zs), - desc="Computing D matrices", - verbose=execution.verbose, - ): - _, 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_exp.append( - operators.build_convolution_matrix(sel_2d, surround_kernel, surround_kernel_ctr) - ) - rho = activity.compute_rho( - residual, - mot_inds_yx, - umyx, - h_mots, - d_mats, - d_mats_exp, - sel_pix_idxs, - ref_d, - ref_r, - ref_c, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - psf2d, - verbose=execution.verbose, - ) - nan_ct = activity.mask_high_nan_rho(rho) - temporal_kernel = activity.decay_kernel_1d(params.decay_tau_s, align_hz) - rho = activity.smooth_rho( - rho, - temporal_kernel, - verbose=execution.verbose, - ) - act_im = si.accumulate_activity_image( - rho, - sel_pix_idxs, - num_fast_zs, - dmd_pixels_per_column, - dmd_pixels_per_row, - verbose=execution.verbose, - ) - # Only final median geometry follows the dominant retained motion bin. - # Dropped frames (-1) do not vote; rho/NMF retain original scan centers. - motion_counts = np.bincount(mot_inds_yx[mot_inds_yx >= 0]) - dominant_motion = umyx[np.argmax(motion_counts)] - act_im = si.finalize_activity_image( - act_im, - sel_pix_idxs, - nan_ct, - ref_r=ref_r + int(dominant_motion[0]), - ref_c=ref_c + int(dominant_motion[1]), - ref_d=ref_d, - ) - source_seeds = get_act_im_peaks( - act_im, - peak_th=params.peakth, - buffer_size=params.peak_buffer, - exclusion_mask=exclusion_mask, - ) - act_im_peaks = source_seeds.copy() - print(f"Number of detected sources: {act_im_peaks.shape[0]}") - result = fit_sources( - source_seeds, - residual, - h_mots, - umyx, - mot_inds_yx, - sel_pix_idxs, - pixel_coords, - n_pixels, - params.d_xy, - params.sparse_fac, - verbose=execution.verbose, - temporal_kernel=temporal_kernel, - seed=params.random_seed, - ) - return ( - act_im, - act_im_peaks, - result["A"], - result["source_params"], - result["source_snr"], - ) +"""Canonical band extraction driver, from prepared inputs to eager results. + +Numerical ordering follows the original BandSILo driver. Acquisition metadata, +execution policy and annotations are separate from scientific configuration; +result assembly and persistence belong to their canonical owners. +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +from torch import Tensor + +from ...io.experiment_summary import write_summary +from ...io.hdf5 import to_serializable +from ...models.experiment_summary import ExperimentSummary, PathSummary +from ...models.params import ( + AnnotationInput, + AnnotationOptions, + BandParamsInput, + BandSiloParams, + ExecutionInput, + ExecutionOptions, + resolve_band_options, +) +from ...models.trial_table import TrialTable +from ...numerics.peaks import get_act_im_peaks +from ...parallel import map_trials +from ...progress import log, progress +from . import activity, inputs, motion_binning, operators +from . import background as bg +from . import geometry as geo +from . import summary_images as si +from . import trial_data as td +from .annotation import ( + build_user_roi_geometry, + resolve_interactivity, + resolve_user_rois, +) +from .inputs import compute_keep_trials, load_trial_table, read_align_info +from .localization import fit_sources +from .result_assembly import ( + PathResult, + _dmd_user_rois, + assemble_path_summary, +) +from .traces import get_high_res_traces +from .types import ResolvedAcquisition, TrialTraceResult + + +def _resolve_session_user_rois( + result_dr: str, + trial_table: dict, + lookup: dict, + annotations: AnnotationOptions, +) -> 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) + return resolve_user_rois( + Path(result_dr) / "annotations", + trial_table["n_dmds"], + user_roi_geo, + interactive=resolve_interactivity(annotations.interactive), + ref_files=ref_files, + ) + + +def extract_band_sources( + input: str | Path | TrialTable, + params: BandParamsInput = None, + *, + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> ExperimentSummary: + """Extract all paths from an exact filename or an already loaded table. + + Loaded models are prepared directly, without inferring or reopening a + 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) + trial_table = load_trial_table(input) + result_dr = str(trial_table["savedr"]) + src_extr_dr = Path(result_dr) / "source_extraction" + src_extr_dr.mkdir(parents=True, exist_ok=True) + output_path = src_extr_dr / "experiment_summary.h5" + + lookup = inputs.load_lookup_table( + Path(result_dr) / "motion_correction" / "bandRegLookupTable.h5", + trial_table["n_dmds"], + ) + psf = inputs.load_psf(params.psf_dilation, trial_table["n_dmds"]) + trial_table["keep_trials"] = compute_keep_trials( + trial_table["fn_adata"], trial_table["filename"], trial_table["datadr"] + ) + align_hz, num_channels = read_align_info( + trial_table["fn_adata"], + trial_table["keep_trials"], + trial_table["n_dmds"], + ) + if num_channels is None: + raise ValueError( + "num_channels could not be determined from the alignment data " + "(no kept trials?); provide acquisition metadata for a kept trial." + ) + acquisition = ResolvedAcquisition(num_channels, align_hz) + user_rois = _resolve_session_user_rois(result_dr, trial_table, lookup, roi) + + n_dmds = trial_table["n_dmds"] + log(f"Extracting sources for {n_dmds} DMD path(s)", run.verbose) + paths: list[PathSummary] = [] + for dmd_ix in range(n_dmds): + paths.append( + assemble_path_summary( + _process_dmd( + dmd_ix, + trial_table, + params, + lookup, + psf, + user_rois, + acquisition=acquisition, + execution=run, + annotations=roi, + ), + path_index=dmd_ix, + ) + ) + + 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) + return summary + + +def _params_dict( + params: BandSiloParams, + acquisition: ResolvedAcquisition, + annotations: AnnotationOptions, +) -> dict: + """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, + "denoiseWindow_s": params.denoise_window_s, + "baselineWindow_s": params.baseline_window_s, + "backgroundInterpolation": "cubic", + "decayTau_s": params.decay_tau_s, + "dXY": params.d_xy, + "sparse_fac": params.sparse_fac, + "vif": params.vif, + "peakth": params.peakth, + "peak_buffer": params.peak_buffer, + "trace_beta_fraction": params.trace_beta_fraction, + "trace_max_iter": params.trace_max_iter, + "trace_tolerance": params.trace_tolerance, + "trace_debias": params.trace_debias, + "trace_event_threshold": params.trace_event_threshold, + "random_seed": params.random_seed, + "draw_user_rois": annotations.enabled, + } + + +def _process_dmd( + dmd_ix: int, + trial_table: dict, + params: BandSiloParams, + lookup: dict, + psf: dict, + user_rois: dict | None = None, + *, + acquisition: ResolvedAcquisition, + execution: ExecutionOptions, + annotations: AnnotationOptions, +) -> PathResult: + """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) + datadr = str(trial_table["datadr"]) + n_trials = trial_table["filename"].shape[1] + if execution.max_trials is not None: + n_trials = min(n_trials, execution.max_trials) + log(f"Debug: limiting to first {n_trials} trial(s)", execution.verbose) + num_channels = acquisition.num_channels + 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) + 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) + fastz_to_refz = lookup["fastZ2RefZ"][key] + num_fast_zs = fastz_to_refz.shape[0] + all_sp_ids = lookup["allSuperPixelIDs"][key] + 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]) + 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) + + 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]), + dmd_ix, + align_hz, + all_sp_ids, + datadr, + trial_table, + num_channels, + ) + + low = td.assemble_lowres_data( + map_trials( + _read, + range(n_trials), + execution.max_workers, + desc=f"{key} reading trials" if execution.verbose else None, + ), + num_channels, + ) + 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 + unique_motion, mot_inds = motion_binning.bin_motion( + low["lowResMotionR"], low["lowResMotionC"], low["lowResMotionZ"] + ) + median_z = np.median(low["lowResMotionZ"]) + _, frames_to_keep = motion_binning.select_motion_bins( + unique_motion, mot_inds, low["lowResMotionZ"], z_tol=params.z_tol + ) + mean_im = si.compute_mean_image( + low_res_data_norm, + unique_motion, + mot_inds, + frames_to_keep, + ref_d, + ref_r, + ref_c, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + num_channels, + low2, + ) + umyx, mot_inds_yx = motion_binning.bin_motion_yx( + low["lowResMotionR"], low["lowResMotionC"], frames_to_keep + ) + _, sel_pix_idxs = geo.build_selected_pixel_mask( + umyx, + ref_d, + ref_r, + ref_c, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + psf2d, + ) + pixel_coords = geo.pixel_coords_from_idxs( + sel_pix_idxs, dmd_pixels_per_column, dmd_pixels_per_row + ) + background = _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, + execution=execution, + ) + 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, + 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, + execution=execution, + exclusion_mask=( + np.logical_or.reduce(soma_masks) + if soma_masks is not None and len(soma_masks) > 0 + else None + ), + ) + + # Trace-only options: never passed to localization or its QR solver. + from .transient import TransientOptions + + transient_options = TransientOptions( + tau_s=params.decay_tau_s, + beta_fraction=params.trace_beta_fraction, + max_iter=params.trace_max_iter, + tolerance=params.trace_tolerance, + debias=params.trace_debias, + event_threshold=params.trace_event_threshold, + ) + + 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, + bool(keep_trials[dmd_ix, trial_ix]), + background[:, low["lowResTrialID"] == trial_ix], + ), + dmd_ix, + params.analyze_hz, + all_sp_ids, + datadr, + trial_table, + smi, + sparse_h_inds, + sparse_h_vals, + a, + umyx, + np.arange(umyx.shape[0]), + median_z, + psf2d, + num_super_pixels, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + num_channels, + soma_sps, + z_tol=params.z_tol, + transient_options=transient_options, + ) + + trace_results = map_trials( + _traces, + range(n_trials), + execution.max_workers, + desc=f"{key} extracting traces" if execution.verbose else None, + ) + trace_results = [r for r in trace_results if r.d_f.shape[0] > 0] + return PathResult( + a=a, + source_params=source_params, + source_snr=source_snr, + act_im=act_im, + mean_im=mean_im, + act_im_peaks=act_im_peaks, + trace_results=trace_results, + z_depths=fastz_to_refz, + num_fast_zs=num_fast_zs, + 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)), + draw_user_rois=annotations.enabled, + soma_masks=soma_masks, + soma_labels=soma_labels, + yx_shape=yx_shape, + ) + + +def _estimate_background( + 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: 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( + (sel_pix_idxs.shape[0], low_res_data_norm.shape[1]), + np.nan, + dtype=np.float32, + ) + for z in progress( + range(num_fast_zs), + desc="Interpolating planes", + verbose=execution.verbose, + ): + z_idxs, sel_2d = geo.selected_pixels_2d_for_plane( + sel_pix_idxs, z, dmd_pixels_per_column, dmd_pixels_per_row + ) + if z_idxs.size == 0: + continue + ref_z = np.flatnonzero(ref_d == z) + interp_data[z_idxs], _, _ = bg.build_interp_data( + low_res_data_norm[ref_z], + ref_r[ref_z], + ref_c[ref_z], + sel_2d, + umyx, + 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) + return bg.assemble_background( + interp_background, + umyx, + mot_inds_yx, + sel_pix_idxs, + ref_d, + ref_r, + ref_c, + low_res_data_norm.shape[0], + low_res_data_norm.shape[1], + dmd_pixels_per_column, + dmd_pixels_per_row, + ) + + +def _localize( + 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: 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( + sparse_h_inds, + sparse_h_vals, + umyx, + sel_pix_idxs, + num_super_pixels, + dmd_pixels_per_row, + ) + # compute_rho normalizes center/surround columns separately. The PSF still + # 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) + d_mats, d_mats_exp = [], [] + for z in progress( + range(num_fast_zs), + desc="Computing D matrices", + verbose=execution.verbose, + ): + _, 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_exp.append( + operators.build_convolution_matrix(sel_2d, surround_kernel, surround_kernel_ctr) + ) + rho = activity.compute_rho( + residual, + mot_inds_yx, + umyx, + h_mots, + d_mats, + d_mats_exp, + sel_pix_idxs, + ref_d, + ref_r, + ref_c, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + psf2d, + verbose=execution.verbose, + ) + nan_ct = activity.mask_high_nan_rho(rho) + temporal_kernel = activity.decay_kernel_1d(params.decay_tau_s, align_hz) + rho = activity.smooth_rho( + rho, + temporal_kernel, + verbose=execution.verbose, + ) + act_im = si.accumulate_activity_image( + rho, + sel_pix_idxs, + num_fast_zs, + dmd_pixels_per_column, + dmd_pixels_per_row, + verbose=execution.verbose, + ) + # Only final median geometry follows the dominant retained motion bin. + # Dropped frames (-1) do not vote; rho/NMF retain original scan centers. + motion_counts = np.bincount(mot_inds_yx[mot_inds_yx >= 0]) + dominant_motion = umyx[np.argmax(motion_counts)] + act_im = si.finalize_activity_image( + act_im, + sel_pix_idxs, + nan_ct, + ref_r=ref_r + int(dominant_motion[0]), + ref_c=ref_c + int(dominant_motion[1]), + ref_d=ref_d, + ) + source_seeds = get_act_im_peaks( + act_im, + peak_th=params.peakth, + buffer_size=params.peak_buffer, + exclusion_mask=exclusion_mask, + ) + act_im_peaks = source_seeds.copy() + print(f"Number of detected sources: {act_im_peaks.shape[0]}") + result = fit_sources( + source_seeds, + residual, + h_mots, + umyx, + mot_inds_yx, + sel_pix_idxs, + pixel_coords, + n_pixels, + params.d_xy, + params.sparse_fac, + verbose=execution.verbose, + temporal_kernel=temporal_kernel, + seed=params.random_seed, + ) + return ( + act_im, + act_im_peaks, + result["A"], + result["source_params"], + result["source_snr"], + ) diff --git a/src/giant_python/extraction/raster/__init__.py b/src/giant_python/extraction/raster/__init__.py index b3fde097..8b867184 100644 --- a/src/giant_python/extraction/raster/__init__.py +++ b/src/giant_python/extraction/raster/__init__.py @@ -1,5 +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/annotations.py b/src/giant_python/extraction/raster/annotations.py index 14700dc8..4aad671f 100644 --- a/src/giant_python/extraction/raster/annotations.py +++ b/src/giant_python/extraction/raster/annotations.py @@ -1,379 +1,379 @@ -"""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. -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]. -""" - -from __future__ import annotations - -import re -import warnings -from collections.abc import Sequence -from dataclasses import dataclass, field, replace -from pathlib import Path, PurePath - -import h5py -import numpy as np - -from .alignment import TrialWarp, mask_to_consensus - - -@dataclass -class UserRoi: - """One user ROI. - - Attributes - ---------- - label : str - The ROI's label (Label); SOMA in it marks a soma. - type : str - '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, - row), one-based. Moved with the mask into the consensus frame. - radius, rotation_angle : float or None - semi_axes : ndarray or None - """ - - label: str - type: str - mask: np.ndarray - 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: - """Whether SILo treats the ROI as a soma (no sources seeded).""" - return "SOMA" in self.label.upper() - - -@dataclass -class PathAnnotations: - """One imaging path's ROIs (an entry of MATLAB's ROIs). - - Attributes - ---------- - fn : str - The annotation trial's registered file stem; empty if the path - was not annotated. - dr : str - 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 - read from a file). - """ - - fn: str = "" - dr: str = "" - rois: list = field(default_factory=list) - path: int = 0 - - -def _text(f: h5py.File, path: str, default: str = "") -> str: - """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][()]) - if raw.dtype.kind in ("S", "O", "U"): - value = raw.ravel()[0] if raw.size else "" - return value.decode() if isinstance(value, bytes) else str(value) - # MATLAB characters are UTF-16 code units - codes = np.asarray(raw.ravel(), dtype=" 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: 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) - xy = np.column_stack([a[:, 1] + 1, a[:, 0] + 1]) if zero_indexed else a - return xy[0] if xy.shape[0] == 1 else xy - - -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: - """Return the ROI type without MATLAB's images.roi. prefix. - - Returns - ------- - str - The stripped, lower-case type name. - """ - t = raw.strip().lower() - return t.removeprefix("images.roi.") - - -def read_annotations(path: str | Path) -> list: - """Read a SILo annotations.h5 (loadAnnotationsH5.m). - - Parameters - ---------- - path : str or Path - The file. - - Returns - ------- - list of PathAnnotations - One entry per Path (or DMD) group, in the order of - their numbers (PathAnnotations.path). - """ - with h5py.File(path, "r") as f: - zero = True - if "coords_zero_indexed" in f: - zero = bool(np.asarray(f["coords_zero_indexed"][()]).ravel()[0]) - else: - zero = False - groups = [] - for name in f: - m = re.fullmatch(r"(?:Path|DMD)(\d+)", name) - if m and isinstance(f[name], h5py.Group): - groups.append((int(m.group(1)), name)) - out = [] - for number, name in sorted(groups): - n_rois = _scalar(_array(f, f"{name}/n_rois")) or 0 - rois = [] - for k in range(1, int(n_rois) + 1): - r = f"{name}/roi_{k:03d}" - mask = _array(f, f"{r}/mask") - rois.append( - 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)), - 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")), - ) - ) - out.append( - PathAnnotations( - fn=_text(f, f"{name}/fn"), - dr=_text(f, f"{name}/dr"), - rois=rois, - path=number, - ) - ) - return out - - -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 - stems of the registered files, then without its extension. - - Parameters - ---------- - fn : str - 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 - order. - - Returns - ------- - int or None - """ - 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] - 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) -> 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]) - return moved.reshape(xy.shape) - - -def rois_to_consensus( - annotations: PathAnnotations, - fn_reg_ds: Sequence[str], - warp: TrialWarp, - shape: tuple, -) -> list: - """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 - 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 - or was not aligned, the ROIs are only cropped or padded, with a - warning, as in MATLAB. - - Parameters - ---------- - annotations : PathAnnotations - The path's ROIs as read. - fn_reg_ds : sequence of str - The path's registered files, in trial order. - warp : TrialWarp - The plan's across-trial alignment. - shape : tuple of int - (rows, cols) of the consensus frame. - - Returns - ------- - list of UserRoi - New ROIs; the input is not changed. - """ - if not annotations.rois: - return [] - trial = annotation_trial(annotations.fn, fn_reg_ds) - if trial is None: - warnings.warn( - f"annotation trial {annotations.fn!r} is not in the trial table; " - "using its ROIs without cross-trial alignment" - ) - elif not warp.aligned[trial]: - warnings.warn( - f"annotation trial {annotations.fn!r} was not aligned across " - "trials; using its ROIs without cross-trial alignment" - ) - trial = None - full_map = trial is not None and not warp.is_shift(trial) - shift = np.zeros(2) if trial is None or full_map else warp.shift(trial) - out = [] - for roi in annotations.rois: - moved = {} - for name in ("center", "position"): - xy = getattr(roi, name) - if xy is None: - continue - xy = np.asarray(xy, dtype=np.float64) - if full_map: - moved[name] = _geometry_to_consensus(xy, warp, trial) - else: - moved[name] = xy - shift[::-1] - mask = ( - mask_to_consensus(roi.mask, warp, trial, tuple(shape)) - if roi.mask.size - else np.zeros(tuple(shape), bool) - ) - out.append(replace(roi, mask=mask, **moved)) - return out - - -def soma_mask(rois: Sequence[UserRoi], shape: tuple) -> np.ndarray: - """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: - h = min(shape[0], roi.mask.shape[0]) - w = min(shape[1], roi.mask.shape[1]) - out[:h, :w] |= roi.mask[:h, :w] - return out - - -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. - n_paths : int - Imaging paths of the session. - - Returns - ------- - list of (PathAnnotations or None) - 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 - every path.) - """ - out: list = [None] * n_paths - if path is None or not Path(path).exists(): - return out - for entry in read_annotations(path): - if 1 <= entry.path <= n_paths: - out[entry.path - 1] = entry - return out +"""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. +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]. +""" + +from __future__ import annotations + +import re +import warnings +from collections.abc import Sequence +from dataclasses import dataclass, field, replace +from pathlib import Path, PurePath + +import h5py +import numpy as np + +from .alignment import TrialWarp, mask_to_consensus + + +@dataclass +class UserRoi: + """One user ROI. + + Attributes + ---------- + label : str + The ROI's label (Label); SOMA in it marks a soma. + type : str + '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, + row), one-based. Moved with the mask into the consensus frame. + radius, rotation_angle : float or None + semi_axes : ndarray or None + """ + + label: str + type: str + mask: np.ndarray + 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: + """Whether SILo treats the ROI as a soma (no sources seeded).""" + return "SOMA" in self.label.upper() + + +@dataclass +class PathAnnotations: + """One imaging path's ROIs (an entry of MATLAB's ROIs). + + Attributes + ---------- + fn : str + The annotation trial's registered file stem; empty if the path + was not annotated. + dr : str + 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 + read from a file). + """ + + fn: str = "" + dr: str = "" + rois: list = field(default_factory=list) + path: int = 0 + + +def _text(f: h5py.File, path: str, default: str = "") -> str: + """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][()]) + if raw.dtype.kind in ("S", "O", "U"): + value = raw.ravel()[0] if raw.size else "" + return value.decode() if isinstance(value, bytes) else str(value) + # MATLAB characters are UTF-16 code units + codes = np.asarray(raw.ravel(), dtype=" 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: 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) + xy = np.column_stack([a[:, 1] + 1, a[:, 0] + 1]) if zero_indexed else a + return xy[0] if xy.shape[0] == 1 else xy + + +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: + """Return the ROI type without MATLAB's images.roi. prefix. + + Returns + ------- + str + The stripped, lower-case type name. + """ + t = raw.strip().lower() + return t.removeprefix("images.roi.") + + +def read_annotations(path: str | Path) -> list: + """Read a SILo annotations.h5 (loadAnnotationsH5.m). + + Parameters + ---------- + path : str or Path + The file. + + Returns + ------- + list of PathAnnotations + One entry per Path (or DMD) group, in the order of + their numbers (PathAnnotations.path). + """ + with h5py.File(path, "r") as f: + zero = True + if "coords_zero_indexed" in f: + zero = bool(np.asarray(f["coords_zero_indexed"][()]).ravel()[0]) + else: + zero = False + groups = [] + for name in f: + m = re.fullmatch(r"(?:Path|DMD)(\d+)", name) + if m and isinstance(f[name], h5py.Group): + groups.append((int(m.group(1)), name)) + out = [] + for number, name in sorted(groups): + n_rois = _scalar(_array(f, f"{name}/n_rois")) or 0 + rois = [] + for k in range(1, int(n_rois) + 1): + r = f"{name}/roi_{k:03d}" + mask = _array(f, f"{r}/mask") + rois.append( + 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)), + 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")), + ) + ) + out.append( + PathAnnotations( + fn=_text(f, f"{name}/fn"), + dr=_text(f, f"{name}/dr"), + rois=rois, + path=number, + ) + ) + return out + + +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 + stems of the registered files, then without its extension. + + Parameters + ---------- + fn : str + 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 + order. + + Returns + ------- + int or None + """ + 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] + 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) -> 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]) + return moved.reshape(xy.shape) + + +def rois_to_consensus( + annotations: PathAnnotations, + fn_reg_ds: Sequence[str], + warp: TrialWarp, + shape: tuple, +) -> list: + """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 + 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 + or was not aligned, the ROIs are only cropped or padded, with a + warning, as in MATLAB. + + Parameters + ---------- + annotations : PathAnnotations + The path's ROIs as read. + fn_reg_ds : sequence of str + The path's registered files, in trial order. + warp : TrialWarp + The plan's across-trial alignment. + shape : tuple of int + (rows, cols) of the consensus frame. + + Returns + ------- + list of UserRoi + New ROIs; the input is not changed. + """ + if not annotations.rois: + return [] + trial = annotation_trial(annotations.fn, fn_reg_ds) + if trial is None: + warnings.warn( + f"annotation trial {annotations.fn!r} is not in the trial table; " + "using its ROIs without cross-trial alignment" + ) + elif not warp.aligned[trial]: + warnings.warn( + f"annotation trial {annotations.fn!r} was not aligned across " + "trials; using its ROIs without cross-trial alignment" + ) + trial = None + full_map = trial is not None and not warp.is_shift(trial) + shift = np.zeros(2) if trial is None or full_map else warp.shift(trial) + out = [] + for roi in annotations.rois: + moved = {} + for name in ("center", "position"): + xy = getattr(roi, name) + if xy is None: + continue + xy = np.asarray(xy, dtype=np.float64) + if full_map: + moved[name] = _geometry_to_consensus(xy, warp, trial) + else: + moved[name] = xy - shift[::-1] + mask = ( + mask_to_consensus(roi.mask, warp, trial, tuple(shape)) + if roi.mask.size + else np.zeros(tuple(shape), bool) + ) + out.append(replace(roi, mask=mask, **moved)) + return out + + +def soma_mask(rois: Sequence[UserRoi], shape: tuple) -> np.ndarray: + """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: + h = min(shape[0], roi.mask.shape[0]) + w = min(shape[1], roi.mask.shape[1]) + out[:h, :w] |= roi.mask[:h, :w] + return out + + +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. + n_paths : int + Imaging paths of the session. + + Returns + ------- + list of (PathAnnotations or None) + 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 + every path.) + """ + out: list = [None] * n_paths + if path is None or not Path(path).exists(): + return out + for entry in read_annotations(path): + if 1 <= entry.path <= n_paths: + out[entry.path - 1] = entry + return out diff --git a/src/giant_python/extraction/raster/container.py b/src/giant_python/extraction/raster/container.py index 83663850..b96aded1 100644 --- a/src/giant_python/extraction/raster/container.py +++ b/src/giant_python/extraction/raster/container.py @@ -1,751 +1,751 @@ -"""The container: one trial-path's inputs of source extraction, in one file. - -A container holds everything a subproblem solver needs, so that solving -needs neither the raw data nor the SLAP2 reader nor the trial table: - -* the data at the path's selected pixels and its variance multiplier, stored - once (overlapping subproblems share pixels instead of copying them); -* the frames' lines, discards and motion, and the pixels' positions in the - consensus frame and in the trial's registered frame; -* the path's sources and each subproblem as index lists (its pixels, its - sources) with its crop of the consensus map; -* the trial's global and user-ROI traces; -* the parameters, the code version and a hash of the settings; -* the F0 network's baseline at the pixels, at the registration's frames, - when the run extracts with it (otherwise the datasets stay empty). - -File layout (HDF5, row-major, zero-based indices; lines are one-based):: - - / attributes: format, format_version, code_version, - settings_hash, params (JSON), source (JSON), - photon_scale, consensus_shape - /data/y (channels, pixels, frames) float32, counts / - photon_scale, channel 0 the activity channel - /data/finv (pixels, frames) float32 variance multiplier - /frames/lines (frames,) one-based line of each frame - /frames/discard (frames,) frames discarded for motion - /frames/motion_r, motion_c - /pixels/consensus_rc (pixels, 2) row, col in the consensus frame, in - MATLAB's column-major order of the map - /pixels/trial_rc (pixels, 2) position in the registered frame - /sources/rc (sources, 2) row, col in the consensus frame - /subproblems/pixel_index, pixel_offset pixels of subproblem k: - pixel_index[pixel_offset[k]:pixel_offset[k + 1]] - /subproblems/source_index, source_offset its sources, likewise - /subproblems/crop (subproblems, 4) row0, col0, rows, cols - /traces/global_f (channels, frames), file channel order - /traces/roi_f, roi_fsvd (rois, channels, frames), analysis order - /baseline/values (pixels, registered frames) float32, resizable: - the F0 network's baseline at the pixels (counts - / photon_scale), at the registration's frames; - 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, -: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`) -when it is read for a solver mode that uses it. -""" - -from __future__ import annotations - -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 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 SolverParams, Subproblem -from .trial_data import TrialData - -__all__ = [ - "Container", - "Subproblem", - "crop_of", - "read_container", - "read_subproblem", - "settings_hash", - "write_container", -] - -FORMAT = "giant-silo-container" -FORMAT_VERSION = 1 - -COMPRESSION = "lzf" -"""Default filter of the data: see :func:`write_container`.""" - -CHUNK_PIXELS = 16 -"""Pixels per chunk of the data (a chunk holds all frames).""" - - -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): - return {str(k): _jsonable(v) for k, v in value.items()} - if isinstance(value, (list, tuple)): - return [_jsonable(v) for v in value] - if isinstance(value, np.ndarray): - return _jsonable(value.tolist()) - if isinstance(value, np.generic): - return value.item() - if isinstance(value, Path): - return str(value) - return value - - -def settings_hash(params: object) -> str: - """SHA-256 of settings, independent of the order of their keys. - - Parameters - ---------- - params : dict or dataclass - The settings (JSON types, NumPy values or dataclasses). - - Returns - ------- - str - Hexadecimal digest, with the container format's version. - """ - record = {"format_version": FORMAT_VERSION, "params": _jsonable(params)} - text = json.dumps(record, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(text.encode("utf-8")).hexdigest() - - -@dataclass -class Container: - """A container's content. - - Attributes - ---------- - y, finv : ndarray or None - The data and its variance multiplier at the selected pixels (None - when read without data). - frame_lines : ndarray of int - One-based line of each frame. - discard : ndarray of bool - Frames discarded for motion. - motion_r, motion_c : ndarray - Motion applied at each frame. - pixel_rc : ndarray of int - (pixels, 2) consensus row and column of each pixel. - trial_rc : ndarray - (pixels, 2) position of each pixel in the registered frame. - sources_rc : ndarray - (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. - consensus_shape : tuple - (rows, cols) of the consensus frame. - global_f, roi_f, roi_fsvd : ndarray - The trial's global and user-ROI traces (see TrialData). - photon_scale : float - 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. - baseline_filled : bool - Whether the network's baseline has been written. - baseline_values : ndarray or None - (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). - baseline_identity : dict - The baseline file and the network's record (when filled). - """ - - y: np.ndarray | None - finv: np.ndarray | None - frame_lines: np.ndarray - discard: np.ndarray - motion_r: np.ndarray - motion_c: np.ndarray - pixel_rc: np.ndarray - trial_rc: np.ndarray - sources_rc: np.ndarray - subproblem_pixels: list - subproblem_sources: list - crops: np.ndarray - consensus_shape: tuple - global_f: np.ndarray - roi_f: np.ndarray - roi_fsvd: np.ndarray - photon_scale: float - params: dict = field(default_factory=dict) - source: dict = field(default_factory=dict) - code_version: str = "" - settings_hash: str = "" - baseline_filled: bool = False - baseline_values: np.ndarray | None = None - baseline_lines: np.ndarray | None = None - baseline_identity: dict = field(default_factory=dict) - - @property - def n_subproblems(self) -> int: - """Number of subproblems.""" - return len(self.subproblem_pixels) - - 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 - 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. - """ - if self.y is None: - raise ValueError("the container was read without its data") - _check_index(k, self.n_subproblems) - pix = self.subproblem_pixels[k] - baseline = None - if _uses_baseline(solver_params): - if self.baseline_values is None: - raise ValueError(_NO_BASELINE) - baseline = subproblem_baseline( - self.baseline_values[pix], - self.baseline_lines, - self.frame_lines, - self.y[0, pix], - solver_params, - ) - return _subproblem( - self.y[:, pix], - self.finv[pix], - self.pixel_rc[pix], - self.sources_rc, - pix, - self.subproblem_sources[k], - self.crops[k], - baseline, - ) - - -_NO_BASELINE = ( - "the container has no network baseline; the solver's baseline mode " - "needs one (prepare it with the network's baselines)" -) - - -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. - - 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. - - 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) - return np.array([lo[0], lo[1], hi[0] - lo[0] + 1, hi[1] - lo[1] + 1]) - - -def _subproblem( - 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 - return Subproblem( - y=y, - finv=finv, - sel=sel, - sources_rc=sources_rc[sources] - np.array([row0, col0]), - pixels=np.asarray(pixels, dtype=np.int64), - sources=np.asarray(sources, dtype=np.int64), - row0=row0, - col0=col0, - baseline=baseline, - ) - - -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) - whole = a.dtype != np.bool_ and np.issubdtype(a.dtype, np.integer) - if not whole and np.issubdtype(a.dtype, np.floating): - whole = bool(np.all(np.isfinite(a)) and np.all(a == np.round(a))) - if not whole: - raise ValueError(f"subproblem {k}: {what} must be whole numbers") - return a.astype(np.int64) - - -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): - raise ValueError(f"subproblem {k}: {what} outside 0..{n_max - 1}") - if np.any(np.diff(v) <= 0): - raise ValueError(f"subproblem {k}: {what} must increase") - offsets = np.concatenate([[0], np.cumsum([v.size for v in lists])]) - flat = np.concatenate(lists) if lists else np.zeros(0, np.int64) - return flat.astype(np.int32), offsets.astype(np.int64) - - -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],) - kwargs = {"chunks": chunks} - if compression: - kwargs.update( - compression=compression, - compression_opts=compression_opts, - shuffle=True, - ) - return kwargs - - -def write_container( - path: str | Path, - trial: TrialData, - sources_rc: ArrayLike, - subproblem_pixels: Sequence, - subproblem_sources: Sequence, - 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: TrialBaseline | None = None, -) -> Path: - """Write one trial-path's container. - - The file is written under a temporary name and moved into place when - complete; a failed write removes it and leaves an existing container - untouched. - - Parameters - ---------- - path : str or Path - Destination (replaced if it exists). - 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. - 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). - consensus_shape : (int, int) - Rows and columns of the consensus frame. - params : dict or dataclass, optional - The settings that produced the container and that solving it will - use; saved as JSON, and hashed. - source : dict, optional - A record of where the data came from (file, trial, path). - 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) - 544 to 528 MB in 17 to 23 s; None 901 MB in 1 s. - compression_opts : int, optional - 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 - chunks read single subproblems faster, at the same file size). - baseline : TrialBaseline, optional - The network's baseline at the trial's pixels - (:func:`~.baseline_map.read_trial_baseline`), written to - /baseline. - - Returns - ------- - Path - The file written. - - Raises - ------ - ValueError - If the subproblem lists do not match, are not whole numbers, are - not increasing, or point outside the pixel or source lists. - """ - path = Path(path) - sources_rc = np.asarray(sources_rc).reshape(-1, 2) - n_px = trial.y.shape[1] - if len(subproblem_pixels) != len(subproblem_sources): - 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 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") - crops = np.array( - [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 {}) - tmp = path.with_name(path.name + ".partial") - try: - with h5py.File(tmp, "w") as f: - f.attrs["format"] = FORMAT - f.attrs["format_version"] = FORMAT_VERSION - 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["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), - ) - f["frames/lines"] = np.asarray(trial.frame_lines, np.int64) - f["frames/discard"] = np.asarray(trial.discard, np.uint8) - f["frames/motion_r"] = np.asarray(trial.motion_r, np.float64) - f["frames/motion_c"] = np.asarray(trial.motion_c, np.float64) - f["pixels/consensus_rc"] = np.asarray(trial.pixel_rc, np.int32) - f["pixels/trial_rc"] = np.asarray(trial.trial_rc, np.float64) - f["sources/rc"] = sources_rc - f["subproblems/pixel_index"] = pix_flat - f["subproblems/pixel_offset"] = pix_off - f["subproblems/source_index"] = src_flat - f["subproblems/source_offset"] = src_off - f["subproblems/crop"] = crops - 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) - if baseline is not None: - _write_baseline(f["baseline"], baseline) - os.replace(tmp, path) - except BaseException: - if tmp.exists(): - tmp.unlink() - raise - return path - - -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 = {} - if compression: - kwargs.update( - compression=compression, - compression_opts=compression_opts, - shuffle=True, - ) - # a trial without selected pixels has no pixel axis to chunk: HDF5 - # needs that axis unlimited then - g.create_dataset( - "values", - shape=(n_px, 0), - maxshape=(n_px or None, None), - dtype=np.float32, - chunks=(max(1, min(chunk_pixels, n_px)), 256), - fillvalue=np.nan, - **kwargs, - ) - 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: 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") - 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) - - -def _check_format(f: h5py.File) -> 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 up to {FORMAT_VERSION}" - ) - - -def _split(flat: np.ndarray, offsets: np.ndarray) -> list: - """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: str | Path, data: bool = True) -> Container: - """Read a container. - - Parameters - ---------- - path : str or Path - The container. - data : bool - Read y and finv too (they are most of the file). Without - them, :func:`read_subproblem` reads single subproblems from the - file. - - Returns - ------- - Container - """ - with h5py.File(path, "r") as f: - _check_format(f) - sub = f["subproblems"] - g = f["baseline"] - filled = bool(g.attrs["filled"]) - return Container( - y=f["data/y"][()] if data else None, - finv=f["data/finv"][()] if data else None, - frame_lines=f["frames/lines"][()], - discard=f["frames/discard"][()].astype(bool), - motion_r=f["frames/motion_r"][()], - motion_c=f["frames/motion_c"][()], - 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"][()]), - crops=sub["crop"][()].astype(np.int64), - consensus_shape=tuple(int(v) for v in f.attrs["consensus_shape"]), - global_f=f["traces/global_f"][()], - roi_f=f["traces/roi_f"][()], - roi_fsvd=f["traces/roi_fsvd"][()], - photon_scale=float(f.attrs["photon_scale"]), - params=json.loads(f.attrs["params"]), - source=json.loads(f.attrs["source"]), - code_version=str(f.attrs["code_version"]), - settings_hash=str(f.attrs["settings_hash"]), - baseline_filled=filled, - 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 {} - ), - ) - - -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, :] - a, b = int(rows[0]), int(rows[-1]) + 1 - return ds[..., a:b, :][..., rows - a, :] - - -def read_subproblem( - container: Container | str | Path | h5py.File, - k: int, - solver_params: SolverParams | None = None, -) -> Subproblem: - """Subproblem k of a container, in the shared convention. - - Parameters - ---------- - container : Container, str, Path or h5py.File - A container read with its data, or the file: then only the - subproblem's part of the data is read. - k : int - Zero-based index of the subproblem. - solver_params : SolverParams, optional - See :meth:`Container.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) - if not isinstance(container, h5py.File): - with h5py.File(container, "r") as f: - return read_subproblem(f, k, solver_params) - f = container - _check_format(f) - sub = f["subproblems"] - _check_index(k, sub["crop"].shape[0]) - p0, p1 = (int(v) for v in sub["pixel_offset"][k : k + 2]) - s0, s1 = (int(v) for v in sub["source_offset"][k : k + 2]) - pix = sub["pixel_index"][p0:p1].astype(np.int64) - rc = _read_rows(f["pixels/consensus_rc"], pix).astype(np.int64) - y = _read_rows(f["data/y"], pix) - baseline = None - if _uses_baseline(solver_params): - g = f["baseline"] - if not g.attrs["filled"]: - raise ValueError(_NO_BASELINE) - baseline = subproblem_baseline( - _read_rows(g["values"], pix), - g["frame_lines"][()], - f["frames/lines"][()], - y[0], - solver_params, - ) - return _subproblem( - y, - _read_rows(f["data/finv"], pix), - rc, - f["sources/rc"][()], - pix, - sub["source_index"][s0:s1].astype(np.int64), - sub["crop"][k], - baseline, - ) +"""The container: one trial-path's inputs of source extraction, in one file. + +A container holds everything a subproblem solver needs, so that solving +needs neither the raw data nor the SLAP2 reader nor the trial table: + +* the data at the path's selected pixels and its variance multiplier, stored + once (overlapping subproblems share pixels instead of copying them); +* the frames' lines, discards and motion, and the pixels' positions in the + consensus frame and in the trial's registered frame; +* the path's sources and each subproblem as index lists (its pixels, its + sources) with its crop of the consensus map; +* the trial's global and user-ROI traces; +* the parameters, the code version and a hash of the settings; +* the F0 network's baseline at the pixels, at the registration's frames, + when the run extracts with it (otherwise the datasets stay empty). + +File layout (HDF5, row-major, zero-based indices; lines are one-based):: + + / attributes: format, format_version, code_version, + settings_hash, params (JSON), source (JSON), + photon_scale, consensus_shape + /data/y (channels, pixels, frames) float32, counts / + photon_scale, channel 0 the activity channel + /data/finv (pixels, frames) float32 variance multiplier + /frames/lines (frames,) one-based line of each frame + /frames/discard (frames,) frames discarded for motion + /frames/motion_r, motion_c + /pixels/consensus_rc (pixels, 2) row, col in the consensus frame, in + MATLAB's column-major order of the map + /pixels/trial_rc (pixels, 2) position in the registered frame + /sources/rc (sources, 2) row, col in the consensus frame + /subproblems/pixel_index, pixel_offset pixels of subproblem k: + pixel_index[pixel_offset[k]:pixel_offset[k + 1]] + /subproblems/source_index, source_offset its sources, likewise + /subproblems/crop (subproblems, 4) row0, col0, rows, cols + /traces/global_f (channels, frames), file channel order + /traces/roi_f, roi_fsvd (rois, channels, frames), analysis order + /baseline/values (pixels, registered frames) float32, resizable: + the F0 network's baseline at the pixels (counts + / photon_scale), at the registration's frames; + 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, +: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`) +when it is read for a solver mode that uses it. +""" + +from __future__ import annotations + +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 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 SolverParams, Subproblem +from .trial_data import TrialData + +__all__ = [ + "Container", + "Subproblem", + "crop_of", + "read_container", + "read_subproblem", + "settings_hash", + "write_container", +] + +FORMAT = "giant-silo-container" +FORMAT_VERSION = 1 + +COMPRESSION = "lzf" +"""Default filter of the data: see :func:`write_container`.""" + +CHUNK_PIXELS = 16 +"""Pixels per chunk of the data (a chunk holds all frames).""" + + +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): + return {str(k): _jsonable(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(v) for v in value] + if isinstance(value, np.ndarray): + return _jsonable(value.tolist()) + if isinstance(value, np.generic): + return value.item() + if isinstance(value, Path): + return str(value) + return value + + +def settings_hash(params: object) -> str: + """SHA-256 of settings, independent of the order of their keys. + + Parameters + ---------- + params : dict or dataclass + The settings (JSON types, NumPy values or dataclasses). + + Returns + ------- + str + Hexadecimal digest, with the container format's version. + """ + record = {"format_version": FORMAT_VERSION, "params": _jsonable(params)} + text = json.dumps(record, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +@dataclass +class Container: + """A container's content. + + Attributes + ---------- + y, finv : ndarray or None + The data and its variance multiplier at the selected pixels (None + when read without data). + frame_lines : ndarray of int + One-based line of each frame. + discard : ndarray of bool + Frames discarded for motion. + motion_r, motion_c : ndarray + Motion applied at each frame. + pixel_rc : ndarray of int + (pixels, 2) consensus row and column of each pixel. + trial_rc : ndarray + (pixels, 2) position of each pixel in the registered frame. + sources_rc : ndarray + (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. + consensus_shape : tuple + (rows, cols) of the consensus frame. + global_f, roi_f, roi_fsvd : ndarray + The trial's global and user-ROI traces (see TrialData). + photon_scale : float + 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. + baseline_filled : bool + Whether the network's baseline has been written. + baseline_values : ndarray or None + (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). + baseline_identity : dict + The baseline file and the network's record (when filled). + """ + + y: np.ndarray | None + finv: np.ndarray | None + frame_lines: np.ndarray + discard: np.ndarray + motion_r: np.ndarray + motion_c: np.ndarray + pixel_rc: np.ndarray + trial_rc: np.ndarray + sources_rc: np.ndarray + subproblem_pixels: list + subproblem_sources: list + crops: np.ndarray + consensus_shape: tuple + global_f: np.ndarray + roi_f: np.ndarray + roi_fsvd: np.ndarray + photon_scale: float + params: dict = field(default_factory=dict) + source: dict = field(default_factory=dict) + code_version: str = "" + settings_hash: str = "" + baseline_filled: bool = False + baseline_values: np.ndarray | None = None + baseline_lines: np.ndarray | None = None + baseline_identity: dict = field(default_factory=dict) + + @property + def n_subproblems(self) -> int: + """Number of subproblems.""" + return len(self.subproblem_pixels) + + 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 + 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. + """ + if self.y is None: + raise ValueError("the container was read without its data") + _check_index(k, self.n_subproblems) + pix = self.subproblem_pixels[k] + baseline = None + if _uses_baseline(solver_params): + if self.baseline_values is None: + raise ValueError(_NO_BASELINE) + baseline = subproblem_baseline( + self.baseline_values[pix], + self.baseline_lines, + self.frame_lines, + self.y[0, pix], + solver_params, + ) + return _subproblem( + self.y[:, pix], + self.finv[pix], + self.pixel_rc[pix], + self.sources_rc, + pix, + self.subproblem_sources[k], + self.crops[k], + baseline, + ) + + +_NO_BASELINE = ( + "the container has no network baseline; the solver's baseline mode " + "needs one (prepare it with the network's baselines)" +) + + +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. + + 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. + + 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) + return np.array([lo[0], lo[1], hi[0] - lo[0] + 1, hi[1] - lo[1] + 1]) + + +def _subproblem( + 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 + return Subproblem( + y=y, + finv=finv, + sel=sel, + sources_rc=sources_rc[sources] - np.array([row0, col0]), + pixels=np.asarray(pixels, dtype=np.int64), + sources=np.asarray(sources, dtype=np.int64), + row0=row0, + col0=col0, + baseline=baseline, + ) + + +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) + whole = a.dtype != np.bool_ and np.issubdtype(a.dtype, np.integer) + if not whole and np.issubdtype(a.dtype, np.floating): + whole = bool(np.all(np.isfinite(a)) and np.all(a == np.round(a))) + if not whole: + raise ValueError(f"subproblem {k}: {what} must be whole numbers") + return a.astype(np.int64) + + +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): + raise ValueError(f"subproblem {k}: {what} outside 0..{n_max - 1}") + if np.any(np.diff(v) <= 0): + raise ValueError(f"subproblem {k}: {what} must increase") + offsets = np.concatenate([[0], np.cumsum([v.size for v in lists])]) + flat = np.concatenate(lists) if lists else np.zeros(0, np.int64) + return flat.astype(np.int32), offsets.astype(np.int64) + + +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],) + kwargs = {"chunks": chunks} + if compression: + kwargs.update( + compression=compression, + compression_opts=compression_opts, + shuffle=True, + ) + return kwargs + + +def write_container( + path: str | Path, + trial: TrialData, + sources_rc: ArrayLike, + subproblem_pixels: Sequence, + subproblem_sources: Sequence, + 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: TrialBaseline | None = None, +) -> Path: + """Write one trial-path's container. + + The file is written under a temporary name and moved into place when + complete; a failed write removes it and leaves an existing container + untouched. + + Parameters + ---------- + path : str or Path + Destination (replaced if it exists). + 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. + 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). + consensus_shape : (int, int) + Rows and columns of the consensus frame. + params : dict or dataclass, optional + The settings that produced the container and that solving it will + use; saved as JSON, and hashed. + source : dict, optional + A record of where the data came from (file, trial, path). + 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) + 544 to 528 MB in 17 to 23 s; None 901 MB in 1 s. + compression_opts : int, optional + 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 + chunks read single subproblems faster, at the same file size). + baseline : TrialBaseline, optional + The network's baseline at the trial's pixels + (:func:`~.baseline_map.read_trial_baseline`), written to + /baseline. + + Returns + ------- + Path + The file written. + + Raises + ------ + ValueError + If the subproblem lists do not match, are not whole numbers, are + not increasing, or point outside the pixel or source lists. + """ + path = Path(path) + sources_rc = np.asarray(sources_rc).reshape(-1, 2) + n_px = trial.y.shape[1] + if len(subproblem_pixels) != len(subproblem_sources): + 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 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") + crops = np.array( + [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 {}) + tmp = path.with_name(path.name + ".partial") + try: + with h5py.File(tmp, "w") as f: + f.attrs["format"] = FORMAT + f.attrs["format_version"] = FORMAT_VERSION + 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["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), + ) + f["frames/lines"] = np.asarray(trial.frame_lines, np.int64) + f["frames/discard"] = np.asarray(trial.discard, np.uint8) + f["frames/motion_r"] = np.asarray(trial.motion_r, np.float64) + f["frames/motion_c"] = np.asarray(trial.motion_c, np.float64) + f["pixels/consensus_rc"] = np.asarray(trial.pixel_rc, np.int32) + f["pixels/trial_rc"] = np.asarray(trial.trial_rc, np.float64) + f["sources/rc"] = sources_rc + f["subproblems/pixel_index"] = pix_flat + f["subproblems/pixel_offset"] = pix_off + f["subproblems/source_index"] = src_flat + f["subproblems/source_offset"] = src_off + f["subproblems/crop"] = crops + 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) + if baseline is not None: + _write_baseline(f["baseline"], baseline) + os.replace(tmp, path) + except BaseException: + if tmp.exists(): + tmp.unlink() + raise + return path + + +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 = {} + if compression: + kwargs.update( + compression=compression, + compression_opts=compression_opts, + shuffle=True, + ) + # a trial without selected pixels has no pixel axis to chunk: HDF5 + # needs that axis unlimited then + g.create_dataset( + "values", + shape=(n_px, 0), + maxshape=(n_px or None, None), + dtype=np.float32, + chunks=(max(1, min(chunk_pixels, n_px)), 256), + fillvalue=np.nan, + **kwargs, + ) + 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: 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") + 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) + + +def _check_format(f: h5py.File) -> 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 up to {FORMAT_VERSION}" + ) + + +def _split(flat: np.ndarray, offsets: np.ndarray) -> list: + """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: str | Path, data: bool = True) -> Container: + """Read a container. + + Parameters + ---------- + path : str or Path + The container. + data : bool + Read y and finv too (they are most of the file). Without + them, :func:`read_subproblem` reads single subproblems from the + file. + + Returns + ------- + Container + """ + with h5py.File(path, "r") as f: + _check_format(f) + sub = f["subproblems"] + g = f["baseline"] + filled = bool(g.attrs["filled"]) + return Container( + y=f["data/y"][()] if data else None, + finv=f["data/finv"][()] if data else None, + frame_lines=f["frames/lines"][()], + discard=f["frames/discard"][()].astype(bool), + motion_r=f["frames/motion_r"][()], + motion_c=f["frames/motion_c"][()], + 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"][()]), + crops=sub["crop"][()].astype(np.int64), + consensus_shape=tuple(int(v) for v in f.attrs["consensus_shape"]), + global_f=f["traces/global_f"][()], + roi_f=f["traces/roi_f"][()], + roi_fsvd=f["traces/roi_fsvd"][()], + photon_scale=float(f.attrs["photon_scale"]), + params=json.loads(f.attrs["params"]), + source=json.loads(f.attrs["source"]), + code_version=str(f.attrs["code_version"]), + settings_hash=str(f.attrs["settings_hash"]), + baseline_filled=filled, + 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 {} + ), + ) + + +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, :] + a, b = int(rows[0]), int(rows[-1]) + 1 + return ds[..., a:b, :][..., rows - a, :] + + +def read_subproblem( + container: Container | str | Path | h5py.File, + k: int, + solver_params: SolverParams | None = None, +) -> Subproblem: + """Subproblem k of a container, in the shared convention. + + Parameters + ---------- + container : Container, str, Path or h5py.File + A container read with its data, or the file: then only the + subproblem's part of the data is read. + k : int + Zero-based index of the subproblem. + solver_params : SolverParams, optional + See :meth:`Container.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) + if not isinstance(container, h5py.File): + with h5py.File(container, "r") as f: + return read_subproblem(f, k, solver_params) + f = container + _check_format(f) + sub = f["subproblems"] + _check_index(k, sub["crop"].shape[0]) + p0, p1 = (int(v) for v in sub["pixel_offset"][k : k + 2]) + s0, s1 = (int(v) for v in sub["source_offset"][k : k + 2]) + pix = sub["pixel_index"][p0:p1].astype(np.int64) + rc = _read_rows(f["pixels/consensus_rc"], pix).astype(np.int64) + y = _read_rows(f["data/y"], pix) + baseline = None + if _uses_baseline(solver_params): + g = f["baseline"] + if not g.attrs["filled"]: + raise ValueError(_NO_BASELINE) + baseline = subproblem_baseline( + _read_rows(g["values"], pix), + g["frame_lines"][()], + f["frames/lines"][()], + y[0], + solver_params, + ) + return _subproblem( + y, + _read_rows(f["data/finv"], pix), + rc, + f["sources/rc"][()], + pix, + sub["source_index"][s0:s1].astype(np.int64), + sub["crop"][k], + baseline, + ) diff --git a/src/giant_python/extraction/raster/peaks.py b/src/giant_python/extraction/raster/peaks.py index b9d7f71a..f9686537 100644 --- a/src/giant_python/extraction/raster/peaks.py +++ b/src/giant_python/extraction/raster/peaks.py @@ -1,1101 +1,1101 @@ -"""Source seeds in a multi-ROI (raster) SiLo activity image. - -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 -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 -Jacobian, at most 5000 function evaluations). This port uses -: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): -each Gaussian is evaluated only near its start pixel, every fit runs to -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. - -Coordinates follow MATLAB internally (1-based pixel centres); the public -function returns 0-based rows and columns. -""" - -from __future__ import annotations - -import numpy as np -import numpy.typing as npt -from numpy.lib.stride_tricks import sliding_window_view -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 -_MAX_FUN_EVALS = 5000 -_SQRT_PI_2 = np.sqrt(np.pi / 2) -_SQRT2 = np.sqrt(2.0) - -#: Seed fits: MATLAB's (``"matlab"``) and the local variant (``"local"``). -SEED_FITS = ("matlab", "local") -#: The final amplitude test of a fitted peak: MATLAB's (``"matlab"``) or its -#: value on its own pixel (``"pixel"``); see :func:`get_act_im_peaks`. -AMPLITUDE_RULES = ("matlab", "pixel") -# the local fit: pixels (Chebyshev) around its start pixel a Gaussian is -# evaluated at (its centre stays within 1.5 px of it, and activity-image -# peaks are narrower than a pixel); peaks within this distance of a new -# residual peak are refitted with it; tolerances of each fit; largest fit -# (parameters) solved with a dense Jacobian rather than iteratively -_LOCAL_WINDOW = 10 -_LOCAL_REFIT_RADIUS = 6.0 -_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. - - 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). - - 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) - win = sliding_window_view(padded, (3, 3)).reshape(a.shape + (9,)) - out = np.partition(win, order - 1, axis=-1)[..., order - 1] - nan_win = ndimage.maximum_filter(nan, size=3, mode="constant", cval=False) - return np.where(nan_win, np.nan, out) - - -def _edges(u: np.ndarray) -> np.ndarray: - """Pixel edges from sorted unique centres, as gaussianPeaksIntegrated. - - 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]]) - - -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, ... - """ - - def __init__(self, y: np.ndarray, x: np.ndarray) -> None: - """Precompute the pixel-edge grid of the selected pixels.""" - yu, yi = np.unique(y, return_inverse=True) - xu, xi = np.unique(x, return_inverse=True) - ye, xe = _edges(yu), _edges(xu) - self.y_lo, self.y_hi = ye[:-1][yi], ye[1:][yi] - self.x_lo, self.x_hi = xe[:-1][xi], xe[1:][xi] - - @staticmethod - 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)) - if not derivs: - return val - e_hi, e_lo = np.exp(-(u_hi**2)), np.exp(-(u_lo**2)) - d_mu = -(e_hi - e_lo) - 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) -> 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) - iy = self._axis(self.y_lo, self.y_hi, my, s, derivs) - ix = self._axis(self.x_lo, self.x_hi, mx, s, derivs) - return a, iy, ix - - def value(self, theta: np.ndarray) -> np.ndarray: - """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. - - 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)]) - - -def _eval_budget(n_par: int) -> int: - """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 - 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: 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 = { - "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) - return res.x.reshape(theta0.shape, order="F") - - -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), - ]) - 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. - - 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: 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[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: 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) - if top > th: - return explored == top - return np.zeros(explored.shape, bool) - - -def get_act_im_peaks( - act_im: np.ndarray, - peak_th: float, - exclusion_mask: np.ndarray | None = None, - min_peak_distance: int = 1, - fit: str = "matlab", - merge_px: float = 0.0, - background: tuple[float, float] | None = None, - amplitude_rule: str = "matlab", -) -> np.ndarray: - """Seed sources in a 2-D activity image (port of getActImPeaks.m). - - Parameters - ---------- - act_im : ndarray of shape (H, W) - Activity image (NaN outside the imaged pixels). - peak_th : float - Threshold in robust SDs (MAD over all finite pixels) above the median. - exclusion_mask : ndarray of bool, optional - Pixels where no peak may be placed (e.g. somata). Unlike MATLAB, a - peak whose fitted centre ends up in the mask is also dropped. - 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 - residual peak with its whole connected region, every fit stopped - 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 - fit in place. Much faster on large images; the same search - otherwise. - merge_px : float - Also reject a residual peak whose fitted centre ends closer than - this to another peak's (0: only MATLAB's rule, which rejects a peak - that does not move). An activity image's peak that falls between - 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 - 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 - 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 - 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 - 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}, 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) - min_peak_distance = max(1, int(min_peak_distance)) - buffer_se = np.ones((2 * min_peak_distance - 1,) * 2, bool) - finite = ~np.isnan(act) - if background is None: - vals = act[finite] - mu_bg = float(np.median(vals)) - sigma_bg = float(np.median(np.abs(vals - mu_bg))) / _MAD_SCALE - 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") - 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)) - if not p_tmp.any(): - return np.zeros((0, 4)) - if fit == "local": - local = _LocalFit(act, (mu_bg, sigma_bg), peak_th, excl, buffer_se) - theta = local.run(p_tmp, merge_px) - return _finish( - theta, - peak_thresh, - excl, - exclusion_mask is not None, - amplitude_rule, - mu_bg, - _pixel_bounds(finite) if amplitude_rule == "pixel" else None, - ) - - p_y, p_x = _find_f(p_tmp) - amp = act[(p_y - 1).astype(int), (p_x - 1).astype(int)] * _AMP_SCALE - theta = np.column_stack([amp, p_y, p_x, np.full(p_y.size, 0.35)]) - locs = np.column_stack([p_y, p_x]) - sel = ndimage.binary_dilation(p_tmp, np.ones((9, 9), bool)) & finite - sy, sx = _find_f(sel) - lb, ub = _bounds(locs, shape) - 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: 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: 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 - return p_im - - p_im = peak_image(theta) - buffer_mask = ndimage.binary_dilation(p_im, buffer_se) - fit_im = fit_image(theta, sy, sx, np.zeros(shape)) - res_im = (act - fit_im - mu_bg) / sigma_bg - 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) - - 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], - ]) - locs = np.vstack([locs, [r_new + 1, c_new + 1]]) - new_idx = theta.shape[0] - 1 - - labels, _ = ndimage.label(sel, structure=struct8) - lab = labels[r_new, c_new] - if lab == 0: - raise RuntimeError( - f"peak at row {r_new + 1}, col {c_new + 1} is not in any " - "connected component of the fitted pixels" - ) - sel = labels == lab - sy, sx = _find_f(sel) - iy, ix = _rounded_index(theta, shape) - to_fit = sel[iy, ix] - data = act[(sy - 1).astype(int), (sx - 1).astype(int)] - mu_bg - lb, ub = _bounds(locs[to_fit], shape) - theta[to_fit] = _fit(theta[to_fit], sy, sx, data, lb, ub) - - 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 - ) 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 - others = to_fit.copy() - others[new_idx] = False - if others.any(): - lb, ub = _bounds(locs[others], shape) - theta[others] = _fit(theta[others], sy, sx, data, lb, ub) - theta = np.delete(theta, new_idx, axis=0) - locs = np.delete(locs, new_idx, axis=0) - reject[r_new, c_new] = True - - p_im = peak_image(theta) - buffer_mask = ndimage.binary_dilation(p_im, buffer_se) - fit_im = fit_image(theta, sy, sx, fit_im) - res_im = (act - fit_im - mu_bg) / sigma_bg - 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) - - return _finish( - theta, - peak_thresh, - excl, - exclusion_mask is not None, - amplitude_rule, - mu_bg, - _pixel_bounds(finite) if amplitude_rule == "pixel" else None, - ) - - -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]) - d[idx] = np.inf - return bool(d.min() < merge_px) - - -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.) - - 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] - lo = np.arange(n) + 0.5 - hi = lo + 1.0 - used = np.flatnonzero(finite.any(axis=axis)) - if used.size: - e = _edges(used + 1.0) - lo[used], hi[used] = e[:-1], e[1:] - out.append((lo, hi)) - return out - - -def _finish( - 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`). - - 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) - else: - (ylo, yhi), (xlo, xhi) = bounds - own = theta[:, 0] * ( - _integral(ylo[iy], yhi[iy], theta[:, 1], s) - * _integral(xlo[ix], xhi[ix], theta[:, 2], s) - ) - theta = theta[~(own + mu_bg < peak_thresh)] - else: - 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) - iy, ix = _rounded_index(theta, excl.shape) - theta = theta[~excl[iy, ix]] - out = theta.copy() - out[:, 1:3] -= 1.0 - return out - - -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)) - if not derivs: - return val - e_hi, e_lo = np.exp(-(u_hi**2)), np.exp(-(u_lo**2)) - d_mu = -(e_hi - e_lo) - d_s = val / s - _SQRT2 * (u_hi * e_hi - u_lo * e_lo) - return val, d_mu, d_s - - -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 - nowhere else, so the Jacobian is sparse. Positions are parameters as - offsets from the start pixel: x holds all amplitudes, then all row - offsets, column offsets and widths. - """ - - 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 - indices the model is evaluated at. - """ - h, w = idx_im.shape - local = np.full(edges[0].size, -1, np.int64) - local[rows] = np.arange(rows.size) - p_parts, k_parts = [], [] - for k, (cy, cx) in enumerate(np.asarray(starts, int)): - win = idx_im[ - max(cy - window, 0) : min(cy + window + 1, h), - max(cx - window, 0) : min(cx + window + 1, w), - ].ravel() - win = local[win[win >= 0]] - win = win[win >= 0] - p_parts.append(win) - k_parts.append(np.full(win.size, k)) - self.p = np.concatenate(p_parts) if p_parts else np.zeros(0, int) - self.k = np.concatenate(k_parts) if k_parts else np.zeros(0, int) - self.m, self.n = rows.size, len(starts) - src = rows[self.p] - self.lo_y, self.hi_y = edges[0][src], edges[1][src] - self.lo_x, self.hi_x = edges[2][src], edges[3][src] - st = np.asarray(starts, float).reshape(-1, 2) - self.y0, self.x0 = st[:, 0] + 1.0, st[:, 1] + 1.0 - - 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 ( - x[:n][k], - (self.y0 + x[n : 2 * n])[k], - (self.x0 + x[2 * n : 3 * n])[k], - s[k], - ) - - 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: 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) - parts = ( - vy * vx, - a * dmy * vx, - a * vy * dmx, - a * (dsy * vx + vy * dsx), - ) - n = self.n - cols = [self.k + j * n for j in range(4)] - if dense: - jac = np.zeros((self.m, 4 * n)) - for c, v in zip(cols, parts): - jac[self.p, c] = v # a pixel is in a peak's window once - return jac - return sparse.csr_matrix( - ( - np.concatenate(parts), - (np.tile(self.p, 4), np.concatenate(cols)), - ), - shape=(self.m, 4 * n), - ) - - -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: 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 :], - ]) - - -def _offset_bounds(starts: np.ndarray, shape: tuple[int, ...]) -> tuple[np.ndarray, np.ndarray]: - """GetActImPeaks' bounds as offsets. - - 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), - ]) - return lb, ub - - -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 - - -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. - """ - - 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 - self.peak_th, self.excl, self.buffer_se = peak_th, excl, buffer_se - self.finite = ~np.isnan(act) - cols, rows = np.nonzero(self.finite.T) # column-major, as MATLAB - self.ry, self.rx = rows, cols - self.idx_im = np.full(self.shape, -1, np.int64) - self.idx_im[rows, cols] = np.arange(rows.size) - yu, yi = np.unique(rows + 1.0, return_inverse=True) - xu, xi = np.unique(cols + 1.0, return_inverse=True) - ye, xe = _edges(yu), _edges(xu) - 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: 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: 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: 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, - jac=lambda x: model.jacobian(x, dense), - bounds=(lb, ub), - method="trf", - tr_solver="exact" if dense else "lsmr", - x_scale="jac", - ftol=_LOCAL_TOL, - xtol=_LOCAL_TOL, - gtol=_LOCAL_TOL, - max_nfev=100 * start.size, - ) - - try: - res = run(start.size <= _LOCAL_DENSE_MAX) - except np.linalg.LinAlgError: - # LAPACK's SVD now and then fails to converge (see _fit); the - # sparse solver needs none - res = run(False) - return _from_offsets(res.x, starts) - - 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] - w = _LOCAL_WINDOW - near = ( - (starts[:, 0] >= ry.min() - w) - & (starts[:, 0] <= ry.max() + w) - & (starts[:, 1] >= rx.min() - w) - & (starts[:, 1] <= rx.max() + w) - ) - if not near.any(): - return np.zeros(rows.size) - 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: 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 - buffer_mask = ( - p_im - if self.buffer_se.shape == (1, 1) - else ndimage.binary_dilation(p_im, self.buffer_se) - ) - res_im = (self.act - fit_im - self.mu_bg) / self.sigma_bg - with np.errstate(invalid="ignore"): - new = _explore( - res_im, - buffer_mask, - self.excl, - reject, - fit_im > 1e-3, - sel, - self.peak_th, - ) - return new, sel - - 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), - ]) - 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))) - fit_im = np.zeros(self.shape) - 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) - _cover(cover, pix, 1) - reject = np.zeros(self.shape, bool) - new, sel = self.explore(fit_im, pix, cover, reject) - while new.any(): - c_n, r_n = np.nonzero(new.T) - rc = (int(r_n[0]), int(c_n[0])) - added = self._add(theta, starts, pix, sel, fit_im, rc, merge_px) - if added is None: - reject[rc] = True - else: - theta, starts, changed, old = added - _cover(cover, old, -1) - pix = np.column_stack(_rounded_index(theta, self.shape)) - _cover(cover, pix[changed], 1) - new, sel = self.explore(fit_im, pix, cover, reject) - return theta - - 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 - 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)) - comp = labels == labels[r_n, c_n] - in_comp = comp[pix[:, 0], pix[:, 1]] - 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]], - ]) - region = np.zeros(self.shape, bool) - w = _LOCAL_WINDOW - for r, c in f_starts: - region[max(r - w, 0) : r + w + 1, max(c - w, 0) : c + w + 1] = 1 - rows = self.rows_of(region & comp) - # every other peak whose window reaches these pixels is held, - # those of neighbouring regions too (model_at leaves out the rest) - held = np.flatnonzero(~free) - fixed = None - if held.size: - fixed = self.model_at(theta[held], starts[held], rows) - fitted = self.solve(f_theta, f_starts, rows, fixed) - my, mx = fitted[-1, 1], fitted[-1, 2] - if abs(my - _round(my)) < 1e-3 and abs(mx - _round(mx)) < 1e-3: - return None # MATLAB's rule: the new peak did not move - others_y = np.concatenate([theta[~free, 1], fitted[:-1, 1]]) - others_x = np.concatenate([theta[~free, 2], fitted[:-1, 2]]) - if merge_px > 0 and others_y.size: - if np.hypot(others_y - my, others_x - mx).min() < merge_px: - return None - old = pix[free] - theta = theta.copy() - theta[free] = fitted[:-1] - theta = np.vstack([theta, fitted[-1:]]) - starts = np.vstack([starts, [[r_n, c_n]]]) - changed = np.append(np.flatnonzero(free), theta.shape[0] - 1) - # 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) - return theta, starts, changed, old +"""Source seeds in a multi-ROI (raster) SiLo activity image. + +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 +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 +Jacobian, at most 5000 function evaluations). This port uses +: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): +each Gaussian is evaluated only near its start pixel, every fit runs to +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. + +Coordinates follow MATLAB internally (1-based pixel centres); the public +function returns 0-based rows and columns. +""" + +from __future__ import annotations + +import numpy as np +import numpy.typing as npt +from numpy.lib.stride_tricks import sliding_window_view +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 +_MAX_FUN_EVALS = 5000 +_SQRT_PI_2 = np.sqrt(np.pi / 2) +_SQRT2 = np.sqrt(2.0) + +#: Seed fits: MATLAB's (``"matlab"``) and the local variant (``"local"``). +SEED_FITS = ("matlab", "local") +#: The final amplitude test of a fitted peak: MATLAB's (``"matlab"``) or its +#: value on its own pixel (``"pixel"``); see :func:`get_act_im_peaks`. +AMPLITUDE_RULES = ("matlab", "pixel") +# the local fit: pixels (Chebyshev) around its start pixel a Gaussian is +# evaluated at (its centre stays within 1.5 px of it, and activity-image +# peaks are narrower than a pixel); peaks within this distance of a new +# residual peak are refitted with it; tolerances of each fit; largest fit +# (parameters) solved with a dense Jacobian rather than iteratively +_LOCAL_WINDOW = 10 +_LOCAL_REFIT_RADIUS = 6.0 +_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. + + 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). + + 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) + win = sliding_window_view(padded, (3, 3)).reshape(a.shape + (9,)) + out = np.partition(win, order - 1, axis=-1)[..., order - 1] + nan_win = ndimage.maximum_filter(nan, size=3, mode="constant", cval=False) + return np.where(nan_win, np.nan, out) + + +def _edges(u: np.ndarray) -> np.ndarray: + """Pixel edges from sorted unique centres, as gaussianPeaksIntegrated. + + 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]]) + + +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, ... + """ + + def __init__(self, y: np.ndarray, x: np.ndarray) -> None: + """Precompute the pixel-edge grid of the selected pixels.""" + yu, yi = np.unique(y, return_inverse=True) + xu, xi = np.unique(x, return_inverse=True) + ye, xe = _edges(yu), _edges(xu) + self.y_lo, self.y_hi = ye[:-1][yi], ye[1:][yi] + self.x_lo, self.x_hi = xe[:-1][xi], xe[1:][xi] + + @staticmethod + 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)) + if not derivs: + return val + e_hi, e_lo = np.exp(-(u_hi**2)), np.exp(-(u_lo**2)) + d_mu = -(e_hi - e_lo) + 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) -> 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) + iy = self._axis(self.y_lo, self.y_hi, my, s, derivs) + ix = self._axis(self.x_lo, self.x_hi, mx, s, derivs) + return a, iy, ix + + def value(self, theta: np.ndarray) -> np.ndarray: + """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. + + 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)]) + + +def _eval_budget(n_par: int) -> int: + """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 + 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: 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 = { + "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) + return res.x.reshape(theta0.shape, order="F") + + +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), + ]) + 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. + + 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: 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[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: 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) + if top > th: + return explored == top + return np.zeros(explored.shape, bool) + + +def get_act_im_peaks( + act_im: np.ndarray, + peak_th: float, + exclusion_mask: np.ndarray | None = None, + min_peak_distance: int = 1, + fit: str = "matlab", + merge_px: float = 0.0, + background: tuple[float, float] | None = None, + amplitude_rule: str = "matlab", +) -> np.ndarray: + """Seed sources in a 2-D activity image (port of getActImPeaks.m). + + Parameters + ---------- + act_im : ndarray of shape (H, W) + Activity image (NaN outside the imaged pixels). + peak_th : float + Threshold in robust SDs (MAD over all finite pixels) above the median. + exclusion_mask : ndarray of bool, optional + Pixels where no peak may be placed (e.g. somata). Unlike MATLAB, a + peak whose fitted centre ends up in the mask is also dropped. + 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 + residual peak with its whole connected region, every fit stopped + 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 + fit in place. Much faster on large images; the same search + otherwise. + merge_px : float + Also reject a residual peak whose fitted centre ends closer than + this to another peak's (0: only MATLAB's rule, which rejects a peak + that does not move). An activity image's peak that falls between + 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 + 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 + 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 + 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 + 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}, 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) + min_peak_distance = max(1, int(min_peak_distance)) + buffer_se = np.ones((2 * min_peak_distance - 1,) * 2, bool) + finite = ~np.isnan(act) + if background is None: + vals = act[finite] + mu_bg = float(np.median(vals)) + sigma_bg = float(np.median(np.abs(vals - mu_bg))) / _MAD_SCALE + 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") + 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)) + if not p_tmp.any(): + return np.zeros((0, 4)) + if fit == "local": + local = _LocalFit(act, (mu_bg, sigma_bg), peak_th, excl, buffer_se) + theta = local.run(p_tmp, merge_px) + return _finish( + theta, + peak_thresh, + excl, + exclusion_mask is not None, + amplitude_rule, + mu_bg, + _pixel_bounds(finite) if amplitude_rule == "pixel" else None, + ) + + p_y, p_x = _find_f(p_tmp) + amp = act[(p_y - 1).astype(int), (p_x - 1).astype(int)] * _AMP_SCALE + theta = np.column_stack([amp, p_y, p_x, np.full(p_y.size, 0.35)]) + locs = np.column_stack([p_y, p_x]) + sel = ndimage.binary_dilation(p_tmp, np.ones((9, 9), bool)) & finite + sy, sx = _find_f(sel) + lb, ub = _bounds(locs, shape) + 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: 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: 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 + return p_im + + p_im = peak_image(theta) + buffer_mask = ndimage.binary_dilation(p_im, buffer_se) + fit_im = fit_image(theta, sy, sx, np.zeros(shape)) + res_im = (act - fit_im - mu_bg) / sigma_bg + 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) + + 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], + ]) + locs = np.vstack([locs, [r_new + 1, c_new + 1]]) + new_idx = theta.shape[0] - 1 + + labels, _ = ndimage.label(sel, structure=struct8) + lab = labels[r_new, c_new] + if lab == 0: + raise RuntimeError( + f"peak at row {r_new + 1}, col {c_new + 1} is not in any " + "connected component of the fitted pixels" + ) + sel = labels == lab + sy, sx = _find_f(sel) + iy, ix = _rounded_index(theta, shape) + to_fit = sel[iy, ix] + data = act[(sy - 1).astype(int), (sx - 1).astype(int)] - mu_bg + lb, ub = _bounds(locs[to_fit], shape) + theta[to_fit] = _fit(theta[to_fit], sy, sx, data, lb, ub) + + 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 + ) 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 + others = to_fit.copy() + others[new_idx] = False + if others.any(): + lb, ub = _bounds(locs[others], shape) + theta[others] = _fit(theta[others], sy, sx, data, lb, ub) + theta = np.delete(theta, new_idx, axis=0) + locs = np.delete(locs, new_idx, axis=0) + reject[r_new, c_new] = True + + p_im = peak_image(theta) + buffer_mask = ndimage.binary_dilation(p_im, buffer_se) + fit_im = fit_image(theta, sy, sx, fit_im) + res_im = (act - fit_im - mu_bg) / sigma_bg + 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) + + return _finish( + theta, + peak_thresh, + excl, + exclusion_mask is not None, + amplitude_rule, + mu_bg, + _pixel_bounds(finite) if amplitude_rule == "pixel" else None, + ) + + +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]) + d[idx] = np.inf + return bool(d.min() < merge_px) + + +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.) + + 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] + lo = np.arange(n) + 0.5 + hi = lo + 1.0 + used = np.flatnonzero(finite.any(axis=axis)) + if used.size: + e = _edges(used + 1.0) + lo[used], hi[used] = e[:-1], e[1:] + out.append((lo, hi)) + return out + + +def _finish( + 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`). + + 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) + else: + (ylo, yhi), (xlo, xhi) = bounds + own = theta[:, 0] * ( + _integral(ylo[iy], yhi[iy], theta[:, 1], s) + * _integral(xlo[ix], xhi[ix], theta[:, 2], s) + ) + theta = theta[~(own + mu_bg < peak_thresh)] + else: + 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) + iy, ix = _rounded_index(theta, excl.shape) + theta = theta[~excl[iy, ix]] + out = theta.copy() + out[:, 1:3] -= 1.0 + return out + + +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)) + if not derivs: + return val + e_hi, e_lo = np.exp(-(u_hi**2)), np.exp(-(u_lo**2)) + d_mu = -(e_hi - e_lo) + d_s = val / s - _SQRT2 * (u_hi * e_hi - u_lo * e_lo) + return val, d_mu, d_s + + +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 + nowhere else, so the Jacobian is sparse. Positions are parameters as + offsets from the start pixel: x holds all amplitudes, then all row + offsets, column offsets and widths. + """ + + 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 + indices the model is evaluated at. + """ + h, w = idx_im.shape + local = np.full(edges[0].size, -1, np.int64) + local[rows] = np.arange(rows.size) + p_parts, k_parts = [], [] + for k, (cy, cx) in enumerate(np.asarray(starts, int)): + win = idx_im[ + max(cy - window, 0) : min(cy + window + 1, h), + max(cx - window, 0) : min(cx + window + 1, w), + ].ravel() + win = local[win[win >= 0]] + win = win[win >= 0] + p_parts.append(win) + k_parts.append(np.full(win.size, k)) + self.p = np.concatenate(p_parts) if p_parts else np.zeros(0, int) + self.k = np.concatenate(k_parts) if k_parts else np.zeros(0, int) + self.m, self.n = rows.size, len(starts) + src = rows[self.p] + self.lo_y, self.hi_y = edges[0][src], edges[1][src] + self.lo_x, self.hi_x = edges[2][src], edges[3][src] + st = np.asarray(starts, float).reshape(-1, 2) + self.y0, self.x0 = st[:, 0] + 1.0, st[:, 1] + 1.0 + + 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 ( + x[:n][k], + (self.y0 + x[n : 2 * n])[k], + (self.x0 + x[2 * n : 3 * n])[k], + s[k], + ) + + 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: 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) + parts = ( + vy * vx, + a * dmy * vx, + a * vy * dmx, + a * (dsy * vx + vy * dsx), + ) + n = self.n + cols = [self.k + j * n for j in range(4)] + if dense: + jac = np.zeros((self.m, 4 * n)) + for c, v in zip(cols, parts): + jac[self.p, c] = v # a pixel is in a peak's window once + return jac + return sparse.csr_matrix( + ( + np.concatenate(parts), + (np.tile(self.p, 4), np.concatenate(cols)), + ), + shape=(self.m, 4 * n), + ) + + +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: 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 :], + ]) + + +def _offset_bounds(starts: np.ndarray, shape: tuple[int, ...]) -> tuple[np.ndarray, np.ndarray]: + """GetActImPeaks' bounds as offsets. + + 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), + ]) + return lb, ub + + +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 + + +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. + """ + + 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 + self.peak_th, self.excl, self.buffer_se = peak_th, excl, buffer_se + self.finite = ~np.isnan(act) + cols, rows = np.nonzero(self.finite.T) # column-major, as MATLAB + self.ry, self.rx = rows, cols + self.idx_im = np.full(self.shape, -1, np.int64) + self.idx_im[rows, cols] = np.arange(rows.size) + yu, yi = np.unique(rows + 1.0, return_inverse=True) + xu, xi = np.unique(cols + 1.0, return_inverse=True) + ye, xe = _edges(yu), _edges(xu) + 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: 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: 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: 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, + jac=lambda x: model.jacobian(x, dense), + bounds=(lb, ub), + method="trf", + tr_solver="exact" if dense else "lsmr", + x_scale="jac", + ftol=_LOCAL_TOL, + xtol=_LOCAL_TOL, + gtol=_LOCAL_TOL, + max_nfev=100 * start.size, + ) + + try: + res = run(start.size <= _LOCAL_DENSE_MAX) + except np.linalg.LinAlgError: + # LAPACK's SVD now and then fails to converge (see _fit); the + # sparse solver needs none + res = run(False) + return _from_offsets(res.x, starts) + + 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] + w = _LOCAL_WINDOW + near = ( + (starts[:, 0] >= ry.min() - w) + & (starts[:, 0] <= ry.max() + w) + & (starts[:, 1] >= rx.min() - w) + & (starts[:, 1] <= rx.max() + w) + ) + if not near.any(): + return np.zeros(rows.size) + 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: 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 + buffer_mask = ( + p_im + if self.buffer_se.shape == (1, 1) + else ndimage.binary_dilation(p_im, self.buffer_se) + ) + res_im = (self.act - fit_im - self.mu_bg) / self.sigma_bg + with np.errstate(invalid="ignore"): + new = _explore( + res_im, + buffer_mask, + self.excl, + reject, + fit_im > 1e-3, + sel, + self.peak_th, + ) + return new, sel + + 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), + ]) + 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))) + fit_im = np.zeros(self.shape) + 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) + _cover(cover, pix, 1) + reject = np.zeros(self.shape, bool) + new, sel = self.explore(fit_im, pix, cover, reject) + while new.any(): + c_n, r_n = np.nonzero(new.T) + rc = (int(r_n[0]), int(c_n[0])) + added = self._add(theta, starts, pix, sel, fit_im, rc, merge_px) + if added is None: + reject[rc] = True + else: + theta, starts, changed, old = added + _cover(cover, old, -1) + pix = np.column_stack(_rounded_index(theta, self.shape)) + _cover(cover, pix[changed], 1) + new, sel = self.explore(fit_im, pix, cover, reject) + return theta + + 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 + 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)) + comp = labels == labels[r_n, c_n] + in_comp = comp[pix[:, 0], pix[:, 1]] + 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]], + ]) + region = np.zeros(self.shape, bool) + w = _LOCAL_WINDOW + for r, c in f_starts: + region[max(r - w, 0) : r + w + 1, max(c - w, 0) : c + w + 1] = 1 + rows = self.rows_of(region & comp) + # every other peak whose window reaches these pixels is held, + # those of neighbouring regions too (model_at leaves out the rest) + held = np.flatnonzero(~free) + fixed = None + if held.size: + fixed = self.model_at(theta[held], starts[held], rows) + fitted = self.solve(f_theta, f_starts, rows, fixed) + my, mx = fitted[-1, 1], fitted[-1, 2] + if abs(my - _round(my)) < 1e-3 and abs(mx - _round(mx)) < 1e-3: + return None # MATLAB's rule: the new peak did not move + others_y = np.concatenate([theta[~free, 1], fitted[:-1, 1]]) + others_x = np.concatenate([theta[~free, 2], fitted[:-1, 2]]) + if merge_px > 0 and others_y.size: + if np.hypot(others_y - my, others_x - mx).min() < merge_px: + return None + old = pix[free] + theta = theta.copy() + theta[free] = fitted[:-1] + theta = np.vstack([theta, fitted[-1:]]) + starts = np.vstack([starts, [[r_n, c_n]]]) + changed = np.append(np.flatnonzero(free), theta.shape[0] - 1) + # 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) + return theta, starts, changed, old diff --git a/src/giant_python/extraction/raster/refit_test.py b/src/giant_python/extraction/raster/refit_test.py index 8d468921..d45c575a 100644 --- a/src/giant_python/extraction/raster/refit_test.py +++ b/src/giant_python/extraction/raster/refit_test.py @@ -1,610 +1,610 @@ -"""Ground-truth refit test of the subproblem solver on real subproblems. - -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 - T and variance F T. -3. Fit Z again and compare the refit with the truth. - -Amplitudes are in the solver's normalized units at each source's peak -pixel. Events are the peaks of each source's true X (see -:func:`find_events`); an event is found when the refit's activity mass in -its window is above a quarter of the truth's. - -Limits, as in MATLAB: the truth uses the fit's own footprints and kernel, -so the test cannot show a footprint-width or kinetics mismatch; noise is -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`, -: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: -: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 -from scipy import ndimage - -from .solver import ( - SolverOptions, - SubproblemResult, - conv_same, - solve_subproblems, -) -from .solver_baseline import source_f0 -from .solver_setup import SolverParams, Subproblem, sel_coords - -SIZE_EDGES = (0.0, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, math.inf) - - -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 - closely is skipped too), not within 5 frames of the start or - 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): - return np.zeros(0, dtype=np.int64) - mid = x0[1:-1] - is_peak = (mid > 0.02 * x0.max()) & (mid >= x0[:-2]) & (mid > x0[2:]) - pk = np.nonzero(is_peak)[0] + 2 # MATLAB's one-based frames - pk = pk[(pk > 5) & (pk < n - lag - 3)] - keep = np.ones(pk.size, dtype=bool) - keep[1:] = np.diff(pk) >= lag - return pk[keep] - 1 - - -@dataclass -class RefitTruth: - """The truth of one subproblem's refit test and the redrawn data. - - Attributes - ---------- - h : ndarray of shape (pixels, sources) - x : ndarray of shape (sources, frames) - True activity (events convolved with the kernel, scaled). - b : ndarray of shape (pixels, frames) - f0 : ndarray of shape (sources, frames) - z : ndarray of shape (pixels, frames) - 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). - """ - - h: np.ndarray - x: np.ndarray - b: np.ndarray - f0: np.ndarray - z: np.ndarray - 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: 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. - - 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)" - ) - f = np.asarray(sub.finv, dtype=np.float64) - x = conv_same(truth_scale * truth.events[0], params.k) - b = truth.baseline[0] - f0 = truth.f0[0] - b_fit = None - if truth_baseline is not None: - b_fit = b - b = np.asarray( - truth_baseline(b.copy(), sub, baseline_rng or np.random.default_rng()), - dtype=np.float64, - ) - if b.shape != b_fit.shape: - raise ValueError("truth_baseline changed the baseline's shape") - f0 = source_f0(truth.footprints, b) - t = np.maximum(b + truth.footprints @ x, 0) - z = f * rng.poisson(t / f) - return RefitTruth(h=truth.footprints, x=x, b=b, f0=f0, z=z, b_fit=b_fit) - - -def score_refit( - truth: RefitTruth, - x1: np.ndarray, - f01: np.ndarray, - ls1: np.ndarray, - tau_frames: float, -) -> tuple[list[dict], list[dict]]: - """Compare a refit with the truth (step 3), per source and per event. - - Parameters - ---------- - truth : RefitTruth - x1, f01, ls1 : ndarray of shape (sources, frames) - 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. - - 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 - baseline under the footprint, per pixel and frame). - events : list of dict - source, size (peak-pixel amplitude), true_mass, - refit_mass and found. - """ - lag = math.ceil(2.5 * tau_frames) - peak_h = truth.h.max(0) - b_mean = truth.b.mean(1) - sources, events = [], [] - nan = float("nan") - for s in range(truth.x.shape[0]): - x0, xr = truth.x[s], x1[s] - active = x0 > 0.2 * x0.max() - mass = float(x0.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()) - row["ls_recovered"] = float(ls1[s].sum() / mass) - 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()) - 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({ - "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: 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). - - 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 itertools.pairwise(edges): - m = (size >= lo) & (size < hi) - if not m.any(): - continue - f = m & found - 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. - - 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. - - 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: 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 { - "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 -class RefitResult: - """Results of :func:`refit_test`. - - Attributes - ---------- - sources, events : list of dict - Rows of :func:`score_refit`, with the subproblem's index added. - summary : dict - :func:`summarize` of them. - by_size : list of dict - :func:`by_size` of the events. - truths : list of RefitTruth - Each subproblem's truth and redrawn data, if kept. - """ - - sources: list - events: list - summary: dict - by_size: list - truths: list - - -def refit_test( - subs: list[Subproblem], - params: SolverParams, - options: SolverOptions | None = None, - *, - refit_params: SolverParams | None = None, - truth_scale: float = 1.0, - seed: int = 0, - keep_truths: bool = False, - fits: list[SubproblemResult] | None = None, - truth_baseline: TruthBaseline | None = None, - given_baseline: GivenBaseline | None = None, -) -> RefitResult: - """Run the refit test on subproblems. - - Parameters - ---------- - subs : list of Subproblem - Their activity channel is used; a second channel is left out. - params : SolverParams - Parameters of the truth fit. - options : SolverOptions, optional - refit_params : SolverParams, optional - Parameters of the refit, if they differ from the truth's. - truth_scale : float - Multiplies the true activity. - seed : int - 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. - truth_baseline : callable, optional - 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)). - 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 - 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 - 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 - one = [replace(sb, y=sb.y[:1], _coords=None) for sb in subs] - if fits is None: - fits = solve_subproblems(one, params, opt) - elif len(fits) != len(one): - raise ValueError(f"{len(fits)} fits for {len(one)} subproblems") - truths = [ - draw_refit_data( - sb, - fit, - params, - np.random.default_rng(seed + i), - truth_scale, - truth_baseline, - np.random.default_rng((seed + i, 1)), - ) - for i, (sb, fit) in enumerate(zip(one, fits)) - ] - if given_baseline is None and truth_baseline is not None: - given_baseline = fit_baseline_given - # the subproblems' own external baselines, unless replaced - given = [sb.baseline for sb in one] - if given_baseline is not None: - given = [ - np.asarray( - given_baseline(tr, sb, np.random.default_rng((seed + i, 2))), - dtype=np.float64, - ) - 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) - ] - refits = solve_subproblems(again, refit_params, opt) - sources, events = [], [] - for i, (tr, fit) in enumerate(zip(truths, refits)): - x1 = conv_same(fit.events[0], refit_params.k) - src, ev = score_refit(tr, x1, fit.f0[0], fit.ls[0], params.tau_frames) - sources += [dict(subproblem=i, **row) for row in src] - events += [dict(subproblem=i, **row) for row in ev] - return RefitResult( - sources=sources, - events=events, - summary=summarize(sources, events), - by_size=by_size(events), - truths=truths if keep_truths else [], - ) - - -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) -> 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. - - Returns - ------- - np.ndarray - The true baseline times 1 + scale. - """ - return truth.b * (1 + scale) - - return given - - -def drift_error(drift: float) -> GivenBaseline: - """given_baseline: the true baseline times a linear drift. - - 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, :] - - return given - - -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). - - 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) - ends[: int(frames)] = True - ends[max(n - int(frames), 0) :] = True - b[:, ends] *= 1 + error - return b - - return given - - -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 - 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: 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 - norm = ndimage.gaussian_filter(mask, sigma, mode="constant") - 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") - return blurred[rows, cols] / norm[:, None] - - return given - - -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 - 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: 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 - course = np.convolve(noise, kern, mode="valid") - course /= np.sqrt(np.mean(course**2)) - return b * (1 + rms * course)[None, :] - - return changed +"""Ground-truth refit test of the subproblem solver on real subproblems. + +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 + T and variance F T. +3. Fit Z again and compare the refit with the truth. + +Amplitudes are in the solver's normalized units at each source's peak +pixel. Events are the peaks of each source's true X (see +:func:`find_events`); an event is found when the refit's activity mass in +its window is above a quarter of the truth's. + +Limits, as in MATLAB: the truth uses the fit's own footprints and kernel, +so the test cannot show a footprint-width or kinetics mismatch; noise is +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`, +: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: +: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 +from scipy import ndimage + +from .solver import ( + SolverOptions, + SubproblemResult, + conv_same, + solve_subproblems, +) +from .solver_baseline import source_f0 +from .solver_setup import SolverParams, Subproblem, sel_coords + +SIZE_EDGES = (0.0, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, math.inf) + + +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 + closely is skipped too), not within 5 frames of the start or + 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): + return np.zeros(0, dtype=np.int64) + mid = x0[1:-1] + is_peak = (mid > 0.02 * x0.max()) & (mid >= x0[:-2]) & (mid > x0[2:]) + pk = np.nonzero(is_peak)[0] + 2 # MATLAB's one-based frames + pk = pk[(pk > 5) & (pk < n - lag - 3)] + keep = np.ones(pk.size, dtype=bool) + keep[1:] = np.diff(pk) >= lag + return pk[keep] - 1 + + +@dataclass +class RefitTruth: + """The truth of one subproblem's refit test and the redrawn data. + + Attributes + ---------- + h : ndarray of shape (pixels, sources) + x : ndarray of shape (sources, frames) + True activity (events convolved with the kernel, scaled). + b : ndarray of shape (pixels, frames) + f0 : ndarray of shape (sources, frames) + z : ndarray of shape (pixels, frames) + 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). + """ + + h: np.ndarray + x: np.ndarray + b: np.ndarray + f0: np.ndarray + z: np.ndarray + 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: 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. + + 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)" + ) + f = np.asarray(sub.finv, dtype=np.float64) + x = conv_same(truth_scale * truth.events[0], params.k) + b = truth.baseline[0] + f0 = truth.f0[0] + b_fit = None + if truth_baseline is not None: + b_fit = b + b = np.asarray( + truth_baseline(b.copy(), sub, baseline_rng or np.random.default_rng()), + dtype=np.float64, + ) + if b.shape != b_fit.shape: + raise ValueError("truth_baseline changed the baseline's shape") + f0 = source_f0(truth.footprints, b) + t = np.maximum(b + truth.footprints @ x, 0) + z = f * rng.poisson(t / f) + return RefitTruth(h=truth.footprints, x=x, b=b, f0=f0, z=z, b_fit=b_fit) + + +def score_refit( + truth: RefitTruth, + x1: np.ndarray, + f01: np.ndarray, + ls1: np.ndarray, + tau_frames: float, +) -> tuple[list[dict], list[dict]]: + """Compare a refit with the truth (step 3), per source and per event. + + Parameters + ---------- + truth : RefitTruth + x1, f01, ls1 : ndarray of shape (sources, frames) + 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. + + 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 + baseline under the footprint, per pixel and frame). + events : list of dict + source, size (peak-pixel amplitude), true_mass, + refit_mass and found. + """ + lag = math.ceil(2.5 * tau_frames) + peak_h = truth.h.max(0) + b_mean = truth.b.mean(1) + sources, events = [], [] + nan = float("nan") + for s in range(truth.x.shape[0]): + x0, xr = truth.x[s], x1[s] + active = x0 > 0.2 * x0.max() + mass = float(x0.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()) + row["ls_recovered"] = float(ls1[s].sum() / mass) + 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()) + 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({ + "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: 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). + + 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 itertools.pairwise(edges): + m = (size >= lo) & (size < hi) + if not m.any(): + continue + f = m & found + 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. + + 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. + + 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: 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 { + "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 +class RefitResult: + """Results of :func:`refit_test`. + + Attributes + ---------- + sources, events : list of dict + Rows of :func:`score_refit`, with the subproblem's index added. + summary : dict + :func:`summarize` of them. + by_size : list of dict + :func:`by_size` of the events. + truths : list of RefitTruth + Each subproblem's truth and redrawn data, if kept. + """ + + sources: list + events: list + summary: dict + by_size: list + truths: list + + +def refit_test( + subs: list[Subproblem], + params: SolverParams, + options: SolverOptions | None = None, + *, + refit_params: SolverParams | None = None, + truth_scale: float = 1.0, + seed: int = 0, + keep_truths: bool = False, + fits: list[SubproblemResult] | None = None, + truth_baseline: TruthBaseline | None = None, + given_baseline: GivenBaseline | None = None, +) -> RefitResult: + """Run the refit test on subproblems. + + Parameters + ---------- + subs : list of Subproblem + Their activity channel is used; a second channel is left out. + params : SolverParams + Parameters of the truth fit. + options : SolverOptions, optional + refit_params : SolverParams, optional + Parameters of the refit, if they differ from the truth's. + truth_scale : float + Multiplies the true activity. + seed : int + 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. + truth_baseline : callable, optional + 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)). + 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 + 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 + 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 + one = [replace(sb, y=sb.y[:1], _coords=None) for sb in subs] + if fits is None: + fits = solve_subproblems(one, params, opt) + elif len(fits) != len(one): + raise ValueError(f"{len(fits)} fits for {len(one)} subproblems") + truths = [ + draw_refit_data( + sb, + fit, + params, + np.random.default_rng(seed + i), + truth_scale, + truth_baseline, + np.random.default_rng((seed + i, 1)), + ) + for i, (sb, fit) in enumerate(zip(one, fits)) + ] + if given_baseline is None and truth_baseline is not None: + given_baseline = fit_baseline_given + # the subproblems' own external baselines, unless replaced + given = [sb.baseline for sb in one] + if given_baseline is not None: + given = [ + np.asarray( + given_baseline(tr, sb, np.random.default_rng((seed + i, 2))), + dtype=np.float64, + ) + 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) + ] + refits = solve_subproblems(again, refit_params, opt) + sources, events = [], [] + for i, (tr, fit) in enumerate(zip(truths, refits)): + x1 = conv_same(fit.events[0], refit_params.k) + src, ev = score_refit(tr, x1, fit.f0[0], fit.ls[0], params.tau_frames) + sources += [dict(subproblem=i, **row) for row in src] + events += [dict(subproblem=i, **row) for row in ev] + return RefitResult( + sources=sources, + events=events, + summary=summarize(sources, events), + by_size=by_size(events), + truths=truths if keep_truths else [], + ) + + +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) -> 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. + + Returns + ------- + np.ndarray + The true baseline times 1 + scale. + """ + return truth.b * (1 + scale) + + return given + + +def drift_error(drift: float) -> GivenBaseline: + """given_baseline: the true baseline times a linear drift. + + 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, :] + + return given + + +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). + + 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) + ends[: int(frames)] = True + ends[max(n - int(frames), 0) :] = True + b[:, ends] *= 1 + error + return b + + return given + + +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 + 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: 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 + norm = ndimage.gaussian_filter(mask, sigma, mode="constant") + 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") + return blurred[rows, cols] / norm[:, None] + + return given + + +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 + 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: 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 + course = np.convolve(noise, kern, mode="valid") + course /= np.sqrt(np.mean(course**2)) + return b * (1 + rms * course)[None, :] + + return changed diff --git a/src/giant_python/extraction/raster/spots.py b/src/giant_python/extraction/raster/spots.py index 4abceefb..4cc39bb5 100644 --- a/src/giant_python/extraction/raster/spots.py +++ b/src/giant_python/extraction/raster/spots.py @@ -1,691 +1,691 @@ -"""Spots: sets of nearby sources that may represent one object. - -SILo can give one spot of the activity image several sources. On injected -ground truth (GIAnT-Python#51) this happens for three kinds of objects: - -* one compact source cut in two: the parts share their events (their event - trains correlate); -* a continuum, an object whose events occur at varying positions (for - example over a spine head or a stretch of dendrite): the parts fire - independently, and the events' positions form one cloud wider than a - point source's; -* two sources close together that fire independently: from about 2 px - 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 -tests, without changing the sources or their traces: - -1. the correlation of the sources' event trains (:func:`event_train_corr`); -2. the event test: single events of the spot localized in the registered - 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 - 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 - 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 - 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 - 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; - an analysis may merge their traces; -* 'undecided': too few strong events, or too little power. -""" - -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") -_MAD = 1.4826 - -# position error model of single events, calibrated on injected point -# sources (GFP session 847983, events with SNR >= 6): SD^2 = (k * fit SE)^2 -# + floor^2 per axis -ERROR_K = 0.60 -ERROR_FLOOR_PX = 0.40 -# the broad component that takes mislocalized events (px^2) -OUTLIER_VAR = 4.0 -MIN_FIT_EVENTS = 5 # fewest events a cloud's mixture fit takes - - -@dataclass -class SpotSettings: - """Settings of the spot annotation. - - Attributes - ---------- - link_px : float - Sources whose centroids lie within this distance belong to one spot - (single linkage). - split_corr : float - Event-train correlation from which a spot's sources count as one - source cut in two. - min_snr : float - Events of the event test: peaks of the spot's two-frame trace at - least this many robust SDs high. - min_events : int - Events needed for the event test. - min_power : float - Power needed to call a spot with one event cluster a continuum. - compact_px : float - Intrinsic major SD (px) up to which one event cloud counts as one - point source (injected point sources: 0.23-0.41 px; continua of - radius 1-1.5 px: 0.45-0.8 px). - bic_margin : float - BIC difference that separate clusters need (6: strong evidence; - injected single sources and continua never came below +6). - trim_px : float - Events farther than this beyond the spot's sources are left out. - sigma_px : float - Width of the Gaussian fitted to each event's image. - n_sim : int - Simulations of the power estimate. - """ - - link_px: float = 2.5 - split_corr: float = 0.3 - min_snr: float = 6.0 - min_events: int = 15 - min_power: float = 0.8 - compact_px: float = 0.45 - bic_margin: float = 6.0 - trim_px: float = 1.5 - sigma_px: float = 1.4 - n_sim: int = 20 - - def to_dict(self) -> 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. - - 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 - - rc = np.asarray(rc, dtype=np.float64).reshape(-1, 2) - n = rc.shape[0] - lab = -np.ones(n, dtype=np.int64) - ok = np.flatnonzero(np.isfinite(rc).all(1)) - g = 0 - if ok.size: - pairs = cKDTree(rc[ok]).query_pairs(link_px, output_type="ndarray") - adj = coo_matrix( - (np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), - shape=(ok.size, ok.size), - ) - _, comp = connected_components(adj, directed=False) - # number the groups in the order of their first member - _, first = np.unique(comp, return_index=True) - order = np.argsort(first, kind="stable") - rank = np.empty_like(order) - rank[order] = np.arange(order.size) - lab[ok] = rank[comp] - g = order.size - for i in np.flatnonzero(lab < 0): # sources without a position: alone - lab[i] = g - g += 1 - return lab - - -def event_train_corr(events: np.ndarray) -> float: - """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") - k = np.ones(3) - sm = np.stack([np.convolve(v, k, mode="same") for v in ev]) - 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") - - -def robust_sd(x: np.ndarray, axis: int | None = None) -> np.ndarray | float: - """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: 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: 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 - - a0 = max(float(np.nanmax(y) - np.nanmedian(y)), 1e-6) - 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)) - except ValueError: - return None - dof = max(int(ok.sum()) - 4, 1) - chi2 = float(np.sum(f.fun**2)) / dof - try: - cov = np.linalg.inv(f.jac.T @ f.jac) * max(chi2, 1.0) - se = np.sqrt(np.clip(np.diag(cov), 0, None)) - except np.linalg.LinAlgError: - return None - return f.x[1], f.x[2], se[1], se[2], f.x[0] - - -def localize_events( - x: np.ndarray, - rr: np.ndarray, - cc: np.ndarray, - center: tuple, - radius: float, - settings: SpotSettings, - weight_sd: float = 1.5, - n_frames: int = 2, -) -> dict: - """Single events of a spot in one trial, in the trial's frame. - - Parameters - ---------- - x : ndarray of shape (frames, pixels) - The movie minus its baseline at the spot's pixels (NaN at discarded - frames and missing samples). - rr, cc : ndarray of shape (pixels,) - The pixels' rows and columns in the trial's registered image. - center : (float, float) - The spot's centre in the trial's image. - radius : float - Fitted positions are kept within this distance of the centre. - settings : SpotSettings - weight_sd, n_frames - The spot trace's Gaussian weights (px) and the frames of each - event's image. - - Returns - ------- - 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) - - -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: - return {k: np.asarray(v) for k, v in out.items()} - 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[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)) - sd = robust_sd(y) - if not np.isfinite(sd) or sd <= 0: - 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 - ) - taken: list = [] - for i in peak[np.argsort(-z[peak], kind="stable")]: - if all(abs(i - j) >= 3 for j in taken): - taken.append(int(i)) - xs = sum(x[k : k + n] for k in range(n_frames)) - px_sd = robust_sd(xs, axis=0) / 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) - if fit is None: - continue - r, c, se_r, se_c, _ = fit - for k, v in zip(out, (i, float(z[i]), r, c, se_r, se_c)): - out[k].append(v) - return {k: np.asarray(v, dtype=np.float64) for k, v in out.items()} - - -# ------------------------------------------------------------ mixture fit - - -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) - inv[:, 0, 0], inv[:, 1, 1] = T[:, 1, 1] / det, T[:, 0, 0] / det - inv[:, 0, 1], inv[:, 1, 0] = -T[:, 0, 1] / det, -T[:, 1, 0] / det - m = np.einsum("ni,nij,nj->n", d, inv, d) - return -0.5 * (m + np.log(det) + 2 * np.log(2 * np.pi)), inv - - -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 - S = np.zeros((se.shape[0], 2, 2)) - S[:, 0, 0], S[:, 1, 1] = v[:, 0], v[:, 1] - return S - - -@dataclass -class MixtureFit: - """A K-component fit of event positions (plus the outlier component). - - Attributes - ---------- - K : int - loglik, bic : float - weights : ndarray (K,) - means : ndarray (K, 2) - covs : ndarray (K, 2, 2) - Each component's intrinsic covariance (the events' errors removed). - outlier : float - The outlier component's weight. - """ - - K: int - loglik: float - bic: float - weights: np.ndarray - means: np.ndarray - covs: np.ndarray - outlier: float = 0.0 - - -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) - best = None - for _ in range(n_init): - mu = x[rng.choice(n, K, replace=False)].copy() - V = np.repeat(np.cov(x.T)[None] / K + w * np.eye(2), K, 0) - al = np.full(K, 0.9 / K) - a_out = 0.1 - ll_old = -np.inf - for _ in range(iters): - lq = np.empty((n, K + 1)) - invs = [] - for k in range(K): - lq[:, k], inv = _logn(x, mu[k], V[k] + S) - lq[:, k] += np.log(max(al[k], 1e-300)) - invs.append(inv) - lq[:, K] = lo_out + np.log(max(a_out, 1e-300)) - mx = lq.max(1, keepdims=True) - ll = float(np.sum(mx[:, 0] + np.log(np.exp(lq - mx).sum(1)))) - q = np.exp(lq - mx) - q /= q.sum(1, keepdims=True) - a_out = float(q[:, K].mean()) - for k in range(K): - qk = q[:, k] - sq = qk.sum() - if sq < 1e-9: - continue - VTi = np.einsum("ij,njk->nik", V[k], invs[k]) - b = mu[k] + np.einsum("nij,nj->ni", VTi, x - mu[k]) - B = V[k] - np.einsum("nij,jk->nik", VTi, V[k]) - al[k] = sq / n - 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) - ) / sq + w * np.eye(2) - if ll - ll_old < 1e-6 * abs(ll): - break - ll_old = ll - if best is None or ll > best[0]: - best = (ll, al.copy(), mu.copy(), V.copy(), a_out) - return best - - -def mixture_fit( - 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 - ---------- - x : ndarray (n, 2) - Event positions. - S : ndarray (n, 2, 2) - Their error covariances (:func:`error_cov`). - center : (float, float) - 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) - 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)) - 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: 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: 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") - rng = np.random.default_rng(seed) - n = S.shape[0] - L = np.linalg.cholesky(S) - hits = 0 - for _ in range(n_sim): - 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 - ) - best, _ = mixture_fit( - x, - S, - center, - kmax=2, - n_init=3, - iters=150, - seed=int(rng.integers(1 << 30)), - bic_margin=bic_margin, - ) - hits += best.K >= 2 - return hits / n_sim - - -@dataclass -class SpotResult: - """One spot's annotation. - - Attributes - ---------- - sources : ndarray of int - The spot's sources (zero-based indices of the kept sources). - label : str - One of :data:`LABELS`. - event_corr : float - n_events : int - Events of the event test (0 when it did not run). - K : int - Components of the event test's fit (0 when it did not run). - power : float - Power to see the sources as separate points (NaN when not run). - cloud_major, cloud_minor : float - Intrinsic SDs (px) of the one-component fit along its axes. - bic_gain : float - BIC of one component minus the lowest with more (:func:`bic_gain`). - center : ndarray (2,) - """ - - sources: np.ndarray - label: str - event_corr: float = float("nan") - n_events: int = 0 - K: int = 0 - power: float = float("nan") - cloud_major: float = float("nan") - cloud_minor: float = float("nan") - bic_gain: float = float("nan") - 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: - """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) - ) - 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]) - out.update( - K=int(best.K), - bic_gain=bic_gain(fits), - cloud_major=float(np.sqrt(max(w[1], 0))), - cloud_minor=float(np.sqrt(max(w[0], 0))), - ) - if best.K == 1: - out["power"] = separation_power( - src, - S, - fits[0].outlier, - center, - settings.n_sim, - seed, - settings.bic_margin, - ) - return out - - -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) - if k >= 2: - return "close_pair" - if np.isfinite(event_corr) and event_corr >= settings.split_corr: - return "merge" - if k == 1 and test.get("cloud_major", np.inf) <= settings.compact_px: - return "merge" - if k == 1 and test.get("power", 0.0) >= settings.min_power: - return "continuum" - return "undecided" +"""Spots: sets of nearby sources that may represent one object. + +SILo can give one spot of the activity image several sources. On injected +ground truth (GIAnT-Python#51) this happens for three kinds of objects: + +* one compact source cut in two: the parts share their events (their event + trains correlate); +* a continuum, an object whose events occur at varying positions (for + example over a spine head or a stretch of dendrite): the parts fire + independently, and the events' positions form one cloud wider than a + point source's; +* two sources close together that fire independently: from about 2 px + 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 +tests, without changing the sources or their traces: + +1. the correlation of the sources' event trains (:func:`event_train_corr`); +2. the event test: single events of the spot localized in the registered + 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 + 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 + 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 + 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 + 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; + an analysis may merge their traces; +* 'undecided': too few strong events, or too little power. +""" + +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") +_MAD = 1.4826 + +# position error model of single events, calibrated on injected point +# sources (GFP session 847983, events with SNR >= 6): SD^2 = (k * fit SE)^2 +# + floor^2 per axis +ERROR_K = 0.60 +ERROR_FLOOR_PX = 0.40 +# the broad component that takes mislocalized events (px^2) +OUTLIER_VAR = 4.0 +MIN_FIT_EVENTS = 5 # fewest events a cloud's mixture fit takes + + +@dataclass +class SpotSettings: + """Settings of the spot annotation. + + Attributes + ---------- + link_px : float + Sources whose centroids lie within this distance belong to one spot + (single linkage). + split_corr : float + Event-train correlation from which a spot's sources count as one + source cut in two. + min_snr : float + Events of the event test: peaks of the spot's two-frame trace at + least this many robust SDs high. + min_events : int + Events needed for the event test. + min_power : float + Power needed to call a spot with one event cluster a continuum. + compact_px : float + Intrinsic major SD (px) up to which one event cloud counts as one + point source (injected point sources: 0.23-0.41 px; continua of + radius 1-1.5 px: 0.45-0.8 px). + bic_margin : float + BIC difference that separate clusters need (6: strong evidence; + injected single sources and continua never came below +6). + trim_px : float + Events farther than this beyond the spot's sources are left out. + sigma_px : float + Width of the Gaussian fitted to each event's image. + n_sim : int + Simulations of the power estimate. + """ + + link_px: float = 2.5 + split_corr: float = 0.3 + min_snr: float = 6.0 + min_events: int = 15 + min_power: float = 0.8 + compact_px: float = 0.45 + bic_margin: float = 6.0 + trim_px: float = 1.5 + sigma_px: float = 1.4 + n_sim: int = 20 + + def to_dict(self) -> 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. + + 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 + + rc = np.asarray(rc, dtype=np.float64).reshape(-1, 2) + n = rc.shape[0] + lab = -np.ones(n, dtype=np.int64) + ok = np.flatnonzero(np.isfinite(rc).all(1)) + g = 0 + if ok.size: + pairs = cKDTree(rc[ok]).query_pairs(link_px, output_type="ndarray") + adj = coo_matrix( + (np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), + shape=(ok.size, ok.size), + ) + _, comp = connected_components(adj, directed=False) + # number the groups in the order of their first member + _, first = np.unique(comp, return_index=True) + order = np.argsort(first, kind="stable") + rank = np.empty_like(order) + rank[order] = np.arange(order.size) + lab[ok] = rank[comp] + g = order.size + for i in np.flatnonzero(lab < 0): # sources without a position: alone + lab[i] = g + g += 1 + return lab + + +def event_train_corr(events: np.ndarray) -> float: + """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") + k = np.ones(3) + sm = np.stack([np.convolve(v, k, mode="same") for v in ev]) + 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") + + +def robust_sd(x: np.ndarray, axis: int | None = None) -> np.ndarray | float: + """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: 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: 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 + + a0 = max(float(np.nanmax(y) - np.nanmedian(y)), 1e-6) + 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)) + except ValueError: + return None + dof = max(int(ok.sum()) - 4, 1) + chi2 = float(np.sum(f.fun**2)) / dof + try: + cov = np.linalg.inv(f.jac.T @ f.jac) * max(chi2, 1.0) + se = np.sqrt(np.clip(np.diag(cov), 0, None)) + except np.linalg.LinAlgError: + return None + return f.x[1], f.x[2], se[1], se[2], f.x[0] + + +def localize_events( + x: np.ndarray, + rr: np.ndarray, + cc: np.ndarray, + center: tuple, + radius: float, + settings: SpotSettings, + weight_sd: float = 1.5, + n_frames: int = 2, +) -> dict: + """Single events of a spot in one trial, in the trial's frame. + + Parameters + ---------- + x : ndarray of shape (frames, pixels) + The movie minus its baseline at the spot's pixels (NaN at discarded + frames and missing samples). + rr, cc : ndarray of shape (pixels,) + The pixels' rows and columns in the trial's registered image. + center : (float, float) + The spot's centre in the trial's image. + radius : float + Fitted positions are kept within this distance of the centre. + settings : SpotSettings + weight_sd, n_frames + The spot trace's Gaussian weights (px) and the frames of each + event's image. + + Returns + ------- + 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) + + +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: + return {k: np.asarray(v) for k, v in out.items()} + 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[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)) + sd = robust_sd(y) + if not np.isfinite(sd) or sd <= 0: + 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 + ) + taken: list = [] + for i in peak[np.argsort(-z[peak], kind="stable")]: + if all(abs(i - j) >= 3 for j in taken): + taken.append(int(i)) + xs = sum(x[k : k + n] for k in range(n_frames)) + px_sd = robust_sd(xs, axis=0) / 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) + if fit is None: + continue + r, c, se_r, se_c, _ = fit + for k, v in zip(out, (i, float(z[i]), r, c, se_r, se_c)): + out[k].append(v) + return {k: np.asarray(v, dtype=np.float64) for k, v in out.items()} + + +# ------------------------------------------------------------ mixture fit + + +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) + inv[:, 0, 0], inv[:, 1, 1] = T[:, 1, 1] / det, T[:, 0, 0] / det + inv[:, 0, 1], inv[:, 1, 0] = -T[:, 0, 1] / det, -T[:, 1, 0] / det + m = np.einsum("ni,nij,nj->n", d, inv, d) + return -0.5 * (m + np.log(det) + 2 * np.log(2 * np.pi)), inv + + +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 + S = np.zeros((se.shape[0], 2, 2)) + S[:, 0, 0], S[:, 1, 1] = v[:, 0], v[:, 1] + return S + + +@dataclass +class MixtureFit: + """A K-component fit of event positions (plus the outlier component). + + Attributes + ---------- + K : int + loglik, bic : float + weights : ndarray (K,) + means : ndarray (K, 2) + covs : ndarray (K, 2, 2) + Each component's intrinsic covariance (the events' errors removed). + outlier : float + The outlier component's weight. + """ + + K: int + loglik: float + bic: float + weights: np.ndarray + means: np.ndarray + covs: np.ndarray + outlier: float = 0.0 + + +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) + best = None + for _ in range(n_init): + mu = x[rng.choice(n, K, replace=False)].copy() + V = np.repeat(np.cov(x.T)[None] / K + w * np.eye(2), K, 0) + al = np.full(K, 0.9 / K) + a_out = 0.1 + ll_old = -np.inf + for _ in range(iters): + lq = np.empty((n, K + 1)) + invs = [] + for k in range(K): + lq[:, k], inv = _logn(x, mu[k], V[k] + S) + lq[:, k] += np.log(max(al[k], 1e-300)) + invs.append(inv) + lq[:, K] = lo_out + np.log(max(a_out, 1e-300)) + mx = lq.max(1, keepdims=True) + ll = float(np.sum(mx[:, 0] + np.log(np.exp(lq - mx).sum(1)))) + q = np.exp(lq - mx) + q /= q.sum(1, keepdims=True) + a_out = float(q[:, K].mean()) + for k in range(K): + qk = q[:, k] + sq = qk.sum() + if sq < 1e-9: + continue + VTi = np.einsum("ij,njk->nik", V[k], invs[k]) + b = mu[k] + np.einsum("nij,nj->ni", VTi, x - mu[k]) + B = V[k] - np.einsum("nij,jk->nik", VTi, V[k]) + al[k] = sq / n + 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) + ) / sq + w * np.eye(2) + if ll - ll_old < 1e-6 * abs(ll): + break + ll_old = ll + if best is None or ll > best[0]: + best = (ll, al.copy(), mu.copy(), V.copy(), a_out) + return best + + +def mixture_fit( + 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 + ---------- + x : ndarray (n, 2) + Event positions. + S : ndarray (n, 2, 2) + Their error covariances (:func:`error_cov`). + center : (float, float) + 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) + 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)) + 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: 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: 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") + rng = np.random.default_rng(seed) + n = S.shape[0] + L = np.linalg.cholesky(S) + hits = 0 + for _ in range(n_sim): + 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 + ) + best, _ = mixture_fit( + x, + S, + center, + kmax=2, + n_init=3, + iters=150, + seed=int(rng.integers(1 << 30)), + bic_margin=bic_margin, + ) + hits += best.K >= 2 + return hits / n_sim + + +@dataclass +class SpotResult: + """One spot's annotation. + + Attributes + ---------- + sources : ndarray of int + The spot's sources (zero-based indices of the kept sources). + label : str + One of :data:`LABELS`. + event_corr : float + n_events : int + Events of the event test (0 when it did not run). + K : int + Components of the event test's fit (0 when it did not run). + power : float + Power to see the sources as separate points (NaN when not run). + cloud_major, cloud_minor : float + Intrinsic SDs (px) of the one-component fit along its axes. + bic_gain : float + BIC of one component minus the lowest with more (:func:`bic_gain`). + center : ndarray (2,) + """ + + sources: np.ndarray + label: str + event_corr: float = float("nan") + n_events: int = 0 + K: int = 0 + power: float = float("nan") + cloud_major: float = float("nan") + cloud_minor: float = float("nan") + bic_gain: float = float("nan") + 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: + """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) + ) + 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]) + out.update( + K=int(best.K), + bic_gain=bic_gain(fits), + cloud_major=float(np.sqrt(max(w[1], 0))), + cloud_minor=float(np.sqrt(max(w[0], 0))), + ) + if best.K == 1: + out["power"] = separation_power( + src, + S, + fits[0].outlier, + center, + settings.n_sim, + seed, + settings.bic_margin, + ) + return out + + +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) + if k >= 2: + return "close_pair" + if np.isfinite(event_corr) and event_corr >= settings.split_corr: + return "merge" + if k == 1 and test.get("cloud_major", np.inf) <= settings.compact_px: + return "merge" + if k == 1 and test.get("power", 0.0) >= settings.min_power: + return "continuum" + return "undecided" diff --git a/src/giant_python/extraction/raster/stage_files.py b/src/giant_python/extraction/raster/stage_files.py index 7885932f..4fd39927 100644 --- a/src/giant_python/extraction/raster/stage_files.py +++ b/src/giant_python/extraction/raster/stage_files.py @@ -1,390 +1,390 @@ -"""Small files that SILo's stages hand to each other. - -* 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). - -Layout of a localization file (HDF5, row-major; images in MATLAB's -orientation, zero-based coordinates):: - - / attributes: format, format_version, code_version, - settings_hash, movie, path, trial (one-based), align_hz, - num_channels, z_depth, peaks_fitted (0/1), half_ims (0/1) - /mean_im (rows, cols, channels) mean image, file channel order - /act_im (rows, cols) activity image - /summary (rows, cols) the image the trial's peaks are fitted in - /discard (frames,) uint8: registered frames discarded for motion - /peaks (n, 4) [amplitude, row, col, sigma], when fitted with the - localization - /half_ims (2, rows, cols, channels) float32: mean images of two - halves of the frames (MATLAB's halfIMs), when the run's - 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') - -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). -""" - -from __future__ import annotations - -import os -from dataclasses import dataclass -from pathlib import Path -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 - - -@dataclass -class LocalizationRecord: - """One localized trial-path, as the later stages use it. - - Attributes - ---------- - mean_im : ndarray of shape (rows, cols, channels) - act_im, summary : ndarray of shape (rows, cols) - discard : ndarray of bool, shape (frames,) - peaks : ndarray of shape (n, 4) or None - The trial's own peaks (zero-based, in its registered frame), when - fitted. - attrs : dict - The file's attributes. - half_ims : ndarray of shape (2, rows, cols, channels) or None - Mean images of two halves of the frames, when stored. - null_im : ndarray of shape (draws, rows, cols) or None - The calibrated null activity images, when stored. - """ - - mean_im: np.ndarray - act_im: np.ndarray - summary: np.ndarray - discard: np.ndarray - peaks: np.ndarray | None - attrs: dict - 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`. - - 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( - self.mean_im, - self.act_im, - self.peaks, - self.discard, - self.half_ims, - self.null_im, - ) - - -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): - return v.item() - return v - - -def write_localization( - path: str | Path, - mean_im: np.ndarray, - act_im: np.ndarray, - summary: np.ndarray, - discard: np.ndarray, - peaks: np.ndarray | None, - attrs: dict, - half_ims: np.ndarray | None = None, - null_im: np.ndarray | None = None, -) -> Path: - """Write a localization file (written whole, then moved into place). - - Parameters - ---------- - 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. - attrs : dict - Attributes (settings_hash, movie, path, trial, - align_hz, num_channels, z_depth). - - Returns - ------- - Path - """ - path = Path(path) - tmp = path.with_name(f"{path.name}.{os.getpid()}.partial") - try: - with h5py.File(tmp, "w") as f: - f.attrs["format"] = LOCALIZATION_FORMAT - f.attrs["format_version"] = LOCALIZATION_VERSION - f.attrs["code_version"] = __version__ - for key, value in attrs.items(): - f.attrs[key] = value - f.attrs["peaks_fitted"] = int(peaks is not None) - f.attrs["half_ims"] = int(half_ims is not None) - 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) - f["discard"] = np.asarray(discard, dtype=np.uint8) - 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) - if null_im is not None: - f.attrs["null_im"] = 1 - null = np.asarray(null_im, np.float32) - f.create_dataset( - "null_im", - data=null.reshape((-1,) + null.shape[-2:]), - **opts, - ) - side = peaks_file(path) - if side.exists(): # peaks of an earlier localization - side.unlink() - os.replace(tmp, path) - except BaseException: - if tmp.exists(): - tmp.unlink() - raise - return path - - -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: 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 - with h5py.File(side, "r") as f: - return f["peaks"][()] - - -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. - - 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: - if _value(f.attrs.get("format")) != LOCALIZATION_FORMAT: - return None - attrs = {k: _value(v) for k, v in f.attrs.items()} - except OSError: - return None - if not attrs.get("peaks_fitted") and peaks_file(path).exists(): - attrs["peaks_fitted"] = 1 - return attrs - - -def read_localization( - path: str | Path, peaks: bool = True, half_ims: bool = True -) -> LocalizationRecord: - """Read a localization file (and its peaks' sidecar, if there is one). - - Parameters - ---------- - path : str or Path - The file. - peaks : bool - Read the sidecar's peaks too (the plan stage does not: a sidecar may - be being written then). - half_ims : bool - 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 - If the file is not a localization file of a version this code - reads. - """ - with h5py.File(path, "r") as f: - if _value(f.attrs.get("format")) != LOCALIZATION_FORMAT: - raise ValueError(f"{path} is not a SILo localization file") - if int(f.attrs["format_version"]) > LOCALIZATION_VERSION: - raise ValueError( - f"{path} has localization format " - f"{int(f.attrs['format_version'])}; this code reads up to " - f"{LOCALIZATION_VERSION}" - ) - rec = LocalizationRecord( - mean_im=f["mean_im"][()], - act_im=f["act_im"][()], - summary=f["summary"][()], - 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), - null_im=f["null_im"][()] if "null_im" in f else None, - ) - if rec.peaks is None and peaks: - rec.peaks = _sidecar_peaks(path) - if rec.peaks is not None: - rec.attrs["peaks_fitted"] = 1 - return rec - - -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. - - Returns - ------- - Path - The sidecar. - """ - side = peaks_file(path) - tmp = side.with_name(f"{side.name}.{os.getpid()}.partial") - try: - with h5py.File(tmp, "w") as f: - f.attrs["format"] = LOCALIZATION_FORMAT + " peaks" - f["peaks"] = np.asarray(peaks, dtype=np.float64).reshape(-1, 4) - os.replace(tmp, side) - except BaseException: - if tmp.exists(): - tmp.unlink() - raise - return side - - -def write_seeds(path: str | Path, seeds: dict, index_base: int = 0) -> Path: - """Write a seeds file. - - Parameters - ---------- - path : str or Path - Destination (replaced). - seeds : dict - 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") - with h5py.File(path, "w") as f: - f.attrs["index_base"] = int(index_base) - for d, s in seeds.items(): - f[f"Path{int(d)}/seeds"] = np.asarray(s, np.float64).reshape(-1, 4) - return Path(path) - - -def read_seeds(path: str | Path, n_paths: int) -> list: - """Each path's seeds from a seeds file, zero-based. - - Parameters - ---------- - path : str or Path - The file. - n_paths : int - Imaging paths of the session. - - Returns - ------- - list of (ndarray or None) - 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: - base = int(f.attrs.get("index_base", 0)) - if base not in (0, 1): - raise ValueError(f"{path}: index_base must be 0 or 1") - for d in range(n_paths): - key = f"Path{d + 1}/seeds" - if key in f: - s = np.asarray(f[key][()], np.float64).reshape(-1, 4).copy() - s[:, 1:3] -= base - out[d] = s - return out +"""Small files that SILo's stages hand to each other. + +* 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). + +Layout of a localization file (HDF5, row-major; images in MATLAB's +orientation, zero-based coordinates):: + + / attributes: format, format_version, code_version, + settings_hash, movie, path, trial (one-based), align_hz, + num_channels, z_depth, peaks_fitted (0/1), half_ims (0/1) + /mean_im (rows, cols, channels) mean image, file channel order + /act_im (rows, cols) activity image + /summary (rows, cols) the image the trial's peaks are fitted in + /discard (frames,) uint8: registered frames discarded for motion + /peaks (n, 4) [amplitude, row, col, sigma], when fitted with the + localization + /half_ims (2, rows, cols, channels) float32: mean images of two + halves of the frames (MATLAB's halfIMs), when the run's + 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') + +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). +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path +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 + + +@dataclass +class LocalizationRecord: + """One localized trial-path, as the later stages use it. + + Attributes + ---------- + mean_im : ndarray of shape (rows, cols, channels) + act_im, summary : ndarray of shape (rows, cols) + discard : ndarray of bool, shape (frames,) + peaks : ndarray of shape (n, 4) or None + The trial's own peaks (zero-based, in its registered frame), when + fitted. + attrs : dict + The file's attributes. + half_ims : ndarray of shape (2, rows, cols, channels) or None + Mean images of two halves of the frames, when stored. + null_im : ndarray of shape (draws, rows, cols) or None + The calibrated null activity images, when stored. + """ + + mean_im: np.ndarray + act_im: np.ndarray + summary: np.ndarray + discard: np.ndarray + peaks: np.ndarray | None + attrs: dict + 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`. + + 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( + self.mean_im, + self.act_im, + self.peaks, + self.discard, + self.half_ims, + self.null_im, + ) + + +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): + return v.item() + return v + + +def write_localization( + path: str | Path, + mean_im: np.ndarray, + act_im: np.ndarray, + summary: np.ndarray, + discard: np.ndarray, + peaks: np.ndarray | None, + attrs: dict, + half_ims: np.ndarray | None = None, + null_im: np.ndarray | None = None, +) -> Path: + """Write a localization file (written whole, then moved into place). + + Parameters + ---------- + 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. + attrs : dict + Attributes (settings_hash, movie, path, trial, + align_hz, num_channels, z_depth). + + Returns + ------- + Path + """ + path = Path(path) + tmp = path.with_name(f"{path.name}.{os.getpid()}.partial") + try: + with h5py.File(tmp, "w") as f: + f.attrs["format"] = LOCALIZATION_FORMAT + f.attrs["format_version"] = LOCALIZATION_VERSION + f.attrs["code_version"] = __version__ + for key, value in attrs.items(): + f.attrs[key] = value + f.attrs["peaks_fitted"] = int(peaks is not None) + f.attrs["half_ims"] = int(half_ims is not None) + 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) + f["discard"] = np.asarray(discard, dtype=np.uint8) + 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) + if null_im is not None: + f.attrs["null_im"] = 1 + null = np.asarray(null_im, np.float32) + f.create_dataset( + "null_im", + data=null.reshape((-1,) + null.shape[-2:]), + **opts, + ) + side = peaks_file(path) + if side.exists(): # peaks of an earlier localization + side.unlink() + os.replace(tmp, path) + except BaseException: + if tmp.exists(): + tmp.unlink() + raise + return path + + +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: 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 + with h5py.File(side, "r") as f: + return f["peaks"][()] + + +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. + + 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: + if _value(f.attrs.get("format")) != LOCALIZATION_FORMAT: + return None + attrs = {k: _value(v) for k, v in f.attrs.items()} + except OSError: + return None + if not attrs.get("peaks_fitted") and peaks_file(path).exists(): + attrs["peaks_fitted"] = 1 + return attrs + + +def read_localization( + path: str | Path, peaks: bool = True, half_ims: bool = True +) -> LocalizationRecord: + """Read a localization file (and its peaks' sidecar, if there is one). + + Parameters + ---------- + path : str or Path + The file. + peaks : bool + Read the sidecar's peaks too (the plan stage does not: a sidecar may + be being written then). + half_ims : bool + 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 + If the file is not a localization file of a version this code + reads. + """ + with h5py.File(path, "r") as f: + if _value(f.attrs.get("format")) != LOCALIZATION_FORMAT: + raise ValueError(f"{path} is not a SILo localization file") + if int(f.attrs["format_version"]) > LOCALIZATION_VERSION: + raise ValueError( + f"{path} has localization format " + f"{int(f.attrs['format_version'])}; this code reads up to " + f"{LOCALIZATION_VERSION}" + ) + rec = LocalizationRecord( + mean_im=f["mean_im"][()], + act_im=f["act_im"][()], + summary=f["summary"][()], + 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), + null_im=f["null_im"][()] if "null_im" in f else None, + ) + if rec.peaks is None and peaks: + rec.peaks = _sidecar_peaks(path) + if rec.peaks is not None: + rec.attrs["peaks_fitted"] = 1 + return rec + + +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. + + Returns + ------- + Path + The sidecar. + """ + side = peaks_file(path) + tmp = side.with_name(f"{side.name}.{os.getpid()}.partial") + try: + with h5py.File(tmp, "w") as f: + f.attrs["format"] = LOCALIZATION_FORMAT + " peaks" + f["peaks"] = np.asarray(peaks, dtype=np.float64).reshape(-1, 4) + os.replace(tmp, side) + except BaseException: + if tmp.exists(): + tmp.unlink() + raise + return side + + +def write_seeds(path: str | Path, seeds: dict, index_base: int = 0) -> Path: + """Write a seeds file. + + Parameters + ---------- + path : str or Path + Destination (replaced). + seeds : dict + 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") + with h5py.File(path, "w") as f: + f.attrs["index_base"] = int(index_base) + for d, s in seeds.items(): + f[f"Path{int(d)}/seeds"] = np.asarray(s, np.float64).reshape(-1, 4) + return Path(path) + + +def read_seeds(path: str | Path, n_paths: int) -> list: + """Each path's seeds from a seeds file, zero-based. + + Parameters + ---------- + path : str or Path + The file. + n_paths : int + Imaging paths of the session. + + Returns + ------- + list of (ndarray or None) + 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: + base = int(f.attrs.get("index_base", 0)) + if base not in (0, 1): + raise ValueError(f"{path}: index_base must be 0 or 1") + for d in range(n_paths): + key = f"Path{d + 1}/seeds" + if key in f: + s = np.asarray(f[key][()], np.float64).reshape(-1, 4).copy() + s[:, 1:3] -= base + out[d] = s + return out diff --git a/src/giant_python/gui/__init__.py b/src/giant_python/gui/__init__.py index a7393ad5..32c7c481 100644 --- a/src/giant_python/gui/__init__.py +++ b/src/giant_python/gui/__init__.py @@ -1,4 +1,4 @@ -"""Parameter and ROI editors with toolkit imports deferred until use. - -Use the public pipeline annotation service for the complete ROI workflow. -""" +"""Parameter and ROI editors with toolkit imports deferred until use. + +Use the public pipeline annotation service for the complete ROI workflow. +""" diff --git a/src/giant_python/gui/parameters_gui.py b/src/giant_python/gui/parameters_gui.py index 47fae395..59c4b0b7 100644 --- a/src/giant_python/gui/parameters_gui.py +++ b/src/giant_python/gui/parameters_gui.py @@ -1,136 +1,136 @@ -"""Existing tkinter BandSILo parameter form, with lazy toolkit imports.""" - -from dataclasses import asdict, replace - -import numpy as np - -from ..models.params import ( - AnnotationInput, - AnnotationOptions, - BandParamsInput, - BandSiloParams, - ExecutionInput, - ExecutionOptions, - resolve_band_options, -) - -_PARAM_GUI_FIELDS = ( - ("analyze_hz", "Analyze Hz:"), - ("decay_tau_s", "Decay Tau (s):"), - ("baseline_window_s", "Baseline Window (s):"), - ("denoise_window_s", "Denoise Window (s):"), - ("vif", "Variance Inflation Factor (VIF):"), - ("d_xy", "dXY:"), - ("peakth", "Peak Threshold:"), - ("peak_buffer", "Peak Buffer:"), - ("max_workers", "Max Workers:"), - ("z_tol", "Z Tolerance (µm):"), -) - - -def run_parameter_gui( - params: BandParamsInput = None, - *, - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> 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 - - base, run, roi = resolve_band_options(params, execution, annotations) - values = {**asdict(base), **asdict(run), **asdict(roi)} - root = tk.Tk() - root.title("SLAP2 Analysis Parameters") - frame = ttk.Frame(root, padding="10") - frame.grid(row=0, column=0) - entries = {} - row = 0 - for attr, label in _PARAM_GUI_FIELDS: - ttk.Label(frame, text=label).grid(row=row, column=0, sticky=tk.W) - var = tk.StringVar(value=str(values[attr])) - 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) - 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 - ttk.Label(frame, text="LS and convolution traces are always saved.").grid( - row=row, column=0, columnspan=2, sticky=tk.W - ) - row += 1 - for attr, label in ( - ("trace_beta_fraction", "Trace Event Penalty Fraction:"), - ("trace_max_iter", "Trace Maximum Iterations:"), - ("trace_tolerance", "Trace Optimizer Tolerance:"), - ("trace_event_threshold", "Trace Debias Event Threshold:"), - ): - ttk.Label(frame, text=label).grid(row=row, column=0, sticky=tk.W) - var = tk.StringVar(value=str(values[attr])) - 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) - 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) - 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, - tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] | None, - ] = {"options": None} - - def on_ok() -> None: - """Validate controls and return a replacement parameter instance.""" - try: - updates = { - "analyze_hz": float(entries["analyze_hz"].get()), - "decay_tau_s": float(entries["decay_tau_s"].get()), - "baseline_window_s": float(entries["baseline_window_s"].get()), - "denoise_window_s": float(entries["denoise_window_s"].get()), - "vif": float(entries["vif"].get()), - "d_xy": int(entries["d_xy"].get()), - "peakth": float(entries["peakth"].get()), - "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_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_debias": bool(debias_var.get()), - } - result["options"] = ( - replace(base, **updates), - replace(run, max_workers=int(entries["max_workers"].get())), - replace(roi, enabled=bool(draw_rois_var.get())), - ) - root.destroy() - except ValueError as error: - messagebox.showerror("Error", f"Invalid parameter values: {error}") - - 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) - root.grab_set() - root.mainloop() - return result["options"] +"""Existing tkinter BandSILo parameter form, with lazy toolkit imports.""" + +from dataclasses import asdict, replace + +import numpy as np + +from ..models.params import ( + AnnotationInput, + AnnotationOptions, + BandParamsInput, + BandSiloParams, + ExecutionInput, + ExecutionOptions, + resolve_band_options, +) + +_PARAM_GUI_FIELDS = ( + ("analyze_hz", "Analyze Hz:"), + ("decay_tau_s", "Decay Tau (s):"), + ("baseline_window_s", "Baseline Window (s):"), + ("denoise_window_s", "Denoise Window (s):"), + ("vif", "Variance Inflation Factor (VIF):"), + ("d_xy", "dXY:"), + ("peakth", "Peak Threshold:"), + ("peak_buffer", "Peak Buffer:"), + ("max_workers", "Max Workers:"), + ("z_tol", "Z Tolerance (µm):"), +) + + +def run_parameter_gui( + params: BandParamsInput = None, + *, + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> 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 + + base, run, roi = resolve_band_options(params, execution, annotations) + values = {**asdict(base), **asdict(run), **asdict(roi)} + root = tk.Tk() + root.title("SLAP2 Analysis Parameters") + frame = ttk.Frame(root, padding="10") + frame.grid(row=0, column=0) + entries = {} + row = 0 + for attr, label in _PARAM_GUI_FIELDS: + ttk.Label(frame, text=label).grid(row=row, column=0, sticky=tk.W) + var = tk.StringVar(value=str(values[attr])) + 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) + 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 + ttk.Label(frame, text="LS and convolution traces are always saved.").grid( + row=row, column=0, columnspan=2, sticky=tk.W + ) + row += 1 + for attr, label in ( + ("trace_beta_fraction", "Trace Event Penalty Fraction:"), + ("trace_max_iter", "Trace Maximum Iterations:"), + ("trace_tolerance", "Trace Optimizer Tolerance:"), + ("trace_event_threshold", "Trace Debias Event Threshold:"), + ): + ttk.Label(frame, text=label).grid(row=row, column=0, sticky=tk.W) + var = tk.StringVar(value=str(values[attr])) + 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) + 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) + 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, + tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] | None, + ] = {"options": None} + + def on_ok() -> None: + """Validate controls and return a replacement parameter instance.""" + try: + updates = { + "analyze_hz": float(entries["analyze_hz"].get()), + "decay_tau_s": float(entries["decay_tau_s"].get()), + "baseline_window_s": float(entries["baseline_window_s"].get()), + "denoise_window_s": float(entries["denoise_window_s"].get()), + "vif": float(entries["vif"].get()), + "d_xy": int(entries["d_xy"].get()), + "peakth": float(entries["peakth"].get()), + "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_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_debias": bool(debias_var.get()), + } + result["options"] = ( + replace(base, **updates), + replace(run, max_workers=int(entries["max_workers"].get())), + replace(roi, enabled=bool(draw_rois_var.get())), + ) + root.destroy() + except ValueError as error: + messagebox.showerror("Error", f"Invalid parameter values: {error}") + + 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) + 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 1efc3a4e..382fc45c 100644 --- a/src/giant_python/gui/roi_editor.py +++ b/src/giant_python/gui/roi_editor.py @@ -1,220 +1,220 @@ -"""The existing OpenCV rectangle selector and tkinter label prompt. - -Accepts prepared band reference geometry and returns in-memory records/masks. -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 - - -def _ask_roi_label( - roi_num: int, - path_num: int, - plane_num: int, -) -> str: - """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 - - text = None - try: - root = tk.Tk() - root.withdraw() - root.attributes("-topmost", True) - text = simpledialog.askstring( - "ROI label", - f"Label for ROI {roi_num} (Path {path_num}, fast-Z plane {plane_num}):", - parent=root, - ) - root.destroy() - except Exception as error: # noqa: BLE001 - GUI best-effort - print(f"Could not prompt for ROI label ({error}); using default.") - if not text or not text.strip(): - return f"ROI{roi_num}" - return text.strip() - - -def run_user_roi_selection(user_roi_geo: dict, n_dmds: int) -> dict: - """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 = { - "user_roi_masks": {}, - "user_roi_superpixels": {}, - "user_roi_labels": {}, - "roi_records": {}, - } - for dmd_ix in range(n_dmds): - key = f"DMD{dmd_ix + 1}" - 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_labels"][key] = [record["label"] for record in roi_records] - out["roi_records"][key] = roi_records - return out - - -def _normalize_plane( - plane: np.ndarray, -) -> np.ndarray: - """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) - if not np.isfinite(vmin): - vmin = float(np.nanmin(im)) if np.any(np.isfinite(im)) else 0.0 - if not np.isfinite(vmax): - vmax = float(np.nanmax(im)) if np.any(np.isfinite(im)) else 1.0 - if vmax <= vmin: - vmax = vmin + 1.0 - im8 = np.clip((im - vmin) / (vmax - vmin), 0, 1) - return (im8 * 255).astype(np.uint8) - - -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"] - best_ch = g["best_ch"] - z_map = g["z_map"] - num_fast_z = g["num_fast_z"] - sp_mask = g["sp_mask"] - roi_masks = [] - roi_records = [] - roi_union = np.zeros((num_fast_z, *yx_shape), dtype=bool) - window_name = f"Select user ROI(s) DMD{dmd_ix + 1}" - cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) - cv2.resizeWindow(window_name, 800, 500) - has_z_trackbar = num_fast_z > 1 - if has_z_trackbar: - cv2.createTrackbar("z", window_name, 0, num_fast_z - 1, lambda v: None) - curr_fz = 0 - while True: - if has_z_trackbar: - 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]) - cv2.imshow(window_name, disp) - keycode = cv2.waitKey(50) & 0xFF - if keycode == ord("e"): - _edit_rois( - cv2, - im8, - sp_mask[curr_fz], - curr_fz, - dmd_ix, - num_fast_z, - yx_shape, - roi_masks, - roi_union, - roi_records, - ) - elif keycode == ord("n"): - curr_fz = min(curr_fz + 1, num_fast_z - 1) - if has_z_trackbar: - cv2.setTrackbarPos("z", window_name, curr_fz) - elif keycode == ord("p"): - curr_fz = max(curr_fz - 1, 0) - if has_z_trackbar: - cv2.setTrackbarPos("z", window_name, curr_fz) - elif keycode in (27, ord("q")): - break - cv2.destroyWindow(window_name) - return roi_masks, roi_records - - -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) - sp_color[sp_plane] = (0, 255, 0) - disp = cv2.addWeighted(disp, 0.75, sp_color, 0.25, 0) - if roi_plane.any(): - roi_color = np.zeros_like(disp) - roi_color[roi_plane] = (0, 0, 255) - disp = cv2.addWeighted(disp, 0.7, roi_color, 0.3, 0) - return disp - - -def _edit_rois( - 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) - cv2.resizeWindow(edit_name, 800, 500) - if rois is not None and len(rois) > 0: - for x, y, w, h in rois: - roi_num = len(roi_masks) + 1 - y_stop, x_stop = y + h, x + w - mask = np.zeros((num_fast_z, *yx_shape), dtype=bool) - mask[curr_fz, y:y_stop, x:x_stop] = True - roi_masks.append(mask) - roi_union[curr_fz, y:y_stop, x:x_stop] = True - label = _ask_roi_label(roi_num, dmd_ix + 1, curr_fz + 1) - position = np.array( - [[y, x], [y, x + w], [y + h, x + w], [y + h, x]], - dtype=np.float64, - ) - 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) +"""The existing OpenCV rectangle selector and tkinter label prompt. + +Accepts prepared band reference geometry and returns in-memory records/masks. +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 + + +def _ask_roi_label( + roi_num: int, + path_num: int, + plane_num: int, +) -> str: + """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 + + text = None + try: + root = tk.Tk() + root.withdraw() + root.attributes("-topmost", True) + text = simpledialog.askstring( + "ROI label", + f"Label for ROI {roi_num} (Path {path_num}, fast-Z plane {plane_num}):", + parent=root, + ) + root.destroy() + except Exception as error: # noqa: BLE001 - GUI best-effort + print(f"Could not prompt for ROI label ({error}); using default.") + if not text or not text.strip(): + return f"ROI{roi_num}" + return text.strip() + + +def run_user_roi_selection(user_roi_geo: dict, n_dmds: int) -> dict: + """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 = { + "user_roi_masks": {}, + "user_roi_superpixels": {}, + "user_roi_labels": {}, + "roi_records": {}, + } + for dmd_ix in range(n_dmds): + key = f"DMD{dmd_ix + 1}" + 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_labels"][key] = [record["label"] for record in roi_records] + out["roi_records"][key] = roi_records + return out + + +def _normalize_plane( + plane: np.ndarray, +) -> np.ndarray: + """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) + if not np.isfinite(vmin): + vmin = float(np.nanmin(im)) if np.any(np.isfinite(im)) else 0.0 + if not np.isfinite(vmax): + vmax = float(np.nanmax(im)) if np.any(np.isfinite(im)) else 1.0 + if vmax <= vmin: + vmax = vmin + 1.0 + im8 = np.clip((im - vmin) / (vmax - vmin), 0, 1) + return (im8 * 255).astype(np.uint8) + + +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"] + best_ch = g["best_ch"] + z_map = g["z_map"] + num_fast_z = g["num_fast_z"] + sp_mask = g["sp_mask"] + roi_masks = [] + roi_records = [] + roi_union = np.zeros((num_fast_z, *yx_shape), dtype=bool) + window_name = f"Select user ROI(s) DMD{dmd_ix + 1}" + cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) + cv2.resizeWindow(window_name, 800, 500) + has_z_trackbar = num_fast_z > 1 + if has_z_trackbar: + cv2.createTrackbar("z", window_name, 0, num_fast_z - 1, lambda v: None) + curr_fz = 0 + while True: + if has_z_trackbar: + 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]) + cv2.imshow(window_name, disp) + keycode = cv2.waitKey(50) & 0xFF + if keycode == ord("e"): + _edit_rois( + cv2, + im8, + sp_mask[curr_fz], + curr_fz, + dmd_ix, + num_fast_z, + yx_shape, + roi_masks, + roi_union, + roi_records, + ) + elif keycode == ord("n"): + curr_fz = min(curr_fz + 1, num_fast_z - 1) + if has_z_trackbar: + cv2.setTrackbarPos("z", window_name, curr_fz) + elif keycode == ord("p"): + curr_fz = max(curr_fz - 1, 0) + if has_z_trackbar: + cv2.setTrackbarPos("z", window_name, curr_fz) + elif keycode in (27, ord("q")): + break + cv2.destroyWindow(window_name) + return roi_masks, roi_records + + +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) + sp_color[sp_plane] = (0, 255, 0) + disp = cv2.addWeighted(disp, 0.75, sp_color, 0.25, 0) + if roi_plane.any(): + roi_color = np.zeros_like(disp) + roi_color[roi_plane] = (0, 0, 255) + disp = cv2.addWeighted(disp, 0.7, roi_color, 0.3, 0) + return disp + + +def _edit_rois( + 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) + cv2.resizeWindow(edit_name, 800, 500) + if rois is not None and len(rois) > 0: + for x, y, w, h in rois: + roi_num = len(roi_masks) + 1 + y_stop, x_stop = y + h, x + w + mask = np.zeros((num_fast_z, *yx_shape), dtype=bool) + mask[curr_fz, y:y_stop, x:x_stop] = True + roi_masks.append(mask) + roi_union[curr_fz, y:y_stop, x:x_stop] = True + label = _ask_roi_label(roi_num, dmd_ix + 1, curr_fz + 1) + position = np.array( + [[y, x], [y, x + w], [y + h, x + w], [y + h, x]], + dtype=np.float64, + ) + 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 a9b696ce..69686302 100644 --- a/src/giant_python/io/__init__.py +++ b/src/giant_python/io/__init__.py @@ -1,70 +1,70 @@ -"""Input/output for GIAnT-Python. - -This package is the compatibility contract with GIAnT-MATLAB: it reads and -writes the shared HDF5 structures, ScanImage TIFF stacks, and SLAP2 binary -data files. Pay special attention to 0- vs 1-based indices and array -transposition when porting from MATLAB. -""" - -from collections.abc import Callable -from importlib import import_module -from typing import TYPE_CHECKING - -from .hdf5 import load_struct_h5 -from .slap2 import ( - Slap2Reader, - load_alignment_data_h5, - open_slap2_file, -) -from .tiff import read_tiff - -if TYPE_CHECKING: - from .annotations import read_annotations_h5, save_annotations_h5 - from .experiment_summary import ( - read_summary, - write_summary, - ) - from .trial_table import read_trial_table - -_SCHEMA_EXPORTS = { - "read_trial_table": ".trial_table", - "read_annotations_h5": ".annotations", - "save_annotations_h5": ".annotations", - "read_summary": ".experiment_summary", - "write_summary": ".experiment_summary", -} - - -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) - globals()[name] = value - return value - - -__all__ = [ - "Slap2Reader", - "load_alignment_data_h5", - "load_struct_h5", - "open_slap2_file", - "read_annotations_h5", - "read_summary", - "read_tiff", - "read_trial_table", - "save_annotations_h5", - "write_summary", -] +"""Input/output for GIAnT-Python. + +This package is the compatibility contract with GIAnT-MATLAB: it reads and +writes the shared HDF5 structures, ScanImage TIFF stacks, and SLAP2 binary +data files. Pay special attention to 0- vs 1-based indices and array +transposition when porting from MATLAB. +""" + +from collections.abc import Callable +from importlib import import_module +from typing import TYPE_CHECKING + +from .hdf5 import load_struct_h5 +from .slap2 import ( + Slap2Reader, + load_alignment_data_h5, + open_slap2_file, +) +from .tiff import read_tiff + +if TYPE_CHECKING: + from .annotations import read_annotations_h5, save_annotations_h5 + from .experiment_summary import ( + read_summary, + write_summary, + ) + from .trial_table import read_trial_table + +_SCHEMA_EXPORTS = { + "read_trial_table": ".trial_table", + "read_annotations_h5": ".annotations", + "save_annotations_h5": ".annotations", + "read_summary": ".experiment_summary", + "write_summary": ".experiment_summary", +} + + +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) + globals()[name] = value + return value + + +__all__ = [ + "Slap2Reader", + "load_alignment_data_h5", + "load_struct_h5", + "open_slap2_file", + "read_annotations_h5", + "read_summary", + "read_tiff", + "read_trial_table", + "save_annotations_h5", + "write_summary", +] diff --git a/src/giant_python/io/annotations.py b/src/giant_python/io/annotations.py index 855e03b7..0cf53bb8 100644 --- a/src/giant_python/io/annotations.py +++ b/src/giant_python/io/annotations.py @@ -1,103 +1,103 @@ -"""Raw ROI records, masks and provenance IO without band geometry or UI.""" - -from pathlib import Path - -import h5py -import numpy as np - -from .hdf5 import load_struct_h5 - - -def _h5_scalar_str(ds: h5py.Dataset) -> str: - """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] - if isinstance(value, bytes): - return value.decode("utf-8", "replace") - return str(value) - - -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) - - -def save_annotations_h5( - dr: str, - roi_records_by_dmd: dict, - user_roi_masks: dict, - n_dmds: int, - 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") - ref_files = ref_files or {} - with h5py.File(path, "w") as f: - f["row_major"] = 1 - f["coords_zero_indexed"] = 1 - for dmd_ix in range(n_dmds): - key = f"DMD{dmd_ix + 1}" - group = f.create_group(f"Path{dmd_ix + 1}") - ref_file = ref_files.get(key) - group.create_dataset( - "dr", - data=str(Path(ref_file).parent) if ref_file else "", - dtype=str_dt, - ) - group.create_dataset( - "fn", - data=Path(ref_file).name if ref_file else "", - dtype=str_dt, - ) - records = roi_records_by_dmd.get(key, []) - group.create_dataset("n_rois", data=len(records)) - mask_list = user_roi_masks.get(key, []) - for i, record in enumerate(records): - _write_roi_group(group, i, record, mask_list, str_dt) - return path - - -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) - if i < len(mask_list): - group.create_dataset( - "mask", - data=np.asarray(mask_list[i]).astype(np.uint8), - compression="gzip", - shuffle=True, - ) - if roi_type == "polygon" and "position" in rec: - group.create_dataset("position", data=np.asarray(rec["position"], dtype=np.float64)) +"""Raw ROI records, masks and provenance IO without band geometry or UI.""" + +from pathlib import Path + +import h5py +import numpy as np + +from .hdf5 import load_struct_h5 + + +def _h5_scalar_str(ds: h5py.Dataset) -> str: + """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] + if isinstance(value, bytes): + return value.decode("utf-8", "replace") + return str(value) + + +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) + + +def save_annotations_h5( + dr: str, + roi_records_by_dmd: dict, + user_roi_masks: dict, + n_dmds: int, + 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") + ref_files = ref_files or {} + with h5py.File(path, "w") as f: + f["row_major"] = 1 + f["coords_zero_indexed"] = 1 + for dmd_ix in range(n_dmds): + key = f"DMD{dmd_ix + 1}" + group = f.create_group(f"Path{dmd_ix + 1}") + ref_file = ref_files.get(key) + group.create_dataset( + "dr", + data=str(Path(ref_file).parent) if ref_file else "", + dtype=str_dt, + ) + group.create_dataset( + "fn", + data=Path(ref_file).name if ref_file else "", + dtype=str_dt, + ) + records = roi_records_by_dmd.get(key, []) + group.create_dataset("n_rois", data=len(records)) + mask_list = user_roi_masks.get(key, []) + for i, record in enumerate(records): + _write_roi_group(group, i, record, mask_list, str_dt) + return path + + +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) + if i < len(mask_list): + group.create_dataset( + "mask", + data=np.asarray(mask_list[i]).astype(np.uint8), + compression="gzip", + shuffle=True, + ) + if roi_type == "polygon" and "position" in rec: + group.create_dataset("position", data=np.asarray(rec["position"], dtype=np.float64)) diff --git a/src/giant_python/io/hdf5.py b/src/giant_python/io/hdf5.py index 08822a05..336fde87 100644 --- a/src/giant_python/io/hdf5.py +++ b/src/giant_python/io/hdf5.py @@ -1,315 +1,315 @@ -"""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. - -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 - code can use the same size checks on either toolbox's outputs after - consulting row_major. -""" - -from pathlib import Path -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. - - 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: 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: object) -> str | np.ndarray: - """Decode a scalar or ndarray of (variable-length) strings to str. - - Parameters - ---------- - val : bytes, str, or ndarray - Raw value read from a string dataset. - - Returns - ------- - str or ndarray of object - Decoded scalar string, or an object array of decoded strings. - """ - if isinstance(val, (bytes, str, np.bytes_, np.str_)): - return _decode_one(val) - arr = np.asarray(val, dtype=object) - if arr.size == 0: - return arr - return np.vectorize(_decode_one, otypes=[object])(arr) - - -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 - MATLAB shape. Column-major files have their 2-D+ axes transposed to recover - the README orientation. - - Parameters - ---------- - ds : h5py.Dataset - The dataset to read. - row_major : bool - Whether the file was written row-major (True) or column-major. - - Returns - ------- - object - The decoded value (str, scalar, or ndarray). - """ - val = ds[()] - if _is_string_dataset(ds): - val = _decode_strings(val) - if isinstance(val, np.ndarray): - if (not row_major) and val.ndim >= 2: - val = val.T - if val.size == 1: - return val.reshape(-1)[0] - return val - val = np.asarray(val) - if (not row_major) and val.ndim >= 2: - val = val.T - return val - - -def _read_group(grp: h5py.Group, row_major: bool) -> dict: - """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": - continue - if isinstance(item, h5py.Group): - out[key] = _read_group(item, row_major) - else: - out[key] = _read_dataset(item, row_major) - return out - - -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 - compatibility. Corresponds to loadStructFromH5.m in GIAnT-MATLAB. - - 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) - selects whether 2-D+ axes are transposed. - - Parameters - ---------- - path : str or Path - Path to the HDF5 file. - - Returns - ------- - dict - Nested dictionary mirroring the HDF5 group hierarchy. - """ - with h5py.File(path, "r") as f: - row_major = False - if "row_major" in f: - flag = cast(h5py.Dataset, f["row_major"]) - row_major = bool(np.asarray(flag[()]).reshape(-1)[0]) - return _read_group(f, row_major) - - -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)): - return type(val)(to_serializable(v) for v in val) - if isinstance(val, np.ndarray): - return val.tolist() - if isinstance(val, np.generic): - return val.item() - return val - - -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"): - grp.create_dataset( - key, - data=np.asarray(_decode_strings(arr), dtype=object), - dtype=h5py.string_dtype(encoding="utf-8"), - ) - else: - grp.create_dataset(key, data=arr) - - -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: - return - if arr.dtype.kind in ("U", "S", "O"): - grp.create_dataset( - key, - data=np.array([str(x) for x in value], dtype=object), - dtype=h5py.string_dtype(encoding="utf-8"), - ) - else: - grp.create_dataset(key, data=arr) - - -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. - - 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)]]) - arr = np.asarray(value) - if arr.dtype == np.bool_: - arr = arr.astype(np.int8) - if isinstance(value, (int, float)): - arr = arr.astype(np.float64) - if arr.ndim == 0: - arr = arr.reshape(1, 1) - elif arr.ndim == 1: - arr = arr.reshape(1, -1) - return arr - - -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 - skipped, as MATLAB skips empty fields. - - Parameters - ---------- - grp : h5py.Group - Destination group. - key : str - 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). - """ - if isinstance(value, dict): - sub = grp.create_group(key) - for k, v in value.items(): - write_matlab_value(sub, str(k), v) - 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) - 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) - return - grp.create_dataset(key, data=np.ascontiguousarray(arr.T)) - - -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. - - Parameters - ---------- - path : str or Path - Destination file (overwritten). - struct : dict - Values as accepted by :func:`write_matlab_value`. - """ - with h5py.File(path, "w") as f: - for key, value in struct.items(): - write_matlab_value(f, str(key), value) - f.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) - - -def write_dict_to_h5group(grp: h5py.Group, d: dict) -> None: - """Write params, skipping empty sequences/None and stringifying unknowns. - - This is deliberately NOT a general lossless struct serializer. Its policy - preserves the existing experiment-summary params contract. Decoded arrays - retain their dtype/rank (including uint8 boolean parameter scalars). - """ - str_dt = h5py.string_dtype(encoding="utf-8") - for key, v in d.items(): - key = str(key) - if isinstance(v, dict): - write_dict_to_h5group(grp.create_group(key), v) - elif isinstance(v, (np.ndarray, np.generic)): - _write_preserved_array(grp, key, v) - elif isinstance(v, bool): - grp.create_dataset(key, data=np.uint8(v)) - elif isinstance(v, str): - grp.create_dataset(key, data=v, dtype=str_dt) - elif isinstance(v, (int, float)): - grp.create_dataset(key, data=v) - elif isinstance(v, (list, tuple)): - _write_sequence(grp, key, v) - elif v is not None: - grp.create_dataset(key, data=str(v), dtype=str_dt) +"""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. + +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 + code can use the same size checks on either toolbox's outputs after + consulting row_major. +""" + +from pathlib import Path +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. + + 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: 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: object) -> str | np.ndarray: + """Decode a scalar or ndarray of (variable-length) strings to str. + + Parameters + ---------- + val : bytes, str, or ndarray + Raw value read from a string dataset. + + Returns + ------- + str or ndarray of object + Decoded scalar string, or an object array of decoded strings. + """ + if isinstance(val, (bytes, str, np.bytes_, np.str_)): + return _decode_one(val) + arr = np.asarray(val, dtype=object) + if arr.size == 0: + return arr + return np.vectorize(_decode_one, otypes=[object])(arr) + + +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 + MATLAB shape. Column-major files have their 2-D+ axes transposed to recover + the README orientation. + + Parameters + ---------- + ds : h5py.Dataset + The dataset to read. + row_major : bool + Whether the file was written row-major (True) or column-major. + + Returns + ------- + object + The decoded value (str, scalar, or ndarray). + """ + val = ds[()] + if _is_string_dataset(ds): + val = _decode_strings(val) + if isinstance(val, np.ndarray): + if (not row_major) and val.ndim >= 2: + val = val.T + if val.size == 1: + return val.reshape(-1)[0] + return val + val = np.asarray(val) + if (not row_major) and val.ndim >= 2: + val = val.T + return val + + +def _read_group(grp: h5py.Group, row_major: bool) -> dict: + """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": + continue + if isinstance(item, h5py.Group): + out[key] = _read_group(item, row_major) + else: + out[key] = _read_dataset(item, row_major) + return out + + +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 + compatibility. Corresponds to loadStructFromH5.m in GIAnT-MATLAB. + + 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) + selects whether 2-D+ axes are transposed. + + Parameters + ---------- + path : str or Path + Path to the HDF5 file. + + Returns + ------- + dict + Nested dictionary mirroring the HDF5 group hierarchy. + """ + with h5py.File(path, "r") as f: + row_major = False + if "row_major" in f: + flag = cast(h5py.Dataset, f["row_major"]) + row_major = bool(np.asarray(flag[()]).reshape(-1)[0]) + return _read_group(f, row_major) + + +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)): + return type(val)(to_serializable(v) for v in val) + if isinstance(val, np.ndarray): + return val.tolist() + if isinstance(val, np.generic): + return val.item() + return val + + +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"): + grp.create_dataset( + key, + data=np.asarray(_decode_strings(arr), dtype=object), + dtype=h5py.string_dtype(encoding="utf-8"), + ) + else: + grp.create_dataset(key, data=arr) + + +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: + return + if arr.dtype.kind in ("U", "S", "O"): + grp.create_dataset( + key, + data=np.array([str(x) for x in value], dtype=object), + dtype=h5py.string_dtype(encoding="utf-8"), + ) + else: + grp.create_dataset(key, data=arr) + + +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. + + 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)]]) + arr = np.asarray(value) + if arr.dtype == np.bool_: + arr = arr.astype(np.int8) + if isinstance(value, (int, float)): + arr = arr.astype(np.float64) + if arr.ndim == 0: + arr = arr.reshape(1, 1) + elif arr.ndim == 1: + arr = arr.reshape(1, -1) + return arr + + +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 + skipped, as MATLAB skips empty fields. + + Parameters + ---------- + grp : h5py.Group + Destination group. + key : str + 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). + """ + if isinstance(value, dict): + sub = grp.create_group(key) + for k, v in value.items(): + write_matlab_value(sub, str(k), v) + 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) + 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) + return + grp.create_dataset(key, data=np.ascontiguousarray(arr.T)) + + +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. + + Parameters + ---------- + path : str or Path + Destination file (overwritten). + struct : dict + Values as accepted by :func:`write_matlab_value`. + """ + with h5py.File(path, "w") as f: + for key, value in struct.items(): + write_matlab_value(f, str(key), value) + f.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) + + +def write_dict_to_h5group(grp: h5py.Group, d: dict) -> None: + """Write params, skipping empty sequences/None and stringifying unknowns. + + This is deliberately NOT a general lossless struct serializer. Its policy + preserves the existing experiment-summary params contract. Decoded arrays + retain their dtype/rank (including uint8 boolean parameter scalars). + """ + str_dt = h5py.string_dtype(encoding="utf-8") + for key, v in d.items(): + key = str(key) + if isinstance(v, dict): + write_dict_to_h5group(grp.create_group(key), v) + elif isinstance(v, (np.ndarray, np.generic)): + _write_preserved_array(grp, key, v) + elif isinstance(v, bool): + grp.create_dataset(key, data=np.uint8(v)) + elif isinstance(v, str): + grp.create_dataset(key, data=v, dtype=str_dt) + elif isinstance(v, (int, float)): + grp.create_dataset(key, data=v) + elif isinstance(v, (list, tuple)): + _write_sequence(grp, key, v) + elif v is not None: + grp.create_dataset(key, data=str(v), dtype=str_dt) diff --git a/src/giant_python/io/slap2.py b/src/giant_python/io/slap2.py index e8584188..3b74b3bc 100644 --- a/src/giant_python/io/slap2.py +++ b/src/giant_python/io/slap2.py @@ -1,331 +1,331 @@ -"""SLAP2 binary reader access and saved alignment-data decoding. - -Band geometry and superpixel reduction belong to the extraction.band backend, -not this raw acquisition adapter. -""" - -from __future__ import annotations - -from pathlib import Path -from typing import Any, Protocol - -import h5py -import numpy as np - -from .hdf5 import load_struct_h5 - - -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: 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 {} - return { - "DSframes": _reshape_1d(data, "DSframes"), - "motionDSr": _reshape_1d(data, "motionDSr"), - "motionDSc": _reshape_1d(data, "motionDSc"), - "motionDSz": _reshape_1d(data, "motionDSz"), - "onlineYshift": _reshape_1d(online, "onlineMotionYshift"), - "onlineXshift": _reshape_1d(online, "onlineMotionXshift"), - "onlineZshift": _reshape_1d(online, "onlineMotionZshift"), - "numChannels": int(np.asarray(data["numChannels"]).reshape(-1)[0]), - "alignHz": float(np.asarray(data["alignHz"]).reshape(-1)[0]), - } - - -class Slap2Reader(Protocol): - """Minimal raw-reader surface consumed by the existing band reducer. - - Line/cycle indexes passed to getLineData remain 1-based. The owning - caller retains the reader for the entire batched reduction; this protocol - deliberately promises neither a close method nor context-manager support. - """ - - header: dict - metaData: Any - numCycles: int - lineDataNumElements: Any - lineSuperPixelIDs: Any - lineFastZIdxs: Any - - 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: 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 - 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 - - -_LINE_MAGIC = 322379495 -"""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: _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. - - Parameters - ---------- - datafile : slap2_utils.DataFile - One file of a recording. - - Returns - ------- - 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: - f.seek(offset) - raw = f.read(32) - if len(raw) < 32: - raise ValueError(f"no line header in {datafile.datFileName}") - magic = int(np.frombuffer(raw[4:8], " list: - """Property sets of an MCOS ``FileWrapper__`` segment. - - 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], " 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 - string table and segments for classes, objects and property sets; each - object row gives the indexes of its two property sets. - - Returns - ------- - 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 - - refs = np.asarray(h["#subsystem#/MCOS"][()]).ravel() - blob = np.asarray(h[refs[0]][()]).ravel().tobytes() - _, n_str = struct.unpack_from(" 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 - - try: - zone = ZoneInfo("UTC" if tz.upper() == "UTC" else tz) - except (ZoneInfoNotFoundError, ValueError): - return None - epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) - local = (epoch + datetime.timedelta(milliseconds=ms)).astimezone(zone) - wall = local.replace(tzinfo=None) - epoch.replace(tzinfo=None) - return wall / datetime.timedelta(milliseconds=1) - - -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: 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 - 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. - - Parameters - ---------- - path : str or Path - The MAT (v7.3, HDF5) file, e.g. a SLAP2 .meta file. - name : str - 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. - - 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 - understands. - """ - import struct - - import h5py - - try: - with h5py.File(path, "r") as h: - ds = h.get(name) - if ds is None or ds.attrs.get("MATLAB_class") not in ( - b"datetime", - "datetime", - ): - return None - object_id = int(np.asarray(ds[()]).ravel()[-2]) - props = _mcos_object_properties(h, object_id) - except (OSError, KeyError, ValueError, IndexError, struct.error): - return None - if not isinstance(props.get("data"), np.ndarray): - return None - data = props["data"].ravel() - if data.size != 1: # MATLAB's builder needs one reference time - return None - data = data[0] - if data.dtype.names: - ms = float(data["real"]) + float(data["imag"]) - else: - ms = float(np.real(data)) + float(np.imag(data)) - tz = _text(props.get("tz", "")) - if not np.isfinite(ms): - return None - ms += offset_ms - return _wall_clock_ms(ms, tz) if tz else ms - - -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 - - import slap2_utils - - importlib.reload(slap2_utils) - path = str(path) - if is_cycle_split(path): - return slap2_utils.MultiDataFiles(path) - return slap2_utils.DataFile(path) +"""SLAP2 binary reader access and saved alignment-data decoding. + +Band geometry and superpixel reduction belong to the extraction.band backend, +not this raw acquisition adapter. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Protocol + +import h5py +import numpy as np + +from .hdf5 import load_struct_h5 + + +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: 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 {} + return { + "DSframes": _reshape_1d(data, "DSframes"), + "motionDSr": _reshape_1d(data, "motionDSr"), + "motionDSc": _reshape_1d(data, "motionDSc"), + "motionDSz": _reshape_1d(data, "motionDSz"), + "onlineYshift": _reshape_1d(online, "onlineMotionYshift"), + "onlineXshift": _reshape_1d(online, "onlineMotionXshift"), + "onlineZshift": _reshape_1d(online, "onlineMotionZshift"), + "numChannels": int(np.asarray(data["numChannels"]).reshape(-1)[0]), + "alignHz": float(np.asarray(data["alignHz"]).reshape(-1)[0]), + } + + +class Slap2Reader(Protocol): + """Minimal raw-reader surface consumed by the existing band reducer. + + Line/cycle indexes passed to getLineData remain 1-based. The owning + caller retains the reader for the entire batched reduction; this protocol + deliberately promises neither a close method nor context-manager support. + """ + + header: dict + metaData: Any + numCycles: int + lineDataNumElements: Any + lineSuperPixelIDs: Any + lineFastZIdxs: Any + + 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: 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 + 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 + + +_LINE_MAGIC = 322379495 +"""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: _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. + + Parameters + ---------- + datafile : slap2_utils.DataFile + One file of a recording. + + Returns + ------- + 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: + f.seek(offset) + raw = f.read(32) + if len(raw) < 32: + raise ValueError(f"no line header in {datafile.datFileName}") + magic = int(np.frombuffer(raw[4:8], " list: + """Property sets of an MCOS ``FileWrapper__`` segment. + + 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], " 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 + string table and segments for classes, objects and property sets; each + object row gives the indexes of its two property sets. + + Returns + ------- + 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 + + refs = np.asarray(h["#subsystem#/MCOS"][()]).ravel() + blob = np.asarray(h[refs[0]][()]).ravel().tobytes() + _, n_str = struct.unpack_from(" 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 + + try: + zone = ZoneInfo("UTC" if tz.upper() == "UTC" else tz) + except (ZoneInfoNotFoundError, ValueError): + return None + epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) + local = (epoch + datetime.timedelta(milliseconds=ms)).astimezone(zone) + wall = local.replace(tzinfo=None) - epoch.replace(tzinfo=None) + return wall / datetime.timedelta(milliseconds=1) + + +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: 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 + 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. + + Parameters + ---------- + path : str or Path + The MAT (v7.3, HDF5) file, e.g. a SLAP2 .meta file. + name : str + 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. + + 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 + understands. + """ + import struct + + import h5py + + try: + with h5py.File(path, "r") as h: + ds = h.get(name) + if ds is None or ds.attrs.get("MATLAB_class") not in ( + b"datetime", + "datetime", + ): + return None + object_id = int(np.asarray(ds[()]).ravel()[-2]) + props = _mcos_object_properties(h, object_id) + except (OSError, KeyError, ValueError, IndexError, struct.error): + return None + if not isinstance(props.get("data"), np.ndarray): + return None + data = props["data"].ravel() + if data.size != 1: # MATLAB's builder needs one reference time + return None + data = data[0] + if data.dtype.names: + ms = float(data["real"]) + float(data["imag"]) + else: + ms = float(np.real(data)) + float(np.imag(data)) + tz = _text(props.get("tz", "")) + if not np.isfinite(ms): + return None + ms += offset_ms + return _wall_clock_ms(ms, tz) if tz else ms + + +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 + + import slap2_utils + + importlib.reload(slap2_utils) + path = str(path) + if is_cycle_split(path): + return slap2_utils.MultiDataFiles(path) + return slap2_utils.DataFile(path) diff --git a/src/giant_python/io/slap2_raster.py b/src/giant_python/io/slap2_raster.py index 33e2e424..b4ac071d 100644 --- a/src/giant_python/io/slap2_raster.py +++ b/src/giant_python/io/slap2_raster.py @@ -1,564 +1,564 @@ -"""Raster sample layout, raw sample reads and line headers of SLAP2 files. - -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 -file reader, and decodes the online-motion fields of line headers, as -getOnlineMotion does. - -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). - -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 -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 -that frames give them no weight. -""" - -import logging -from collections.abc import Iterator, Sequence -from dataclasses import dataclass -from pathlib import Path - -import numpy as np -from numpy.typing import ArrayLike - -from .slap2 import Slap2Reader, open_slap2_file - -log = logging.getLogger(__name__) - -INVALID_SAMPLE = -32768 -"""Raw value marking a sample the acquisition did not record.""" - -_PLACEHOLDER_Z = -10203 -"""First entry of slap2_utils fastZs for old-format metadata.""" - - -@dataclass(frozen=True) -class RasterLayout: - """Where every raster sample of a SLAP2 recording lies in its files. - - Attributes - ---------- - files : tuple of str - Data files in cycle order (several for CYCLE-split recordings). - file_cycles : ndarray of int - Number of cycles in each file. - file_offset_words : ndarray of int - Word (int16) offset of the first cycle in each file. - words_per_cycle : int - Words per cycle, identical in every file. - lines_per_cycle : int - Lines per cycle (P). - n_rows, n_cols : int - DMD image rows (dmdPixelsPerColumn) and columns - (dmdPixelsPerRow). - num_channels : int - Recorded channels. - line_period_s : float - Line period from the metadata file. - line_header_bytes : int - Size of each line header. - line_header_words : ndarray of int - Zero-based word offset of each line's header within a cycle. - row_base : ndarray of int - Zero-based word offset of each line's samples within a cycle. - n_per_channel : ndarray of int - Samples per channel on each line. - line_fast_z : ndarray of int - Fast-z plane index (one-based, 0 for none) of each line. - fast_zs : ndarray of float - Fast-z positions of the planes. - slot_line : ndarray of int - One-based line index of each raster slot. - slot_pos : ndarray of int - Zero-based position of each raster slot within its line's samples. - 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 - 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 - curtain follows; zeros when the metadata do not record it. - """ - - files: tuple[str, ...] - file_cycles: np.ndarray - file_offset_words: np.ndarray - words_per_cycle: int - lines_per_cycle: int - n_rows: int - n_cols: int - num_channels: int - line_period_s: float - line_header_bytes: int - line_header_words: np.ndarray - row_base: np.ndarray - n_per_channel: np.ndarray - line_fast_z: np.ndarray - fast_zs: np.ndarray - slot_line: np.ndarray - slot_pos: np.ndarray - slot_pixel: np.ndarray - dmd_curtain: np.ndarray | None = None - line_shear: np.ndarray | None = None - - @property - def num_cycles(self) -> int: - """Total number of cycles over all files.""" - return int(np.sum(self.file_cycles)) - - @property - def total_lines(self) -> int: - """Total number of lines over all files.""" - return self.num_cycles * self.lines_per_cycle - - -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. - - 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: - return ids[:0] - if ids.size != n_samples: - raise ValueError( - f"parse plan lists {ids.size} superpixels for a line with " - f"{n_samples} samples per channel" - ) - return ids - - -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: 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: - return "" - return "".join(chr(int(c)) for c in np.asarray(value).ravel()) - - -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 - 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 {} - path = config.get(_text(getattr(meta, "acquisitionPathName", ""))) - if not isinstance(path, dict) or "dmdCurtain" not in path: - return None, None - curtain = np.asarray(path["dmdCurtain"], dtype=np.float64).ravel() - if curtain.size != 2 or not np.all(np.isfinite(curtain)): - return None, None - dmd = config.get(_text(path.get("hDmd")), {}) - shear = np.asarray( - dmd.get("lineShear", []) if isinstance(dmd, dict) else [], - dtype=np.float64, - ).ravel() - if shear.size != n_rows or not np.all(np.isfinite(shear)): - shear = np.zeros(n_rows) - return curtain, shear - - -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. - - Returns - ------- - RasterLayout - The layout; only raster superpixels (IDs within the DMD) are listed, - 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) - first = files[0] - hdr = first.header - p = int(hdr["linesPerCycle"]) - n_cols = int(hdr["dmdPixelsPerRow"]) - n_rows = int(hdr["dmdPixelsPerColumn"]) - n_ch = int(hdr["numChannels"]) - if int(hdr.get("channelsInterleave", 0)): - raise ValueError("only deinterleaved SLAP2 data are supported") - header_idx = np.asarray(first.lineHeaderIdxs, dtype=np.int64) - start_idx = np.asarray(first.lineDataStartIdxs, dtype=np.int64) - n_elem = np.asarray(first.lineDataNumElements, dtype=np.int64) - n_per_ch = n_elem // n_ch - words = int(hdr["bytesPerCycle"]) // 2 - for df in files[1:]: - if int(df.header["bytesPerCycle"]) // 2 != words or not np.array_equal( - np.asarray(df.lineDataStartIdxs), start_idx - ): - raise ValueError("the files of a recording differ in layout") - slot_line, slot_pos, slot_pixel = [], [], [] - n_px = n_rows * n_cols - for line in range(1, p + 1): - ids = _line_ids(first.lineSuperPixelIDs[line - 1], n_per_ch[line - 1]) - pix = ids + 1 - sel = np.flatnonzero(pix <= n_px) - slot_line.append(np.full(sel.size, line, dtype=np.int64)) - slot_pos.append(sel.astype(np.int64)) - slot_pixel.append(pix[sel]) - fast_zs = np.asarray(first.fastZs, dtype=np.float64).ravel() - if fast_zs.size and fast_zs[0] == _PLACEHOLDER_Z: - fast_zs = fast_zs[1:] - curtain, shear = _dmd_curtain(first.metaData, n_rows) - 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]), - words_per_cycle=words, - lines_per_cycle=p, - n_rows=n_rows, - n_cols=n_cols, - num_channels=n_ch, - line_period_s=float(first.metaData.linePeriod_s), - line_header_bytes=int(hdr["lineHeaderSizeBytes"]), - line_header_words=header_idx - header_idx[0], - row_base=start_idx - header_idx[0], - n_per_channel=n_per_ch, - line_fast_z=np.asarray(first.lineFastZIdxs).astype(np.int64), - fast_zs=fast_zs, - slot_line=np.concatenate(slot_line), - slot_pos=np.concatenate(slot_pos), - slot_pixel=np.concatenate(slot_pixel), - dmd_curtain=curtain, - line_shear=shear, - ) - - -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)): - lo, hi = max(c0, s), min(c1, e) - if lo < hi: - yield f, int(lo - s), int(hi - lo), int(lo - c0) - - -def read_raster_samples( - layout: RasterLayout, - cycles: tuple[int, int], - slots: np.ndarray | None = None, - chunk_cycles: int = 256, - mask_unlit: bool = False, -) -> np.ndarray: - """Read raw raster samples of a range of cycles. - - Parameters - ---------- - layout : RasterLayout - The recording's layout. - cycles : (int, int) - 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 - that frames formed from them give them no weight. Default: the raw - values. - - Returns - ------- - ndarray of int16 - 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: - raise ValueError(f"cycle range {cycles} outside the recording") - if slots is None: - 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] - for ch in range(layout.num_channels) - ] - out = np.empty((layout.num_channels, slots.size, c1 - c0), dtype=np.int16) - wpc = layout.words_per_cycle - for f, local, count, dst in _file_spans(layout, c0, c1): - mm = np.memmap( - layout.files[f], - dtype=np.int16, - mode="r", - offset=2 * int(layout.file_offset_words[f]), - shape=(int(layout.file_cycles[f]), wpc), - ) - for a in range(0, count, chunk_cycles): - b = min(count, a + chunk_cycles) - block = np.asarray(mm[local + a : local + b]) - for ch in range(layout.num_channels): - out[ch, :, dst + a : dst + b] = block[:, word[ch]].T - del mm - if mask_unlit: - s, c = unlit_samples(layout, (c0, c1), slots) - out[:, s, c] = INVALID_SAMPLE - if s.size: - log.debug( - "%d samples of %d slots in cycles %d-%d are behind the DMD curtain", - s.size, - np.unique(s).size, - c0, - c1 - 1, - ) - return out - - -def read_line_offsets( - layout: RasterLayout, lines: Sequence[int] -) -> 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 - when headers are longer than 32 bytes; 0 otherwise). - - Parameters - ---------- - layout : RasterLayout - The recording's layout. - lines : sequence of int - One-based global line numbers. - - Returns - ------- - x, y, z : ndarray of float - 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 - if lines.size and (lines.min() < 1 or lines.max() > layout.total_lines): - raise ValueError("line numbers outside the recording") - cyc = (lines - 1) // p - li = (lines - 1) % p - x = np.full(lines.size, np.nan) - y = np.full(lines.size, np.nan) - z = np.zeros(lines.size) - ends = np.cumsum(layout.file_cycles) - starts = ends - layout.file_cycles - for f in range(len(layout.files)): - sel = np.flatnonzero((cyc >= starts[f]) & (cyc < ends[f])) - if sel.size == 0: - continue - byte = 2 * ( - layout.file_offset_words[f] - + (cyc[sel] - starts[f]) * layout.words_per_cycle - + layout.line_header_words[li[sel]] - ) - mm = np.memmap(layout.files[f], dtype=np.uint8, mode="r") - raw = mm[byte[:, None] + np.arange(min(40, layout.line_header_bytes))] - del mm - x[sel] = raw[:, 20:22].copy().view(np.int16).ravel() - y[sel] = raw[:, 22:24].copy().view(np.int16).ravel() - if layout.line_header_bytes > 32: - z[sel] = raw[:, 32:36].copy().view(np.float32).ravel() - return x, y, z - - -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. - 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. - - Returns - ------- - ndarray of bool - 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). - """ - n = layout.n_cols - c1, c2 = (float(v) for v in layout.dmd_curtain) - shear = layout.line_shear - if shear is None: - shear = np.zeros(layout.n_rows) - rows = np.clip(np.asarray(rows, dtype=np.int64), 0, layout.n_rows - 1) - frac = np.asarray(cols, dtype=np.int64) / (n - 1) - shear[rows] / n - return (frac >= c1 + 1 / n) & (frac <= c2 - 1 / n) - - -def unlit_samples( - layout: RasterLayout, - cycles: tuple[int, int], - slots: np.ndarray | None = None, - block_slots: int = 2048, -) -> 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 - 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 - :func:`giant_python.registration.compensation.line_offsets`). y only - selects the row's shear. - - Parameters - ---------- - layout : RasterLayout - The recording's layout. - cycles : (int, int) - Zero-based cycle range [c0, c1). - slots : ndarray of int, optional - Raster slots (default: all). - block_slots : int - Slots near the curtain tested at a time, bounding temporary memory. - - Returns - ------- - slot, cycle : ndarray of int - 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) - c0, c1 = int(cycles[0]), int(cycles[1]) - if slots is None: - slots = np.arange(layout.slot_line.size) - slots = np.asarray(slots, dtype=np.int64) - if layout.dmd_curtain is None or c1 <= c0 or slots.size == 0: - return empty, empty - from ..registration.compensation import Y_LEAD, dmd_y - - p = layout.lines_per_cycle - # the cycles' headers and a margin for the lead of y switches: the y on - # the DMD is exact on the cycles' lines, as from line_offsets - pad = max(Y_LEAD) + 1 - lo = max(1, c0 * p + 1 - pad) - hi = min(layout.total_lines, c1 * p + pad) - x, y, _ = read_line_offsets(layout, np.arange(lo, hi + 1)) - x, y = x.astype(np.int64), y.astype(np.int64) - switch = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 - y = dmd_y(x, y, switch, Y_LEAD) - a = c0 * p + 1 - lo - x = x[a : a + (c1 - c0) * p].reshape(c1 - c0, p) - y = y[a : a + (c1 - c0) * p].reshape(c1 - c0, p) - rows = (layout.slot_pixel[slots] - 1) // layout.n_cols - cols = (layout.slot_pixel[slots] - 1) % layout.n_cols - lines = layout.slot_line[slots] - 1 - # lit columns of every DMD row (an interval: the mask is monotonic in - # the column); a slot whose columns stay inside all rows' intervals at - # its line's extreme x offsets is lit throughout - grid = lit_mirrors( - layout, - np.arange(layout.n_rows)[:, None], - np.arange(layout.n_cols)[None, :], - ) - if grid.any(1).all(): - lo = int(np.max(np.argmax(grid, 1))) - 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)) - out_s, out_c = [], [] - for a in range(0, near.size, block_slots): - idx = near[a : a + block_slots] - lit = lit_mirrors( - layout, - rows[idx][:, None] + y[:, lines[idx]].T, - cols[idx][:, None] + x[:, lines[idx]].T, - ) - s, c = np.nonzero(~lit) - out_s.append(idx[s]) - out_c.append(c) - if not out_s: - return empty, empty - return np.concatenate(out_s), np.concatenate(out_c) +"""Raster sample layout, raw sample reads and line headers of SLAP2 files. + +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 +file reader, and decodes the online-motion fields of line headers, as +getOnlineMotion does. + +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). + +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 +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 +that frames give them no weight. +""" + +import logging +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +from numpy.typing import ArrayLike + +from .slap2 import Slap2Reader, open_slap2_file + +log = logging.getLogger(__name__) + +INVALID_SAMPLE = -32768 +"""Raw value marking a sample the acquisition did not record.""" + +_PLACEHOLDER_Z = -10203 +"""First entry of slap2_utils fastZs for old-format metadata.""" + + +@dataclass(frozen=True) +class RasterLayout: + """Where every raster sample of a SLAP2 recording lies in its files. + + Attributes + ---------- + files : tuple of str + Data files in cycle order (several for CYCLE-split recordings). + file_cycles : ndarray of int + Number of cycles in each file. + file_offset_words : ndarray of int + Word (int16) offset of the first cycle in each file. + words_per_cycle : int + Words per cycle, identical in every file. + lines_per_cycle : int + Lines per cycle (P). + n_rows, n_cols : int + DMD image rows (dmdPixelsPerColumn) and columns + (dmdPixelsPerRow). + num_channels : int + Recorded channels. + line_period_s : float + Line period from the metadata file. + line_header_bytes : int + Size of each line header. + line_header_words : ndarray of int + Zero-based word offset of each line's header within a cycle. + row_base : ndarray of int + Zero-based word offset of each line's samples within a cycle. + n_per_channel : ndarray of int + Samples per channel on each line. + line_fast_z : ndarray of int + Fast-z plane index (one-based, 0 for none) of each line. + fast_zs : ndarray of float + Fast-z positions of the planes. + slot_line : ndarray of int + One-based line index of each raster slot. + slot_pos : ndarray of int + Zero-based position of each raster slot within its line's samples. + 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 + 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 + curtain follows; zeros when the metadata do not record it. + """ + + files: tuple[str, ...] + file_cycles: np.ndarray + file_offset_words: np.ndarray + words_per_cycle: int + lines_per_cycle: int + n_rows: int + n_cols: int + num_channels: int + line_period_s: float + line_header_bytes: int + line_header_words: np.ndarray + row_base: np.ndarray + n_per_channel: np.ndarray + line_fast_z: np.ndarray + fast_zs: np.ndarray + slot_line: np.ndarray + slot_pos: np.ndarray + slot_pixel: np.ndarray + dmd_curtain: np.ndarray | None = None + line_shear: np.ndarray | None = None + + @property + def num_cycles(self) -> int: + """Total number of cycles over all files.""" + return int(np.sum(self.file_cycles)) + + @property + def total_lines(self) -> int: + """Total number of lines over all files.""" + return self.num_cycles * self.lines_per_cycle + + +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. + + 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: + return ids[:0] + if ids.size != n_samples: + raise ValueError( + f"parse plan lists {ids.size} superpixels for a line with " + f"{n_samples} samples per channel" + ) + return ids + + +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: 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: + return "" + return "".join(chr(int(c)) for c in np.asarray(value).ravel()) + + +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 + 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 {} + path = config.get(_text(getattr(meta, "acquisitionPathName", ""))) + if not isinstance(path, dict) or "dmdCurtain" not in path: + return None, None + curtain = np.asarray(path["dmdCurtain"], dtype=np.float64).ravel() + if curtain.size != 2 or not np.all(np.isfinite(curtain)): + return None, None + dmd = config.get(_text(path.get("hDmd")), {}) + shear = np.asarray( + dmd.get("lineShear", []) if isinstance(dmd, dict) else [], + dtype=np.float64, + ).ravel() + if shear.size != n_rows or not np.all(np.isfinite(shear)): + shear = np.zeros(n_rows) + return curtain, shear + + +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. + + Returns + ------- + RasterLayout + The layout; only raster superpixels (IDs within the DMD) are listed, + 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) + first = files[0] + hdr = first.header + p = int(hdr["linesPerCycle"]) + n_cols = int(hdr["dmdPixelsPerRow"]) + n_rows = int(hdr["dmdPixelsPerColumn"]) + n_ch = int(hdr["numChannels"]) + if int(hdr.get("channelsInterleave", 0)): + raise ValueError("only deinterleaved SLAP2 data are supported") + header_idx = np.asarray(first.lineHeaderIdxs, dtype=np.int64) + start_idx = np.asarray(first.lineDataStartIdxs, dtype=np.int64) + n_elem = np.asarray(first.lineDataNumElements, dtype=np.int64) + n_per_ch = n_elem // n_ch + words = int(hdr["bytesPerCycle"]) // 2 + for df in files[1:]: + if int(df.header["bytesPerCycle"]) // 2 != words or not np.array_equal( + np.asarray(df.lineDataStartIdxs), start_idx + ): + raise ValueError("the files of a recording differ in layout") + slot_line, slot_pos, slot_pixel = [], [], [] + n_px = n_rows * n_cols + for line in range(1, p + 1): + ids = _line_ids(first.lineSuperPixelIDs[line - 1], n_per_ch[line - 1]) + pix = ids + 1 + sel = np.flatnonzero(pix <= n_px) + slot_line.append(np.full(sel.size, line, dtype=np.int64)) + slot_pos.append(sel.astype(np.int64)) + slot_pixel.append(pix[sel]) + fast_zs = np.asarray(first.fastZs, dtype=np.float64).ravel() + if fast_zs.size and fast_zs[0] == _PLACEHOLDER_Z: + fast_zs = fast_zs[1:] + curtain, shear = _dmd_curtain(first.metaData, n_rows) + 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]), + words_per_cycle=words, + lines_per_cycle=p, + n_rows=n_rows, + n_cols=n_cols, + num_channels=n_ch, + line_period_s=float(first.metaData.linePeriod_s), + line_header_bytes=int(hdr["lineHeaderSizeBytes"]), + line_header_words=header_idx - header_idx[0], + row_base=start_idx - header_idx[0], + n_per_channel=n_per_ch, + line_fast_z=np.asarray(first.lineFastZIdxs).astype(np.int64), + fast_zs=fast_zs, + slot_line=np.concatenate(slot_line), + slot_pos=np.concatenate(slot_pos), + slot_pixel=np.concatenate(slot_pixel), + dmd_curtain=curtain, + line_shear=shear, + ) + + +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)): + lo, hi = max(c0, s), min(c1, e) + if lo < hi: + yield f, int(lo - s), int(hi - lo), int(lo - c0) + + +def read_raster_samples( + layout: RasterLayout, + cycles: tuple[int, int], + slots: np.ndarray | None = None, + chunk_cycles: int = 256, + mask_unlit: bool = False, +) -> np.ndarray: + """Read raw raster samples of a range of cycles. + + Parameters + ---------- + layout : RasterLayout + The recording's layout. + cycles : (int, int) + 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 + that frames formed from them give them no weight. Default: the raw + values. + + Returns + ------- + ndarray of int16 + 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: + raise ValueError(f"cycle range {cycles} outside the recording") + if slots is None: + 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] + for ch in range(layout.num_channels) + ] + out = np.empty((layout.num_channels, slots.size, c1 - c0), dtype=np.int16) + wpc = layout.words_per_cycle + for f, local, count, dst in _file_spans(layout, c0, c1): + mm = np.memmap( + layout.files[f], + dtype=np.int16, + mode="r", + offset=2 * int(layout.file_offset_words[f]), + shape=(int(layout.file_cycles[f]), wpc), + ) + for a in range(0, count, chunk_cycles): + b = min(count, a + chunk_cycles) + block = np.asarray(mm[local + a : local + b]) + for ch in range(layout.num_channels): + out[ch, :, dst + a : dst + b] = block[:, word[ch]].T + del mm + if mask_unlit: + s, c = unlit_samples(layout, (c0, c1), slots) + out[:, s, c] = INVALID_SAMPLE + if s.size: + log.debug( + "%d samples of %d slots in cycles %d-%d are behind the DMD curtain", + s.size, + np.unique(s).size, + c0, + c1 - 1, + ) + return out + + +def read_line_offsets( + layout: RasterLayout, lines: Sequence[int] +) -> 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 + when headers are longer than 32 bytes; 0 otherwise). + + Parameters + ---------- + layout : RasterLayout + The recording's layout. + lines : sequence of int + One-based global line numbers. + + Returns + ------- + x, y, z : ndarray of float + 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 + if lines.size and (lines.min() < 1 or lines.max() > layout.total_lines): + raise ValueError("line numbers outside the recording") + cyc = (lines - 1) // p + li = (lines - 1) % p + x = np.full(lines.size, np.nan) + y = np.full(lines.size, np.nan) + z = np.zeros(lines.size) + ends = np.cumsum(layout.file_cycles) + starts = ends - layout.file_cycles + for f in range(len(layout.files)): + sel = np.flatnonzero((cyc >= starts[f]) & (cyc < ends[f])) + if sel.size == 0: + continue + byte = 2 * ( + layout.file_offset_words[f] + + (cyc[sel] - starts[f]) * layout.words_per_cycle + + layout.line_header_words[li[sel]] + ) + mm = np.memmap(layout.files[f], dtype=np.uint8, mode="r") + raw = mm[byte[:, None] + np.arange(min(40, layout.line_header_bytes))] + del mm + x[sel] = raw[:, 20:22].copy().view(np.int16).ravel() + y[sel] = raw[:, 22:24].copy().view(np.int16).ravel() + if layout.line_header_bytes > 32: + z[sel] = raw[:, 32:36].copy().view(np.float32).ravel() + return x, y, z + + +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. + 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. + + Returns + ------- + ndarray of bool + 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). + """ + n = layout.n_cols + c1, c2 = (float(v) for v in layout.dmd_curtain) + shear = layout.line_shear + if shear is None: + shear = np.zeros(layout.n_rows) + rows = np.clip(np.asarray(rows, dtype=np.int64), 0, layout.n_rows - 1) + frac = np.asarray(cols, dtype=np.int64) / (n - 1) - shear[rows] / n + return (frac >= c1 + 1 / n) & (frac <= c2 - 1 / n) + + +def unlit_samples( + layout: RasterLayout, + cycles: tuple[int, int], + slots: np.ndarray | None = None, + block_slots: int = 2048, +) -> 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 + 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 + :func:`giant_python.registration.compensation.line_offsets`). y only + selects the row's shear. + + Parameters + ---------- + layout : RasterLayout + The recording's layout. + cycles : (int, int) + Zero-based cycle range [c0, c1). + slots : ndarray of int, optional + Raster slots (default: all). + block_slots : int + Slots near the curtain tested at a time, bounding temporary memory. + + Returns + ------- + slot, cycle : ndarray of int + 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) + c0, c1 = int(cycles[0]), int(cycles[1]) + if slots is None: + slots = np.arange(layout.slot_line.size) + slots = np.asarray(slots, dtype=np.int64) + if layout.dmd_curtain is None or c1 <= c0 or slots.size == 0: + return empty, empty + from ..registration.compensation import Y_LEAD, dmd_y + + p = layout.lines_per_cycle + # the cycles' headers and a margin for the lead of y switches: the y on + # the DMD is exact on the cycles' lines, as from line_offsets + pad = max(Y_LEAD) + 1 + lo = max(1, c0 * p + 1 - pad) + hi = min(layout.total_lines, c1 * p + pad) + x, y, _ = read_line_offsets(layout, np.arange(lo, hi + 1)) + x, y = x.astype(np.int64), y.astype(np.int64) + switch = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 + y = dmd_y(x, y, switch, Y_LEAD) + a = c0 * p + 1 - lo + x = x[a : a + (c1 - c0) * p].reshape(c1 - c0, p) + y = y[a : a + (c1 - c0) * p].reshape(c1 - c0, p) + rows = (layout.slot_pixel[slots] - 1) // layout.n_cols + cols = (layout.slot_pixel[slots] - 1) % layout.n_cols + lines = layout.slot_line[slots] - 1 + # lit columns of every DMD row (an interval: the mask is monotonic in + # the column); a slot whose columns stay inside all rows' intervals at + # its line's extreme x offsets is lit throughout + grid = lit_mirrors( + layout, + np.arange(layout.n_rows)[:, None], + np.arange(layout.n_cols)[None, :], + ) + if grid.any(1).all(): + lo = int(np.max(np.argmax(grid, 1))) + 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)) + out_s, out_c = [], [] + for a in range(0, near.size, block_slots): + idx = near[a : a + block_slots] + lit = lit_mirrors( + layout, + rows[idx][:, None] + y[:, lines[idx]].T, + cols[idx][:, None] + x[:, lines[idx]].T, + ) + s, c = np.nonzero(~lit) + out_s.append(idx[s]) + out_c.append(c) + if not out_s: + return empty, empty + return np.concatenate(out_s), np.concatenate(out_c) diff --git a/src/giant_python/io/tiff.py b/src/giant_python/io/tiff.py index 7342b0ec..f5dc9268 100644 --- a/src/giant_python/io/tiff.py +++ b/src/giant_python/io/tiff.py @@ -1,21 +1,21 @@ -"""Native TIFF array reading without acquisition-specific transformations.""" - -from pathlib import Path - -import numpy as np - - -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 - - return tifffile.imread(path) +"""Native TIFF array reading without acquisition-specific transformations.""" + +from pathlib import Path + +import numpy as np + + +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 + + return tifffile.imread(path) diff --git a/src/giant_python/io/trial_table.py b/src/giant_python/io/trial_table.py index 90a9817d..cb4ee590 100644 --- a/src/giant_python/io/trial_table.py +++ b/src/giant_python/io/trial_table.py @@ -1,55 +1,55 @@ -"""Faithful trial-table schema decoding, without runtime file discovery.""" - -from pathlib import Path - -import numpy as np - -from ..models.trial_table import Slap2Info, TrialTable -from .hdf5 import load_struct_h5 - - -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 = ( - "ref_stack", - "first_line", - "last_line", - "trial_start_time_inferred", - "trial_end_time_from_pc", - ) - return Slap2Info(**{key: slap2[key] for key in names if key in slap2}) - - -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. - Numeric ranks are retained; the filename string grid is always rank two. - - 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)), - true_trial_ix=raw.get("true_trial_ix", []), - epoch=raw.get("epoch", []), - slap2_info=slap2_info_from_raw(raw.get("slap2_info")), - motion_correction=raw.get("motion_correction"), - source_extraction=raw.get("source_extraction"), - source_path=Path(path).absolute(), - ) +"""Faithful trial-table schema decoding, without runtime file discovery.""" + +from pathlib import Path + +import numpy as np + +from ..models.trial_table import Slap2Info, TrialTable +from .hdf5 import load_struct_h5 + + +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 = ( + "ref_stack", + "first_line", + "last_line", + "trial_start_time_inferred", + "trial_end_time_from_pc", + ) + return Slap2Info(**{key: slap2[key] for key in names if key in slap2}) + + +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. + Numeric ranks are retained; the filename string grid is always rank two. + + 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)), + true_trial_ix=raw.get("true_trial_ix", []), + epoch=raw.get("epoch", []), + slap2_info=slap2_info_from_raw(raw.get("slap2_info")), + motion_correction=raw.get("motion_correction"), + source_extraction=raw.get("source_extraction"), + source_path=Path(path).absolute(), + ) diff --git a/src/giant_python/models/__init__.py b/src/giant_python/models/__init__.py index baf05c0b..97680e44 100644 --- a/src/giant_python/models/__init__.py +++ b/src/giant_python/models/__init__.py @@ -1,46 +1,46 @@ -"""Typed data models for GIAnT-Python. - -Scientific configuration is distinct from run and annotation policy. -Implemented model codecs delegate to shared IO. -""" - -from .experiment_summary import ( - ExperimentSummary, - FrameInfo, - PathSummary, - Source, - UserRoi, - Visualizations, -) -from .params import ( - AnnotationOptions, - BandSiloParams, - ExecutionOptions, - MultiRoiRegistrationParams, - SiloExecution, - SiloParams, - resolve_band_options, - resolve_registration_options, - resolve_silo_options, -) -from .trial_table import Slap2Info, TrialTable - -__all__ = [ - "AnnotationOptions", - "BandSiloParams", - "ExecutionOptions", - "ExperimentSummary", - "FrameInfo", - "MultiRoiRegistrationParams", - "PathSummary", - "SiloExecution", - "SiloParams", - "Slap2Info", - "Source", - "TrialTable", - "UserRoi", - "Visualizations", - "resolve_band_options", - "resolve_registration_options", - "resolve_silo_options", -] +"""Typed data models for GIAnT-Python. + +Scientific configuration is distinct from run and annotation policy. +Implemented model codecs delegate to shared IO. +""" + +from .experiment_summary import ( + ExperimentSummary, + FrameInfo, + PathSummary, + Source, + UserRoi, + Visualizations, +) +from .params import ( + AnnotationOptions, + BandSiloParams, + ExecutionOptions, + MultiRoiRegistrationParams, + SiloExecution, + SiloParams, + resolve_band_options, + resolve_registration_options, + resolve_silo_options, +) +from .trial_table import Slap2Info, TrialTable + +__all__ = [ + "AnnotationOptions", + "BandSiloParams", + "ExecutionOptions", + "ExperimentSummary", + "FrameInfo", + "MultiRoiRegistrationParams", + "PathSummary", + "SiloExecution", + "SiloParams", + "Slap2Info", + "Source", + "TrialTable", + "UserRoi", + "Visualizations", + "resolve_band_options", + "resolve_registration_options", + "resolve_silo_options", +] diff --git a/src/giant_python/models/trial_table.py b/src/giant_python/models/trial_table.py index ef0e9fec..d94c9135 100644 --- a/src/giant_python/models/trial_table.py +++ b/src/giant_python/models/trial_table.py @@ -1,102 +1,102 @@ -"""Trial table model (trialTable struct / trial_table.h5).""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path - -import numpy as np - - -@dataclass -class Slap2Info: - """SLAP2-specific trial metadata stored alongside the trial table. - - Corresponds to the slap2_info sub-struct in GIAnT-MATLAB. Holds the - reference stack(s), per-trial line ranges, and inferred timing. - - Attributes - ---------- - ref_stack : dict - Reference stack(s), keyed by DMD path, each with image, channels, - Zs, and the DMD-pixel-to-sample transform. - first_line, last_line : ndarray or list - First/last scanned line index for each trial. - trial_start_time_inferred, trial_end_time_from_pc : ndarray or list - Inferred and PC-reported trial timing. - """ - - ref_stack: dict = field(default_factory=dict) - 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 - GIAnT-MATLAB. The motion-correction and source-extraction stages append - their groups (motion_correction, source_extraction) to this same - structure, so it is the shared state held by :class:`~giant_python.\ -pipeline.pipeline.Pipeline`. - - Attributes - ---------- - datadr : Path or None - Directory containing the raw data files. - savedr : Path or None - Directory in which results are written. - filename : ndarray or list - File names, shaped (n_dmds, n_trials). - true_trial_ix : ndarray or list - Trial indices, shaped (n_dmds, n_trials). - epoch : ndarray or list - Epoch numbers, shaped (n_dmds, n_trials). - slap2_info : Slap2Info or None - 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). - source_extraction : dict or None - Populated by the extraction stage (analysis params, raw input files). - """ - - 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: Path | None = field(default=None, repr=False, compare=False) - - @classmethod - 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 - 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. - - Parameters - ---------- - path : str or Path - Path to the trial_table.h5 file. - - Returns - ------- - TrialTable - The deserialized trial table. - """ - from ..io.trial_table import read_trial_table - - return read_trial_table(path) +"""Trial table model (trialTable struct / trial_table.h5).""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + + +@dataclass +class Slap2Info: + """SLAP2-specific trial metadata stored alongside the trial table. + + Corresponds to the slap2_info sub-struct in GIAnT-MATLAB. Holds the + reference stack(s), per-trial line ranges, and inferred timing. + + Attributes + ---------- + ref_stack : dict + Reference stack(s), keyed by DMD path, each with image, channels, + Zs, and the DMD-pixel-to-sample transform. + first_line, last_line : ndarray or list + First/last scanned line index for each trial. + trial_start_time_inferred, trial_end_time_from_pc : ndarray or list + Inferred and PC-reported trial timing. + """ + + ref_stack: dict = field(default_factory=dict) + 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 + GIAnT-MATLAB. The motion-correction and source-extraction stages append + their groups (motion_correction, source_extraction) to this same + structure, so it is the shared state held by :class:`~giant_python.\ +pipeline.pipeline.Pipeline`. + + Attributes + ---------- + datadr : Path or None + Directory containing the raw data files. + savedr : Path or None + Directory in which results are written. + filename : ndarray or list + File names, shaped (n_dmds, n_trials). + true_trial_ix : ndarray or list + Trial indices, shaped (n_dmds, n_trials). + epoch : ndarray or list + Epoch numbers, shaped (n_dmds, n_trials). + slap2_info : Slap2Info or None + 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). + source_extraction : dict or None + Populated by the extraction stage (analysis params, raw input files). + """ + + 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: Path | None = field(default=None, repr=False, compare=False) + + @classmethod + 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 + 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. + + Parameters + ---------- + path : str or Path + Path to the trial_table.h5 file. + + Returns + ------- + TrialTable + The deserialized trial table. + """ + from ..io.trial_table import read_trial_table + + return read_trial_table(path) diff --git a/src/giant_python/numerics/__init__.py b/src/giant_python/numerics/__init__.py index ef7f1da6..97556228 100644 --- a/src/giant_python/numerics/__init__.py +++ b/src/giant_python/numerics/__init__.py @@ -1,4 +1,4 @@ -"""Implemented baseline, peak, interpolation and morphology kernels. - -Import individual modules as needed. -""" +"""Implemented baseline, peak, interpolation and morphology kernels. + +Import individual modules as needed. +""" diff --git a/src/giant_python/numerics/baseline.py b/src/giant_python/numerics/baseline.py index d4669fb8..e187cd52 100644 --- a/src/giant_python/numerics/baseline.py +++ b/src/giant_python/numerics/baseline.py @@ -1,187 +1,187 @@ -"""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). -: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. -""" - -from __future__ import annotations - -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). - - Uses partial windows at the edges and returns NaN where a window contains - no valid samples. - - Parameters - ---------- - x : ndarray - 1-D input (NaNs allowed). - window : int - Window length in samples (clamped to >= 1). - - Returns - ------- - ndarray of float - The smoothed signal. - """ - window = max(int(window), 1) - if window == 1: - return x.astype(float, copy=True) - - kernel = np.ones(window, dtype=float) - valid = ~np.isnan(x) - x_filled = np.where(valid, x, 0.0) - - num = np.convolve(x_filled, kernel, mode="same") - den = np.convolve(valid.astype(float), kernel, mode="same") - - return num / np.where(den == 0.0, np.nan, den) - - -def _compute_f0_column( - f0_col: np.ndarray, - sample_times: np.ndarray, - n_samps_in_hull: int, - total_frames: int, -) -> np.ndarray: - """Estimate the baseline for one already-median-filtered trace 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. - - 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) - ff = np.nanmin(f00, axis=1) - - doubt = np.sum(~np.isnan(f00), axis=1) < int(np.ceil(n_samps_in_hull / 2)) - if np.sum(~doubt) > 2: - ff[doubt] = np.nan - - win = 2 * int(np.ceil(n_samps_in_hull / 2.0)) + 1 - fill = _movmean_nan(ff, win) - nan_mask = np.isnan(ff) - ff[nan_mask] = fill[nan_mask] - ff = _movmean_nan(ff, win) - - nan_mask = np.isnan(ff) - if np.any(nan_mask): - ff = np.interp(sample_times, sample_times[~nan_mask], ff[~nan_mask]) - - pchip = PchipInterpolator(sample_times, ff, extrapolate=True) - 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. - - 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. - - Parameters - ---------- - f_in : ndarray of shape (T, ...) - Fluorescence with time along axis 0 (NaNs allowed). - denoise_window : int - Rolling-median window (time samples). - hull_window : int - Window controlling the convex-hull-like envelope. - - Returns - ------- - ndarray - The baseline F0, same shape as f_in. - """ - f = np.asarray(f_in) - orig_shape = f.shape - if f.ndim == 1: - f = f[:, None] - else: - f = f.reshape(f.shape[0], -1) - - 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) - - 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)) - ).astype(int) - n_samps_in_hull = int(np.ceil(hull_window / delta_des)) - - f0 = ( - pd - .DataFrame(f) - .rolling(window=denoise_window, center=True, min_periods=1) - .median() - .to_numpy() - ) - - # ``to_numpy()`` can hand back a read-only view (pandas copy-on-write), so - # take a writable, owned copy before assigning the per-column baselines. - f0 = np.array(f0, dtype=float).reshape(f0.shape[0], -1) - 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) - - return f0.reshape(orig_shape) - - -def assemble_dff( - d_f_ls: np.ndarray, - 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. - - 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). - - Parameters - ---------- - d_f_ls : ndarray of shape (T, n_sources) - 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 - Windows passed to :func:`compute_f0`. - - Returns - ------- - f, f0, d_f, d_ff : ndarray - Total fluorescence, baseline, baseline-subtracted, and dF/F. - """ - f = d_f_ls + f0_ls - f0 = compute_f0(f, denoise_window, hull_window) - d_f = f - f0 - d_ff = d_f / np.clip(f0, 1e-4, None) - return f, f0, d_f, d_ff +"""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). +: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. +""" + +from __future__ import annotations + +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). + + Uses partial windows at the edges and returns NaN where a window contains + no valid samples. + + Parameters + ---------- + x : ndarray + 1-D input (NaNs allowed). + window : int + Window length in samples (clamped to >= 1). + + Returns + ------- + ndarray of float + The smoothed signal. + """ + window = max(int(window), 1) + if window == 1: + return x.astype(float, copy=True) + + kernel = np.ones(window, dtype=float) + valid = ~np.isnan(x) + x_filled = np.where(valid, x, 0.0) + + num = np.convolve(x_filled, kernel, mode="same") + den = np.convolve(valid.astype(float), kernel, mode="same") + + return num / np.where(den == 0.0, np.nan, den) + + +def _compute_f0_column( + f0_col: np.ndarray, + sample_times: np.ndarray, + n_samps_in_hull: int, + total_frames: int, +) -> np.ndarray: + """Estimate the baseline for one already-median-filtered trace 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. + + 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) + ff = np.nanmin(f00, axis=1) + + doubt = np.sum(~np.isnan(f00), axis=1) < int(np.ceil(n_samps_in_hull / 2)) + if np.sum(~doubt) > 2: + ff[doubt] = np.nan + + win = 2 * int(np.ceil(n_samps_in_hull / 2.0)) + 1 + fill = _movmean_nan(ff, win) + nan_mask = np.isnan(ff) + ff[nan_mask] = fill[nan_mask] + ff = _movmean_nan(ff, win) + + nan_mask = np.isnan(ff) + if np.any(nan_mask): + ff = np.interp(sample_times, sample_times[~nan_mask], ff[~nan_mask]) + + pchip = PchipInterpolator(sample_times, ff, extrapolate=True) + 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. + + 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. + + Parameters + ---------- + f_in : ndarray of shape (T, ...) + Fluorescence with time along axis 0 (NaNs allowed). + denoise_window : int + Rolling-median window (time samples). + hull_window : int + Window controlling the convex-hull-like envelope. + + Returns + ------- + ndarray + The baseline F0, same shape as f_in. + """ + f = np.asarray(f_in) + orig_shape = f.shape + if f.ndim == 1: + f = f[:, None] + else: + f = f.reshape(f.shape[0], -1) + + 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) + + 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)) + ).astype(int) + n_samps_in_hull = int(np.ceil(hull_window / delta_des)) + + f0 = ( + pd + .DataFrame(f) + .rolling(window=denoise_window, center=True, min_periods=1) + .median() + .to_numpy() + ) + + # ``to_numpy()`` can hand back a read-only view (pandas copy-on-write), so + # take a writable, owned copy before assigning the per-column baselines. + f0 = np.array(f0, dtype=float).reshape(f0.shape[0], -1) + 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) + + return f0.reshape(orig_shape) + + +def assemble_dff( + d_f_ls: np.ndarray, + 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. + + 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). + + Parameters + ---------- + d_f_ls : ndarray of shape (T, n_sources) + 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 + Windows passed to :func:`compute_f0`. + + Returns + ------- + f, f0, d_f, d_ff : ndarray + Total fluorescence, baseline, baseline-subtracted, and dF/F. + """ + f = d_f_ls + f0_ls + f0 = compute_f0(f, denoise_window, hull_window) + d_f = f - f0 + d_ff = d_f / np.clip(f0, 1e-4, None) + return f, f0, d_f, d_ff diff --git a/src/giant_python/numerics/interpolation.py b/src/giant_python/numerics/interpolation.py index 64b5482e..2e67f59d 100644 --- a/src/giant_python/numerics/interpolation.py +++ b/src/giant_python/numerics/interpolation.py @@ -1,28 +1,28 @@ -"""Shared nearest-neighbor interpolation.""" - -import numpy as np - - -def nearest_interp(x: np.ndarray, xp: np.ndarray, yp: np.ndarray) -> np.ndarray: - """Nearest-neighbor interpolation (MATLAB interp1(...,'nearest')). - - Parameters - ---------- - x : ndarray - Query points. - xp : ndarray - Sample positions (assumed sorted ascending). - yp : ndarray - Sample values aligned with xp. - - Returns - ------- - ndarray - yp sampled at the nearest xp for each x. - """ - if len(xp) == 1: - return yp - x_bds = xp[:-1] / 2.0 + xp[1:] / 2.0 - idx = np.searchsorted(x_bds, x, side="left") - idx = np.clip(idx, 0, len(xp) - 1) - return yp[idx] +"""Shared nearest-neighbor interpolation.""" + +import numpy as np + + +def nearest_interp(x: np.ndarray, xp: np.ndarray, yp: np.ndarray) -> np.ndarray: + """Nearest-neighbor interpolation (MATLAB interp1(...,'nearest')). + + Parameters + ---------- + x : ndarray + Query points. + xp : ndarray + Sample positions (assumed sorted ascending). + yp : ndarray + Sample values aligned with xp. + + Returns + ------- + ndarray + yp sampled at the nearest xp for each x. + """ + if len(xp) == 1: + return yp + x_bds = xp[:-1] / 2.0 + xp[1:] / 2.0 + idx = np.searchsorted(x_bds, x, side="left") + idx = np.clip(idx, 0, len(xp) - 1) + return yp[idx] diff --git a/src/giant_python/numerics/morphology.py b/src/giant_python/numerics/morphology.py index 6cd6386a..372478ad 100644 --- a/src/giant_python/numerics/morphology.py +++ b/src/giant_python/numerics/morphology.py @@ -1,58 +1,58 @@ -"""Shared binary morphology on trailing image axes.""" - -from __future__ import annotations - -import numpy as np - - -def fast_dilation( - mask: np.ndarray, - kernel: np.ndarray | None = None, - iterations: int = 1, -) -> np.ndarray: - """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. - - Parameters - ---------- - mask : ndarray - Boolean (or 0/1) array; the last two axes are the image plane. - kernel : ndarray, optional - Structuring element; defaults to a 7x7 block. - iterations : int - Number of dilation iterations (generic path only). - - Returns - ------- - ndarray of bool - The dilated mask. - """ - if kernel is None: - kernel = np.ones((7, 7), np.uint8) - - if iterations == 1 and kernel.shape == (3, 3) and np.all(kernel): - m = mask.astype(bool, copy=False) - pad = [(0, 0)] * (m.ndim - 2) + [(1, 1), (1, 1)] - p = np.pad(m, pad, mode="constant", constant_values=False) - out = np.zeros_like(m, dtype=bool) - h, w = m.shape[-2], m.shape[-1] - for dr in range(3): - r_end = dr + h - for dc in range(3): - c_end = dc + w - out |= p[..., dr:r_end, dc:c_end] - return out - - import cv2 - - out = np.empty_like(mask, dtype=bool) - for idx in np.ndindex(mask.shape[:-2]): - out[idx] = cv2.dilate( - mask[idx].astype(np.uint8, copy=False), - kernel, - iterations=iterations, - ).astype(bool, copy=False) - return out +"""Shared binary morphology on trailing image axes.""" + +from __future__ import annotations + +import numpy as np + + +def fast_dilation( + mask: np.ndarray, + kernel: np.ndarray | None = None, + iterations: int = 1, +) -> np.ndarray: + """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. + + Parameters + ---------- + mask : ndarray + Boolean (or 0/1) array; the last two axes are the image plane. + kernel : ndarray, optional + Structuring element; defaults to a 7x7 block. + iterations : int + Number of dilation iterations (generic path only). + + Returns + ------- + ndarray of bool + The dilated mask. + """ + if kernel is None: + kernel = np.ones((7, 7), np.uint8) + + if iterations == 1 and kernel.shape == (3, 3) and np.all(kernel): + m = mask.astype(bool, copy=False) + pad = [(0, 0)] * (m.ndim - 2) + [(1, 1), (1, 1)] + p = np.pad(m, pad, mode="constant", constant_values=False) + out = np.zeros_like(m, dtype=bool) + h, w = m.shape[-2], m.shape[-1] + for dr in range(3): + r_end = dr + h + for dc in range(3): + c_end = dc + w + out |= p[..., dr:r_end, dc:c_end] + return out + + import cv2 + + out = np.empty_like(mask, dtype=bool) + for idx in np.ndindex(mask.shape[:-2]): + out[idx] = cv2.dilate( + mask[idx].astype(np.uint8, copy=False), + kernel, + iterations=iterations, + ).astype(bool, copy=False) + return out diff --git a/src/giant_python/numerics/peaks.py b/src/giant_python/numerics/peaks.py index 4f0b5a8b..f6cf3f3f 100644 --- a/src/giant_python/numerics/peaks.py +++ b/src/giant_python/numerics/peaks.py @@ -1,836 +1,836 @@ -"""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 -(Z, H, W) activity image produced by -:mod:`giant_python.extraction.band.summary_images`; those seeds initialize the -Phase-6 NMF localization. - -Detection fits integrated axis-aligned 2-D Gaussians (each Gaussian integrated -over unit pixels) to the activity image with a bounded Levenberg-Marquardt -solver (:func:`_lsq_curvefit`, using the analytical Jacobian from -:func:`_gaussian_peaks_integrated_val_jac`). Per plane, an initial set of local -maxima is fit jointly, then residual peaks are added one per connected -component per round until none exceed the threshold, and finally -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 -module-level functions for independent reuse. -""" - -from __future__ import annotations - -from typing import cast - -import numpy as np -from scipy import ndimage -from scipy.special import erf - -# Amplitude rescale applied to raw activity-image peak values when seeding the -# Gaussian fit (matches the reference ``AMP_SCALE = 1 / 0.75``). -_AMP_SCALE = 1.0 / 0.75 - -# MAD -> Gaussian-sigma scale factor (median absolute deviation / 0.6745). -_MAD_TO_SIGMA = 0.67449 - -# Minimum finite-pixel count for an independent background estimate. -_MIN_COMPONENT_PIXELS = 100 - - -def _validate_theta(theta: np.ndarray) -> None: - """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): " - "[amp, mu_y, mu_x, sigma_y, sigma_x]; " - "repeat the width for equal-width Gaussians" - ) - - -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 - (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 - must be supplied explicitly in both width columns. - yxdata : ndarray of shape (M, 2) - 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]. - """ - _validate_theta(theta) - x_int = yxdata[:, 1].astype(np.intp) - y_int = yxdata[:, 0].astype(np.intp) - x_min = int(x_int.min()) - x_max = int(x_int.max()) - y_min = int(y_int.min()) - y_max = int(y_int.max()) - x_idx = x_int - x_min - y_idx = y_int - y_min - - amp = theta[:, 0] - my = theta[:, 1] - mx = theta[:, 2] - sy = np.maximum(theta[:, 3], np.finfo(float).eps) - sx = np.maximum(theta[:, 4], np.finfo(float).eps) - - c = np.sqrt(np.pi / 2) - rt2 = np.sqrt(2.0) - - xc = np.arange(x_min, x_max + 1, dtype=float) - xl = (xc - 0.5)[:, np.newaxis] - xr = (xc + 0.5)[:, np.newaxis] - ix = ( - c - * sx[np.newaxis, :] - * ( - erf((xr - mx[np.newaxis, :]) / (rt2 * sx[np.newaxis, :])) - - erf((xl - mx[np.newaxis, :]) / (rt2 * sx[np.newaxis, :])) - ) - ) - - yc = np.arange(y_min, y_max + 1, dtype=float) - yb = (yc - 0.5)[:, np.newaxis] - yt = (yc + 0.5)[:, np.newaxis] - iy = ( - c - * sy[np.newaxis, :] - * ( - erf((yt - my[np.newaxis, :]) / (rt2 * sy[np.newaxis, :])) - - erf((yb - my[np.newaxis, :]) / (rt2 * sy[np.newaxis, :])) - ) - ) - - return (iy[y_idx, :] * ix[x_idx, :]) @ amp - - -def _gaussian_peaks_integrated_val_jac( - theta: np.ndarray, yxdata: 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. - - Parameters - ---------- - theta : ndarray of shape (N, 5) - Per-Gaussian [amp, mu_y, mu_x, sigma_y, sigma_x]. - yxdata : ndarray of shape (M, 2) - 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(). - """ - _validate_theta(theta) - x_int = yxdata[:, 1].astype(np.intp) - y_int = yxdata[:, 0].astype(np.intp) - m = len(x_int) - n = theta.shape[0] - - x_min = int(x_int.min()) - x_max = int(x_int.max()) - y_min = int(y_int.min()) - y_max = int(y_int.max()) - x_idx = x_int - x_min - y_idx = y_int - y_min - - amp = theta[:, 0] - my = theta[:, 1] - mx = theta[:, 2] - sy = np.maximum(theta[:, 3], np.finfo(float).eps) - sx = np.maximum(theta[:, 4], np.finfo(float).eps) - - c = np.sqrt(np.pi / 2) - rt2 = np.sqrt(2.0) - inv_rt2sx = 1.0 / (rt2 * sx[np.newaxis, :]) - inv_rt2sy = 1.0 / (rt2 * sy[np.newaxis, :]) - - xc = np.arange(x_min, x_max + 1, dtype=float) - xl = (xc - 0.5)[:, np.newaxis] - xr = (xc + 0.5)[:, np.newaxis] - ux_l = (xl - mx[np.newaxis, :]) * inv_rt2sx - ux_r = (xr - mx[np.newaxis, :]) * inv_rt2sx - erf_ux_l = erf(ux_l) - erf_ux_r = erf(ux_r) - ix = c * sx[np.newaxis, :] * (erf_ux_r - erf_ux_l) - - yc = np.arange(y_min, y_max + 1, dtype=float) - yb = (yc - 0.5)[:, np.newaxis] - yt = (yc + 0.5)[:, np.newaxis] - uy_b = (yb - my[np.newaxis, :]) * inv_rt2sy - uy_t = (yt - my[np.newaxis, :]) * inv_rt2sy - erf_uy_b = erf(uy_b) - erf_uy_t = erf(uy_t) - iy = c * sy[np.newaxis, :] * (erf_uy_t - erf_uy_b) - - iy_m = iy[y_idx, :] - ix_m = ix[x_idx, :] - - dval_da = iy_m * ix_m - val = dval_da @ amp - - exp_uyb2 = np.exp(-(uy_b**2)) - exp_uyt2 = np.exp(-(uy_t**2)) - d_iy_dmy_m = (exp_uyb2 - exp_uyt2)[y_idx, :] - dval_dmy = amp[np.newaxis, :] * d_iy_dmy_m * ix_m - - exp_uxl2 = np.exp(-(ux_l**2)) - exp_uxr2 = np.exp(-(ux_r**2)) - d_ix_dmx_m = (exp_uxl2 - exp_uxr2)[x_idx, :] - 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, :] - dval_dsy = amp[np.newaxis, :] * d_iy_ds_m * ix_m - dval_dsx = amp[np.newaxis, :] * iy_m * d_ix_ds_m - - jac = np.empty((m, 5 * n), dtype=float) - jac[:, 0::5] = dval_da - jac[:, 1::5] = dval_dmy - jac[:, 2::5] = dval_dmx - jac[:, 3::5] = dval_dsy - jac[:, 4::5] = dval_dsx - - return val, jac - - -def _lsq_curvefit( - theta0: np.ndarray, - xdata: np.ndarray, - ydata: np.ndarray, - lb_flat: np.ndarray, - ub_flat: np.ndarray, - max_nfev: int = 5000, - *, - shared_widths: bool = False, -) -> 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 - 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. - xdata : ndarray of shape (M, 2) - Pixel-center [y, x] coordinates. - ydata : ndarray of shape (M,) - 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 - Cap on value+Jacobian evaluations. - shared_widths : bool - Constrain width updates to be equal for the isotropic warm start. - Both initial width columns and their bounds must already match. - - Returns - ------- - 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,): - raise ValueError("Gaussian bounds must have shape (5*N,)") - if shared_widths and ( - not np.array_equal(theta0[:, 3], theta0[:, 4]) - 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") - x = np.clip(theta0.ravel().copy(), lb_flat, ub_flat) - - val, jac = _gaussian_peaks_integrated_val_jac(x.reshape(-1, 5), xdata) - r = val - ydata - cost = np.dot(r, r) - nfev = 1 - - lam = 1e-2 # initial damping (MATLAB InitDamping default) - - for _ in range(400): # MATLAB MaxIter default - if nfev >= max_nfev: - break - - if shared_widths: - # Optimize one width degree of freedom, keeping five-column - # parameters throughout. The chain rule ties the two widths. - full_jac = jac.reshape(len(r), -1, 5) - fit_jac = full_jac[:, :, :4].copy() - fit_jac[:, :, 3] = full_jac[:, :, 3] + full_jac[:, :, 4] - fit_jac = fit_jac.reshape(len(r), -1) - else: - fit_jac = jac - jtj = fit_jac.T @ fit_jac - jtr = fit_jac.T @ r - diag_jtj = np.maximum(np.diag(jtj), 1e-8) - - delta = np.linalg.solve(jtj + lam * np.diag(diag_jtj), -jtr) - if shared_widths: - updates = delta.reshape(-1, 4) - 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) - r_new = val_new - ydata - cost_new = np.dot(r_new, r_new) - nfev += 1 - - if cost_new < cost: - step_norm = np.max(np.abs(x_new - x)) - rel_cost_drop = (cost - cost_new) / max(cost, 1.0) - - x = x_new - r = r_new - jac = jac_new - cost = cost_new - lam = max(lam * 0.1, 1e-10) - - if step_norm < 1e-6 or rel_cost_drop < 1e-6: - break - else: - lam = min(lam * 10.0, 1e10) - - return x.reshape(-1, 5) - - -def _fit_isotropic_then_anisotropic( - theta0: np.ndarray, - xdata: np.ndarray, - ydata: np.ndarray, - lb_flat: np.ndarray, - ub_flat: np.ndarray, - max_nfev: int = 5000, -) -> np.ndarray: - """Fit shared widths first, then relax to independent y/x widths. - - All peaks in the supplied fit region are optimized jointly in both stages. - Both stages use five-column parameters. The first stage ties the two - widths and constrains their shared sigma to the intersection of the y/x - 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. - - 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,): - raise ValueError("Gaussian bounds must have shape (5*N,)") - if theta0.shape[0] == 0: - return theta0.copy() - - lb = lb_flat.reshape(-1, 5) - ub = ub_flat.reshape(-1, 5) - iso_lb = lb.copy() - iso_ub = ub.copy() - iso_lb[:, 3] = np.maximum(lb[:, 3], lb[:, 4]) - iso_ub[:, 3] = np.minimum(ub[:, 3], ub[:, 4]) - 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") - - clipped = np.clip(theta0, lb, ub) - iso0 = clipped.copy() - iso0[:, 3] = np.sqrt(clipped[:, 3] * clipped[:, 4]) - iso0[:, 4] = iso0[:, 3] - isotropic = _lsq_curvefit( - iso0, - xdata, - ydata, - iso_lb.ravel(), - iso_ub.ravel(), - max_nfev=max_nfev, - shared_widths=True, - ) - 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. - - 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. - - Parameters - ---------- - plocs : ndarray of shape (N, 2) - Seed [y, x] locations. - height, width : int - Image extents (for clipping the mean bounds). - - Returns - ------- - lb_flat, ub_flat : ndarray of shape (5*N,) - 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), - ]) - 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. - - 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) - ix = np.clip(np.round(tf[:, 2]).astype(int), 0, width - 1) - pim[iy, ix] = True - return pim - - -def _buffer_mask(pim: np.ndarray, buffer_size: int) -> np.ndarray: - """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 pim - - -def _process_cc_new_peak( - new_peak: tuple[tuple[int, int], int], - thetaf: np.ndarray, - p_locs: np.ndarray, - labeled_full: np.ndarray, - act_im_2d: np.ndarray, - mu_bg: float, - reject_mask: np.ndarray, - height: int, - width: int, -) -> 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 - center lands in the component, and — if the new peak barely moved (its - center stayed near-integer) — rejects it (refitting the others without it - and marking its pixel so it is not re-proposed). - - Parameters - ---------- - new_peak : tuple - ((pY, pX), cc_label) for the candidate. - thetaf : ndarray of shape (N, 5) - Current Gaussian parameters. - p_locs : ndarray of shape (N, 2) - Current seed locations. - labeled_full : ndarray - Connected-component labels of the current support. - act_im_2d : ndarray - The plane's activity image. - mu_bg : float - Background median subtracted from the fit target. - reject_mask : ndarray of bool - Mutated in place: the rejected peak's pixel is set True. - height, width : int - Image extents. - - Returns - ------- - thetaf, p_locs, cc_mask, cc_yx - Updated parameters/locations plus the component mask and its pixel - coordinates (for the caller's per-round fit-image update). - """ - (py_new, px_new), cc_label = 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]]) - p_locs = np.vstack([p_locs, [float(py_new), float(px_new)]]) - new_idx = n_before - - cc_mask = labeled_full == cc_label - cc_yx = np.column_stack(np.where(cc_mask)).astype(float) - cc_vals = act_im_2d[cc_mask] - mu_bg - - iy = np.clip(np.round(thetaf[:, 1]).astype(int), 0, height - 1) - ix = np.clip(np.round(thetaf[:, 2]).astype(int), 0, width - 1) - in_cc = cc_mask[iy, ix] - - lb_cc, ub_cc = _make_bounds(p_locs[in_cc], height, width) - thetaf[in_cc] = _fit_isotropic_then_anisotropic( - thetaf[in_cc], cc_yx, cc_vals, lb_cc, ub_cc, max_nfev=5000 - ) - - 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: - refit_mask = in_cc.copy() - refit_mask[new_idx] = False - if np.any(refit_mask): - lb_rf, ub_rf = _make_bounds(p_locs[refit_mask], height, width) - thetaf[refit_mask] = _fit_isotropic_then_anisotropic( - thetaf[refit_mask], cc_yx, cc_vals, lb_rf, ub_rf, max_nfev=5000 - ) - thetaf = np.delete(thetaf, new_idx, axis=0) - p_locs = np.delete(p_locs, new_idx, axis=0) - reject_mask[py_new, px_new] = True - - return thetaf, p_locs, cc_mask, cc_yx - - -def _refine_residual_peaks( - thetaf: np.ndarray, - p_locs: np.ndarray, - act_im_2d: np.ndarray, - exclusion_mask: np.ndarray, - mu_bg: float, - sigma_bg: float, - peak_th: float, - buffer_size: int, - height: int, - width: int, - buffer_mask: np.ndarray, - res_im: np.ndarray, - fit_support: np.ndarray, - act_sel_pix: np.ndarray, - fit_im: np.ndarray, -) -> np.ndarray: - """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 - :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. - - Parameters - ---------- - thetaf, p_locs : ndarray - Current Gaussian parameters and seed locations. - act_im_2d, exclusion_mask : ndarray - The plane's activity image and its exclusion mask. - mu_bg, sigma_bg : float - Background median and MAD-scaled sigma. - peak_th : float - Residual threshold (in sigma) for accepting a new peak. - buffer_size : int - Peak-buffer dilation size. - height, width : int - Image extents. - buffer_mask, res_im, fit_support, act_sel_pix, fit_im : ndarray - Initial per-round state from the first fit. - - Returns - ------- - ndarray of shape (N, 5) - The refined Gaussian parameters. - """ - reject_mask = np.zeros((height, width), dtype=bool) - # With output omitted, label returns (label array, component count). - labeled_full, _ = cast(tuple[np.ndarray, int], ndimage.label(act_sel_pix)) - - while True: - e = res_im.copy() - e[buffer_mask | exclusion_mask | reject_mask | ~fit_support] = -np.inf - e[np.isnan(e)] = -np.inf - - n_labels = int(labeled_full.max()) - if n_labels == 0: - break - - label_ids = list(range(1, n_labels + 1)) - 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] - if not new_peaks: - break - - modified_ccs = [] - for new_peak in new_peaks: - thetaf, p_locs, cc_mask, cc_yx = _process_cc_new_peak( - new_peak, - thetaf, - p_locs, - labeled_full, - act_im_2d, - mu_bg, - reject_mask, - height, - width, - ) - modified_ccs.append((cc_mask, cc_yx)) - - p_im = _peak_mask(thetaf, height, width) - buffer_mask = _buffer_mask(p_im, buffer_size) - for cc_mask, cc_yx in modified_ccs: - fit_im[cc_mask] = gaussian_peaks_integrated(thetaf, cc_yx) - res_im = (act_im_2d - fit_im - mu_bg) / sigma_bg - fit_support = fit_im > 1e-3 - - 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)) - - return thetaf - - -def detect_peaks_2d( - act_im_2d: np.ndarray, - exclusion_mask: np.ndarray, - mu_bg: float, - sigma_bg: float, - peak_thresh: float, - peak_th: float, - buffer_size: int = 0, -) -> np.ndarray: - """Detect Gaussian peaks in one activity-image plane. - - 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. - - Parameters - ---------- - act_im_2d : ndarray of shape (H, W) - One activity-image plane (may contain NaNs). - exclusion_mask : ndarray of bool, shape (H, W) - Pixels to exclude from detection. - 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. - peak_th : float - Threshold in sigma for residual peaks. - buffer_size : int - 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. - """ - height, width = act_im_2d.shape - empty = np.zeros((0, 5)) - - explored = act_im_2d.copy() - explored[exclusion_mask | np.isnan(explored)] = -np.inf - - rank8 = ndimage.rank_filter(explored, rank=7, size=3) - rank9 = ndimage.maximum_filter(explored, size=3) - p_tmp = (rank8 > peak_thresh) & (explored == rank9) - - if not np.any(p_tmp): - return empty - - py, px = np.where(p_tmp) - amp = act_im_2d[py, px] * _AMP_SCALE - n_peaks = len(py) - - 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), - ]) - 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) - - p_im = _peak_mask(thetaf, height, width) - buffer_mask = _buffer_mask(p_im, buffer_size) - - fit_im = np.zeros((height, width), dtype=float) - fit_im[act_sel_pix] = gaussian_peaks_integrated(thetaf, sel_yx) - res_im = (act_im_2d - fit_im - mu_bg) / sigma_bg - fit_support = fit_im > 1e-3 - - thetaf = _refine_residual_peaks( - thetaf, - p_locs, - act_im_2d, - exclusion_mask, - mu_bg, - sigma_bg, - peak_th, - buffer_size, - height, - width, - buffer_mask, - res_im, - fit_support, - act_sel_pix, - fit_im, - ) - - if thetaf.shape[0] > 0: - 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)) - ) - thetaf = thetaf[thetaf[:, 0] >= adj_thresh] - - return thetaf - - -def get_act_im_peaks( - act_im: np.ndarray, - peak_th: float = 3.0, - exclusion_mask: np.ndarray | None = None, - buffer_size: int = 0, -) -> np.ndarray: - """Find Gaussian source seeds in a 3-D (Z, H, W) activity image. - - Each plane is split into 4-connected components of finite pixels. Regions - with fewer than 100 pixels or zero MAD are skipped. Background statistics - (median and MAD-scaled sigma) and the detection threshold are computed - independently for each remaining component. Detection and fitting are - restricted to that component (:func:`detect_peaks_2d`). Exclusion masks - 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. - 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. - - Parameters - ---------- - act_im : ndarray of shape (Z, H, W) - Activity image; nonfinite pixels separate valid-pixel components. - 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). - buffer_size : int - 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. - """ - n_z, height, width = act_im.shape - empty = np.zeros((0, 3)) - - if exclusion_mask is None: - excl_planes = [np.zeros((height, width), dtype=bool)] * n_z - elif exclusion_mask.ndim == 2: - excl_planes = [exclusion_mask.astype(bool)] * n_z - else: - excl_planes = [exclusion_mask[z].astype(bool) for z in range(n_z)] - - source_seeds_list = [] - for z in range(n_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: - continue - - component = labels[bounds] == label - 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 - if sigma_bg <= 0: - continue - - # NaN-mask other regions, including any inside this bounding box, - # so neither the initial fit nor residual refinement uses them. - thetaf = detect_peaks_2d( - np.where(component, plane_crop, np.nan), - excl_planes[z][bounds], - mu_bg, - sigma_bg, - mu_bg + peak_th * sigma_bg, - peak_th, - buffer_size=buffer_size, - ) - 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, - ]) - ) - - return np.vstack(source_seeds_list) if source_seeds_list else empty +"""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 +(Z, H, W) activity image produced by +:mod:`giant_python.extraction.band.summary_images`; those seeds initialize the +Phase-6 NMF localization. + +Detection fits integrated axis-aligned 2-D Gaussians (each Gaussian integrated +over unit pixels) to the activity image with a bounded Levenberg-Marquardt +solver (:func:`_lsq_curvefit`, using the analytical Jacobian from +:func:`_gaussian_peaks_integrated_val_jac`). Per plane, an initial set of local +maxima is fit jointly, then residual peaks are added one per connected +component per round until none exceed the threshold, and finally +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 +module-level functions for independent reuse. +""" + +from __future__ import annotations + +from typing import cast + +import numpy as np +from scipy import ndimage +from scipy.special import erf + +# Amplitude rescale applied to raw activity-image peak values when seeding the +# Gaussian fit (matches the reference ``AMP_SCALE = 1 / 0.75``). +_AMP_SCALE = 1.0 / 0.75 + +# MAD -> Gaussian-sigma scale factor (median absolute deviation / 0.6745). +_MAD_TO_SIGMA = 0.67449 + +# Minimum finite-pixel count for an independent background estimate. +_MIN_COMPONENT_PIXELS = 100 + + +def _validate_theta(theta: np.ndarray) -> None: + """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): " + "[amp, mu_y, mu_x, sigma_y, sigma_x]; " + "repeat the width for equal-width Gaussians" + ) + + +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 + (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 + must be supplied explicitly in both width columns. + yxdata : ndarray of shape (M, 2) + 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]. + """ + _validate_theta(theta) + x_int = yxdata[:, 1].astype(np.intp) + y_int = yxdata[:, 0].astype(np.intp) + x_min = int(x_int.min()) + x_max = int(x_int.max()) + y_min = int(y_int.min()) + y_max = int(y_int.max()) + x_idx = x_int - x_min + y_idx = y_int - y_min + + amp = theta[:, 0] + my = theta[:, 1] + mx = theta[:, 2] + sy = np.maximum(theta[:, 3], np.finfo(float).eps) + sx = np.maximum(theta[:, 4], np.finfo(float).eps) + + c = np.sqrt(np.pi / 2) + rt2 = np.sqrt(2.0) + + xc = np.arange(x_min, x_max + 1, dtype=float) + xl = (xc - 0.5)[:, np.newaxis] + xr = (xc + 0.5)[:, np.newaxis] + ix = ( + c + * sx[np.newaxis, :] + * ( + erf((xr - mx[np.newaxis, :]) / (rt2 * sx[np.newaxis, :])) + - erf((xl - mx[np.newaxis, :]) / (rt2 * sx[np.newaxis, :])) + ) + ) + + yc = np.arange(y_min, y_max + 1, dtype=float) + yb = (yc - 0.5)[:, np.newaxis] + yt = (yc + 0.5)[:, np.newaxis] + iy = ( + c + * sy[np.newaxis, :] + * ( + erf((yt - my[np.newaxis, :]) / (rt2 * sy[np.newaxis, :])) + - erf((yb - my[np.newaxis, :]) / (rt2 * sy[np.newaxis, :])) + ) + ) + + return (iy[y_idx, :] * ix[x_idx, :]) @ amp + + +def _gaussian_peaks_integrated_val_jac( + theta: np.ndarray, yxdata: 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. + + Parameters + ---------- + theta : ndarray of shape (N, 5) + Per-Gaussian [amp, mu_y, mu_x, sigma_y, sigma_x]. + yxdata : ndarray of shape (M, 2) + 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(). + """ + _validate_theta(theta) + x_int = yxdata[:, 1].astype(np.intp) + y_int = yxdata[:, 0].astype(np.intp) + m = len(x_int) + n = theta.shape[0] + + x_min = int(x_int.min()) + x_max = int(x_int.max()) + y_min = int(y_int.min()) + y_max = int(y_int.max()) + x_idx = x_int - x_min + y_idx = y_int - y_min + + amp = theta[:, 0] + my = theta[:, 1] + mx = theta[:, 2] + sy = np.maximum(theta[:, 3], np.finfo(float).eps) + sx = np.maximum(theta[:, 4], np.finfo(float).eps) + + c = np.sqrt(np.pi / 2) + rt2 = np.sqrt(2.0) + inv_rt2sx = 1.0 / (rt2 * sx[np.newaxis, :]) + inv_rt2sy = 1.0 / (rt2 * sy[np.newaxis, :]) + + xc = np.arange(x_min, x_max + 1, dtype=float) + xl = (xc - 0.5)[:, np.newaxis] + xr = (xc + 0.5)[:, np.newaxis] + ux_l = (xl - mx[np.newaxis, :]) * inv_rt2sx + ux_r = (xr - mx[np.newaxis, :]) * inv_rt2sx + erf_ux_l = erf(ux_l) + erf_ux_r = erf(ux_r) + ix = c * sx[np.newaxis, :] * (erf_ux_r - erf_ux_l) + + yc = np.arange(y_min, y_max + 1, dtype=float) + yb = (yc - 0.5)[:, np.newaxis] + yt = (yc + 0.5)[:, np.newaxis] + uy_b = (yb - my[np.newaxis, :]) * inv_rt2sy + uy_t = (yt - my[np.newaxis, :]) * inv_rt2sy + erf_uy_b = erf(uy_b) + erf_uy_t = erf(uy_t) + iy = c * sy[np.newaxis, :] * (erf_uy_t - erf_uy_b) + + iy_m = iy[y_idx, :] + ix_m = ix[x_idx, :] + + dval_da = iy_m * ix_m + val = dval_da @ amp + + exp_uyb2 = np.exp(-(uy_b**2)) + exp_uyt2 = np.exp(-(uy_t**2)) + d_iy_dmy_m = (exp_uyb2 - exp_uyt2)[y_idx, :] + dval_dmy = amp[np.newaxis, :] * d_iy_dmy_m * ix_m + + exp_uxl2 = np.exp(-(ux_l**2)) + exp_uxr2 = np.exp(-(ux_r**2)) + d_ix_dmx_m = (exp_uxl2 - exp_uxr2)[x_idx, :] + 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, :] + dval_dsy = amp[np.newaxis, :] * d_iy_ds_m * ix_m + dval_dsx = amp[np.newaxis, :] * iy_m * d_ix_ds_m + + jac = np.empty((m, 5 * n), dtype=float) + jac[:, 0::5] = dval_da + jac[:, 1::5] = dval_dmy + jac[:, 2::5] = dval_dmx + jac[:, 3::5] = dval_dsy + jac[:, 4::5] = dval_dsx + + return val, jac + + +def _lsq_curvefit( + theta0: np.ndarray, + xdata: np.ndarray, + ydata: np.ndarray, + lb_flat: np.ndarray, + ub_flat: np.ndarray, + max_nfev: int = 5000, + *, + shared_widths: bool = False, +) -> 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 + 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. + xdata : ndarray of shape (M, 2) + Pixel-center [y, x] coordinates. + ydata : ndarray of shape (M,) + 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 + Cap on value+Jacobian evaluations. + shared_widths : bool + Constrain width updates to be equal for the isotropic warm start. + Both initial width columns and their bounds must already match. + + Returns + ------- + 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,): + raise ValueError("Gaussian bounds must have shape (5*N,)") + if shared_widths and ( + not np.array_equal(theta0[:, 3], theta0[:, 4]) + 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") + x = np.clip(theta0.ravel().copy(), lb_flat, ub_flat) + + val, jac = _gaussian_peaks_integrated_val_jac(x.reshape(-1, 5), xdata) + r = val - ydata + cost = np.dot(r, r) + nfev = 1 + + lam = 1e-2 # initial damping (MATLAB InitDamping default) + + for _ in range(400): # MATLAB MaxIter default + if nfev >= max_nfev: + break + + if shared_widths: + # Optimize one width degree of freedom, keeping five-column + # parameters throughout. The chain rule ties the two widths. + full_jac = jac.reshape(len(r), -1, 5) + fit_jac = full_jac[:, :, :4].copy() + fit_jac[:, :, 3] = full_jac[:, :, 3] + full_jac[:, :, 4] + fit_jac = fit_jac.reshape(len(r), -1) + else: + fit_jac = jac + jtj = fit_jac.T @ fit_jac + jtr = fit_jac.T @ r + diag_jtj = np.maximum(np.diag(jtj), 1e-8) + + delta = np.linalg.solve(jtj + lam * np.diag(diag_jtj), -jtr) + if shared_widths: + updates = delta.reshape(-1, 4) + 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) + r_new = val_new - ydata + cost_new = np.dot(r_new, r_new) + nfev += 1 + + if cost_new < cost: + step_norm = np.max(np.abs(x_new - x)) + rel_cost_drop = (cost - cost_new) / max(cost, 1.0) + + x = x_new + r = r_new + jac = jac_new + cost = cost_new + lam = max(lam * 0.1, 1e-10) + + if step_norm < 1e-6 or rel_cost_drop < 1e-6: + break + else: + lam = min(lam * 10.0, 1e10) + + return x.reshape(-1, 5) + + +def _fit_isotropic_then_anisotropic( + theta0: np.ndarray, + xdata: np.ndarray, + ydata: np.ndarray, + lb_flat: np.ndarray, + ub_flat: np.ndarray, + max_nfev: int = 5000, +) -> np.ndarray: + """Fit shared widths first, then relax to independent y/x widths. + + All peaks in the supplied fit region are optimized jointly in both stages. + Both stages use five-column parameters. The first stage ties the two + widths and constrains their shared sigma to the intersection of the y/x + 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. + + 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,): + raise ValueError("Gaussian bounds must have shape (5*N,)") + if theta0.shape[0] == 0: + return theta0.copy() + + lb = lb_flat.reshape(-1, 5) + ub = ub_flat.reshape(-1, 5) + iso_lb = lb.copy() + iso_ub = ub.copy() + iso_lb[:, 3] = np.maximum(lb[:, 3], lb[:, 4]) + iso_ub[:, 3] = np.minimum(ub[:, 3], ub[:, 4]) + 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") + + clipped = np.clip(theta0, lb, ub) + iso0 = clipped.copy() + iso0[:, 3] = np.sqrt(clipped[:, 3] * clipped[:, 4]) + iso0[:, 4] = iso0[:, 3] + isotropic = _lsq_curvefit( + iso0, + xdata, + ydata, + iso_lb.ravel(), + iso_ub.ravel(), + max_nfev=max_nfev, + shared_widths=True, + ) + 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. + + 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. + + Parameters + ---------- + plocs : ndarray of shape (N, 2) + Seed [y, x] locations. + height, width : int + Image extents (for clipping the mean bounds). + + Returns + ------- + lb_flat, ub_flat : ndarray of shape (5*N,) + 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), + ]) + 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. + + 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) + ix = np.clip(np.round(tf[:, 2]).astype(int), 0, width - 1) + pim[iy, ix] = True + return pim + + +def _buffer_mask(pim: np.ndarray, buffer_size: int) -> np.ndarray: + """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 pim + + +def _process_cc_new_peak( + new_peak: tuple[tuple[int, int], int], + thetaf: np.ndarray, + p_locs: np.ndarray, + labeled_full: np.ndarray, + act_im_2d: np.ndarray, + mu_bg: float, + reject_mask: np.ndarray, + height: int, + width: int, +) -> 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 + center lands in the component, and — if the new peak barely moved (its + center stayed near-integer) — rejects it (refitting the others without it + and marking its pixel so it is not re-proposed). + + Parameters + ---------- + new_peak : tuple + ((pY, pX), cc_label) for the candidate. + thetaf : ndarray of shape (N, 5) + Current Gaussian parameters. + p_locs : ndarray of shape (N, 2) + Current seed locations. + labeled_full : ndarray + Connected-component labels of the current support. + act_im_2d : ndarray + The plane's activity image. + mu_bg : float + Background median subtracted from the fit target. + reject_mask : ndarray of bool + Mutated in place: the rejected peak's pixel is set True. + height, width : int + Image extents. + + Returns + ------- + thetaf, p_locs, cc_mask, cc_yx + Updated parameters/locations plus the component mask and its pixel + coordinates (for the caller's per-round fit-image update). + """ + (py_new, px_new), cc_label = 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]]) + p_locs = np.vstack([p_locs, [float(py_new), float(px_new)]]) + new_idx = n_before + + cc_mask = labeled_full == cc_label + cc_yx = np.column_stack(np.where(cc_mask)).astype(float) + cc_vals = act_im_2d[cc_mask] - mu_bg + + iy = np.clip(np.round(thetaf[:, 1]).astype(int), 0, height - 1) + ix = np.clip(np.round(thetaf[:, 2]).astype(int), 0, width - 1) + in_cc = cc_mask[iy, ix] + + lb_cc, ub_cc = _make_bounds(p_locs[in_cc], height, width) + thetaf[in_cc] = _fit_isotropic_then_anisotropic( + thetaf[in_cc], cc_yx, cc_vals, lb_cc, ub_cc, max_nfev=5000 + ) + + 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: + refit_mask = in_cc.copy() + refit_mask[new_idx] = False + if np.any(refit_mask): + lb_rf, ub_rf = _make_bounds(p_locs[refit_mask], height, width) + thetaf[refit_mask] = _fit_isotropic_then_anisotropic( + thetaf[refit_mask], cc_yx, cc_vals, lb_rf, ub_rf, max_nfev=5000 + ) + thetaf = np.delete(thetaf, new_idx, axis=0) + p_locs = np.delete(p_locs, new_idx, axis=0) + reject_mask[py_new, px_new] = True + + return thetaf, p_locs, cc_mask, cc_yx + + +def _refine_residual_peaks( + thetaf: np.ndarray, + p_locs: np.ndarray, + act_im_2d: np.ndarray, + exclusion_mask: np.ndarray, + mu_bg: float, + sigma_bg: float, + peak_th: float, + buffer_size: int, + height: int, + width: int, + buffer_mask: np.ndarray, + res_im: np.ndarray, + fit_support: np.ndarray, + act_sel_pix: np.ndarray, + fit_im: np.ndarray, +) -> np.ndarray: + """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 + :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. + + Parameters + ---------- + thetaf, p_locs : ndarray + Current Gaussian parameters and seed locations. + act_im_2d, exclusion_mask : ndarray + The plane's activity image and its exclusion mask. + mu_bg, sigma_bg : float + Background median and MAD-scaled sigma. + peak_th : float + Residual threshold (in sigma) for accepting a new peak. + buffer_size : int + Peak-buffer dilation size. + height, width : int + Image extents. + buffer_mask, res_im, fit_support, act_sel_pix, fit_im : ndarray + Initial per-round state from the first fit. + + Returns + ------- + ndarray of shape (N, 5) + The refined Gaussian parameters. + """ + reject_mask = np.zeros((height, width), dtype=bool) + # With output omitted, label returns (label array, component count). + labeled_full, _ = cast(tuple[np.ndarray, int], ndimage.label(act_sel_pix)) + + while True: + e = res_im.copy() + e[buffer_mask | exclusion_mask | reject_mask | ~fit_support] = -np.inf + e[np.isnan(e)] = -np.inf + + n_labels = int(labeled_full.max()) + if n_labels == 0: + break + + label_ids = list(range(1, n_labels + 1)) + 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] + if not new_peaks: + break + + modified_ccs = [] + for new_peak in new_peaks: + thetaf, p_locs, cc_mask, cc_yx = _process_cc_new_peak( + new_peak, + thetaf, + p_locs, + labeled_full, + act_im_2d, + mu_bg, + reject_mask, + height, + width, + ) + modified_ccs.append((cc_mask, cc_yx)) + + p_im = _peak_mask(thetaf, height, width) + buffer_mask = _buffer_mask(p_im, buffer_size) + for cc_mask, cc_yx in modified_ccs: + fit_im[cc_mask] = gaussian_peaks_integrated(thetaf, cc_yx) + res_im = (act_im_2d - fit_im - mu_bg) / sigma_bg + fit_support = fit_im > 1e-3 + + 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)) + + return thetaf + + +def detect_peaks_2d( + act_im_2d: np.ndarray, + exclusion_mask: np.ndarray, + mu_bg: float, + sigma_bg: float, + peak_thresh: float, + peak_th: float, + buffer_size: int = 0, +) -> np.ndarray: + """Detect Gaussian peaks in one activity-image plane. + + 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. + + Parameters + ---------- + act_im_2d : ndarray of shape (H, W) + One activity-image plane (may contain NaNs). + exclusion_mask : ndarray of bool, shape (H, W) + Pixels to exclude from detection. + 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. + peak_th : float + Threshold in sigma for residual peaks. + buffer_size : int + 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. + """ + height, width = act_im_2d.shape + empty = np.zeros((0, 5)) + + explored = act_im_2d.copy() + explored[exclusion_mask | np.isnan(explored)] = -np.inf + + rank8 = ndimage.rank_filter(explored, rank=7, size=3) + rank9 = ndimage.maximum_filter(explored, size=3) + p_tmp = (rank8 > peak_thresh) & (explored == rank9) + + if not np.any(p_tmp): + return empty + + py, px = np.where(p_tmp) + amp = act_im_2d[py, px] * _AMP_SCALE + n_peaks = len(py) + + 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), + ]) + 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) + + p_im = _peak_mask(thetaf, height, width) + buffer_mask = _buffer_mask(p_im, buffer_size) + + fit_im = np.zeros((height, width), dtype=float) + fit_im[act_sel_pix] = gaussian_peaks_integrated(thetaf, sel_yx) + res_im = (act_im_2d - fit_im - mu_bg) / sigma_bg + fit_support = fit_im > 1e-3 + + thetaf = _refine_residual_peaks( + thetaf, + p_locs, + act_im_2d, + exclusion_mask, + mu_bg, + sigma_bg, + peak_th, + buffer_size, + height, + width, + buffer_mask, + res_im, + fit_support, + act_sel_pix, + fit_im, + ) + + if thetaf.shape[0] > 0: + 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)) + ) + thetaf = thetaf[thetaf[:, 0] >= adj_thresh] + + return thetaf + + +def get_act_im_peaks( + act_im: np.ndarray, + peak_th: float = 3.0, + exclusion_mask: np.ndarray | None = None, + buffer_size: int = 0, +) -> np.ndarray: + """Find Gaussian source seeds in a 3-D (Z, H, W) activity image. + + Each plane is split into 4-connected components of finite pixels. Regions + with fewer than 100 pixels or zero MAD are skipped. Background statistics + (median and MAD-scaled sigma) and the detection threshold are computed + independently for each remaining component. Detection and fitting are + restricted to that component (:func:`detect_peaks_2d`). Exclusion masks + 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. + 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. + + Parameters + ---------- + act_im : ndarray of shape (Z, H, W) + Activity image; nonfinite pixels separate valid-pixel components. + 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). + buffer_size : int + 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. + """ + n_z, height, width = act_im.shape + empty = np.zeros((0, 3)) + + if exclusion_mask is None: + excl_planes = [np.zeros((height, width), dtype=bool)] * n_z + elif exclusion_mask.ndim == 2: + excl_planes = [exclusion_mask.astype(bool)] * n_z + else: + excl_planes = [exclusion_mask[z].astype(bool) for z in range(n_z)] + + source_seeds_list = [] + for z in range(n_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: + continue + + component = labels[bounds] == label + 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 + if sigma_bg <= 0: + continue + + # NaN-mask other regions, including any inside this bounding box, + # so neither the initial fit nor residual refinement uses them. + thetaf = detect_peaks_2d( + np.where(component, plane_crop, np.nan), + excl_planes[z][bounds], + mu_bg, + sigma_bg, + mu_bg + peak_th * sigma_bg, + peak_th, + buffer_size=buffer_size, + ) + 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, + ]) + ) + + return np.vstack(source_seeds_list) if source_seeds_list else empty diff --git a/src/giant_python/pipeline/__init__.py b/src/giant_python/pipeline/__init__.py index 0db74b8d..8aa94d9c 100644 --- a/src/giant_python/pipeline/__init__.py +++ b/src/giant_python/pipeline/__init__.py @@ -1,20 +1,20 @@ -"""Trial tables, registration, band annotation/extraction and a facade. - -register_multiroi imports PyTorch only when called. -""" - -from .annotate import annotate_rois -from .extract import extract_band_sources, extract_sources -from .pipeline import Pipeline -from .register import register_multiroi -from .trial_table import build_trial_table_slap2, trim_trial_table - -__all__ = [ - "Pipeline", - "annotate_rois", - "build_trial_table_slap2", - "extract_band_sources", - "extract_sources", - "register_multiroi", - "trim_trial_table", -] +"""Trial tables, registration, band annotation/extraction and a facade. + +register_multiroi imports PyTorch only when called. +""" + +from .annotate import annotate_rois +from .extract import extract_band_sources, extract_sources +from .pipeline import Pipeline +from .register import register_multiroi +from .trial_table import build_trial_table_slap2, trim_trial_table + +__all__ = [ + "Pipeline", + "annotate_rois", + "build_trial_table_slap2", + "extract_band_sources", + "extract_sources", + "register_multiroi", + "trim_trial_table", +] diff --git a/src/giant_python/pipeline/annotate.py b/src/giant_python/pipeline/annotate.py index 3e243949..ef79b851 100644 --- a/src/giant_python/pipeline/annotate.py +++ b/src/giant_python/pipeline/annotate.py @@ -1,56 +1,56 @@ -"""Public ROI annotation service with lazy band/GUI imports.""" - -from __future__ import annotations - -from ..models.params import ( - AnnotationInput, - BandParamsInput, - ExecutionInput, -) -from .extract import TrialTableInput, _require_band_mode - - -def annotate_rois( - input: TrialTableInput, - params: BandParamsInput = None, - *, - microscope: str = "slap2", - scan_mode: str | None = "band", - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> str: - """Load or draw and save band ROIs through the shared annotation service. - - Parameters - ---------- - input : str, Path or TrialTable - Exact filename or loaded trial table; never reconstructed from a - results directory. - params : BandSiloParams, dict or None - Scientific configuration only. - microscope : str - Currently only 'slap2' is supported. - scan_mode : str or None - 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. - - 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) +"""Public ROI annotation service with lazy band/GUI imports.""" + +from __future__ import annotations + +from ..models.params import ( + AnnotationInput, + BandParamsInput, + ExecutionInput, +) +from .extract import TrialTableInput, _require_band_mode + + +def annotate_rois( + input: TrialTableInput, + params: BandParamsInput = None, + *, + microscope: str = "slap2", + scan_mode: str | None = "band", + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> str: + """Load or draw and save band ROIs through the shared annotation service. + + Parameters + ---------- + input : str, Path or TrialTable + Exact filename or loaded trial table; never reconstructed from a + results directory. + params : BandSiloParams, dict or None + Scientific configuration only. + microscope : str + Currently only 'slap2' is supported. + scan_mode : str or None + 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. + + 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) diff --git a/src/giant_python/pipeline/extract.py b/src/giant_python/pipeline/extract.py index 2904060d..2c5a5f10 100644 --- a/src/giant_python/pipeline/extract.py +++ b/src/giant_python/pipeline/extract.py @@ -1,120 +1,120 @@ -"""Canonical standalone extraction services. - -Only SLAP2 band extraction is supported. Backend imports are lazy; no input -table is reloaded here. -""" - -from __future__ import annotations - -from pathlib import Path -from typing import Union - -from ..models.experiment_summary import ExperimentSummary -from ..models.params import ( - AnnotationInput, - BandParamsInput, - ExecutionInput, -) -from ..models.trial_table import TrialTable - -TrialTableInput = Union[str, Path, TrialTable] - - -def _require_band_mode( - microscope: str, - scan_mode: str | None, -) -> None: - """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") - 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" - ) - - -def extract_sources( - input: TrialTableInput, - params: BandParamsInput = None, - *, - microscope: str = "slap2", - scan_mode: str | None = "band", - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> ExperimentSummary: - """Extract sources through the supported workflow service. - - Parameters - ---------- - input : str, Path or TrialTable - Exact trial-table filename or a loaded table, passed through intact. - params : BandSiloParams, dict or None - Scientific settings only. - microscope : str - Currently only 'slap2' is supported. - scan_mode : str or None - Explicit routing, defaulting to band. None also selects band. - execution : ExecutionOptions, dict or None - Run policy, independent of science. - annotations : AnnotationOptions, dict or None - ROI inclusion and interactivity policy. - - Returns - ------- - ExperimentSummary - Eager extraction results, also persisted by the backend. - """ - _require_band_mode(microscope, scan_mode) - return extract_band_sources(input, params, execution=execution, annotations=annotations) - - -def extract_band_sources( - input: TrialTableInput, - params: BandParamsInput = None, - *, - execution: ExecutionInput = None, - annotations: AnnotationInput = None, -) -> ExperimentSummary: - """Perform band-scan source extraction for SLAP2. - - 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. - - Delegates lazily to giant_python.extraction.band.workflow. All option - resolution belongs to that service. - - Parameters - ---------- - input : str, Path or TrialTable - Trial-table path or loaded metadata with band alignment data. - params : BandSiloParams, dict or None - Scientific settings only. - execution : ExecutionOptions, dict or None - Run policy, independent of scientific settings. - annotations : AnnotationOptions, dict or None - ROI inclusion and GUI policy. - - Returns - ------- - 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") - from ..extraction.band.workflow import extract_band_sources as extract - - return extract(input, params, execution=execution, annotations=annotations) +"""Canonical standalone extraction services. + +Only SLAP2 band extraction is supported. Backend imports are lazy; no input +table is reloaded here. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Union + +from ..models.experiment_summary import ExperimentSummary +from ..models.params import ( + AnnotationInput, + BandParamsInput, + ExecutionInput, +) +from ..models.trial_table import TrialTable + +TrialTableInput = Union[str, Path, TrialTable] + + +def _require_band_mode( + microscope: str, + scan_mode: str | None, +) -> None: + """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") + 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" + ) + + +def extract_sources( + input: TrialTableInput, + params: BandParamsInput = None, + *, + microscope: str = "slap2", + scan_mode: str | None = "band", + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> ExperimentSummary: + """Extract sources through the supported workflow service. + + Parameters + ---------- + input : str, Path or TrialTable + Exact trial-table filename or a loaded table, passed through intact. + params : BandSiloParams, dict or None + Scientific settings only. + microscope : str + Currently only 'slap2' is supported. + scan_mode : str or None + Explicit routing, defaulting to band. None also selects band. + execution : ExecutionOptions, dict or None + Run policy, independent of science. + annotations : AnnotationOptions, dict or None + ROI inclusion and interactivity policy. + + Returns + ------- + ExperimentSummary + Eager extraction results, also persisted by the backend. + """ + _require_band_mode(microscope, scan_mode) + return extract_band_sources(input, params, execution=execution, annotations=annotations) + + +def extract_band_sources( + input: TrialTableInput, + params: BandParamsInput = None, + *, + execution: ExecutionInput = None, + annotations: AnnotationInput = None, +) -> ExperimentSummary: + """Perform band-scan source extraction for SLAP2. + + 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. + + Delegates lazily to giant_python.extraction.band.workflow. All option + resolution belongs to that service. + + Parameters + ---------- + input : str, Path or TrialTable + Trial-table path or loaded metadata with band alignment data. + params : BandSiloParams, dict or None + Scientific settings only. + execution : ExecutionOptions, dict or None + Run policy, independent of scientific settings. + annotations : AnnotationOptions, dict or None + ROI inclusion and GUI policy. + + Returns + ------- + 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") + from ..extraction.band.workflow import extract_band_sources as extract + + return extract(input, params, execution=execution, annotations=annotations) diff --git a/src/giant_python/pipeline/pipeline.py b/src/giant_python/pipeline/pipeline.py index 313aad4e..4d19d0cc 100644 --- a/src/giant_python/pipeline/pipeline.py +++ b/src/giant_python/pipeline/pipeline.py @@ -1,179 +1,179 @@ -"""Chainable coordinator over the same services as standalone functions. - -Band annotation/extraction starts from existing registered trial metadata. -Returned summaries currently contain eager arrays. -""" - -from __future__ import annotations - -from dataclasses import replace -from pathlib import Path -from typing import Any - -from ..models.experiment_summary import ExperimentSummary -from ..models.params import ( - AnnotationInput, - BandParamsInput, - BandSiloParams, - ExecutionInput, - resolve_band_options, -) -from ..models.trial_table import TrialTable -from .annotate import annotate_rois -from .extract import TrialTableInput, extract_sources - - -class Pipeline: - """Coordinator for annotation and extraction from a registered trial table. - - Parameters - ---------- - microscope : str - Acquisition type; only "slap2" band extraction is implemented. - params : BandSiloParams, dict or None - Scientific settings only; defaults to band. - execution : ExecutionOptions, dict or None - Run policy, separate from science. - annotations : AnnotationOptions, dict or None - ROI inclusion and GUI policy. - scan_mode : str or None - Optional explicit routing override; unsupported modes fail honestly. - - Attributes - ---------- - tt : TrialTable or None - The session's trial table (lightweight metadata), threaded between - stages. - 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. - """ - - def __init__( - self, - microscope: str = "slap2", - params: BandParamsInput = None, - *, - execution: ExecutionInput = None, - annotations: AnnotationInput = None, - scan_mode: str | None = "band", - ) -> None: - """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: 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: Any, # noqa: ANN401 - ) -> Pipeline: - """Start a session from a trial-table path or loaded metadata. - - Parameters - ---------- - path : str, Path or TrialTable - 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. - **kwargs - Forwarded to :class:`Pipeline` (e.g. params or execution). - - Returns - ------- - Pipeline - 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 - source_path = table.source_path - elif isinstance(path, (str, Path)): - source_path = Path(path) - table = TrialTable.from_h5(source_path) - # Keep the supplied filename even when savedr points elsewhere. - table.source_path = source_path - else: - 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 - return pipeline - - def _require_trial_table(self) -> TrialTable: - """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() " - "before annotation or extraction" - ) - return self.tt - - 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 - explicit/headless/automatic GUI policy. Caller options are not edited. - - Returns - ------- - Pipeline - self (supports method chaining). - """ - table = self._require_trial_table() - self.annotation_path = annotate_rois( - table, - self.params, - microscope=self.microscope, - scan_mode=self.scan_mode, - execution=self.execution, - annotations=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. - - Returns - ------- - Pipeline - self (supports method chaining). - """ - table = self._require_trial_table() - self.summary = extract_sources( - table, - self.params, - microscope=self.microscope, - scan_mode=self.scan_mode, - execution=self.execution, - annotations=self.annotations, - ) - return self +"""Chainable coordinator over the same services as standalone functions. + +Band annotation/extraction starts from existing registered trial metadata. +Returned summaries currently contain eager arrays. +""" + +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path +from typing import Any + +from ..models.experiment_summary import ExperimentSummary +from ..models.params import ( + AnnotationInput, + BandParamsInput, + BandSiloParams, + ExecutionInput, + resolve_band_options, +) +from ..models.trial_table import TrialTable +from .annotate import annotate_rois +from .extract import TrialTableInput, extract_sources + + +class Pipeline: + """Coordinator for annotation and extraction from a registered trial table. + + Parameters + ---------- + microscope : str + Acquisition type; only "slap2" band extraction is implemented. + params : BandSiloParams, dict or None + Scientific settings only; defaults to band. + execution : ExecutionOptions, dict or None + Run policy, separate from science. + annotations : AnnotationOptions, dict or None + ROI inclusion and GUI policy. + scan_mode : str or None + Optional explicit routing override; unsupported modes fail honestly. + + Attributes + ---------- + tt : TrialTable or None + The session's trial table (lightweight metadata), threaded between + stages. + 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. + """ + + def __init__( + self, + microscope: str = "slap2", + params: BandParamsInput = None, + *, + execution: ExecutionInput = None, + annotations: AnnotationInput = None, + scan_mode: str | None = "band", + ) -> None: + """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: 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: Any, # noqa: ANN401 + ) -> Pipeline: + """Start a session from a trial-table path or loaded metadata. + + Parameters + ---------- + path : str, Path or TrialTable + 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. + **kwargs + Forwarded to :class:`Pipeline` (e.g. params or execution). + + Returns + ------- + Pipeline + 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 + source_path = table.source_path + elif isinstance(path, (str, Path)): + source_path = Path(path) + table = TrialTable.from_h5(source_path) + # Keep the supplied filename even when savedr points elsewhere. + table.source_path = source_path + else: + 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 + return pipeline + + def _require_trial_table(self) -> TrialTable: + """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() " + "before annotation or extraction" + ) + return self.tt + + 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 + explicit/headless/automatic GUI policy. Caller options are not edited. + + Returns + ------- + Pipeline + self (supports method chaining). + """ + table = self._require_trial_table() + self.annotation_path = annotate_rois( + table, + self.params, + microscope=self.microscope, + scan_mode=self.scan_mode, + execution=self.execution, + annotations=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. + + Returns + ------- + Pipeline + self (supports method chaining). + """ + table = self._require_trial_table() + self.summary = extract_sources( + table, + self.params, + microscope=self.microscope, + scan_mode=self.scan_mode, + execution=self.execution, + annotations=self.annotations, + ) + return self diff --git a/src/giant_python/pipeline/reg_stats.py b/src/giant_python/pipeline/reg_stats.py index fd2d5d0a..4d4a986a 100644 --- a/src/giant_python/pipeline/reg_stats.py +++ b/src/giant_python/pipeline/reg_stats.py @@ -1,634 +1,634 @@ -"""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 -order, so the maps equal registration's (bit for bit on the same device). - -The frame times, motion, registration window and online compensation are -taken from the alignment file and checked against the frame source built -from the raw recording; a mismatch (other settings than the file's) is an -error, not a silent difference. -""" - -from __future__ import annotations - -import json -import logging -import os -from collections.abc import Iterator, Sequence -from pathlib import Path -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: 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: - """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: 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 - 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), - "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)), - "unlit_masked": bool(_scalar(f, "slap2/unlitMasked", 0)), - "settings": None, - } - out["compensation"] = ( - _compensation_record(f["slap2/onlineCompensation"], row_major) - if out["compensated"] - else None - ) - saved = f.attrs.get("align_params") - if saved is not None: - out["settings"] = json.loads(saved) - if not np.array_equal(out["ds"], ds): - raise ValueError(f"{path}: DSframes are not whole lines") - return out - - -def _matlab_2d(ds: h5py.Dataset, row_major: bool) -> np.ndarray: - """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. - - 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: - """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"), - "frameRefY": _vector(grp, "frameRefY"), - "mapping": _matlab_2d(grp["mapping"], row_major), - "yLead": _vector(grp, "yLead"), - } - - -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: - return - rec = compensation_record(source.compensation, source.references(ds)) - for key, value in saved.items(): - 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" - ) - - -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 - alignment file says. - - Returns - ------- - MultiRoiRegistrationParams - The registration settings, with align_hz and compensate_online taken from - `alignment`. - """ - from ..models.params import MultiRoiRegistrationParams - - rec = alignment["settings"] or table_settings or {} - kw = {} - for field, key in ( - ("init_frames", "initFrames"), - ("maxshift", "maxshift"), - ): - if key in rec and rec[key] is not None: - kw[field] = int(np.asarray(rec[key]).ravel()[0]) - kw["align_hz"] = alignment["align_hz"] - kw["compensate_online"] = alignment["compensated"] - return MultiRoiRegistrationParams(**kw) - - -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 - - # the samples as the registration formed its frames: without those - # behind the DMD curtain only where it left them out - layout, former, init, ds, dtk = open_trial( - dat, first, last, params, device, alignment["unlit_masked"] - ) - if not np.array_equal(ds, alignment["ds"]): - raise ValueError( - 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) - win = source.window - if not ( - np.array_equal(win.trim_rows, alignment["trim_rows"]) - and np.array_equal(win.trim_cols, alignment["trim_cols"]) - ): - raise ValueError(f"{dat}: registration window differs from trimRows") - _check_compensation(dat, source, ds, alignment.get("compensation")) - return layout, source, ds - - -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()))] - n = data.shape[0] // n_channels - for a in range(0, n, FRAMES_PER_READ): - b = min(n, a + FRAMES_PER_READ) - pages = data[a * n_channels : b * n_channels] - pages = pages.reshape(b - a, n_channels, *pages.shape[1:]) - for i in range(b - a): - yield a + i, np.swapaxes(pages[i], -1, -2) - return - import tifffile - - with tifffile.TiffFile(path) as tf: - 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)] - yield k, np.stack(frame).astype(np.float32, copy=False) - - -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] - for a in range(0, n, FRAMES_PER_READ): - block = vf[a : min(n, a + FRAMES_PER_READ)] - for page in block: - yield np.ascontiguousarray(page.T, dtype=np.float32) - - -def trial_stats( - dat: str | Path, - first: float, - last: float, - 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. - - Parameters - ---------- - dat : str or Path - The raw recording. - first, last : float - The trial's line range (trial table slap2_info). - movie, adata : str or Path - Registered movie and alignment file. - out : str or Path - The statistics file to write. - device : str or torch.device - Where the statistics are formed. - table_settings : dict, optional - 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 - - from ..registration.stats import ( - alignment_digest, - new_accumulator, - write_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) - h, w = source.window.shape - margin = (align["out_shape"][0] - h) // 2 - if align["out_shape"] != (h + 2 * margin, w + 2 * margin): - raise ValueError(f"{adata}: meanIM does not fit the window") - acc = new_accumulator(source, ds, margin, align["n_channels"]) - dev = source.former.device - vfs = _var_factor_reader(adata) - for k, frame in _movie_reader(movie, align["n_channels"]): - vf = next(vfs) - 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()): - acc.add_missing(k) - continue - x = torch.from_numpy(np.ascontiguousarray(frame)).to(dev) - acc.add(k, list(x), torch.from_numpy(vf).to(dev), (mr, mc)) - result = acc.finish() - attrs = { - "source": "reg-stats", - "movie": movie.name, - "movie_size": int(movie.stat().st_size), - "alignment": adata.name, - "alignment_digest": alignment_digest( - align["ds"], align["motion"][:, 0], align["motion"][:, 1] - ), - "align_hz": align["align_hz"], - "device": str(dev), - } - out.parent.mkdir(parents=True, exist_ok=True) - tmp = out.with_name(out.name + ".partial") - write_stats(tmp, result, attrs) - os.replace(tmp, out) - return result - - -def _up_to_date(out: Path, adata: Path, movie: Path) -> bool: - """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()): - return False - try: - with h5py.File(out, "r") as f: - version = int(f.attrs.get("stats_version", -1)) - digest = f.attrs.get("alignment_digest", "") - size = int(f.attrs.get("movie_size", -1)) - 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 - - -def _stats_job(job: dict) -> dict: - """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"]: - torch.set_num_threads(job["threads"]) - try: - trial_stats( - job["dat"], - job["first"], - job["last"], - job["movie"], - job["adata"], - job["out"], - job["device"], - job["settings"], - ) - return {"out": str(job["out"]), "error": None} - except Exception as exc: # reported per trial - log.exception("statistics failed for %s", job["movie"]) - return {"out": str(job["out"]), "error": repr(exc)} - - -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: - mc = load_struct_h5(path).get("motion_correction", {}) - except (OSError, KeyError, ValueError): - return None - ap = mc.get("align_params") - return ap if isinstance(ap, dict) else None - - -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: 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] - if trials is not None: - keep &= np.isin(np.arange(shape[1]) + 1, list(trials))[None, :] - return keep - - -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 - mc = tt.motion_correction or {} - fn_reg = _grid(mc.get("fn_reg_ds", np.full(shape, "")), shape) - fn_ad = _grid(mc.get("fn_adata", np.full(shape, "")), shape) - first = np.asarray(tt.slap2_info.first_line, float).reshape(shape) - last = np.asarray(tt.slap2_info.last_line, float).reshape(shape) - present = recorded_cells(files) & recorded_cells(fn_reg) - present &= _selected(shape, opts["paths"], opts["trials"]) - moco = opts["moco"] - jobs, missing = [], [] - for d, t in zip(*np.nonzero(present)): - movie, adata = moco / str(fn_reg[d, t]), moco / str(fn_ad[d, t]) - out = stats_path(movie) - if opts["out_dir"] is not None: - out = Path(opts["out_dir"]) / out.name - if not (movie.exists() and adata.exists()): - log.warning("%s or its alignment file is missing", movie.name) - error = f"{movie.name} or its alignment file is missing" - missing.append({"out": out, "error": error}) - continue - if not opts["overwrite"] and _up_to_date(out, adata, movie): - log.info("%s is up to date; skipping", out.name) - continue - 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: str | Path, - out_dir: str | Path | None = None, - *, - datadr: str | Path | None = None, - moco: str | Path | None = None, - device: str = "auto", - max_workers: int = 1, - overwrite: bool = False, - 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). - 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). - 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. - max_workers : int - Parallel trials on the CPU. - overwrite : bool - Recompute statistics that are up to date (same version, same - registration). - paths, trials : sequence of int, optional - One-based paths (DMDs) and trials to do (default: all). - - Returns - ------- - list of dict - 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 - - path = Path(trial_table) - tt = read_trial_table(path) - if tt.slap2_info is None: - raise ValueError("the trial table has no slap2_info") - files = np.atleast_2d(np.asarray(tt.filename, dtype=object)) - dev = resolve_device(device) - 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": - workers = max(1, min(max_workers, len(jobs), os.cpu_count() or 1)) - if workers > 1: - for job in jobs: - job["threads"] = max(1, (os.cpu_count() or 1) // workers) - return missing + map_trials(_stats_job, jobs, n_workers=workers) +"""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 +order, so the maps equal registration's (bit for bit on the same device). + +The frame times, motion, registration window and online compensation are +taken from the alignment file and checked against the frame source built +from the raw recording; a mismatch (other settings than the file's) is an +error, not a silent difference. +""" + +from __future__ import annotations + +import json +import logging +import os +from collections.abc import Iterator, Sequence +from pathlib import Path +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: 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: + """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: 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 + 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), + "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)), + "unlit_masked": bool(_scalar(f, "slap2/unlitMasked", 0)), + "settings": None, + } + out["compensation"] = ( + _compensation_record(f["slap2/onlineCompensation"], row_major) + if out["compensated"] + else None + ) + saved = f.attrs.get("align_params") + if saved is not None: + out["settings"] = json.loads(saved) + if not np.array_equal(out["ds"], ds): + raise ValueError(f"{path}: DSframes are not whole lines") + return out + + +def _matlab_2d(ds: h5py.Dataset, row_major: bool) -> np.ndarray: + """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. + + 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: + """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"), + "frameRefY": _vector(grp, "frameRefY"), + "mapping": _matlab_2d(grp["mapping"], row_major), + "yLead": _vector(grp, "yLead"), + } + + +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: + return + rec = compensation_record(source.compensation, source.references(ds)) + for key, value in saved.items(): + 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" + ) + + +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 + alignment file says. + + Returns + ------- + MultiRoiRegistrationParams + The registration settings, with align_hz and compensate_online taken from + `alignment`. + """ + from ..models.params import MultiRoiRegistrationParams + + rec = alignment["settings"] or table_settings or {} + kw = {} + for field, key in ( + ("init_frames", "initFrames"), + ("maxshift", "maxshift"), + ): + if key in rec and rec[key] is not None: + kw[field] = int(np.asarray(rec[key]).ravel()[0]) + kw["align_hz"] = alignment["align_hz"] + kw["compensate_online"] = alignment["compensated"] + return MultiRoiRegistrationParams(**kw) + + +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 + + # the samples as the registration formed its frames: without those + # behind the DMD curtain only where it left them out + layout, former, init, ds, dtk = open_trial( + dat, first, last, params, device, alignment["unlit_masked"] + ) + if not np.array_equal(ds, alignment["ds"]): + raise ValueError( + 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) + win = source.window + if not ( + np.array_equal(win.trim_rows, alignment["trim_rows"]) + and np.array_equal(win.trim_cols, alignment["trim_cols"]) + ): + raise ValueError(f"{dat}: registration window differs from trimRows") + _check_compensation(dat, source, ds, alignment.get("compensation")) + return layout, source, ds + + +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()))] + n = data.shape[0] // n_channels + for a in range(0, n, FRAMES_PER_READ): + b = min(n, a + FRAMES_PER_READ) + pages = data[a * n_channels : b * n_channels] + pages = pages.reshape(b - a, n_channels, *pages.shape[1:]) + for i in range(b - a): + yield a + i, np.swapaxes(pages[i], -1, -2) + return + import tifffile + + with tifffile.TiffFile(path) as tf: + 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)] + yield k, np.stack(frame).astype(np.float32, copy=False) + + +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] + for a in range(0, n, FRAMES_PER_READ): + block = vf[a : min(n, a + FRAMES_PER_READ)] + for page in block: + yield np.ascontiguousarray(page.T, dtype=np.float32) + + +def trial_stats( + dat: str | Path, + first: float, + last: float, + 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. + + Parameters + ---------- + dat : str or Path + The raw recording. + first, last : float + The trial's line range (trial table slap2_info). + movie, adata : str or Path + Registered movie and alignment file. + out : str or Path + The statistics file to write. + device : str or torch.device + Where the statistics are formed. + table_settings : dict, optional + 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 + + from ..registration.stats import ( + alignment_digest, + new_accumulator, + write_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) + h, w = source.window.shape + margin = (align["out_shape"][0] - h) // 2 + if align["out_shape"] != (h + 2 * margin, w + 2 * margin): + raise ValueError(f"{adata}: meanIM does not fit the window") + acc = new_accumulator(source, ds, margin, align["n_channels"]) + dev = source.former.device + vfs = _var_factor_reader(adata) + for k, frame in _movie_reader(movie, align["n_channels"]): + vf = next(vfs) + 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()): + acc.add_missing(k) + continue + x = torch.from_numpy(np.ascontiguousarray(frame)).to(dev) + acc.add(k, list(x), torch.from_numpy(vf).to(dev), (mr, mc)) + result = acc.finish() + attrs = { + "source": "reg-stats", + "movie": movie.name, + "movie_size": int(movie.stat().st_size), + "alignment": adata.name, + "alignment_digest": alignment_digest( + align["ds"], align["motion"][:, 0], align["motion"][:, 1] + ), + "align_hz": align["align_hz"], + "device": str(dev), + } + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(out.name + ".partial") + write_stats(tmp, result, attrs) + os.replace(tmp, out) + return result + + +def _up_to_date(out: Path, adata: Path, movie: Path) -> bool: + """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()): + return False + try: + with h5py.File(out, "r") as f: + version = int(f.attrs.get("stats_version", -1)) + digest = f.attrs.get("alignment_digest", "") + size = int(f.attrs.get("movie_size", -1)) + 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 + + +def _stats_job(job: dict) -> dict: + """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"]: + torch.set_num_threads(job["threads"]) + try: + trial_stats( + job["dat"], + job["first"], + job["last"], + job["movie"], + job["adata"], + job["out"], + job["device"], + job["settings"], + ) + return {"out": str(job["out"]), "error": None} + except Exception as exc: # reported per trial + log.exception("statistics failed for %s", job["movie"]) + return {"out": str(job["out"]), "error": repr(exc)} + + +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: + mc = load_struct_h5(path).get("motion_correction", {}) + except (OSError, KeyError, ValueError): + return None + ap = mc.get("align_params") + return ap if isinstance(ap, dict) else None + + +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: 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] + if trials is not None: + keep &= np.isin(np.arange(shape[1]) + 1, list(trials))[None, :] + return keep + + +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 + mc = tt.motion_correction or {} + fn_reg = _grid(mc.get("fn_reg_ds", np.full(shape, "")), shape) + fn_ad = _grid(mc.get("fn_adata", np.full(shape, "")), shape) + first = np.asarray(tt.slap2_info.first_line, float).reshape(shape) + last = np.asarray(tt.slap2_info.last_line, float).reshape(shape) + present = recorded_cells(files) & recorded_cells(fn_reg) + present &= _selected(shape, opts["paths"], opts["trials"]) + moco = opts["moco"] + jobs, missing = [], [] + for d, t in zip(*np.nonzero(present)): + movie, adata = moco / str(fn_reg[d, t]), moco / str(fn_ad[d, t]) + out = stats_path(movie) + if opts["out_dir"] is not None: + out = Path(opts["out_dir"]) / out.name + if not (movie.exists() and adata.exists()): + log.warning("%s or its alignment file is missing", movie.name) + error = f"{movie.name} or its alignment file is missing" + missing.append({"out": out, "error": error}) + continue + if not opts["overwrite"] and _up_to_date(out, adata, movie): + log.info("%s is up to date; skipping", out.name) + continue + 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: str | Path, + out_dir: str | Path | None = None, + *, + datadr: str | Path | None = None, + moco: str | Path | None = None, + device: str = "auto", + max_workers: int = 1, + overwrite: bool = False, + 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). + 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). + 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. + max_workers : int + Parallel trials on the CPU. + overwrite : bool + Recompute statistics that are up to date (same version, same + registration). + paths, trials : sequence of int, optional + One-based paths (DMDs) and trials to do (default: all). + + Returns + ------- + list of dict + 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 + + path = Path(trial_table) + tt = read_trial_table(path) + if tt.slap2_info is None: + raise ValueError("the trial table has no slap2_info") + files = np.atleast_2d(np.asarray(tt.filename, dtype=object)) + dev = resolve_device(device) + 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": + workers = max(1, min(max_workers, len(jobs), os.cpu_count() or 1)) + if workers > 1: + for job in jobs: + job["threads"] = max(1, (os.cpu_count() or 1) // workers) + return missing + map_trials(_stats_job, jobs, n_workers=workers) diff --git a/src/giant_python/pipeline/trial_table.py b/src/giant_python/pipeline/trial_table.py index 5c6eb318..41655170 100644 --- a/src/giant_python/pipeline/trial_table.py +++ b/src/giant_python/pipeline/trial_table.py @@ -1,835 +1,835 @@ -"""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 -stacks and the trial times. :func:`build_trial_table_slap2` writes the same -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. - -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 -most 200000 lines. Trial times come from the FPGA line clock when the -.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 - -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.""" - -MULTI_CYCLE_LINES_PER_TRIAL = 200000 -"""Continuous recordings are cut into trials of at most this many lines.""" - -_DATENUM_1970 = 719529.0 -"""MATLAB datenum(1970, 1, 1).""" - -_MS_PER_DAY = 86400000.0 - - -class TrialTableWarning(UserWarning): - """File order or trial times may be wrong (as MATLAB's warnings).""" - - -@dataclass(frozen=True) -class DatInfo: - """What the trial table needs from one recording (all its files). - - Attributes - ---------- - num_lines : int - Lines in the recording (totalNumLines). - first_line_time : float - MATLAB datenum of the first line by the FPGA clock, or NaN. - line_period_s : float - Line period from the metadata file. - """ - - num_lines: int - first_line_time: float - line_period_s: float - - -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. - - Parameters - ---------- - path : str or Path - A .dat file. - - Returns - ------- - DatInfo - The recording's line count, first-line time and line period. - """ - from ..io.slap2 import ( - first_line_timestamp, - open_slap2_file, - read_mat_datetime_ms, - ) - - reader = open_slap2_file(path) - files = list(getattr(reader, "hDataFiles", None) or [reader]) - first = files[0] - lines_per_cycle = int(first.header["linesPerCycle"]) - num_lines = int(sum(int(df.numCycles) for df in files)) * lines_per_cycle - line_period_s = float(first.metaData.linePeriod_s) - t = math.nan - try: - ticks = min(first_line_timestamp(df) for df in files) - except (OSError, ValueError): - ticks = 0 - clock_hz = float(first.header.get("fpgaSystemClock_Hz", 0) or 0) - if ticks > 0 and clock_hz > 0: - wall_ms = read_mat_datetime_ms( - first.metaDataFileName, - "fpgaTimeReference", - offset_ms=1000.0 * ticks / clock_hz, - ) - if wall_ms is not None: - t = _DATENUM_1970 + wall_ms / _MS_PER_DAY - return DatInfo(num_lines, t, line_period_s) - - -def _mtime_datenum(path: Path) -> float: - """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. - - 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: 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) :])] - 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. - - 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): - 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 - - -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, - the trial number. - - Parameters - ---------- - names : sequence of str - File names of one path. - - Returns - ------- - order : ndarray of int - Zero-based indexes in acquisition order (the identity when not ok). - ok : bool - False when files of different acquisitions have no timestamp in - their names, or when two files get the same position. - """ - n = len(names) - acq = np.full(n, np.nan) - trial = np.zeros(n) - base = [] - for k, name in enumerate(names): - 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)) - b = re.sub(r"-TRIAL\d+$", "", stem, flags=re.IGNORECASE) - base.append(b) - stamps = re.findall(r"(? str: - """Why modification times look like copy times rather than write times. - - 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 "" - mtime_s = mtimes * 86400.0 - recorded_s = num_lines * line_period_s - min_span_s = recorded_s.sum() - recorded_s.max() - span_s = mtime_s.max() - mtime_s.min() - 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 {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). - - 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) - if n == 1: - return np.array([float(d2)]) - n1 = n - 1 - y = d1 + (np.arange(n, dtype=np.float64) * (d2 - d1)) / n1 - y[0], y[-1] = d1, d2 - return y - - -def _find_reference(dat_dir: Path, dmd: int) -> Path: - """Find the reference stack TIFF of one path, searched under dat_dir. - - 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*") - if not found: - 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!") - if len(tifs) > 1: - raise ValueError("Too many CONFIG1 reference stacks found in the specified directory!") - return tifs[0] - - -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) - if arr.ndim == 1: - return arr.reshape(-1, 1) - return arr - - -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. - - Returns - ------- - dict - 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. - - Raises - ------ - ValueError - If the reference stack's pages are not 2-D. - """ - import tifffile - - with tifffile.TiffFile(path) as tf: - pages = tf.pages - first = pages[0] - n = len(pages) - stack = np.empty((n,) + tuple(first.shape), dtype=first.dtype) - descs = [] - for k, page in enumerate(pages): - stack[k] = page.asarray() - descs.append(page.description) - channels: list[float] = [] - zs: list[float] = [] - accum = None - meta = {} - for k, desc in enumerate(descs): - meta = json.loads(desc) - ch = float(meta["channel"]) - if ch not in channels: - channels.append(ch) - if k == 0: - accum = ch - if ch == accum: - zs.append(float(meta["z"])) - if stack.ndim != 3: - raise ValueError(f"reference stack pages must be 2-D: {path}") - im = stack[0].T if n == 1 else stack.transpose(2, 1, 0) - return { - "IM": im, - "channels": np.asarray(channels, dtype=np.float64), - "Zs": np.asarray(zs, dtype=np.float64), - "dmdPixel2SampleTransform": _json_array(meta["dmdPixel2SampleTransform"]), - } - - -@dataclass -class _PathFiles: - """One path's files in acquisition order, with what trials need.""" - - names: list[str] - lines: np.ndarray - clock: np.ndarray - mtime: np.ndarray - - -@dataclass -class _Trials: - """Analysis trials as rows (one tuple per trial, path 1 then 2).""" - - files: list = field(default_factory=list) - first: list = field(default_factory=list) - last: list = field(default_factory=list) - start: list = field(default_factory=list) - end: list = field(default_factory=list) - - 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) - self.last.append(last) - self.start.append(start) - self.end.append(end) - - -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, - np.array([info[n].num_lines for n in ordered], dtype=np.float64), - np.array([info[n].first_line_time for n in ordered]), - np.array([mtime[n] for n in ordered]), - ) - - -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] - o1, ok1 = acquisition_order(d1) - o2, ok2 = acquisition_order(d2) - names_ok = ok1 and ok2 - if not names_ok: - warnings.warn( - "Could not read acquisition times and trial numbers from the " - ".dat file names in epoch 1; ordering files by modification time " - "instead, which is wrong for copied files.", - TrialTableWarning, - stacklevel=3, - ) - o1 = np.argsort([mtime[n] for n in d1], kind="stable") - o2 = np.argsort([mtime[n] for n in d2], kind="stable") - p1 = _path_files(d1, o1, info, mtime) - p2 = _path_files(d2, o2, info, mtime) - return p1, p2, names_ok - - -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 - ) - if reason: - warnings.warn( - f"File modification times in epoch 1 do not look like acquisition " - f"times ({reason}). trial_end_time_from_pc and " - f"trial_start_time_inferred come from these times and are " - f"probably copy times.", - TrialTableWarning, - stacklevel=3, - ) - - -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 " - "using continuous acquisitions" - ) - line_days = line_period_s / 86400.0 - trials = _Trials() - for f in range(len(p1.names)): - 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 itertools.pairwise(edges): - if use_clock: - start = p1.clock[f] + (a - 1) * line_days - end = p1.clock[f] + (b - 1) * line_days - else: - start = p1.mtime[f] - (p1.lines[f] - a) * line_days - end = p1.mtime[f] - (p1.lines[f] - b) * line_days - trials.add((p1.names[f], p2.names[f]), (a, a), (b, b), start, end) - return 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() - i1 = i2 = 0 - acc = [0.0, 0.0] - while i2 < len(p2.names) and i1 < len(p1.names): - c1 = np.cumsum(p1.lines[i1 : i1 + 5]) - acc[0] - c2 = np.cumsum(p2.lines[i2 : i2 + 5]) - acc[1] - if not np.min(np.abs(c1[:, None] - c2[None, :])) < LINE_DIFF_THRESH: - raise ValueError("Error lining up trials across DMDs!") - n = min(c1[0], c2[0]) - files = (p1.names[i1], p2.names[i2]) - first = (acc[0] + 1, acc[1] + 1) - last = (acc[0] + n, acc[1] + n) - clock_start = p1.clock[i1] if acc[0] == 0 else p2.clock[i2] - if abs(c1[0] - c2[0]) < LINE_DIFF_THRESH: - end_mtime = p1.mtime[i1] - i1, i2, acc = i1 + 1, i2 + 1, [0.0, 0.0] - elif c1[0] < c2[0]: - end_mtime = p1.mtime[i1] - i1, acc = i1 + 1, [0.0, acc[1] + n] - else: - end_mtime = p2.mtime[i2] - i2, acc = i2 + 1, [acc[0] + n, 0.0] - if use_clock: - start, end = clock_start, clock_start + n * line_days - else: - start, end = end_mtime - n * line_days, end_mtime - trials.add(files, first, last, start, end) - left1 = float(p1.lines[i1:].sum() - acc[0]) - left2 = float(p2.lines[i2:].sum() - acc[1]) - if left1 > 0 or left2 > 0: - warnings.warn( - f"After trial {len(trials.files)} the paths could not be lined " - f"up further, so {left1:.0f} lines of DMD1 " - f"({len(p1.names) - i1} files) and {left2:.0f} lines of DMD2 " - f"({len(p2.names) - i2} files) are left out of the trial table, " - f"as in MATLAB.", - TrialTableWarning, - stacklevel=3, - ) - return trials - - -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: 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) - out_dir.mkdir(parents=True, exist_ok=True) - if max_duration_s is None: - save_struct_h5(out_dir / "trial_table.h5", table) - return table - save_struct_h5(out_dir / "trial_table_untrimmed.h5", table) - trimmed, _ = trim_trial_table(table, max_duration_s, line_period_s) - save_struct_h5(out_dir / "trial_table.h5", trimmed) - return trimmed - - -def build_trial_table_slap2( - 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 - 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. - save_dir : str or Path, optional - 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. - 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). - - 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) - all_names = sorted(p.name for p in dat_dir.glob("*.dat") if p.is_file()) - 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)} - 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} - print("done loading") - line_period_s = info[names[0]].line_period_s - - p1, p2, names_ok = _paths_in_order(names, info, mtime) - use_clock = all(math.isfinite(info[n].first_line_time) for n in names) - if not use_clock: - _warn_copy_times(p1, p2, line_period_s, names_ok) - cycle = ["-CYCLE" in name for name in p1.names + p2.names] - if any(cycle) and not all(cycle): - raise ValueError( - f"{dat_dir} holds both continuous (-CYCLE-) and triggered " - f"recordings; build a trial table for each kind separately." - ) - if all(cycle): - trials = _continuous_trials(p1, p2, use_clock, line_period_s) - else: - trials = _triggered_trials(p1, p2, use_clock, line_period_s) - - n = len(trials.files) - if n == 0: - raise ValueError( - f"No trials could be lined up across the two paths " - f"({len(p1.names)} DMD1 and {len(p2.names)} DMD2 recordings)." - ) - table = { - "datadr": dat_dir_str, - "savedr": save_dir_str, - "filename": _rows(trials.files, n, dtype=object), - "true_trial_ix": np.tile(np.arange(1.0, n + 1), (2, 1)), - "epoch": np.ones((2, n)), - "slap2_info": { - "ref_stack": ref_stack, - "first_line": _rows(trials.first, n), - "last_line": _rows(trials.last, n), - "trial_end_time_from_pc": np.array(trials.end).reshape(1, -1), - "trial_start_time_inferred": np.array(trials.start).reshape(1, -1), - }, - } - if write: - 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]: - """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. - - Parameters - ---------- - table : dict - Trial table in MATLAB orientation (from - :func:`build_trial_table_slap2` or load_struct_h5). - max_duration_s : float - Seconds to keep. - line_period_s : float - Line period of the recording. - - Returns - ------- - 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. - - 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) - last = np.asarray(s2["last_line"], dtype=np.float64).reshape(2, -1).copy() - n_lines = last - first + 1 - trial_dur_s = n_lines.max(axis=0) * line_period_s - n_in = trial_dur_s.size - start_s = np.concatenate([[0.0], np.cumsum(trial_dur_s[:-1])]) - keep = np.flatnonzero(start_s < max_duration_s) - if keep.size == 0: - raise ValueError(f"No trials start before {max_duration_s:g} s.") - k = keep[-1] - remaining_s = max_duration_s - start_s[k] - shortened = bool(remaining_s < trial_dur_s[k]) - if shortened: - 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: 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["true_trial_ix"] = cols(table["true_trial_ix"]) - out["epoch"] = cols(table["epoch"]) - new_s2 = dict(s2) - new_s2["first_line"] = first[:, keep] - new_s2["last_line"] = last[:, keep] - for key in ("trial_end_time_from_pc", "trial_start_time_inferred"): - if key in s2 and np.asarray(s2[key]).size == n_in: - new_s2[key] = np.asarray(s2[key]).reshape(1, -1)[:, keep] - out["slap2_info"] = new_s2 - kept = new_s2["last_line"] - new_s2["first_line"] + 1 - info = { - "n_trials_untrimmed": int(n_in), - "duration_untrimmed_s": float(trial_dur_s.sum()), - "n_trials_kept": int(keep.size), - "duration_kept_s": float(kept.max(axis=0).sum() * line_period_s), - "last_trial_shortened": shortened, - } - print( - f"Trimmed trial table: kept {info['n_trials_kept']} of {n_in} trials, " - f"{info['duration_kept_s']:.1f} of " - f"{info['duration_untrimmed_s']:.1f} s" - ) - return out, info +"""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 +stacks and the trial times. :func:`build_trial_table_slap2` writes the same +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. + +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 +most 200000 lines. Trial times come from the FPGA line clock when the +.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 + +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.""" + +MULTI_CYCLE_LINES_PER_TRIAL = 200000 +"""Continuous recordings are cut into trials of at most this many lines.""" + +_DATENUM_1970 = 719529.0 +"""MATLAB datenum(1970, 1, 1).""" + +_MS_PER_DAY = 86400000.0 + + +class TrialTableWarning(UserWarning): + """File order or trial times may be wrong (as MATLAB's warnings).""" + + +@dataclass(frozen=True) +class DatInfo: + """What the trial table needs from one recording (all its files). + + Attributes + ---------- + num_lines : int + Lines in the recording (totalNumLines). + first_line_time : float + MATLAB datenum of the first line by the FPGA clock, or NaN. + line_period_s : float + Line period from the metadata file. + """ + + num_lines: int + first_line_time: float + line_period_s: float + + +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. + + Parameters + ---------- + path : str or Path + A .dat file. + + Returns + ------- + DatInfo + The recording's line count, first-line time and line period. + """ + from ..io.slap2 import ( + first_line_timestamp, + open_slap2_file, + read_mat_datetime_ms, + ) + + reader = open_slap2_file(path) + files = list(getattr(reader, "hDataFiles", None) or [reader]) + first = files[0] + lines_per_cycle = int(first.header["linesPerCycle"]) + num_lines = int(sum(int(df.numCycles) for df in files)) * lines_per_cycle + line_period_s = float(first.metaData.linePeriod_s) + t = math.nan + try: + ticks = min(first_line_timestamp(df) for df in files) + except (OSError, ValueError): + ticks = 0 + clock_hz = float(first.header.get("fpgaSystemClock_Hz", 0) or 0) + if ticks > 0 and clock_hz > 0: + wall_ms = read_mat_datetime_ms( + first.metaDataFileName, + "fpgaTimeReference", + offset_ms=1000.0 * ticks / clock_hz, + ) + if wall_ms is not None: + t = _DATENUM_1970 + wall_ms / _MS_PER_DAY + return DatInfo(num_lines, t, line_period_s) + + +def _mtime_datenum(path: Path) -> float: + """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. + + 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: 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) :])] + 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. + + 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): + 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 + + +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, + the trial number. + + Parameters + ---------- + names : sequence of str + File names of one path. + + Returns + ------- + order : ndarray of int + Zero-based indexes in acquisition order (the identity when not ok). + ok : bool + False when files of different acquisitions have no timestamp in + their names, or when two files get the same position. + """ + n = len(names) + acq = np.full(n, np.nan) + trial = np.zeros(n) + base = [] + for k, name in enumerate(names): + 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)) + b = re.sub(r"-TRIAL\d+$", "", stem, flags=re.IGNORECASE) + base.append(b) + stamps = re.findall(r"(? str: + """Why modification times look like copy times rather than write times. + + 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 "" + mtime_s = mtimes * 86400.0 + recorded_s = num_lines * line_period_s + min_span_s = recorded_s.sum() - recorded_s.max() + span_s = mtime_s.max() - mtime_s.min() + 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 {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). + + 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) + if n == 1: + return np.array([float(d2)]) + n1 = n - 1 + y = d1 + (np.arange(n, dtype=np.float64) * (d2 - d1)) / n1 + y[0], y[-1] = d1, d2 + return y + + +def _find_reference(dat_dir: Path, dmd: int) -> Path: + """Find the reference stack TIFF of one path, searched under dat_dir. + + 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*") + if not found: + 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!") + if len(tifs) > 1: + raise ValueError("Too many CONFIG1 reference stacks found in the specified directory!") + return tifs[0] + + +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) + if arr.ndim == 1: + return arr.reshape(-1, 1) + return arr + + +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. + + Returns + ------- + dict + 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. + + Raises + ------ + ValueError + If the reference stack's pages are not 2-D. + """ + import tifffile + + with tifffile.TiffFile(path) as tf: + pages = tf.pages + first = pages[0] + n = len(pages) + stack = np.empty((n,) + tuple(first.shape), dtype=first.dtype) + descs = [] + for k, page in enumerate(pages): + stack[k] = page.asarray() + descs.append(page.description) + channels: list[float] = [] + zs: list[float] = [] + accum = None + meta = {} + for k, desc in enumerate(descs): + meta = json.loads(desc) + ch = float(meta["channel"]) + if ch not in channels: + channels.append(ch) + if k == 0: + accum = ch + if ch == accum: + zs.append(float(meta["z"])) + if stack.ndim != 3: + raise ValueError(f"reference stack pages must be 2-D: {path}") + im = stack[0].T if n == 1 else stack.transpose(2, 1, 0) + return { + "IM": im, + "channels": np.asarray(channels, dtype=np.float64), + "Zs": np.asarray(zs, dtype=np.float64), + "dmdPixel2SampleTransform": _json_array(meta["dmdPixel2SampleTransform"]), + } + + +@dataclass +class _PathFiles: + """One path's files in acquisition order, with what trials need.""" + + names: list[str] + lines: np.ndarray + clock: np.ndarray + mtime: np.ndarray + + +@dataclass +class _Trials: + """Analysis trials as rows (one tuple per trial, path 1 then 2).""" + + files: list = field(default_factory=list) + first: list = field(default_factory=list) + last: list = field(default_factory=list) + start: list = field(default_factory=list) + end: list = field(default_factory=list) + + 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) + self.last.append(last) + self.start.append(start) + self.end.append(end) + + +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, + np.array([info[n].num_lines for n in ordered], dtype=np.float64), + np.array([info[n].first_line_time for n in ordered]), + np.array([mtime[n] for n in ordered]), + ) + + +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] + o1, ok1 = acquisition_order(d1) + o2, ok2 = acquisition_order(d2) + names_ok = ok1 and ok2 + if not names_ok: + warnings.warn( + "Could not read acquisition times and trial numbers from the " + ".dat file names in epoch 1; ordering files by modification time " + "instead, which is wrong for copied files.", + TrialTableWarning, + stacklevel=3, + ) + o1 = np.argsort([mtime[n] for n in d1], kind="stable") + o2 = np.argsort([mtime[n] for n in d2], kind="stable") + p1 = _path_files(d1, o1, info, mtime) + p2 = _path_files(d2, o2, info, mtime) + return p1, p2, names_ok + + +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 + ) + if reason: + warnings.warn( + f"File modification times in epoch 1 do not look like acquisition " + f"times ({reason}). trial_end_time_from_pc and " + f"trial_start_time_inferred come from these times and are " + f"probably copy times.", + TrialTableWarning, + stacklevel=3, + ) + + +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 " + "using continuous acquisitions" + ) + line_days = line_period_s / 86400.0 + trials = _Trials() + for f in range(len(p1.names)): + 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 itertools.pairwise(edges): + if use_clock: + start = p1.clock[f] + (a - 1) * line_days + end = p1.clock[f] + (b - 1) * line_days + else: + start = p1.mtime[f] - (p1.lines[f] - a) * line_days + end = p1.mtime[f] - (p1.lines[f] - b) * line_days + trials.add((p1.names[f], p2.names[f]), (a, a), (b, b), start, end) + return 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() + i1 = i2 = 0 + acc = [0.0, 0.0] + while i2 < len(p2.names) and i1 < len(p1.names): + c1 = np.cumsum(p1.lines[i1 : i1 + 5]) - acc[0] + c2 = np.cumsum(p2.lines[i2 : i2 + 5]) - acc[1] + if not np.min(np.abs(c1[:, None] - c2[None, :])) < LINE_DIFF_THRESH: + raise ValueError("Error lining up trials across DMDs!") + n = min(c1[0], c2[0]) + files = (p1.names[i1], p2.names[i2]) + first = (acc[0] + 1, acc[1] + 1) + last = (acc[0] + n, acc[1] + n) + clock_start = p1.clock[i1] if acc[0] == 0 else p2.clock[i2] + if abs(c1[0] - c2[0]) < LINE_DIFF_THRESH: + end_mtime = p1.mtime[i1] + i1, i2, acc = i1 + 1, i2 + 1, [0.0, 0.0] + elif c1[0] < c2[0]: + end_mtime = p1.mtime[i1] + i1, acc = i1 + 1, [0.0, acc[1] + n] + else: + end_mtime = p2.mtime[i2] + i2, acc = i2 + 1, [acc[0] + n, 0.0] + if use_clock: + start, end = clock_start, clock_start + n * line_days + else: + start, end = end_mtime - n * line_days, end_mtime + trials.add(files, first, last, start, end) + left1 = float(p1.lines[i1:].sum() - acc[0]) + left2 = float(p2.lines[i2:].sum() - acc[1]) + if left1 > 0 or left2 > 0: + warnings.warn( + f"After trial {len(trials.files)} the paths could not be lined " + f"up further, so {left1:.0f} lines of DMD1 " + f"({len(p1.names) - i1} files) and {left2:.0f} lines of DMD2 " + f"({len(p2.names) - i2} files) are left out of the trial table, " + f"as in MATLAB.", + TrialTableWarning, + stacklevel=3, + ) + return trials + + +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: 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) + out_dir.mkdir(parents=True, exist_ok=True) + if max_duration_s is None: + save_struct_h5(out_dir / "trial_table.h5", table) + return table + save_struct_h5(out_dir / "trial_table_untrimmed.h5", table) + trimmed, _ = trim_trial_table(table, max_duration_s, line_period_s) + save_struct_h5(out_dir / "trial_table.h5", trimmed) + return trimmed + + +def build_trial_table_slap2( + 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 + 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. + save_dir : str or Path, optional + 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. + 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). + + 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) + all_names = sorted(p.name for p in dat_dir.glob("*.dat") if p.is_file()) + 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)} + 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} + print("done loading") + line_period_s = info[names[0]].line_period_s + + p1, p2, names_ok = _paths_in_order(names, info, mtime) + use_clock = all(math.isfinite(info[n].first_line_time) for n in names) + if not use_clock: + _warn_copy_times(p1, p2, line_period_s, names_ok) + cycle = ["-CYCLE" in name for name in p1.names + p2.names] + if any(cycle) and not all(cycle): + raise ValueError( + f"{dat_dir} holds both continuous (-CYCLE-) and triggered " + f"recordings; build a trial table for each kind separately." + ) + if all(cycle): + trials = _continuous_trials(p1, p2, use_clock, line_period_s) + else: + trials = _triggered_trials(p1, p2, use_clock, line_period_s) + + n = len(trials.files) + if n == 0: + raise ValueError( + f"No trials could be lined up across the two paths " + f"({len(p1.names)} DMD1 and {len(p2.names)} DMD2 recordings)." + ) + table = { + "datadr": dat_dir_str, + "savedr": save_dir_str, + "filename": _rows(trials.files, n, dtype=object), + "true_trial_ix": np.tile(np.arange(1.0, n + 1), (2, 1)), + "epoch": np.ones((2, n)), + "slap2_info": { + "ref_stack": ref_stack, + "first_line": _rows(trials.first, n), + "last_line": _rows(trials.last, n), + "trial_end_time_from_pc": np.array(trials.end).reshape(1, -1), + "trial_start_time_inferred": np.array(trials.start).reshape(1, -1), + }, + } + if write: + 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]: + """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. + + Parameters + ---------- + table : dict + Trial table in MATLAB orientation (from + :func:`build_trial_table_slap2` or load_struct_h5). + max_duration_s : float + Seconds to keep. + line_period_s : float + Line period of the recording. + + Returns + ------- + 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. + + 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) + last = np.asarray(s2["last_line"], dtype=np.float64).reshape(2, -1).copy() + n_lines = last - first + 1 + trial_dur_s = n_lines.max(axis=0) * line_period_s + n_in = trial_dur_s.size + start_s = np.concatenate([[0.0], np.cumsum(trial_dur_s[:-1])]) + keep = np.flatnonzero(start_s < max_duration_s) + if keep.size == 0: + raise ValueError(f"No trials start before {max_duration_s:g} s.") + k = keep[-1] + remaining_s = max_duration_s - start_s[k] + shortened = bool(remaining_s < trial_dur_s[k]) + if shortened: + 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: 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["true_trial_ix"] = cols(table["true_trial_ix"]) + out["epoch"] = cols(table["epoch"]) + new_s2 = dict(s2) + new_s2["first_line"] = first[:, keep] + new_s2["last_line"] = last[:, keep] + for key in ("trial_end_time_from_pc", "trial_start_time_inferred"): + if key in s2 and np.asarray(s2[key]).size == n_in: + new_s2[key] = np.asarray(s2[key]).reshape(1, -1)[:, keep] + out["slap2_info"] = new_s2 + kept = new_s2["last_line"] - new_s2["first_line"] + 1 + info = { + "n_trials_untrimmed": int(n_in), + "duration_untrimmed_s": float(trial_dur_s.sum()), + "n_trials_kept": int(keep.size), + "duration_kept_s": float(kept.max(axis=0).sum() * line_period_s), + "last_trial_shortened": shortened, + } + print( + f"Trimmed trial table: kept {info['n_trials_kept']} of {n_in} trials, " + f"{info['duration_kept_s']:.1f} of " + f"{info['duration_untrimmed_s']:.1f} s" + ) + return out, info diff --git a/src/giant_python/progress.py b/src/giant_python/progress.py index e4915343..35ad97e1 100644 --- a/src/giant_python/progress.py +++ b/src/giant_python/progress.py @@ -1,63 +1,63 @@ -"""Shared opt-in verbose logging and progress bars. - -The BandSILo port stays quiet by default (headless / batch friendly); the -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 collections.abc import Iterable - - -def log(message: str, verbose: bool) -> None: - """Print message when verbose is set; otherwise do nothing. - - Parameters - ---------- - message : str - The status message to display. - verbose : bool - Whether verbose output is enabled. - """ - if verbose: - print(message) - - -def progress( - iterable: Iterable, - *, - desc: str, - verbose: bool, - total: int | None = None, -) -> Iterable: - """Wrap iterable in a tqdm progress bar when verbose is set. - - Returns the iterable unchanged when verbose is False so callers can - wrap any loop unconditionally at zero cost (and without importing - tqdm). - - Parameters - ---------- - iterable : iterable - The loop iterable to (optionally) wrap. - desc : str - Progress-bar label. - verbose : bool - Whether to show the bar. - total : int, optional - Item count, for iterables without a len (e.g. a generator). - - Returns - ------- - iterable - The tqdm-wrapped iterable, or the original iterable. - """ - if not verbose: - return iterable - from tqdm import tqdm - - return tqdm(iterable, desc=desc, total=total) +"""Shared opt-in verbose logging and progress bars. + +The BandSILo port stays quiet by default (headless / batch friendly); the +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 collections.abc import Iterable + + +def log(message: str, verbose: bool) -> None: + """Print message when verbose is set; otherwise do nothing. + + Parameters + ---------- + message : str + The status message to display. + verbose : bool + Whether verbose output is enabled. + """ + if verbose: + print(message) + + +def progress( + iterable: Iterable, + *, + desc: str, + verbose: bool, + total: int | None = None, +) -> Iterable: + """Wrap iterable in a tqdm progress bar when verbose is set. + + Returns the iterable unchanged when verbose is False so callers can + wrap any loop unconditionally at zero cost (and without importing + tqdm). + + Parameters + ---------- + iterable : iterable + The loop iterable to (optionally) wrap. + desc : str + Progress-bar label. + verbose : bool + Whether to show the bar. + total : int, optional + Item count, for iterables without a len (e.g. a generator). + + Returns + ------- + iterable + The tqdm-wrapped iterable, or the original iterable. + """ + if not verbose: + return iterable + from tqdm import tqdm + + return tqdm(iterable, desc=desc, total=total) diff --git a/src/giant_python/registration/__init__.py b/src/giant_python/registration/__init__.py index 69589434..b75a9ebc 100644 --- a/src/giant_python/registration/__init__.py +++ b/src/giant_python/registration/__init__.py @@ -1,14 +1,14 @@ -"""Motion registration of SLAP2 raster recordings (MultiRoiRegistration). - -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 -SILo reads them unchanged. - -Computations run in PyTorch on the CPU or a CUDA device. -""" - -from .multiroi import register_trial - -__all__ = ["register_trial"] +"""Motion registration of SLAP2 raster recordings (MultiRoiRegistration). + +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 +SILo reads them unchanged. + +Computations run in PyTorch on the CPU or a CUDA device. +""" + +from .multiroi import register_trial + +__all__ = ["register_trial"] diff --git a/src/giant_python/registration/compensation.py b/src/giant_python/registration/compensation.py index d4ccd6ed..c966ce22 100644 --- a/src/giant_python/registration/compensation.py +++ b/src/giant_python/registration/compensation.py @@ -1,238 +1,238 @@ -"""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 -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 -does, but never before the previous x/y switch. -""" - -from dataclasses import dataclass - -import numpy as np -from numpy.typing import ArrayLike - -from ..io.slap2_raster import RasterLayout, read_line_offsets - -Y_LEAD = (2, 6) -"""Lines by which a new y precedes its header (x unchanged, x changed).""" - -MAPPING = np.array([[0.0, 1.0], [1.0, 0.0]]) -"""Header offset difference [dx; dy] to [row; col] sample displacement.""" - - -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) - - -@dataclass -class LineOffsets: - """Online offsets of every line of a recording. - - 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 - 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). - 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. - """ - - x: np.ndarray - y: np.ndarray - y_eff: np.ndarray - median_xy: np.ndarray - switch_lines: np.ndarray - lines_read: tuple[int, int] - y_lead: tuple[int, int] = Y_LEAD - - -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 - ---------- - x, y : ndarray - Header offsets of every line. - switch_lines : ndarray of int - One-based x/y switch lines. - lead : (int, int) - Lead when x is unchanged / changes on the same line. - - Returns - ------- - ndarray - 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 - sw0 = np.asarray(switch_lines) - 1 - for s in y_sw: - k = lead[1] if x[s] != x[s - 1] else lead[0] - before = sw0[sw0 < s] - prev = before[-1] if before.size else 0 - y_eff[max(s - k, prev) : s] = y[s] - return y_eff - - -def line_offsets( - layout: RasterLayout, lines: tuple[int, int], lead: tuple[int, int] = Y_LEAD -) -> LineOffsets: - """Read the headers covering lines (getLineOnlineOffsets). - - Parameters - ---------- - layout : RasterLayout - The recording's layout. - lines : (int, int) - First and last line needed (may extend past the recording). - lead : (int, int) - Lead of y switches. - - Returns - ------- - LineOffsets - Offsets of every line of the recording, exact within the cycles - 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 - pad = max(lead) + 1 - first_c = max(1, int(np.floor((lines[0] - pad - 1) / p)) + 1) - last_c = min(n_c, int(np.ceil((lines[1] + pad) / p))) - if first_c > last_c: - raise ValueError(f"lines {lines} are outside the recording") - read = (int((first_c - 1) * p + 1), int(last_c * p)) - x, y, _ = read_line_offsets(layout, np.arange(read[0], read[1] + 1)) - x, y = x.astype(np.int64), y.astype(np.int64) - median_xy = _mround([np.median(x), np.median(y)]) - n_before, n_after = read[0] - 1, layout.total_lines - read[1] - x = np.pad(x, (n_before, n_after), mode="edge") - y = np.pad(y, (n_before, n_after), mode="edge") - switch = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 - return LineOffsets( - x=x, - y=y, - y_eff=dmd_y(x, y, switch, lead), - median_xy=median_xy, - switch_lines=switch, - lines_read=read, - y_lead=tuple(lead), - ) - - -def frame_offsets( - offsets: LineOffsets, times: ArrayLike, dt: int, lines_per_cycle: int -) -> np.ndarray: - """Compute the offset each frame mostly saw (frameOnlineOffsets). - - Parameters - ---------- - offsets : LineOffsets - Line offsets of the recording. - times : array_like of int - One-based frame times. - dt : int - Kernel time constant in lines. - lines_per_cycle : int - 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 - over each frame's lines, rounded. - """ - times = np.asarray(times, dtype=np.int64).ravel() - n = offsets.x.size - dt_read = max(3 * dt, lines_per_cycle) - out = np.zeros((times.size, 2), dtype=np.int64) - 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()) - return out - - -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). - refs : ndarray of int - (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. - """ - extra = (1,) * (lines.ndim - 1) - idx = np.clip(lines, 1, offsets.x.size) - 1 - dx = offsets.x[idx] - refs[:, 0].reshape((-1,) + extra) - dy = offsets.y_eff[idx] - refs[:, 1].reshape((-1,) + extra) - return dy, dx - - -def compensation_record(offsets: LineOffsets, refs: np.ndarray) -> dict: - """Build the slap2/onlineCompensation group of the alignment file. - - Parameters - ---------- - offsets : LineOffsets - Line offsets (gives refOffset and yLead). - refs : ndarray of int - (frames, 2) reference offsets [x, y] of the DS frames. - - Returns - ------- - dict - Fields as MATLAB's compensationRecord saves them. - """ - return { - "enabled": np.int8(1), - "refOffset": offsets.median_xy.astype(np.float64), - "frameRefX": refs[:, 0].astype(np.int16), - "frameRefY": refs[:, 1].astype(np.int16), - "mapping": MAPPING.copy(), - "yLead": np.asarray(offsets.y_lead, dtype=np.float64), - } +"""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 +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 +does, but never before the previous x/y switch. +""" + +from dataclasses import dataclass + +import numpy as np +from numpy.typing import ArrayLike + +from ..io.slap2_raster import RasterLayout, read_line_offsets + +Y_LEAD = (2, 6) +"""Lines by which a new y precedes its header (x unchanged, x changed).""" + +MAPPING = np.array([[0.0, 1.0], [1.0, 0.0]]) +"""Header offset difference [dx; dy] to [row; col] sample displacement.""" + + +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) + + +@dataclass +class LineOffsets: + """Online offsets of every line of a recording. + + 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 + 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). + 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. + """ + + x: np.ndarray + y: np.ndarray + y_eff: np.ndarray + median_xy: np.ndarray + switch_lines: np.ndarray + lines_read: tuple[int, int] + y_lead: tuple[int, int] = Y_LEAD + + +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 + ---------- + x, y : ndarray + Header offsets of every line. + switch_lines : ndarray of int + One-based x/y switch lines. + lead : (int, int) + Lead when x is unchanged / changes on the same line. + + Returns + ------- + ndarray + 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 + sw0 = np.asarray(switch_lines) - 1 + for s in y_sw: + k = lead[1] if x[s] != x[s - 1] else lead[0] + before = sw0[sw0 < s] + prev = before[-1] if before.size else 0 + y_eff[max(s - k, prev) : s] = y[s] + return y_eff + + +def line_offsets( + layout: RasterLayout, lines: tuple[int, int], lead: tuple[int, int] = Y_LEAD +) -> LineOffsets: + """Read the headers covering lines (getLineOnlineOffsets). + + Parameters + ---------- + layout : RasterLayout + The recording's layout. + lines : (int, int) + First and last line needed (may extend past the recording). + lead : (int, int) + Lead of y switches. + + Returns + ------- + LineOffsets + Offsets of every line of the recording, exact within the cycles + 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 + pad = max(lead) + 1 + first_c = max(1, int(np.floor((lines[0] - pad - 1) / p)) + 1) + last_c = min(n_c, int(np.ceil((lines[1] + pad) / p))) + if first_c > last_c: + raise ValueError(f"lines {lines} are outside the recording") + read = (int((first_c - 1) * p + 1), int(last_c * p)) + x, y, _ = read_line_offsets(layout, np.arange(read[0], read[1] + 1)) + x, y = x.astype(np.int64), y.astype(np.int64) + median_xy = _mround([np.median(x), np.median(y)]) + n_before, n_after = read[0] - 1, layout.total_lines - read[1] + x = np.pad(x, (n_before, n_after), mode="edge") + y = np.pad(y, (n_before, n_after), mode="edge") + switch = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 + return LineOffsets( + x=x, + y=y, + y_eff=dmd_y(x, y, switch, lead), + median_xy=median_xy, + switch_lines=switch, + lines_read=read, + y_lead=tuple(lead), + ) + + +def frame_offsets( + offsets: LineOffsets, times: ArrayLike, dt: int, lines_per_cycle: int +) -> np.ndarray: + """Compute the offset each frame mostly saw (frameOnlineOffsets). + + Parameters + ---------- + offsets : LineOffsets + Line offsets of the recording. + times : array_like of int + One-based frame times. + dt : int + Kernel time constant in lines. + lines_per_cycle : int + 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 + over each frame's lines, rounded. + """ + times = np.asarray(times, dtype=np.int64).ravel() + n = offsets.x.size + dt_read = max(3 * dt, lines_per_cycle) + out = np.zeros((times.size, 2), dtype=np.int64) + 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()) + return out + + +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). + refs : ndarray of int + (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. + """ + extra = (1,) * (lines.ndim - 1) + idx = np.clip(lines, 1, offsets.x.size) - 1 + dx = offsets.x[idx] - refs[:, 0].reshape((-1,) + extra) + dy = offsets.y_eff[idx] - refs[:, 1].reshape((-1,) + extra) + return dy, dx + + +def compensation_record(offsets: LineOffsets, refs: np.ndarray) -> dict: + """Build the slap2/onlineCompensation group of the alignment file. + + Parameters + ---------- + offsets : LineOffsets + Line offsets (gives refOffset and yLead). + refs : ndarray of int + (frames, 2) reference offsets [x, y] of the DS frames. + + Returns + ------- + dict + Fields as MATLAB's compensationRecord saves them. + """ + return { + "enabled": np.int8(1), + "refOffset": offsets.median_xy.astype(np.float64), + "frameRefX": refs[:, 0].astype(np.int16), + "frameRefY": refs[:, 1].astype(np.int16), + "mapping": MAPPING.copy(), + "yLead": np.asarray(offsets.y_lead, dtype=np.float64), + } diff --git a/src/giant_python/registration/growth.py b/src/giant_python/registration/growth.py index c9bde122..b1d4af16 100644 --- a/src/giant_python/registration/growth.py +++ b/src/giant_python/registration/growth.py @@ -1,949 +1,949 @@ -"""Batched registration that grows the template outward from seed frames. - -An alternative to MATLAB's strictly sequential frame loop that keeps its -flavour (each frame starts from an aligned neighbour's motion and is matched -to a template of the frames aligned so far) while matching many frames at -once: - -1. *Seeds.* The DS frames nearest the consensus frames of the initial - 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 - 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 - 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). - 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 - 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 - 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 - contribution. - -Frames without valid samples are left out of growth (they neither seed nor -anchor other frames) and get NaN motion, as in sequential mode. Outputs are -then rendered in frame order, exactly as in sequential mode. -""" - -import logging -from collections.abc import Iterable, Sequence -from dataclasses import dataclass, field - -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 CompensatedFrames, PlainFrames, has_samples -from .template import ConsensusResult, TemplateState - -log = logging.getLogger(__name__) - -GROWN, CONSENSUS, SEED, REGROWN, AT_LIMIT, MISSING = 0, 1, 2, 3, 4, 5 -"""Values of :attr:`GrowthQC.kind`.""" - - -class FrameCache: - """Every DS frame of a trial at the window's pixels, formed once. - - Parameters - ---------- - source : PlainFrames or CompensatedFrames - Forms the frames. - ds : ndarray of int - Frame times. - chunk : int - Frames formed at a time. - max_device_bytes : float - Larger caches are kept in CPU memory and moved per batch. - """ - - def __init__( - 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 - n = ds.size - n_pix = self.window.rows.numel() - n_ch = source.former.layout.num_channels - size = (n_ch + 1) * n * n_pix * 4 - store = self.device if size <= max_device_bytes else "cpu" - self.values = torch.empty(n_ch, n, n_pix, device=store) - self.freshness = torch.empty(n, n_pix, device=store) - for a in range(0, n, chunk): - b = min(n, a + chunk) - v, f = source.frames(ds[a:b]) - self.values[:, a:b] = v.to(store) - self.freshness[a:b] = f.to(store) - - def __len__(self) -> int: - """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. - - Returns - ------- - np.ndarray - Boolean per frame: True where the frame has a valid sample. - """ - return has_samples(self.values) - - 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: 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: 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: 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 = [] - for ch in range(vals.shape[0]): - img = self.window.image(vals[ch, 0], float("nan")) - out.append(interp_frame(img, fimg, motion[0], motion[1], margin)) - return out - - 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) - total = regs[0][0] - for reg, _ in regs[1:]: - total = total + reg - 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.stack(imgs) - - -@dataclass -class GrowthQC: - """Per-frame record of how each frame was registered. - - Attributes - ---------- - peak, margin : ndarray - Correlation at the peak, and its excess over the best correlation - more than 2 shifts away. - round : ndarray of int - Sub-round in which the final motion was found (0: seeds). - anchor : ndarray of int - Frame whose motion started the search (-1 for seeds). - retries : ndarray of int - Boundary retries. - kind : ndarray of int - GROWN, CONSENSUS, SEED, REGROWN, AT_LIMIT or - MISSING (no valid samples; not registered). - junctions : list - (frame, neighbour, jump, outcome) for each conflicting junction. - seeds_tried, seeds_accepted : int - Wide-search seed candidates and how many became islands. - """ - - peak: np.ndarray - margin: np.ndarray - round: np.ndarray - anchor: np.ndarray - retries: np.ndarray - kind: np.ndarray - junctions: list[tuple] = field(default_factory=list) - seeds_tried: int = 0 - seeds_accepted: int = 0 - - def fields(self) -> dict: - """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, - "round": self.round.astype(np.float64), - "anchor": self.anchor.astype(np.float64) + 1, - "retries": self.retries.astype(np.float64), - "kind": self.kind.astype(np.float64), - "seedsTried": float(self.seeds_tried), - "seedsAccepted": float(self.seeds_accepted), - "junctionConflicts": float(len(self.junctions)), - } - - @classmethod - def missing(cls, n: int) -> "GrowthQC": - """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), - round=np.zeros(n, dtype=np.int64), - anchor=np.full(n, -1), - retries=np.zeros(n, dtype=np.int64), - kind=np.full(n, MISSING), - ) - - def expanded(self, present: np.ndarray) -> "GrowthQC": - """Expand this record of the present frames over all frames. - - Frame indices (anchors, junctions) are mapped back; the other - frames are MISSING. - - Returns - ------- - GrowthQC - The record over all frames (self when every frame is present). - """ - if present.all(): - return self - idx = np.flatnonzero(present) - out = GrowthQC.missing(present.size) - 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.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 - ] - out.seeds_tried = self.seeds_tried - out.seeds_accepted = self.seeds_accepted - return out - - -class Grower: - """The growth scheduler for one trial. - - Parameters - ---------- - cache : FrameCache - The trial's frames. - state : TemplateState - Initial template (its sums include the consensus frames). - params : MultiRoiRegistrationParams - 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). - candidates : sequence of int - Further seed candidates (frames nearest the other initial frames). - dtype : torch.dtype - Precision of the correlation sums. - independent : ndarray of bool, optional - Frames that share no samples with the initial template's frames. - Only these calibrate seed acceptance: frames overlapping the - template's own samples correlate with it more than others do. - """ - - def __init__( - self, - cache: FrameCache, - state: TemplateState, - 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 - self.p = params - self.dtype = dtype - self.m = int(params.maxshift) - n = len(cache) - self.n = n - self.motion = np.full((n, 2), np.nan) - self.aligned = np.zeros(n, dtype=bool) - self.root = np.full(n, -1) - self.step = np.full(n, np.nan) - self.qc = GrowthQC( - peak=np.full(n, np.nan), - margin=np.full(n, np.nan), - round=np.zeros(n, dtype=np.int64), - anchor=np.full(n, -1), - retries=np.zeros(n, dtype=np.int64), - kind=np.zeros(n, dtype=np.int64), - ) - 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.tried = set() - self.retry = {} # frame -> (init_r, init_c, search, anchor) - self.sub_round = 0 - - # ----------------------------------------------------------- matching - 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. - peak, margin : ndarray - Peak correlation and margin. - edge : ndarray of bool - Whether the integer peak lies on the search range's edge. - """ - n = len(items) - motion = np.full((n, 2), np.nan) - peak = np.full(n, np.nan) - margin = np.full(n, np.nan) - edge = np.zeros(n, dtype=bool) - if n == 0: - return motion, peak, margin, edge - h, w = self.cache.window.shape - m = self.m - tmpl = self.state.matching_template() - groups = {} - for i, (_, r, c, s) in enumerate(items): - groups.setdefault((r, c, s), []).append(i) - win = self.cache.window - for (r, c, s), idx in groups.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) - 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]) - peak[idx] = pk.cpu().numpy() - margin[idx] = peak_margin(corr).cpu().numpy() - edge[idx] = on_edge.cpu().numpy() - return motion, peak, margin, edge - - 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: 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: - return - self.motion[ks] = motions - self.aligned[ks] = True - self.qc.peak[ks] = peaks - self.qc.margin[ks] = margins - self.qc.anchor[ks] = anchors - self.qc.kind[ks] = kinds - self.qc.round[ks] = self.sub_round - 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) - imgs = self.cache.registered_sum(ks, motions, self.m) - self.state.update(imgs) - - 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) - self.state.update(imgs, sign=-1) - self.aligned[ks] = False - - # -------------------------------------------------------------- seeds - 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( - items, - anchors=[-1] * len(items), - kind=CONSENSUS, - roots=[k for k, _, _ in self.seeds], - ) - - def _step_limit(self) -> float: - """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: 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]): - for a in side: - if np.hypot(*(motion - self.motion[a])) > v * abs(k - a) + 1: - return False - return True - - 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)) - if not ks: - return - self.tried.update(ks) - self.qc.seeds_tried += len(ks) - vals, fresh = self.cache.moving(ks) - win = self.cache.window - corr = wide_correlation( - win.image(vals, float("nan")), - win.image(fresh, 0.0), - self.state.matching_template(), - ) - rr, cc, _ = peak_index(corr) - items = [ - (k, self.m - int(r), self.m - int(c), self.p.clip_shift) - for k, r, c in zip(ks, rr.cpu().numpy(), cc.cpu().numpy()) - ] - motion, peak, margin, edge = self._match(items) - good = self._calibration_set() - q = self.p.seed_accept_quantile - r_min = np.quantile(self.qc.peak[good], q) if good.any() else -1 - mg = self.qc.margin[good] - mg = mg[np.isfinite(mg)] - m_min = np.quantile(mg, q) if mg.size else -np.inf - ok = [ - i - for i, (k, *_rest) in enumerate(items) - if not edge[i] - and np.isfinite(peak[i]) - and np.isfinite(motion[i]).all() - and peak[i] >= r_min - and (not np.isfinite(margin[i]) or margin[i] >= m_min) - and self._plausible(k, motion[i]) - ] - if ok: - acc = [items[i][0] for i in ok] - self._accept( - acc, - motion[ok], - peak[ok], - margin[ok], - [-1] * len(ok), - [SEED] * len(ok), - acc, - ) - self.qc.seeds_accepted += len(ok) - - def _calibration_set(self) -> np.ndarray: - """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 - & np.isfinite(self.qc.peak) - & np.isin(self.qc.kind, (GROWN, REGROWN)) - ) - - def _calibrated(self) -> bool: - """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) -> 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 [] - lengths = np.array([b - a for a, b in gaps]) - need = fronts < self.p.min_fronts - median = np.median(lengths) - out = [] - for i in np.argsort(-lengths, kind="stable"): - a, b = gaps[i] - if lengths[i] < 16: - break - if not need and lengths[i] <= 2 * median: - break - mid = (a + b - 1) // 2 - if mid not in self.tried: - out.append(mid) - if len(out) >= 8: - break - return out - - # ------------------------------------------------------------- growth - 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): - for edge, step in ((a, -1), (b - 1, 1)): - for d in range(1, k_front + 1): - f = edge + step * d - if not 0 <= f < self.n or self.aligned[f]: - break - if f in self.retry: - break - prev = targets.get(f) - if prev is None or self.qc.peak[edge] > self.qc.peak[prev]: - targets[f] = edge - return sorted(targets.items()) - - 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): - if edge[i] and s < self.m and np.isfinite(peak[i]): - nr, nc = self._init_of(motion[i]) - self.retry[k] = ( - nr, - nc, - min(self.m, 2 * s), - anchors[i], - roots[i], - kind, - ) - self.qc.retries[k] += 1 - continue - if not np.isfinite(motion[i]).all(): - motion[i] = self.motion[anchors[i]] if anchors[i] >= 0 else 0 - acc.append(i) - kinds = [AT_LIMIT if edge[i] else kind for i in acc] - self._accept( - [items[i][0] for i in acc], - motion[acc], - peak[acc], - margin[acc], - [anchors[i] for i in acc], - kinds, - [roots[i] for i in acc], - ) - return [items[i][0] for i in acc] - - def _sub_round(self) -> None: - """One wavefront step: retries plus one frame per front.""" - self.sub_round += 1 - fronts = self._fronts() - cand = [] - if self._calibrated(): - cand = [k for k in self.candidates if k not in self.tried] - cand += self._gap_candidates(len(fronts)) - if cand: - self.try_seeds(cand) - fronts = self._fronts() - items, anchors, roots, kinds = [], [], [], [] - for k, (r, c, s, a, root, kind) in sorted(self.retry.items()): - if self.aligned[k]: - continue - items.append((k, r, c, s)) - anchors.append(a) - roots.append(root) - kinds.append(kind) - self.retry = {} - for k, a in fronts: - r, c = self._init_of(self.motion[a]) - items.append((k, r, c, self.p.clip_shift)) - anchors.append(a) - roots.append(self.root[a]) - kinds.append(GROWN) - if not items: - rest = np.flatnonzero(~self.aligned) - if rest.size == 0: # the seeds above aligned the last frames - return - self.try_seeds(rest[:1]) - if not self.aligned[rest[0]]: - items = [(int(rest[0]), 0, 0, self.p.clip_shift)] - anchors, roots, kinds = [-1], [int(rest[0])], [SEED] - done = [] - for kind in sorted(set(kinds)): - sel = [i for i, kd in enumerate(kinds) if kd == kind] - done += self._run_items( - [items[i] for i in sel], - [anchors[i] for i in sel], - kind, - [roots[i] for i in sel], - ) - self._check_junctions(done) - - # ---------------------------------------------------------- junctions - def _jump_limit(self) -> float: - """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: Sequence[int]) -> None: - """Resolve junctions formed by newly aligned frames.""" - limit = self._jump_limit() - for k in ks: - a = self.qc.anchor[k] - for g in (k - 1, k + 1): - if g == a or not 0 <= g < self.n or not self.aligned[g]: - continue - if self.qc.anchor[g] == k or self.root[g] == self.root[k]: - continue - jump = float(np.hypot(*(self.motion[k] - self.motion[g]))) - if jump > limit: - self._resolve(k, g, jump) - - 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)) - prev = start - for i, f in enumerate(order): - r, c = self._init_of(prev) - s = self.p.clip_shift - while True: - mot, pk, mg, edge = self._match([(int(f), r, c, s)]) - if not edge[0] or s >= self.m or not np.isfinite(mot[0]).all(): - break - r, c = self._init_of(mot[0]) - s = min(self.m, 2 * s) - if not np.isfinite(mot[0]).all(): - mot[0] = prev - motion[i], peak[i], margin[i] = mot[0], pk[0], mg[0] - prev = mot[0] - return motion, peak, margin - - 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. - Its old motion is scored against the same template; the solution - with the higher mean peak correlation is kept. - """ - pk = np.nanmedian(self.qc.peak[self.root == self.root[k]]) - pg = np.nanmedian(self.qc.peak[self.root == self.root[g]]) - strong, weak = (k, g) if pk >= pg else (g, k) - members = np.flatnonzero(self.root == self.root[weak]) - order = members[np.argsort((1 if weak > strong else -1) * members)] - saved = { - "motion": self.motion[order].copy(), - "anchor": self.qc.anchor[order].copy(), - "kind": self.qc.kind[order].copy(), - "round": self.qc.round[order].copy(), - "root": self.root[order].copy(), - "step": self.step[order].copy(), - } - 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"]) - ]) - better = np.nanmean(new[1]) > np.nanmean(old[1]) - self.qc.junctions.append((int(k), int(g), jump, "regrown" if better else "kept")) - if better: - anchors = np.concatenate([[strong], order[:-1]]) - self._accept( - order, - new[0], - new[1], - new[2], - anchors, - [REGROWN] * order.size, - [self.root[strong]] * order.size, - ) - return - self._accept( - order, - saved["motion"], - old[1], - old[2], - saved["anchor"], - saved["kind"], - saved["root"], - ) - self.qc.round[order] = saved["round"] - self.step[order] = saved["step"] - - # ---------------------------------------------------------------- run - def run(self, max_rounds: int | None = None) -> tuple[np.ndarray, GrowthQC]: - """Align every frame. - - Returns - ------- - motion : ndarray - (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 - while not self.aligned.all(): - if self.sub_round >= limit: - 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", - self.sub_round, - self.qc.seeds_accepted, - self.qc.seeds_tried, - len(self.qc.junctions), - ) - return self.motion, self.qc - - 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 - win = self.cache.window - for k in range(self.n): - img = self.cache.registered_sum([k], self.motion[[k]], m)[0] - 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")) - both = (st.initial + loo) / 2 - tmpl = torch.where(torch.isnan(st.initial), loo, both) - tmpl = torch.where(torch.isnan(loo), st.initial, tmpl) - r, c = self._init_of(self.motion[k]) - mov, fresh = self.cache.moving([k]) - mot, pk, corr = match_maps( - mov, - fresh, - tmpl[m - r : m - r + h, m - c : m - c + w], - win.rows, - win.cols, - radius, - self.dtype, - ) - if torch.isfinite(mot).all(): - self.motion[k] = mot[0].cpu().numpy() + np.array([r, c]) - self.qc.peak[k] = float(pk[0]) - self.qc.margin[k] = float(peak_margin(corr)[0]) - return self.motion - - -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: 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 - ---------- - cons : ConsensusResult - Pairwise matching of the initial frames. - init, ds : ndarray of int - Initial and DS frame times. - reach : int, optional - Lines within which a DS frame shares samples with an initial frame. - - Returns - ------- - 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. - 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 - every consensus member, so sharing none of its samples (all frames - 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) - ref = cons.reference - seeds, taken = [], set() - for i in cons.members: - k = int(near[i]) - if k in taken: - continue - taken.add(k) - mot = -cons.motion[:, i, ref] - seeds.append((k, int(matlab_round(mot[0])), int(matlab_round(mot[1])))) - 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 - ) - ) - independent = np.ones(ds.size, dtype=bool) - if reach is not None and len(cons.members): - t0 = init[cons.members] - independent = np.abs(ds[:, None] - t0[None, :]).min(1) > reach - return seeds, candidates, independent +"""Batched registration that grows the template outward from seed frames. + +An alternative to MATLAB's strictly sequential frame loop that keeps its +flavour (each frame starts from an aligned neighbour's motion and is matched +to a template of the frames aligned so far) while matching many frames at +once: + +1. *Seeds.* The DS frames nearest the consensus frames of the initial + 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 + 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 + 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). + 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 + 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 + 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 + contribution. + +Frames without valid samples are left out of growth (they neither seed nor +anchor other frames) and get NaN motion, as in sequential mode. Outputs are +then rendered in frame order, exactly as in sequential mode. +""" + +import logging +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field + +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 CompensatedFrames, PlainFrames, has_samples +from .template import ConsensusResult, TemplateState + +log = logging.getLogger(__name__) + +GROWN, CONSENSUS, SEED, REGROWN, AT_LIMIT, MISSING = 0, 1, 2, 3, 4, 5 +"""Values of :attr:`GrowthQC.kind`.""" + + +class FrameCache: + """Every DS frame of a trial at the window's pixels, formed once. + + Parameters + ---------- + source : PlainFrames or CompensatedFrames + Forms the frames. + ds : ndarray of int + Frame times. + chunk : int + Frames formed at a time. + max_device_bytes : float + Larger caches are kept in CPU memory and moved per batch. + """ + + def __init__( + 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 + n = ds.size + n_pix = self.window.rows.numel() + n_ch = source.former.layout.num_channels + size = (n_ch + 1) * n * n_pix * 4 + store = self.device if size <= max_device_bytes else "cpu" + self.values = torch.empty(n_ch, n, n_pix, device=store) + self.freshness = torch.empty(n, n_pix, device=store) + for a in range(0, n, chunk): + b = min(n, a + chunk) + v, f = source.frames(ds[a:b]) + self.values[:, a:b] = v.to(store) + self.freshness[a:b] = f.to(store) + + def __len__(self) -> int: + """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. + + Returns + ------- + np.ndarray + Boolean per frame: True where the frame has a valid sample. + """ + return has_samples(self.values) + + 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: 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: 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: 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 = [] + for ch in range(vals.shape[0]): + img = self.window.image(vals[ch, 0], float("nan")) + out.append(interp_frame(img, fimg, motion[0], motion[1], margin)) + return out + + 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) + total = regs[0][0] + for reg, _ in regs[1:]: + total = total + reg + 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.stack(imgs) + + +@dataclass +class GrowthQC: + """Per-frame record of how each frame was registered. + + Attributes + ---------- + peak, margin : ndarray + Correlation at the peak, and its excess over the best correlation + more than 2 shifts away. + round : ndarray of int + Sub-round in which the final motion was found (0: seeds). + anchor : ndarray of int + Frame whose motion started the search (-1 for seeds). + retries : ndarray of int + Boundary retries. + kind : ndarray of int + GROWN, CONSENSUS, SEED, REGROWN, AT_LIMIT or + MISSING (no valid samples; not registered). + junctions : list + (frame, neighbour, jump, outcome) for each conflicting junction. + seeds_tried, seeds_accepted : int + Wide-search seed candidates and how many became islands. + """ + + peak: np.ndarray + margin: np.ndarray + round: np.ndarray + anchor: np.ndarray + retries: np.ndarray + kind: np.ndarray + junctions: list[tuple] = field(default_factory=list) + seeds_tried: int = 0 + seeds_accepted: int = 0 + + def fields(self) -> dict: + """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, + "round": self.round.astype(np.float64), + "anchor": self.anchor.astype(np.float64) + 1, + "retries": self.retries.astype(np.float64), + "kind": self.kind.astype(np.float64), + "seedsTried": float(self.seeds_tried), + "seedsAccepted": float(self.seeds_accepted), + "junctionConflicts": float(len(self.junctions)), + } + + @classmethod + def missing(cls, n: int) -> "GrowthQC": + """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), + round=np.zeros(n, dtype=np.int64), + anchor=np.full(n, -1), + retries=np.zeros(n, dtype=np.int64), + kind=np.full(n, MISSING), + ) + + def expanded(self, present: np.ndarray) -> "GrowthQC": + """Expand this record of the present frames over all frames. + + Frame indices (anchors, junctions) are mapped back; the other + frames are MISSING. + + Returns + ------- + GrowthQC + The record over all frames (self when every frame is present). + """ + if present.all(): + return self + idx = np.flatnonzero(present) + out = GrowthQC.missing(present.size) + 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.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 + ] + out.seeds_tried = self.seeds_tried + out.seeds_accepted = self.seeds_accepted + return out + + +class Grower: + """The growth scheduler for one trial. + + Parameters + ---------- + cache : FrameCache + The trial's frames. + state : TemplateState + Initial template (its sums include the consensus frames). + params : MultiRoiRegistrationParams + 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). + candidates : sequence of int + Further seed candidates (frames nearest the other initial frames). + dtype : torch.dtype + Precision of the correlation sums. + independent : ndarray of bool, optional + Frames that share no samples with the initial template's frames. + Only these calibrate seed acceptance: frames overlapping the + template's own samples correlate with it more than others do. + """ + + def __init__( + self, + cache: FrameCache, + state: TemplateState, + 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 + self.p = params + self.dtype = dtype + self.m = int(params.maxshift) + n = len(cache) + self.n = n + self.motion = np.full((n, 2), np.nan) + self.aligned = np.zeros(n, dtype=bool) + self.root = np.full(n, -1) + self.step = np.full(n, np.nan) + self.qc = GrowthQC( + peak=np.full(n, np.nan), + margin=np.full(n, np.nan), + round=np.zeros(n, dtype=np.int64), + anchor=np.full(n, -1), + retries=np.zeros(n, dtype=np.int64), + kind=np.zeros(n, dtype=np.int64), + ) + 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.tried = set() + self.retry = {} # frame -> (init_r, init_c, search, anchor) + self.sub_round = 0 + + # ----------------------------------------------------------- matching + 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. + peak, margin : ndarray + Peak correlation and margin. + edge : ndarray of bool + Whether the integer peak lies on the search range's edge. + """ + n = len(items) + motion = np.full((n, 2), np.nan) + peak = np.full(n, np.nan) + margin = np.full(n, np.nan) + edge = np.zeros(n, dtype=bool) + if n == 0: + return motion, peak, margin, edge + h, w = self.cache.window.shape + m = self.m + tmpl = self.state.matching_template() + groups = {} + for i, (_, r, c, s) in enumerate(items): + groups.setdefault((r, c, s), []).append(i) + win = self.cache.window + for (r, c, s), idx in groups.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) + 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]) + peak[idx] = pk.cpu().numpy() + margin[idx] = peak_margin(corr).cpu().numpy() + edge[idx] = on_edge.cpu().numpy() + return motion, peak, margin, edge + + 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: 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: + return + self.motion[ks] = motions + self.aligned[ks] = True + self.qc.peak[ks] = peaks + self.qc.margin[ks] = margins + self.qc.anchor[ks] = anchors + self.qc.kind[ks] = kinds + self.qc.round[ks] = self.sub_round + 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) + imgs = self.cache.registered_sum(ks, motions, self.m) + self.state.update(imgs) + + 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) + self.state.update(imgs, sign=-1) + self.aligned[ks] = False + + # -------------------------------------------------------------- seeds + 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( + items, + anchors=[-1] * len(items), + kind=CONSENSUS, + roots=[k for k, _, _ in self.seeds], + ) + + def _step_limit(self) -> float: + """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: 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]): + for a in side: + if np.hypot(*(motion - self.motion[a])) > v * abs(k - a) + 1: + return False + return True + + 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)) + if not ks: + return + self.tried.update(ks) + self.qc.seeds_tried += len(ks) + vals, fresh = self.cache.moving(ks) + win = self.cache.window + corr = wide_correlation( + win.image(vals, float("nan")), + win.image(fresh, 0.0), + self.state.matching_template(), + ) + rr, cc, _ = peak_index(corr) + items = [ + (k, self.m - int(r), self.m - int(c), self.p.clip_shift) + for k, r, c in zip(ks, rr.cpu().numpy(), cc.cpu().numpy()) + ] + motion, peak, margin, edge = self._match(items) + good = self._calibration_set() + q = self.p.seed_accept_quantile + r_min = np.quantile(self.qc.peak[good], q) if good.any() else -1 + mg = self.qc.margin[good] + mg = mg[np.isfinite(mg)] + m_min = np.quantile(mg, q) if mg.size else -np.inf + ok = [ + i + for i, (k, *_rest) in enumerate(items) + if not edge[i] + and np.isfinite(peak[i]) + and np.isfinite(motion[i]).all() + and peak[i] >= r_min + and (not np.isfinite(margin[i]) or margin[i] >= m_min) + and self._plausible(k, motion[i]) + ] + if ok: + acc = [items[i][0] for i in ok] + self._accept( + acc, + motion[ok], + peak[ok], + margin[ok], + [-1] * len(ok), + [SEED] * len(ok), + acc, + ) + self.qc.seeds_accepted += len(ok) + + def _calibration_set(self) -> np.ndarray: + """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 + & np.isfinite(self.qc.peak) + & np.isin(self.qc.kind, (GROWN, REGROWN)) + ) + + def _calibrated(self) -> bool: + """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) -> 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 [] + lengths = np.array([b - a for a, b in gaps]) + need = fronts < self.p.min_fronts + median = np.median(lengths) + out = [] + for i in np.argsort(-lengths, kind="stable"): + a, b = gaps[i] + if lengths[i] < 16: + break + if not need and lengths[i] <= 2 * median: + break + mid = (a + b - 1) // 2 + if mid not in self.tried: + out.append(mid) + if len(out) >= 8: + break + return out + + # ------------------------------------------------------------- growth + 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): + for edge, step in ((a, -1), (b - 1, 1)): + for d in range(1, k_front + 1): + f = edge + step * d + if not 0 <= f < self.n or self.aligned[f]: + break + if f in self.retry: + break + prev = targets.get(f) + if prev is None or self.qc.peak[edge] > self.qc.peak[prev]: + targets[f] = edge + return sorted(targets.items()) + + 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): + if edge[i] and s < self.m and np.isfinite(peak[i]): + nr, nc = self._init_of(motion[i]) + self.retry[k] = ( + nr, + nc, + min(self.m, 2 * s), + anchors[i], + roots[i], + kind, + ) + self.qc.retries[k] += 1 + continue + if not np.isfinite(motion[i]).all(): + motion[i] = self.motion[anchors[i]] if anchors[i] >= 0 else 0 + acc.append(i) + kinds = [AT_LIMIT if edge[i] else kind for i in acc] + self._accept( + [items[i][0] for i in acc], + motion[acc], + peak[acc], + margin[acc], + [anchors[i] for i in acc], + kinds, + [roots[i] for i in acc], + ) + return [items[i][0] for i in acc] + + def _sub_round(self) -> None: + """One wavefront step: retries plus one frame per front.""" + self.sub_round += 1 + fronts = self._fronts() + cand = [] + if self._calibrated(): + cand = [k for k in self.candidates if k not in self.tried] + cand += self._gap_candidates(len(fronts)) + if cand: + self.try_seeds(cand) + fronts = self._fronts() + items, anchors, roots, kinds = [], [], [], [] + for k, (r, c, s, a, root, kind) in sorted(self.retry.items()): + if self.aligned[k]: + continue + items.append((k, r, c, s)) + anchors.append(a) + roots.append(root) + kinds.append(kind) + self.retry = {} + for k, a in fronts: + r, c = self._init_of(self.motion[a]) + items.append((k, r, c, self.p.clip_shift)) + anchors.append(a) + roots.append(self.root[a]) + kinds.append(GROWN) + if not items: + rest = np.flatnonzero(~self.aligned) + if rest.size == 0: # the seeds above aligned the last frames + return + self.try_seeds(rest[:1]) + if not self.aligned[rest[0]]: + items = [(int(rest[0]), 0, 0, self.p.clip_shift)] + anchors, roots, kinds = [-1], [int(rest[0])], [SEED] + done = [] + for kind in sorted(set(kinds)): + sel = [i for i, kd in enumerate(kinds) if kd == kind] + done += self._run_items( + [items[i] for i in sel], + [anchors[i] for i in sel], + kind, + [roots[i] for i in sel], + ) + self._check_junctions(done) + + # ---------------------------------------------------------- junctions + def _jump_limit(self) -> float: + """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: Sequence[int]) -> None: + """Resolve junctions formed by newly aligned frames.""" + limit = self._jump_limit() + for k in ks: + a = self.qc.anchor[k] + for g in (k - 1, k + 1): + if g == a or not 0 <= g < self.n or not self.aligned[g]: + continue + if self.qc.anchor[g] == k or self.root[g] == self.root[k]: + continue + jump = float(np.hypot(*(self.motion[k] - self.motion[g]))) + if jump > limit: + self._resolve(k, g, jump) + + 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)) + prev = start + for i, f in enumerate(order): + r, c = self._init_of(prev) + s = self.p.clip_shift + while True: + mot, pk, mg, edge = self._match([(int(f), r, c, s)]) + if not edge[0] or s >= self.m or not np.isfinite(mot[0]).all(): + break + r, c = self._init_of(mot[0]) + s = min(self.m, 2 * s) + if not np.isfinite(mot[0]).all(): + mot[0] = prev + motion[i], peak[i], margin[i] = mot[0], pk[0], mg[0] + prev = mot[0] + return motion, peak, margin + + 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. + Its old motion is scored against the same template; the solution + with the higher mean peak correlation is kept. + """ + pk = np.nanmedian(self.qc.peak[self.root == self.root[k]]) + pg = np.nanmedian(self.qc.peak[self.root == self.root[g]]) + strong, weak = (k, g) if pk >= pg else (g, k) + members = np.flatnonzero(self.root == self.root[weak]) + order = members[np.argsort((1 if weak > strong else -1) * members)] + saved = { + "motion": self.motion[order].copy(), + "anchor": self.qc.anchor[order].copy(), + "kind": self.qc.kind[order].copy(), + "round": self.qc.round[order].copy(), + "root": self.root[order].copy(), + "step": self.step[order].copy(), + } + 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"]) + ]) + better = np.nanmean(new[1]) > np.nanmean(old[1]) + self.qc.junctions.append((int(k), int(g), jump, "regrown" if better else "kept")) + if better: + anchors = np.concatenate([[strong], order[:-1]]) + self._accept( + order, + new[0], + new[1], + new[2], + anchors, + [REGROWN] * order.size, + [self.root[strong]] * order.size, + ) + return + self._accept( + order, + saved["motion"], + old[1], + old[2], + saved["anchor"], + saved["kind"], + saved["root"], + ) + self.qc.round[order] = saved["round"] + self.step[order] = saved["step"] + + # ---------------------------------------------------------------- run + def run(self, max_rounds: int | None = None) -> tuple[np.ndarray, GrowthQC]: + """Align every frame. + + Returns + ------- + motion : ndarray + (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 + while not self.aligned.all(): + if self.sub_round >= limit: + 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", + self.sub_round, + self.qc.seeds_accepted, + self.qc.seeds_tried, + len(self.qc.junctions), + ) + return self.motion, self.qc + + 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 + win = self.cache.window + for k in range(self.n): + img = self.cache.registered_sum([k], self.motion[[k]], m)[0] + 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")) + both = (st.initial + loo) / 2 + tmpl = torch.where(torch.isnan(st.initial), loo, both) + tmpl = torch.where(torch.isnan(loo), st.initial, tmpl) + r, c = self._init_of(self.motion[k]) + mov, fresh = self.cache.moving([k]) + mot, pk, corr = match_maps( + mov, + fresh, + tmpl[m - r : m - r + h, m - c : m - c + w], + win.rows, + win.cols, + radius, + self.dtype, + ) + if torch.isfinite(mot).all(): + self.motion[k] = mot[0].cpu().numpy() + np.array([r, c]) + self.qc.peak[k] = float(pk[0]) + self.qc.margin[k] = float(peak_margin(corr)[0]) + return self.motion + + +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: 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 + ---------- + cons : ConsensusResult + Pairwise matching of the initial frames. + init, ds : ndarray of int + Initial and DS frame times. + reach : int, optional + Lines within which a DS frame shares samples with an initial frame. + + Returns + ------- + 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. + 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 + every consensus member, so sharing none of its samples (all frames + 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) + ref = cons.reference + seeds, taken = [], set() + for i in cons.members: + k = int(near[i]) + if k in taken: + continue + taken.add(k) + mot = -cons.motion[:, i, ref] + seeds.append((k, int(matlab_round(mot[0])), int(matlab_round(mot[1])))) + 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 + ) + ) + independent = np.ones(ds.size, dtype=bool) + if reach is not None and len(cons.members): + t0 = init[cons.members] + independent = np.abs(ds[:, None] - t0[None, :]).min(1) > reach + return seeds, candidates, independent diff --git a/src/giant_python/registration/interpolation.py b/src/giant_python/registration/interpolation.py index cc20ee1a..e960b335 100644 --- a/src/giant_python/registration/interpolation.py +++ b/src/giant_python/registration/interpolation.py @@ -1,134 +1,134 @@ -"""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 -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 - -import numpy as np -import torch - - -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)) - bad_r = (ri < 0) | (ri >= h) - bad_c = (ci < 0) | (ci >= w) - out = out.masked_fill(bad_r[:, None], float("nan")) - return out.masked_fill(bad_c[None, :], float("nan")) - - -def interp_frame( - frame: torch.Tensor, - freshness: torch.Tensor, - motion_r: float, - motion_c: float, - margin: int, -) -> tuple[torch.Tensor, torch.Tensor]: - """Resample one frame onto the padded output grid. - - Parameters - ---------- - frame : torch.Tensor - (H, W) float32 frame, NaN where unsampled. - freshness : torch.Tensor - (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. - - Returns - ------- - image : torch.Tensor - (H + 2m, W + 2m) resampled frame. - var_factor : torch.Tensor - Same shape: 1 / sum(coefficient * freshness), NaN where that sum - is 0 or undefined. - """ - h, w = frame.shape - # one-based sample positions, as MATLAB's viewR(:,1) + motion; index - # arithmetic stays on the CPU (no device synchronization) - view_r = np.arange(1, h + 2 * margin + 1) - margin + float(motion_r) - view_c = np.arange(1, w + 2 * margin + 1) - margin + float(motion_c) - first_r = 1 - margin + float(motion_r) - first_c = 1 - margin + float(motion_c) - fr = first_r - math.floor(first_r) - fc = first_c - math.floor(first_c) - idx = ( - np.floor(view_r).astype(np.int64) - 1, - np.ceil(view_r).astype(np.int64) - 1, - np.floor(view_c).astype(np.int64) - 1, - np.ceil(view_c).astype(np.int64) - 1, - ) - coef = [ - float(np.float32(v)) if frame.dtype == torch.float32 else v - for v in ( - (1 - fc) * (1 - fr), - fc * (1 - fr), - (1 - fc) * fr, - fc * fr, - ) - ] - if all(np.all(np.diff(i) == 1) for i in idx): - # every output row/column reads a run of input rows/columns: slice - # NaN-padded copies instead of gathering - 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] - for x in (frame, freshness) - ] - - 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: 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), - torch.from_numpy(ci).to(dev), - ) - - 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))): - cf = coef[k] * corner(1, ri, ci) - term = cf * corner(0, ri, ci) - num = term if num is None else num + term - den = cf if den is None else den + cf - image = num / den - var_factor = 1.0 / den - var_factor = var_factor.masked_fill(torch.isinf(var_factor), float("nan")) - return image, var_factor +"""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 +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 + +import numpy as np +import torch + + +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)) + bad_r = (ri < 0) | (ri >= h) + bad_c = (ci < 0) | (ci >= w) + out = out.masked_fill(bad_r[:, None], float("nan")) + return out.masked_fill(bad_c[None, :], float("nan")) + + +def interp_frame( + frame: torch.Tensor, + freshness: torch.Tensor, + motion_r: float, + motion_c: float, + margin: int, +) -> tuple[torch.Tensor, torch.Tensor]: + """Resample one frame onto the padded output grid. + + Parameters + ---------- + frame : torch.Tensor + (H, W) float32 frame, NaN where unsampled. + freshness : torch.Tensor + (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. + + Returns + ------- + image : torch.Tensor + (H + 2m, W + 2m) resampled frame. + var_factor : torch.Tensor + Same shape: 1 / sum(coefficient * freshness), NaN where that sum + is 0 or undefined. + """ + h, w = frame.shape + # one-based sample positions, as MATLAB's viewR(:,1) + motion; index + # arithmetic stays on the CPU (no device synchronization) + view_r = np.arange(1, h + 2 * margin + 1) - margin + float(motion_r) + view_c = np.arange(1, w + 2 * margin + 1) - margin + float(motion_c) + first_r = 1 - margin + float(motion_r) + first_c = 1 - margin + float(motion_c) + fr = first_r - math.floor(first_r) + fc = first_c - math.floor(first_c) + idx = ( + np.floor(view_r).astype(np.int64) - 1, + np.ceil(view_r).astype(np.int64) - 1, + np.floor(view_c).astype(np.int64) - 1, + np.ceil(view_c).astype(np.int64) - 1, + ) + coef = [ + float(np.float32(v)) if frame.dtype == torch.float32 else v + for v in ( + (1 - fc) * (1 - fr), + fc * (1 - fr), + (1 - fc) * fr, + fc * fr, + ) + ] + if all(np.all(np.diff(i) == 1) for i in idx): + # every output row/column reads a run of input rows/columns: slice + # NaN-padded copies instead of gathering + 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] + for x in (frame, freshness) + ] + + 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: 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), + torch.from_numpy(ci).to(dev), + ) + + 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))): + cf = coef[k] * corner(1, ri, ci) + term = cf * corner(0, ri, ci) + num = term if num is None else num + term + den = cf if den is None else den + cf + image = num / den + var_factor = 1.0 / den + var_factor = var_factor.masked_fill(torch.isinf(var_factor), float("nan")) + return image, var_factor diff --git a/src/giant_python/registration/matching.py b/src/giant_python/registration/matching.py index b812dc19..d184426b 100644 --- a/src/giant_python/registration/matching.py +++ b/src/giant_python/registration/matching.py @@ -1,348 +1,348 @@ -"""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 -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). -""" - -import torch - - -class RegistrationError(RuntimeError): - """Raised when a frame cannot be matched (e.g. NaN motion).""" - - -def shift_tables( - template: torch.Tensor, - rows: torch.Tensor, - cols: torch.Tensor, - search: int, - 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 - shift varies fastest. - - Parameters - ---------- - template : torch.Tensor - (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. - dtype : torch.dtype - Precision of the tables. - - Returns - ------- - valid, value, value2 : torch.Tensor - (pixels, shifts): whether the shifted template pixel is usable, - its value (centred by the template's mean, 0 where unusable) and the - value squared. - """ - h, w = template.shape - s = int(search) - n = 2 * s + 1 - finite = template[~torch.isnan(template)] - 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[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 - base = (rows + s) * wp + (cols + s) - v = padded.reshape(-1)[base[:, None] + offset[None, :]] - valid = ~torch.isnan(v) - value = torch.nan_to_num(v, nan=0.0) - return valid.to(dtype), value, value * value - - -def correlation_map( - frames: torch.Tensor, - weights: torch.Tensor, - tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor], - search: int, -) -> torch.Tensor: - """Weighted Pearson correlation for every shift. - - Parameters - ---------- - frames : torch.Tensor - (B, pixels) frame values; ignored where weights is 0. - weights : torch.Tensor - (B, pixels) freshness, 0 at invalid pixels. - tables : tuple of torch.Tensor - Output of :func:`shift_tables`. - search : int - Largest shift S. - - Returns - ------- - torch.Tensor - (B, 2S + 1, 2S + 1) correlations indexed [b, dr, dc], NaN - where undefined. - """ - valid, value, value2 = tables - dtype = value.dtype - f = frames.to(dtype) - w = torch.where(torch.isnan(f), 0.0, weights.to(dtype)) - b = f.shape[0] - sw0 = w.sum(1, keepdim=True) - mean0 = (w * torch.where(w > 0, f, 0.0)).sum(1, keepdim=True) / sw0 - fc = torch.where(w > 0, f - mean0, 0.0) - wf = w * fc - # three products instead of six: stack the frame-side vectors - on_valid = torch.cat([w, wf, wf * fc]) @ valid - on_value = torch.cat([w, wf]) @ value - sw, s_f, s_ff = on_valid[:b], on_valid[b : 2 * b], on_valid[2 * b :] - s_t, s_ft = on_value[:b], on_value[b:] - s_tt = w @ value2 - m_f = s_f / sw - m_t = s_t / sw - cov = s_ft - sw * m_f * m_t - 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) - n = 2 * search + 1 - return corr.reshape(-1, n, n).transpose(1, 2) - - -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. - - Parameters - ---------- - corr : torch.Tensor - (B, n, n) maps from :func:`correlation_map`. - search : int - Largest shift S. - - Returns - ------- - motion : torch.Tensor of float64 - (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 = 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) - 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) - 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) - mot = torch.where(inner[:, None], sub, mot) - # an undefined map (e.g. a frame without valid samples) has no peak; - # its argmax would be the first shift, a finite but arbitrary motion - mot = mot.masked_fill(torch.isnan(peak)[:, None], float("nan")) - return -mot, peak - - -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 - ignored. - - Returns - ------- - rr, cc : torch.Tensor of int - Row- and column-shift indices of the maximum. - peak : torch.Tensor - The maximum (NaN if the whole map is undefined). - """ - 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. - - Parameters - ---------- - corr : torch.Tensor - (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, n_r, n_c = corr.shape - rr, cc, peak = peak_index(corr) - ir = torch.arange(n_r, device=corr.device) - ic = torch.arange(n_c, device=corr.device) - near = ((ir[None, :, None] - rr[:, None, None]).abs() <= exclude) & ( - (ic[None, None, :] - cc[:, None, None]).abs() <= exclude - ) - rest = torch.nan_to_num(corr, nan=-torch.inf).masked_fill(near, -torch.inf) - second = rest.reshape(b, -1).max(1).values - margin = peak - second - return margin.masked_fill(torch.isinf(second), float("nan")) - - -def match_maps( - frames: torch.Tensor, - weights: torch.Tensor, - template: torch.Tensor, - rows: torch.Tensor, - cols: torch.Tensor, - search: int, - 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). - peak : torch.Tensor of float64 - (B,) correlation at the maximum. - corr : torch.Tensor - (B, 2S + 1, 2S + 1) maps indexed [b, dr, dc]. - """ - search = int(round(search)) - tables = shift_tables(template, rows, cols, search, dtype) - corr = correlation_map(frames, weights, tables, search) - motion, peak = peak_motion(corr, search) - return motion, peak, corr - - -def wide_correlation( - frames: torch.Tensor, weights: torch.Tensor, template: torch.Tensor -) -> torch.Tensor: - """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 - 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. - template : torch.Tensor - (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]. - - Raises - ------ - ValueError - If the template does not pad the frames equally on every side. - """ - dt = torch.float64 - ho, wo = template.shape - h, w = frames.shape[-2:] - reach = (ho - h) // 2 - if ho - h != 2 * reach or wo - w != 2 * reach: - 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) - fc = torch.where(wt > 0, f - mean0, 0.0) - t = template.to(dt) - tv = ~torch.isnan(t) - tz = torch.where(tv, t - t[tv].mean(), 0.0) - size = (ho, wo) - fa = [torch.fft.rfft2(a, s=size) for a in (wt, wt * fc, wt * fc * fc)] - fb = [torch.fft.rfft2(b) for b in (tv.to(dt), tz, tz * tz)] - n = 2 * reach + 1 - - 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] - - sw, s_f, s_ff = xc(fa[0], fb[0]), xc(fa[1], fb[0]), xc(fa[2], fb[0]) - s_t, s_tt, s_ft = xc(fa[0], fb[1]), xc(fa[0], fb[2]), xc(fa[1], fb[1]) - m_f = s_f / sw - m_t = s_t / sw - cov = s_ft - sw * m_f * m_t - 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")) - - -def match( - frames: torch.Tensor, - weights: torch.Tensor, - template: torch.Tensor, - rows: torch.Tensor, - cols: torch.Tensor, - search: int, - 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). - template : torch.Tensor - (H, W) template, NaN where invalid. - rows, cols : torch.Tensor of int - Zero-based pixel positions in the template. - search : int - Largest shift on each axis. - dtype : torch.dtype - Precision of the correlation sums. - - Returns - ------- - motion : torch.Tensor of float64 - (B, 2) [row, col] motion. - peak : torch.Tensor of float64 - (B,) correlation at the maximum. - - Raises - ------ - RegistrationError - 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) - if torch.isnan(motion).any(): - raise RegistrationError("Computed motion contains NaN.") - return motion, peak +"""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 +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). +""" + +import torch + + +class RegistrationError(RuntimeError): + """Raised when a frame cannot be matched (e.g. NaN motion).""" + + +def shift_tables( + template: torch.Tensor, + rows: torch.Tensor, + cols: torch.Tensor, + search: int, + 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 + shift varies fastest. + + Parameters + ---------- + template : torch.Tensor + (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. + dtype : torch.dtype + Precision of the tables. + + Returns + ------- + valid, value, value2 : torch.Tensor + (pixels, shifts): whether the shifted template pixel is usable, + its value (centred by the template's mean, 0 where unusable) and the + value squared. + """ + h, w = template.shape + s = int(search) + n = 2 * s + 1 + finite = template[~torch.isnan(template)] + 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[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 + base = (rows + s) * wp + (cols + s) + v = padded.reshape(-1)[base[:, None] + offset[None, :]] + valid = ~torch.isnan(v) + value = torch.nan_to_num(v, nan=0.0) + return valid.to(dtype), value, value * value + + +def correlation_map( + frames: torch.Tensor, + weights: torch.Tensor, + tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor], + search: int, +) -> torch.Tensor: + """Weighted Pearson correlation for every shift. + + Parameters + ---------- + frames : torch.Tensor + (B, pixels) frame values; ignored where weights is 0. + weights : torch.Tensor + (B, pixels) freshness, 0 at invalid pixels. + tables : tuple of torch.Tensor + Output of :func:`shift_tables`. + search : int + Largest shift S. + + Returns + ------- + torch.Tensor + (B, 2S + 1, 2S + 1) correlations indexed [b, dr, dc], NaN + where undefined. + """ + valid, value, value2 = tables + dtype = value.dtype + f = frames.to(dtype) + w = torch.where(torch.isnan(f), 0.0, weights.to(dtype)) + b = f.shape[0] + sw0 = w.sum(1, keepdim=True) + mean0 = (w * torch.where(w > 0, f, 0.0)).sum(1, keepdim=True) / sw0 + fc = torch.where(w > 0, f - mean0, 0.0) + wf = w * fc + # three products instead of six: stack the frame-side vectors + on_valid = torch.cat([w, wf, wf * fc]) @ valid + on_value = torch.cat([w, wf]) @ value + sw, s_f, s_ff = on_valid[:b], on_valid[b : 2 * b], on_valid[2 * b :] + s_t, s_ft = on_value[:b], on_value[b:] + s_tt = w @ value2 + m_f = s_f / sw + m_t = s_t / sw + cov = s_ft - sw * m_f * m_t + 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) + n = 2 * search + 1 + return corr.reshape(-1, n, n).transpose(1, 2) + + +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. + + Parameters + ---------- + corr : torch.Tensor + (B, n, n) maps from :func:`correlation_map`. + search : int + Largest shift S. + + Returns + ------- + motion : torch.Tensor of float64 + (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 = 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) + 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) + 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) + mot = torch.where(inner[:, None], sub, mot) + # an undefined map (e.g. a frame without valid samples) has no peak; + # its argmax would be the first shift, a finite but arbitrary motion + mot = mot.masked_fill(torch.isnan(peak)[:, None], float("nan")) + return -mot, peak + + +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 + ignored. + + Returns + ------- + rr, cc : torch.Tensor of int + Row- and column-shift indices of the maximum. + peak : torch.Tensor + The maximum (NaN if the whole map is undefined). + """ + 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. + + Parameters + ---------- + corr : torch.Tensor + (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, n_r, n_c = corr.shape + rr, cc, peak = peak_index(corr) + ir = torch.arange(n_r, device=corr.device) + ic = torch.arange(n_c, device=corr.device) + near = ((ir[None, :, None] - rr[:, None, None]).abs() <= exclude) & ( + (ic[None, None, :] - cc[:, None, None]).abs() <= exclude + ) + rest = torch.nan_to_num(corr, nan=-torch.inf).masked_fill(near, -torch.inf) + second = rest.reshape(b, -1).max(1).values + margin = peak - second + return margin.masked_fill(torch.isinf(second), float("nan")) + + +def match_maps( + frames: torch.Tensor, + weights: torch.Tensor, + template: torch.Tensor, + rows: torch.Tensor, + cols: torch.Tensor, + search: int, + 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). + peak : torch.Tensor of float64 + (B,) correlation at the maximum. + corr : torch.Tensor + (B, 2S + 1, 2S + 1) maps indexed [b, dr, dc]. + """ + search = int(round(search)) + tables = shift_tables(template, rows, cols, search, dtype) + corr = correlation_map(frames, weights, tables, search) + motion, peak = peak_motion(corr, search) + return motion, peak, corr + + +def wide_correlation( + frames: torch.Tensor, weights: torch.Tensor, template: torch.Tensor +) -> torch.Tensor: + """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 + 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. + template : torch.Tensor + (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]. + + Raises + ------ + ValueError + If the template does not pad the frames equally on every side. + """ + dt = torch.float64 + ho, wo = template.shape + h, w = frames.shape[-2:] + reach = (ho - h) // 2 + if ho - h != 2 * reach or wo - w != 2 * reach: + 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) + fc = torch.where(wt > 0, f - mean0, 0.0) + t = template.to(dt) + tv = ~torch.isnan(t) + tz = torch.where(tv, t - t[tv].mean(), 0.0) + size = (ho, wo) + fa = [torch.fft.rfft2(a, s=size) for a in (wt, wt * fc, wt * fc * fc)] + fb = [torch.fft.rfft2(b) for b in (tv.to(dt), tz, tz * tz)] + n = 2 * reach + 1 + + 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] + + sw, s_f, s_ff = xc(fa[0], fb[0]), xc(fa[1], fb[0]), xc(fa[2], fb[0]) + s_t, s_tt, s_ft = xc(fa[0], fb[1]), xc(fa[0], fb[2]), xc(fa[1], fb[1]) + m_f = s_f / sw + m_t = s_t / sw + cov = s_ft - sw * m_f * m_t + 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")) + + +def match( + frames: torch.Tensor, + weights: torch.Tensor, + template: torch.Tensor, + rows: torch.Tensor, + cols: torch.Tensor, + search: int, + 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). + template : torch.Tensor + (H, W) template, NaN where invalid. + rows, cols : torch.Tensor of int + Zero-based pixel positions in the template. + search : int + Largest shift on each axis. + dtype : torch.dtype + Precision of the correlation sums. + + Returns + ------- + motion : torch.Tensor of float64 + (B, 2) [row, col] motion. + peak : torch.Tensor of float64 + (B,) correlation at the maximum. + + Raises + ------ + RegistrationError + 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) + 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 c007724a..1d19af26 100644 --- a/src/giant_python/registration/multiroi.py +++ b/src/giant_python/registration/multiroi.py @@ -1,845 +1,845 @@ -"""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 -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 -(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 - -import numpy as np -import torch - -from ..io.slap2_raster import ( - RasterLayout, - raster_layout, - read_line_offsets, - read_raster_samples, -) -from ..models.params import MultiRoiRegistrationParams -from .compensation import compensation_record -from .frames import FrameFormer -from .growth import FrameCache, Grower, GrowthQC, seeds_from_consensus -from .interpolation import interp_frame -from .matching import RegistrationError, match_maps -from .outputs import ( - AlignmentFile, - MovieWriter, - downsample2, - matlab_round, - partial_path, - publish, - rec_neg_err, - settings_record, -) -from .sources import CompensatedFrames, PlainFrames, has_samples, make_source -from .stats.io import stats_path -from .stats.worker import FAILED, StatsWorker -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. - - 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. - - 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 - - -@dataclass -class TrialRegistration: - """Summary of one registered trial. - - Attributes - ---------- - ds_frames : ndarray - Line times of the registered frames. - motion_r, motion_c : ndarray - Row and column motion of each frame. - peak : ndarray - Peak correlation of each frame's match. - 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'. - timings : dict - Wall time in seconds of each phase. - """ - - ds_frames: np.ndarray - motion_r: np.ndarray - motion_c: np.ndarray - peak: np.ndarray - registration_failed: bool - 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: 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.""" - if self.device.type == "cuda": - torch.cuda.synchronize(self.device) - now = time.perf_counter() - self.times[name] = self.times.get(name, 0.0) + now - self._last - self._last = now - - -def resolve_device(device: str) -> torch.device: - """'auto' selects CUDA when available, else the CPU. - - Returns - ------- - torch.device - The device to compute on. - - Raises - ------ - ValueError - For a CUDA device that is not available. - """ - if device == "auto": - 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() - ): - raise ValueError(f"CUDA device {device!r} is not available") - return dev - - -def check_layout(layout: RasterLayout) -> None: - """Reject recordings that registration does not support. - - Raises - ------ - ValueError - For more than one fast-z plane, or channel counts other than 1 - or 2. - """ - if layout.fast_zs.size != 1: - raise ValueError("only single-plane acquisitions are supported") - if layout.num_channels not in (1, 2): - raise ValueError("only one- or two-channel recordings are supported") - - -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 -) -> tuple[np.ndarray, np.ndarray]: - """Line times of the initial frames and of the registered (DS) frames. - - Parameters - ---------- - first_line, last_line : float - One-based line range of the trial (may be fractional). - dt : float - Lines per registered frame (line rate / alignHz). - n_init : int - Number of initial frames. - - Returns - ------- - init, ds : ndarray of int - 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: 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 - ------- - state : TemplateState - The initial template and its sums. - cons : ConsensusResult - The pairwise matching that chose its frames. - """ - window = source.window - vals, fresh = source.frames(init) - y = vals.sum(0) - images = window.image(y, float("nan")) - cons = consensus( - y, - fresh, - images, - window.rows, - window.cols, - params.init_search, - dtype, - keep=has_samples(vals), - ) - state = initial_template( - images, - window.image(fresh, 0.0), - cons, - params.maxshift, - params.min_samples, - ) - log.info( - "template from %d of %d frames (reference %d)", - cons.members.size, - init.size, - cons.reference, - ) - return state, cons - - -class OutputSink: - """Accumulate per-frame outputs: movie pages, variance factors, means. - - The movie and the alignment file are written under temporary names and - replace any existing pair only in :meth:`finish`. - - Parameters - ---------- - movie_path, adata_path : str or Path - Destinations. - out_shape : (int, int) - Registered frame shape. - n_frames, n_channels : int - Frames and channels. - save_tif : bool - Movie format. - device : torch.device - Where the mean images accumulate. - movie_deflate, var_deflate : int - 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 - is given; otherwise an existing one is removed on publishing (it - would describe an earlier registration). - """ - - def __init__( - self, - 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: StatsWorker | None = None, - stats_path: str | Path | None = None, - ) -> None: - """Open the movie and the alignment file.""" - ho, wo = out_shape - self.stats = stats - self.stats_path = None if stats_path is None else Path(stats_path) - 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 = MovieWriter( - movie_path, - out_shape, - n_frames * n_channels, - save_tif, - movie_deflate, - ) - try: - 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) - nan = float("nan") - self.add(k, [blank] * self.sum.shape[0], blank, (nan, nan)) - - def add( - 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. - - 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 - for ch, reg in enumerate(regs): - self.movie.write(reg.cpu().numpy()) - good = ~torch.isnan(reg) - self.sum[ch] += torch.where(good, reg, 0.0) - self.count[ch] += good - total = reg if total is None else total + reg - self.movie_ds[k] = downsample2(downsample2(total)).cpu().numpy() - if self.stats is not None: - self.stats.add(k, regs, var_factor, motion) - if k == self.n_frames - 1: # maps while the files are completed - self.stats.finish() - return total - - @property - def stats_seconds(self) -> float: - """Time the statistics' worker spent on them.""" - 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). - - 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) -> Path | None: - """Finish the statistics and write them under a temporary name. - - Returns - ------- - Path or None - The temporary file (None without statistics). - """ - if self.stats_path is None or self.stats is None: - return None - from .stats.io import alignment_digest, write_stats - - result = self.stats.finish().result() - if result is FAILED: - return None - tmp = partial_path(self.stats_path) - attrs = { - "source": "registration", - "movie": self.movie.path.name, - "movie_size": int(self.movie.tmp.stat().st_size), - "alignment": self.adata.path.name, - "alignment_digest": alignment_digest( - fields["DSframes"], fields["motionDSr"], fields["motionDSc"] - ), - "align_hz": float(fields["alignHz"]), - "device": str(self.sum.device), - } - try: - write_stats(tmp, result, attrs) - except Exception: - log.exception("summary statistics failed; continuing without") - try: - tmp.unlink(missing_ok=True) - except OSError: - log.exception("could not remove %s", tmp) - return None - return tmp - - 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: - stats_tmp = self._write_stats(fields) - except Exception: - log.exception("summary statistics failed; continuing without") - stats_tmp = None - publish(self.movie, self.adata, stats_tmp, self.stats_path) - - def abort(self) -> None: - """Discard the partial movie and alignment file.""" - if self.stats is not None: - self.stats.cancel() - try: - self.movie.abort() - finally: - self.adata.abort() - if self.stats_path is not None: - partial_path(self.stats_path).unlink(missing_ok=True) - - -def register_sequential( - source: PlainFrames | CompensatedFrames, - state: TemplateState, - ds: np.ndarray, - params: MultiRoiRegistrationParams, - sink: OutputSink, - 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) - and skipped. A frame with samples whose correlation is undefined at - every shift keeps the previous frame's motion, as the growth schedule - gives such a frame its anchor's. - - Returns - ------- - 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 - h, w = window.shape - n = ds.size - motion = np.zeros((3, n)) - init_r = init_c = 0 - prev = (0.0, 0.0) - for a in range(0, n, chunk): - b = min(n, a + chunk) - vals, fresh = source.frames(ds[a:b]) - present = has_samples(vals) - mov = torch.sqrt(vals.sum(0)) - for i in range(b - a): - if not present[i]: - motion[:, a + i] = np.nan - sink.add_missing(a + i) - continue - tmpl = state.matching_template()[ - m - init_r : m - init_r + h, m - init_c : m - init_c + w - ] - search = max(abs(init_c), abs(init_r), params.clip_shift) - mot, pk, _ = match_maps( - mov[i : i + 1], - fresh[i : i + 1], - tmpl, - window.rows, - window.cols, - search, - dtype, - ) - if torch.isnan(pk[0]): - mr, mc = prev - elif torch.isnan(mot).any(): - raise RegistrationError("Computed motion contains NaN.") - else: - mr, mc = init_r + float(mot[0, 0]), init_c + float(mot[0, 1]) - motion[:, a + i] = mr, mc, float(pk[0]) - prev = (mr, mc) - fimg = window.image(fresh[i], 0.0) - regs = [] - 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))) - 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) - return motion[0], motion[1], motion[2] - - -def register_grow( - source: PlainFrames | CompensatedFrames, - state: TemplateState, - cons: ConsensusResult, - init: np.ndarray, - ds: np.ndarray, - params: MultiRoiRegistrationParams, - sink: OutputSink, - 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 - ------- - motion_r, motion_c, peak : ndarray - Per-frame motion and peak correlation. - qc : GrowthQC - How each frame was registered. - """ - timer = timer or Timer(source.former.device) - cache = FrameCache(source, ds) - present = cache.present() - if not present.all(): # frames without samples are left out - cache.keep(present) - timer.mark("frames") - motion = np.full((ds.size, 2), np.nan) - 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) - grown, qc = grower.run() - timer.mark("grow") - if params.polish: - grown = grower.polish(params.polish_radius) - timer.mark("polish") - motion[present] = grown - qc = qc.expanded(present) - m = int(params.maxshift) - j = np.cumsum(present) - 1 # index of each frame in the cache - for k in range(ds.size): - if not present[k]: - sink.add_missing(k) - continue - regs = cache.registered(int(j[k]), motion[k], m) - sink.add(k, [r for r, _ in regs], regs[0][1], motion[k]) - timer.mark("render") - return motion[:, 0].copy(), motion[:, 1].copy(), qc.peak.copy(), qc - - -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 - 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) - - -def alignment_fields( - layout: RasterLayout, - source: PlainFrames | CompensatedFrames, - ds: np.ndarray, - motion_r: np.ndarray, - motion_c: np.ndarray, - sink: OutputSink, - params: MultiRoiRegistrationParams, - failed: bool, -) -> 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)) - ho, wo = h + 2 * m, w + 2 * m - x_off, y_off, z_off = read_line_offsets(layout, ds) - return { - "numChannels": float(layout.num_channels), - "meanIM": sink.mean_image().astype(np.float32), - "frametime": 1.0 / params.align_hz, - "alignHz": float(params.align_hz), - "DSframes": ds.astype(np.float64), - "motionDSc": motion_c, - "motionDSr": motion_r, - "recNegErr": rec_neg_err(sink.movie_ds, params.align_hz), - "registrationFailed": failed, - "slap2": { - "Z_depths": layout.fast_zs.astype(np.float32), - "cropRow": float(window.trim_rows[0] - m), - "cropCol": float(window.trim_cols[0] - m), - "viewC": np.repeat((np.arange(wo) + 1.0 - m)[None, :], ho, 0), - "viewR": np.repeat((np.arange(ho) + 1.0 - m)[:, None], wo, 1), - "trimRows": window.trim_rows.astype(np.float64), - "trimCols": window.trim_cols.astype(np.float64), - "onlineMotionXshift": x_off[:, None], - "onlineMotionYshift": y_off[:, None], - "onlineMotionZshift": z_off[:, None], - "onlineCompensation": record, - # the frames left out samples behind the DMD curtain - "unlitMasked": np.int8(1), - }, - } - - -def open_trial( - 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 - invalid (see :func:`giant_python.io.slap2_raster.unlit_samples`), as - registration does since slap2/unlitMasked; False keeps them, as in - registrations made before. - - Returns - ------- - layout : RasterLayout - The recording's layout. - former : FrameFormer - Frame former over every cycle the trial's frames reach. - init, ds : ndarray of int - Initial and registered frame times. - dtk : int - Kernel time constant in lines. - """ - layout = raster_layout(dat_path) - check_layout(layout) - p = layout.lines_per_cycle - dt = (1.0 / layout.line_period_s) / params.align_hz - dtk = int(np.ceil(dt)) - init, ds = frame_times(first_line, last_line, dt, params.init_frames) - dt_read = max(3 * dtk, p) - lo = max(1, int(min(init.min(), ds.min())) - dt_read) - hi = min(layout.total_lines, int(max(init.max(), ds.max())) + dt_read) - c0, c1 = (lo - 1) // p, (hi - 1) // p + 1 - # samples behind the DMD curtain get no weight (see io.slap2_raster) - samples = read_raster_samples(layout, (c0, c1), mask_unlit=mask_unlit) - return layout, FrameFormer(layout, samples, c0, 1, device), init, ds, dtk - - -def trial_stats( - 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. - - Returns - ------- - StatsWorker or None - The statistics worker, or None when it could not be started. - """ - from .stats import new_accumulator - - try: - return StatsWorker( - lambda: new_accumulator(source, ds, margin, n_channels), - source.former.device, - ) - except Exception: # e.g. no CUDA stream: registration goes on - log.exception("summary statistics cannot start; continuing without") - return None - - -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 - acc = trial_stats(source, ds, m, layout.num_channels) if stats else None - try: - state, cons = build_template(source, init, params, dtype) - timer.mark("template") - sink = OutputSink( - paths[0], - paths[1], - (h + 2 * m, w + 2 * m), - ds.size, - layout.num_channels, - params.save_tif, - source.former.device, - params.movie_deflate, - params.var_factor_deflate, - stats=acc, - stats_path=stats_path(paths[0]), - ) - except BaseException: - if acc is not None: - acc.cancel() - raise - return state, cons, sink - - -def register_trial( - dat_path: str | Path, - first_line: float, - last_line: float, - 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. - - Parameters - ---------- - dat_path : str or Path - 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). - movie_path, adata_path : str or Path - Destinations of the registered movie and the alignment data. - params : MultiRoiRegistrationParams, optional - Scientific settings (default: MATLAB's defaults). - device : str or torch.device - Where frames are formed and matched. - dtype : torch.dtype - 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 - it (:func:`.stats.stats_path`). Without, an existing statistics - file of the trial is removed. - - Returns - ------- - TrialRegistration - Motion and quality of the trial. - """ - if params is None: - params = MultiRoiRegistrationParams() - device = torch.device(device) - timer = Timer(device) - layout, former, init, ds, dtk = open_trial( - dat_path, float(first_line), float(last_line), params, device - ) - timer.mark("read") - log.info("%s: %d frames", Path(dat_path).name, ds.size) - source = make_source( - layout, - former, - float(first_line), - float(last_line), - init, - ds, - dtk, - params.compensate_online, - ) - if source.compensation is not None: - log.info( - "undoing the online motion correction (%d x/y switches)", - source.compensation.switch_lines.size, - ) - state, cons, sink = _template_and_sink( - source, init, ds, params, dtype, (movie_path, adata_path), stats, timer - ) - qc = None - try: - if params.schedule == "grow": - motion_r, motion_c, peak, qc = register_grow( - source, state, cons, init, ds, params, sink, dtype, timer - ) - else: - motion_r, motion_c, peak = register_sequential(source, state, ds, params, sink, dtype) - timer.mark("register") - sink.movie.close() - timer.mark("movie") - failed = motion_failed(motion_r, motion_c) - n_ok = int(np.isfinite(motion_r).sum()) - if n_ok < min(2, ds.size): - log.warning( - "%d of %d frames of %s have valid samples; failed", - n_ok, - ds.size, - dat_path, - ) - 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) - if qc is not None: - fields["growthQC"] = qc.fields() - sink.finish(fields, settings_record(params)) - except BaseException: - sink.abort() - 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) +"""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 +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 +(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 + +import numpy as np +import torch + +from ..io.slap2_raster import ( + RasterLayout, + raster_layout, + read_line_offsets, + read_raster_samples, +) +from ..models.params import MultiRoiRegistrationParams +from .compensation import compensation_record +from .frames import FrameFormer +from .growth import FrameCache, Grower, GrowthQC, seeds_from_consensus +from .interpolation import interp_frame +from .matching import RegistrationError, match_maps +from .outputs import ( + AlignmentFile, + MovieWriter, + downsample2, + matlab_round, + partial_path, + publish, + rec_neg_err, + settings_record, +) +from .sources import CompensatedFrames, PlainFrames, has_samples, make_source +from .stats.io import stats_path +from .stats.worker import FAILED, StatsWorker +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. + + 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. + + 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 + + +@dataclass +class TrialRegistration: + """Summary of one registered trial. + + Attributes + ---------- + ds_frames : ndarray + Line times of the registered frames. + motion_r, motion_c : ndarray + Row and column motion of each frame. + peak : ndarray + Peak correlation of each frame's match. + 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'. + timings : dict + Wall time in seconds of each phase. + """ + + ds_frames: np.ndarray + motion_r: np.ndarray + motion_c: np.ndarray + peak: np.ndarray + registration_failed: bool + 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: 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.""" + if self.device.type == "cuda": + torch.cuda.synchronize(self.device) + now = time.perf_counter() + self.times[name] = self.times.get(name, 0.0) + now - self._last + self._last = now + + +def resolve_device(device: str) -> torch.device: + """'auto' selects CUDA when available, else the CPU. + + Returns + ------- + torch.device + The device to compute on. + + Raises + ------ + ValueError + For a CUDA device that is not available. + """ + if device == "auto": + 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() + ): + raise ValueError(f"CUDA device {device!r} is not available") + return dev + + +def check_layout(layout: RasterLayout) -> None: + """Reject recordings that registration does not support. + + Raises + ------ + ValueError + For more than one fast-z plane, or channel counts other than 1 + or 2. + """ + if layout.fast_zs.size != 1: + raise ValueError("only single-plane acquisitions are supported") + if layout.num_channels not in (1, 2): + raise ValueError("only one- or two-channel recordings are supported") + + +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 +) -> tuple[np.ndarray, np.ndarray]: + """Line times of the initial frames and of the registered (DS) frames. + + Parameters + ---------- + first_line, last_line : float + One-based line range of the trial (may be fractional). + dt : float + Lines per registered frame (line rate / alignHz). + n_init : int + Number of initial frames. + + Returns + ------- + init, ds : ndarray of int + 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: 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 + ------- + state : TemplateState + The initial template and its sums. + cons : ConsensusResult + The pairwise matching that chose its frames. + """ + window = source.window + vals, fresh = source.frames(init) + y = vals.sum(0) + images = window.image(y, float("nan")) + cons = consensus( + y, + fresh, + images, + window.rows, + window.cols, + params.init_search, + dtype, + keep=has_samples(vals), + ) + state = initial_template( + images, + window.image(fresh, 0.0), + cons, + params.maxshift, + params.min_samples, + ) + log.info( + "template from %d of %d frames (reference %d)", + cons.members.size, + init.size, + cons.reference, + ) + return state, cons + + +class OutputSink: + """Accumulate per-frame outputs: movie pages, variance factors, means. + + The movie and the alignment file are written under temporary names and + replace any existing pair only in :meth:`finish`. + + Parameters + ---------- + movie_path, adata_path : str or Path + Destinations. + out_shape : (int, int) + Registered frame shape. + n_frames, n_channels : int + Frames and channels. + save_tif : bool + Movie format. + device : torch.device + Where the mean images accumulate. + movie_deflate, var_deflate : int + 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 + is given; otherwise an existing one is removed on publishing (it + would describe an earlier registration). + """ + + def __init__( + self, + 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: StatsWorker | None = None, + stats_path: str | Path | None = None, + ) -> None: + """Open the movie and the alignment file.""" + ho, wo = out_shape + self.stats = stats + self.stats_path = None if stats_path is None else Path(stats_path) + 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 = MovieWriter( + movie_path, + out_shape, + n_frames * n_channels, + save_tif, + movie_deflate, + ) + try: + 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) + nan = float("nan") + self.add(k, [blank] * self.sum.shape[0], blank, (nan, nan)) + + def add( + 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. + + 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 + for ch, reg in enumerate(regs): + self.movie.write(reg.cpu().numpy()) + good = ~torch.isnan(reg) + self.sum[ch] += torch.where(good, reg, 0.0) + self.count[ch] += good + total = reg if total is None else total + reg + self.movie_ds[k] = downsample2(downsample2(total)).cpu().numpy() + if self.stats is not None: + self.stats.add(k, regs, var_factor, motion) + if k == self.n_frames - 1: # maps while the files are completed + self.stats.finish() + return total + + @property + def stats_seconds(self) -> float: + """Time the statistics' worker spent on them.""" + 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). + + 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) -> Path | None: + """Finish the statistics and write them under a temporary name. + + Returns + ------- + Path or None + The temporary file (None without statistics). + """ + if self.stats_path is None or self.stats is None: + return None + from .stats.io import alignment_digest, write_stats + + result = self.stats.finish().result() + if result is FAILED: + return None + tmp = partial_path(self.stats_path) + attrs = { + "source": "registration", + "movie": self.movie.path.name, + "movie_size": int(self.movie.tmp.stat().st_size), + "alignment": self.adata.path.name, + "alignment_digest": alignment_digest( + fields["DSframes"], fields["motionDSr"], fields["motionDSc"] + ), + "align_hz": float(fields["alignHz"]), + "device": str(self.sum.device), + } + try: + write_stats(tmp, result, attrs) + except Exception: + log.exception("summary statistics failed; continuing without") + try: + tmp.unlink(missing_ok=True) + except OSError: + log.exception("could not remove %s", tmp) + return None + return tmp + + 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: + stats_tmp = self._write_stats(fields) + except Exception: + log.exception("summary statistics failed; continuing without") + stats_tmp = None + publish(self.movie, self.adata, stats_tmp, self.stats_path) + + def abort(self) -> None: + """Discard the partial movie and alignment file.""" + if self.stats is not None: + self.stats.cancel() + try: + self.movie.abort() + finally: + self.adata.abort() + if self.stats_path is not None: + partial_path(self.stats_path).unlink(missing_ok=True) + + +def register_sequential( + source: PlainFrames | CompensatedFrames, + state: TemplateState, + ds: np.ndarray, + params: MultiRoiRegistrationParams, + sink: OutputSink, + 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) + and skipped. A frame with samples whose correlation is undefined at + every shift keeps the previous frame's motion, as the growth schedule + gives such a frame its anchor's. + + Returns + ------- + 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 + h, w = window.shape + n = ds.size + motion = np.zeros((3, n)) + init_r = init_c = 0 + prev = (0.0, 0.0) + for a in range(0, n, chunk): + b = min(n, a + chunk) + vals, fresh = source.frames(ds[a:b]) + present = has_samples(vals) + mov = torch.sqrt(vals.sum(0)) + for i in range(b - a): + if not present[i]: + motion[:, a + i] = np.nan + sink.add_missing(a + i) + continue + tmpl = state.matching_template()[ + m - init_r : m - init_r + h, m - init_c : m - init_c + w + ] + search = max(abs(init_c), abs(init_r), params.clip_shift) + mot, pk, _ = match_maps( + mov[i : i + 1], + fresh[i : i + 1], + tmpl, + window.rows, + window.cols, + search, + dtype, + ) + if torch.isnan(pk[0]): + mr, mc = prev + elif torch.isnan(mot).any(): + raise RegistrationError("Computed motion contains NaN.") + else: + mr, mc = init_r + float(mot[0, 0]), init_c + float(mot[0, 1]) + motion[:, a + i] = mr, mc, float(pk[0]) + prev = (mr, mc) + fimg = window.image(fresh[i], 0.0) + regs = [] + 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))) + 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) + return motion[0], motion[1], motion[2] + + +def register_grow( + source: PlainFrames | CompensatedFrames, + state: TemplateState, + cons: ConsensusResult, + init: np.ndarray, + ds: np.ndarray, + params: MultiRoiRegistrationParams, + sink: OutputSink, + 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 + ------- + motion_r, motion_c, peak : ndarray + Per-frame motion and peak correlation. + qc : GrowthQC + How each frame was registered. + """ + timer = timer or Timer(source.former.device) + cache = FrameCache(source, ds) + present = cache.present() + if not present.all(): # frames without samples are left out + cache.keep(present) + timer.mark("frames") + motion = np.full((ds.size, 2), np.nan) + 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) + grown, qc = grower.run() + timer.mark("grow") + if params.polish: + grown = grower.polish(params.polish_radius) + timer.mark("polish") + motion[present] = grown + qc = qc.expanded(present) + m = int(params.maxshift) + j = np.cumsum(present) - 1 # index of each frame in the cache + for k in range(ds.size): + if not present[k]: + sink.add_missing(k) + continue + regs = cache.registered(int(j[k]), motion[k], m) + sink.add(k, [r for r, _ in regs], regs[0][1], motion[k]) + timer.mark("render") + return motion[:, 0].copy(), motion[:, 1].copy(), qc.peak.copy(), qc + + +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 + 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) + + +def alignment_fields( + layout: RasterLayout, + source: PlainFrames | CompensatedFrames, + ds: np.ndarray, + motion_r: np.ndarray, + motion_c: np.ndarray, + sink: OutputSink, + params: MultiRoiRegistrationParams, + failed: bool, +) -> 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)) + ho, wo = h + 2 * m, w + 2 * m + x_off, y_off, z_off = read_line_offsets(layout, ds) + return { + "numChannels": float(layout.num_channels), + "meanIM": sink.mean_image().astype(np.float32), + "frametime": 1.0 / params.align_hz, + "alignHz": float(params.align_hz), + "DSframes": ds.astype(np.float64), + "motionDSc": motion_c, + "motionDSr": motion_r, + "recNegErr": rec_neg_err(sink.movie_ds, params.align_hz), + "registrationFailed": failed, + "slap2": { + "Z_depths": layout.fast_zs.astype(np.float32), + "cropRow": float(window.trim_rows[0] - m), + "cropCol": float(window.trim_cols[0] - m), + "viewC": np.repeat((np.arange(wo) + 1.0 - m)[None, :], ho, 0), + "viewR": np.repeat((np.arange(ho) + 1.0 - m)[:, None], wo, 1), + "trimRows": window.trim_rows.astype(np.float64), + "trimCols": window.trim_cols.astype(np.float64), + "onlineMotionXshift": x_off[:, None], + "onlineMotionYshift": y_off[:, None], + "onlineMotionZshift": z_off[:, None], + "onlineCompensation": record, + # the frames left out samples behind the DMD curtain + "unlitMasked": np.int8(1), + }, + } + + +def open_trial( + 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 + invalid (see :func:`giant_python.io.slap2_raster.unlit_samples`), as + registration does since slap2/unlitMasked; False keeps them, as in + registrations made before. + + Returns + ------- + layout : RasterLayout + The recording's layout. + former : FrameFormer + Frame former over every cycle the trial's frames reach. + init, ds : ndarray of int + Initial and registered frame times. + dtk : int + Kernel time constant in lines. + """ + layout = raster_layout(dat_path) + check_layout(layout) + p = layout.lines_per_cycle + dt = (1.0 / layout.line_period_s) / params.align_hz + dtk = int(np.ceil(dt)) + init, ds = frame_times(first_line, last_line, dt, params.init_frames) + dt_read = max(3 * dtk, p) + lo = max(1, int(min(init.min(), ds.min())) - dt_read) + hi = min(layout.total_lines, int(max(init.max(), ds.max())) + dt_read) + c0, c1 = (lo - 1) // p, (hi - 1) // p + 1 + # samples behind the DMD curtain get no weight (see io.slap2_raster) + samples = read_raster_samples(layout, (c0, c1), mask_unlit=mask_unlit) + return layout, FrameFormer(layout, samples, c0, 1, device), init, ds, dtk + + +def trial_stats( + 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. + + Returns + ------- + StatsWorker or None + The statistics worker, or None when it could not be started. + """ + from .stats import new_accumulator + + try: + return StatsWorker( + lambda: new_accumulator(source, ds, margin, n_channels), + source.former.device, + ) + except Exception: # e.g. no CUDA stream: registration goes on + log.exception("summary statistics cannot start; continuing without") + return None + + +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 + acc = trial_stats(source, ds, m, layout.num_channels) if stats else None + try: + state, cons = build_template(source, init, params, dtype) + timer.mark("template") + sink = OutputSink( + paths[0], + paths[1], + (h + 2 * m, w + 2 * m), + ds.size, + layout.num_channels, + params.save_tif, + source.former.device, + params.movie_deflate, + params.var_factor_deflate, + stats=acc, + stats_path=stats_path(paths[0]), + ) + except BaseException: + if acc is not None: + acc.cancel() + raise + return state, cons, sink + + +def register_trial( + dat_path: str | Path, + first_line: float, + last_line: float, + 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. + + Parameters + ---------- + dat_path : str or Path + 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). + movie_path, adata_path : str or Path + Destinations of the registered movie and the alignment data. + params : MultiRoiRegistrationParams, optional + Scientific settings (default: MATLAB's defaults). + device : str or torch.device + Where frames are formed and matched. + dtype : torch.dtype + 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 + it (:func:`.stats.stats_path`). Without, an existing statistics + file of the trial is removed. + + Returns + ------- + TrialRegistration + Motion and quality of the trial. + """ + if params is None: + params = MultiRoiRegistrationParams() + device = torch.device(device) + timer = Timer(device) + layout, former, init, ds, dtk = open_trial( + dat_path, float(first_line), float(last_line), params, device + ) + timer.mark("read") + log.info("%s: %d frames", Path(dat_path).name, ds.size) + source = make_source( + layout, + former, + float(first_line), + float(last_line), + init, + ds, + dtk, + params.compensate_online, + ) + if source.compensation is not None: + log.info( + "undoing the online motion correction (%d x/y switches)", + source.compensation.switch_lines.size, + ) + state, cons, sink = _template_and_sink( + source, init, ds, params, dtype, (movie_path, adata_path), stats, timer + ) + qc = None + try: + if params.schedule == "grow": + motion_r, motion_c, peak, qc = register_grow( + source, state, cons, init, ds, params, sink, dtype, timer + ) + else: + motion_r, motion_c, peak = register_sequential(source, state, ds, params, sink, dtype) + timer.mark("register") + sink.movie.close() + timer.mark("movie") + failed = motion_failed(motion_r, motion_c) + n_ok = int(np.isfinite(motion_r).sum()) + if n_ok < min(2, ds.size): + log.warning( + "%d of %d frames of %s have valid samples; failed", + n_ok, + ds.size, + dat_path, + ) + 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) + if qc is not None: + fields["growthQC"] = qc.fields() + sink.finish(fields, settings_record(params)) + except BaseException: + sink.abort() + 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) diff --git a/src/giant_python/registration/outputs.py b/src/giant_python/registration/outputs.py index 137b99c6..2fc3aa34 100644 --- a/src/giant_python/registration/outputs.py +++ b/src/giant_python/registration/outputs.py @@ -1,509 +1,509 @@ -"""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 - 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 -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 -mistaken for registered. -""" - -import json -import logging -import math -import os -import warnings -import zlib -from collections import deque -from collections.abc import Callable -from concurrent.futures import Future, ThreadPoolExecutor -from pathlib import Path - -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__) - -PIXELS_PER_CM = 4e4 -"""Resolution tag of the registered TIFF (250 nm pixels), as in MATLAB.""" - -SETTINGS_ATTR = "align_params" -"""Root attribute of an alignment file: JSON of :func:`settings_record`.""" - -FRAME_VERSION = 2 -"""Changes when registration's outputs change for the same settings, so -that outputs saved before are registered again rather than reused. - -2: samples taken behind the DMD curtain get no weight (GIAnT-Python#66). -""" - - -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: 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) - is stored as None. - - Parameters - ---------- - params : MultiRoiRegistrationParams - Settings of the registration. - - Returns - ------- - dict - JSON-serializable record. - """ - record = params.to_matlab() - record.pop("overwriteExisting") - record["frameVersion"] = FRAME_VERSION - return { - key: None if isinstance(value, float) and math.isnan(value) else value - for key, value in record.items() - } - - -class _Background: - """Run writes in order on one thread, with a bounded backlog.""" - - 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: 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: - self._pending.popleft().result() - - def drain(self) -> None: - """Wait for queued writes, re-raising their errors.""" - while self._pending: - self._pending.popleft().result() - - def close(self) -> None: - """Wait for queued writes and stop the thread.""" - try: - self.drain() - finally: - self._pool.shutdown(wait=True) - - -_COMPRESSORS = None - - -def _compressors() -> ThreadPoolExecutor: - """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))) - return _COMPRESSORS - - -def _deflate(page: np.ndarray, level: int) -> bytes: - """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) - - -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. - """ - - 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 = {"compression": "gzip", "compression_opts": self.level} - self.ds = group.create_dataset( - name, - shape=(n_frames, cols, rows), - dtype=np.float32, - chunks=(1, cols, rows) if self.level else None, - **opts, - ) - - 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: 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 - return - self.ds.id.write_direct_chunk((index, 0, 0), prepared.result()) - - -def partial_path(path: Path) -> Path: - """Temporary name of an output until it is published. - - Returns - ------- - Path - path with .partial appended. - """ - return path.with_name(path.name + ".partial") - - -class MovieWriter: - """Append registered pages to a TIFF or HDF5 movie, under a temporary name. - - Parameters - ---------- - path : str or Path - Final destination; the pages go to .partial until - :func:`publish`. - shape : (int, int) - 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]). - deflate : int - HDF5 movies: deflate level (0 for none; MATLAB writes 4). - """ - - def __init__( - self, - 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) - self.tiff = tiff - self.n = 0 - self._closed = False - if self.tmp.exists(): - self.tmp.unlink() - if tiff: - import tifffile - - 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._bg = _Background() - - def write(self, page: np.ndarray) -> None: - """Append one (rows, cols) page. - - 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). - """ - page = np.asarray(page, np.float32) - if not self.tiff: - page = self._frames.prepare(page) - self._bg.submit(self._write, page, self.n) - self.n += 1 - - def _write(self, page: np.ndarray | Future[bytes], index: int) -> None: - """Write one page (on the background thread).""" - if self.tiff: - self._tw.write( - np.ascontiguousarray(page.T), - photometric="minisblack", - resolution=(PIXELS_PER_CM, PIXELS_PER_CM), - resolutionunit="CENTIMETER", - ) - else: - self._frames.store(index, page) - - def close(self) -> None: - """Finish queued pages and close the (still temporary) file.""" - if self._closed: - return - self._closed = True - try: - self._bg.close() - finally: - if self.tiff: - self._tw.close() - else: - self._h5.close() - - def abort(self) -> None: - """Close and delete the temporary file.""" - try: - self.close() - except Exception: - pass - finally: - if self.tmp.exists(): - self.tmp.unlink() - - -class AlignmentFile: - """Build _ALIGNMENTDATA.h5 under a temporary name. - - Parameters - ---------- - path : str or Path - Final destination; the file is .partial until - :func:`publish`. - var_shape : (int, int) - 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). - """ - - def __init__( - self, - 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) - if self.tmp.exists(): - self.tmp.unlink() - self._f = h5py.File(self.tmp, "w") - self._var = _ChunkedFrames( - self._f.require_group("slap2"), - "varFacDS", - n_frames, - var_shape, - deflate, - ) - self._bg = _Background() - - def write_var_factor(self, index: int, var_factor: np.ndarray) -> None: - """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: 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. - settings : dict, optional - :func:`settings_record` of the registration, saved as the root - attribute :data:`SETTINGS_ATTR`. - """ - self._bg.close() - fields = dict(fields) - slap2 = fields.pop("slap2", {}) - for key, value in fields.items(): - write_matlab_value(self._f, key, value) - grp = self._f["slap2"] - for key, value in slap2.items(): - write_matlab_value(grp, key, value) - self._f.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) - if settings is not None: - self._f.attrs[SETTINGS_ATTR] = json.dumps(settings, sort_keys=True) - self._f.close() - - def abort(self) -> None: - """Close and delete the temporary file.""" - try: - self._bg.close() - except Exception: - pass - try: - self._f.close() - finally: - if self.tmp.exists(): - self.tmp.unlink() - - -def publish( - movie: MovieWriter, - adata: AlignmentFile, - stats_tmp: Path | None = None, - stats_path: Path | None = None, -) -> None: - """Move a finished movie and alignment file into place, as a pair. - - The previous alignment file is removed first and the new one is moved - in last. A pair whose alignment file exists is therefore complete and - consistent; if publishing is interrupted, no alignment file remains and - the trial is registered again. - - Parameters - ---------- - movie : MovieWriter - A closed movie. - adata : AlignmentFile - A finished alignment file. - stats_tmp : Path, optional - 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 - (made from an earlier registration) is removed. Failures here are - logged and do not stop the movie and alignment file - (:func:`_publish_stats`). - """ - adata.path.unlink(missing_ok=True) - os.replace(movie.tmp, movie.path) - if stats_path is not None: - _publish_stats(stats_tmp, Path(stats_path)) - os.replace(adata.tmp, adata.path) - - -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. - """ - try: - if stats_tmp is not None: - os.replace(stats_tmp, stats_path) - return - stats_path.unlink(missing_ok=True) - return - except OSError: - log.exception("statistics file %s not published", stats_path) - for path in (stats_tmp, stats_path): - try: - if path is not None: - Path(path).unlink(missing_ok=True) - except OSError: - log.exception("could not remove %s", path) - - -def downsample2(image: np.ndarray) -> np.ndarray: - """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] - - -def matlab_round(x: ArrayLike) -> np.ndarray: - """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) - - -def rec_neg_err(movie_ds: np.ndarray, align_hz: float) -> np.ndarray: - """Per-frame negative reconstruction error (MultiRoiRegistration). - - 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 - 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. - align_hz : float - Frame rate. - - Returns - ------- - ndarray of float64 - (frames,) errors. - """ - n = movie_ds.shape[0] - out = np.full(n, np.nan) - offset = np.float32(10) - n_chunks = int(np.ceil(n / (align_hz * 10))) - edges = matlab_round(np.linspace(1, n + 1, n_chunks + 1)).astype(int) - for a, b in zip(edges[:-1] - 1, edges[1:] - 1): - chunk = movie_ds[a:b] - with np.errstate(all="ignore"), warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) - template = np.nanmedian(chunk, axis=0).astype(np.float32) - nan_frac = np.isnan(chunk).mean(0) - template[nan_frac > 0.2] = np.nan - gamma = np.sqrt(np.maximum(0, template) + offset) - excess = (template - chunk) / gamma - num = np.where(np.isnan(excess), 0, np.maximum(0, excess)) ** 2 - den = (template / gamma) ** 2 + chunk * 0 - den_mean = np.nanmean(den.reshape(den.shape[0], -1), axis=1) - num_mean = num.reshape(num.shape[0], -1).mean(axis=1) - out[a:b] = np.sqrt(num_mean / den_mean) - return out +"""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 + 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 +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 +mistaken for registered. +""" + +import json +import logging +import math +import os +import warnings +import zlib +from collections import deque +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor +from pathlib import Path + +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__) + +PIXELS_PER_CM = 4e4 +"""Resolution tag of the registered TIFF (250 nm pixels), as in MATLAB.""" + +SETTINGS_ATTR = "align_params" +"""Root attribute of an alignment file: JSON of :func:`settings_record`.""" + +FRAME_VERSION = 2 +"""Changes when registration's outputs change for the same settings, so +that outputs saved before are registered again rather than reused. + +2: samples taken behind the DMD curtain get no weight (GIAnT-Python#66). +""" + + +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: 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) + is stored as None. + + Parameters + ---------- + params : MultiRoiRegistrationParams + Settings of the registration. + + Returns + ------- + dict + JSON-serializable record. + """ + record = params.to_matlab() + record.pop("overwriteExisting") + record["frameVersion"] = FRAME_VERSION + return { + key: None if isinstance(value, float) and math.isnan(value) else value + for key, value in record.items() + } + + +class _Background: + """Run writes in order on one thread, with a bounded backlog.""" + + 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: 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: + self._pending.popleft().result() + + def drain(self) -> None: + """Wait for queued writes, re-raising their errors.""" + while self._pending: + self._pending.popleft().result() + + def close(self) -> None: + """Wait for queued writes and stop the thread.""" + try: + self.drain() + finally: + self._pool.shutdown(wait=True) + + +_COMPRESSORS = None + + +def _compressors() -> ThreadPoolExecutor: + """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))) + return _COMPRESSORS + + +def _deflate(page: np.ndarray, level: int) -> bytes: + """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) + + +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. + """ + + 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 = {"compression": "gzip", "compression_opts": self.level} + self.ds = group.create_dataset( + name, + shape=(n_frames, cols, rows), + dtype=np.float32, + chunks=(1, cols, rows) if self.level else None, + **opts, + ) + + 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: 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 + return + self.ds.id.write_direct_chunk((index, 0, 0), prepared.result()) + + +def partial_path(path: Path) -> Path: + """Temporary name of an output until it is published. + + Returns + ------- + Path + path with .partial appended. + """ + return path.with_name(path.name + ".partial") + + +class MovieWriter: + """Append registered pages to a TIFF or HDF5 movie, under a temporary name. + + Parameters + ---------- + path : str or Path + Final destination; the pages go to .partial until + :func:`publish`. + shape : (int, int) + 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]). + deflate : int + HDF5 movies: deflate level (0 for none; MATLAB writes 4). + """ + + def __init__( + self, + 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) + self.tiff = tiff + self.n = 0 + self._closed = False + if self.tmp.exists(): + self.tmp.unlink() + if tiff: + import tifffile + + 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._bg = _Background() + + def write(self, page: np.ndarray) -> None: + """Append one (rows, cols) page. + + 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). + """ + page = np.asarray(page, np.float32) + if not self.tiff: + page = self._frames.prepare(page) + self._bg.submit(self._write, page, self.n) + self.n += 1 + + def _write(self, page: np.ndarray | Future[bytes], index: int) -> None: + """Write one page (on the background thread).""" + if self.tiff: + self._tw.write( + np.ascontiguousarray(page.T), + photometric="minisblack", + resolution=(PIXELS_PER_CM, PIXELS_PER_CM), + resolutionunit="CENTIMETER", + ) + else: + self._frames.store(index, page) + + def close(self) -> None: + """Finish queued pages and close the (still temporary) file.""" + if self._closed: + return + self._closed = True + try: + self._bg.close() + finally: + if self.tiff: + self._tw.close() + else: + self._h5.close() + + def abort(self) -> None: + """Close and delete the temporary file.""" + try: + self.close() + except Exception: + pass + finally: + if self.tmp.exists(): + self.tmp.unlink() + + +class AlignmentFile: + """Build _ALIGNMENTDATA.h5 under a temporary name. + + Parameters + ---------- + path : str or Path + Final destination; the file is .partial until + :func:`publish`. + var_shape : (int, int) + 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). + """ + + def __init__( + self, + 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) + if self.tmp.exists(): + self.tmp.unlink() + self._f = h5py.File(self.tmp, "w") + self._var = _ChunkedFrames( + self._f.require_group("slap2"), + "varFacDS", + n_frames, + var_shape, + deflate, + ) + self._bg = _Background() + + def write_var_factor(self, index: int, var_factor: np.ndarray) -> None: + """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: 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. + settings : dict, optional + :func:`settings_record` of the registration, saved as the root + attribute :data:`SETTINGS_ATTR`. + """ + self._bg.close() + fields = dict(fields) + slap2 = fields.pop("slap2", {}) + for key, value in fields.items(): + write_matlab_value(self._f, key, value) + grp = self._f["slap2"] + for key, value in slap2.items(): + write_matlab_value(grp, key, value) + self._f.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) + if settings is not None: + self._f.attrs[SETTINGS_ATTR] = json.dumps(settings, sort_keys=True) + self._f.close() + + def abort(self) -> None: + """Close and delete the temporary file.""" + try: + self._bg.close() + except Exception: + pass + try: + self._f.close() + finally: + if self.tmp.exists(): + self.tmp.unlink() + + +def publish( + movie: MovieWriter, + adata: AlignmentFile, + stats_tmp: Path | None = None, + stats_path: Path | None = None, +) -> None: + """Move a finished movie and alignment file into place, as a pair. + + The previous alignment file is removed first and the new one is moved + in last. A pair whose alignment file exists is therefore complete and + consistent; if publishing is interrupted, no alignment file remains and + the trial is registered again. + + Parameters + ---------- + movie : MovieWriter + A closed movie. + adata : AlignmentFile + A finished alignment file. + stats_tmp : Path, optional + 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 + (made from an earlier registration) is removed. Failures here are + logged and do not stop the movie and alignment file + (:func:`_publish_stats`). + """ + adata.path.unlink(missing_ok=True) + os.replace(movie.tmp, movie.path) + if stats_path is not None: + _publish_stats(stats_tmp, Path(stats_path)) + os.replace(adata.tmp, adata.path) + + +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. + """ + try: + if stats_tmp is not None: + os.replace(stats_tmp, stats_path) + return + stats_path.unlink(missing_ok=True) + return + except OSError: + log.exception("statistics file %s not published", stats_path) + for path in (stats_tmp, stats_path): + try: + if path is not None: + Path(path).unlink(missing_ok=True) + except OSError: + log.exception("could not remove %s", path) + + +def downsample2(image: np.ndarray) -> np.ndarray: + """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] + + +def matlab_round(x: ArrayLike) -> np.ndarray: + """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) + + +def rec_neg_err(movie_ds: np.ndarray, align_hz: float) -> np.ndarray: + """Per-frame negative reconstruction error (MultiRoiRegistration). + + 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 + 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. + align_hz : float + Frame rate. + + Returns + ------- + ndarray of float64 + (frames,) errors. + """ + n = movie_ds.shape[0] + out = np.full(n, np.nan) + offset = np.float32(10) + n_chunks = int(np.ceil(n / (align_hz * 10))) + edges = matlab_round(np.linspace(1, n + 1, n_chunks + 1)).astype(int) + for a, b in zip(edges[:-1] - 1, edges[1:] - 1): + chunk = movie_ds[a:b] + with np.errstate(all="ignore"), warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + template = np.nanmedian(chunk, axis=0).astype(np.float32) + nan_frac = np.isnan(chunk).mean(0) + template[nan_frac > 0.2] = np.nan + gamma = np.sqrt(np.maximum(0, template) + offset) + excess = (template - chunk) / gamma + num = np.where(np.isnan(excess), 0, np.maximum(0, excess)) ** 2 + den = (template / gamma) ** 2 + chunk * 0 + den_mean = np.nanmean(den.reshape(den.shape[0], -1), axis=1) + num_mean = num.reshape(num.shape[0], -1).mean(axis=1) + out[a:b] = np.sqrt(num_mean / den_mean) + return out diff --git a/src/giant_python/registration/sources.py b/src/giant_python/registration/sources.py index e985f921..71fe2b8c 100644 --- a/src/giant_python/registration/sources.py +++ b/src/giant_python/registration/sources.py @@ -1,421 +1,421 @@ -"""Frames in the registration window, with or without online compensation. - -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: - -* :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= - - -Spine size viewer - - - -
-
-

Spine size viewer

- - - - loading… - -
-
- - - - - - - - -
-
- - - - - keys: ←/→ trial, a mean, n/p next/previous source, r other product, g/s/u/x mark, c clear -
-
-
-
-
-
-
- -
-
-
-
- -
-
-
-
-
- -
-
-
-
- -
-
-
Mark
-
- - - - - - - -
-
-
-
-
-
-
- What is shown -
    -
  • Size: each source's readout of a per-trial image in its fixed window (the mean footprint over the pixels with a value in every trial), normalized as spineTrends.m: log, minus each trial's median over the sources, minus the source's own mean; shown as % against that mean.
  • -
  • Call: a change beyond the shared trend with q ≤ the FDR level and at least the summary's minimum change (10% by default); the table opens sorted by calls, then by that q. ch2 % (or the run's other structural channel): that channel's change beyond its own trend at the same split; a change of a spine's volume shows there too, a change of the indicator's brightness does not (a change of focus does). align px: how much the window moves between trials beyond the trial's overall shift (spread across trials); a change at a source with a large value depends more on the alignment.
  • -
  • Step: the largest t of a change between the trials before and after a split (after trial: the last trial before it); brief: the strongest change of 1–3 trials that comes back, against the 2 trials on each side; beyond trend: the step test once the source's part of the shared trend (first singular vector over the sources) is removed. p from random trial orders of the source, q from Benjamini–Hochberg per path; bold where q ≤ the FDR level.
  • -
  • Field: each trial divided by its median (bleach-normalized), or their mean. Change: trials blurred 0.7 px, against the mean of all trials or the previous trial in the same block of consecutive acquisitions; at the mean, the last block against the earlier ones (one block: second half against first); brightness follows the mean image. Activity: the run's activity image as a robust z.
  • -
  • Crops: the window (footprint weights; contours at 50% and 10% of the peak; hatched: pixels left out because some trial has no value there), then the mean and every trial, on one contrast.
  • -
  • Marks belong to a position and attach to the nearest source within 2.5 px, in any product of the session.
  • -
-
-
-
-
- - - + + + + + +Spine size viewer + + + +
+
+

Spine size viewer

+ + + + loading… + +
+
+ + + + + + + + +
+
+ + + + + keys: ←/→ trial, a mean, n/p next/previous source, r other product, g/s/u/x mark, c clear +
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ +
+
+
+
+ +
+
+
Mark
+
+ + + + + + + +
+
+
+
+
+
+
+ What is shown +
    +
  • Size: each source's readout of a per-trial image in its fixed window (the mean footprint over the pixels with a value in every trial), normalized as spineTrends.m: log, minus each trial's median over the sources, minus the source's own mean; shown as % against that mean.
  • +
  • Call: a change beyond the shared trend with q ≤ the FDR level and at least the summary's minimum change (10% by default); the table opens sorted by calls, then by that q. ch2 % (or the run's other structural channel): that channel's change beyond its own trend at the same split; a change of a spine's volume shows there too, a change of the indicator's brightness does not (a change of focus does). align px: how much the window moves between trials beyond the trial's overall shift (spread across trials); a change at a source with a large value depends more on the alignment.
  • +
  • Step: the largest t of a change between the trials before and after a split (after trial: the last trial before it); brief: the strongest change of 1–3 trials that comes back, against the 2 trials on each side; beyond trend: the step test once the source's part of the shared trend (first singular vector over the sources) is removed. p from random trial orders of the source, q from Benjamini–Hochberg per path; bold where q ≤ the FDR level.
  • +
  • Field: each trial divided by its median (bleach-normalized), or their mean. Change: trials blurred 0.7 px, against the mean of all trials or the previous trial in the same block of consecutive acquisitions; at the mean, the last block against the earlier ones (one block: second half against first); brightness follows the mean image. Activity: the run's activity image as a robust z.
  • +
  • Crops: the window (footprint weights; contours at 50% and 10% of the peak; hatched: pixels left out because some trial has no value there), then the mean and every trial, on one contrast.
  • +
  • Marks belong to a position and attach to the nearest source within 2.5 px, in any product of the session.
  • +
+
+
+
+
+ + + diff --git a/src/giant_python/spine/view/server.py b/src/giant_python/spine/view/server.py index f7fd7db6..d2df8042 100644 --- a/src/giant_python/spine/view/server.py +++ b/src/giant_python/spine/view/server.py @@ -1,398 +1,398 @@ -"""giant spine view: a local page for spine sizes, trends and marks. - -giant spine view PRODUCT [PRODUCT ...] --marks spine_marks.csv serves -http://127.0.0.1:8790 (one page, :data:`PAGE`) for one or more -spine_summary files of a session (:mod:`.data`): the field with the -sources, per-trial crops of the selected source, its size over the trials -in every image with the shared trend and its activity, a sortable table of -the trend tests, and marks written at once to the CSV. Several products -(runs or readout variants) are compared by switching between them at the -same path, trial, view and nearest source. - -API (used by the page): GET /api/meta, /api/sources?prod=&path=, -``/api/field?prod=&path=&image=&trial=&view=image|change|activity&vs=`` -(float32 layers x rows x cols, shape in X-Shape), -/api/roi?prod=&path=&id= (JSON), /api/crops?prod=&path=&id=&image= -&view=&vs= (float32 layers x tiles x s x s); POST /api/mark -(JSON {prod, path, id, label, note}; label null keeps the -source's label and sets the note). -""" - -from __future__ import annotations - -import argparse -import json -import socket -import threading -import webbrowser -from collections.abc import Callable, Iterable -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse - -import numpy as np - -from .data import SpineStore - -PAGE = Path(__file__).with_name("page.html") -DEFAULT_PORT = 8790 - - -def json_safe(o: object) -> object: - """``o`` with non-finite floats as None (the browser rejects NaN). - - Returns - ------- - object - o with non-finite floats replaced by None, and dicts, lists, tuples and numpy - scalars converted to JSON-compatible Python values (recursively). - """ - if isinstance(o, float): - return o if np.isfinite(o) else None - if isinstance(o, dict): - return {str(k): json_safe(v) for k, v in o.items()} - if isinstance(o, (list, tuple)): - return [json_safe(v) for v in o] - if isinstance(o, np.generic): - return json_safe(o.item()) - return o - - -def route( - store: SpineStore, path: str, q: dict[str, str] -) -> tuple[str, dict | np.ndarray, dict[str, str]]: - """Answer one GET request: (kind, payload, headers). - - Returns - ------- - kind : str - "json" or "bin". - payload : dict or np.ndarray - The JSON-serializable answer for "json", or the float32 array for "bin". - headers : dict[str, str] - Extra response headers (X-Shape for arrays). - - Raises - ------ - LookupError - If the path is not one of the API's GET routes. - """ - if path == "/api/meta": - return "json", store.meta(), {} - i = int(q.get("prod", 0)) - if path == "/api/sources": - return "json", store.sources(i, int(q["path"])), {} - if path == "/api/field": - img = store.product(i).field( - int(q["path"]), - q.get("image", ""), - int(q.get("trial", -1)), - q.get("view", "image"), - q.get("vs", "average"), - ) - return "bin", img, {"X-Shape": json.dumps(list(img.shape))} - if path == "/api/roi": - return "json", store.roi(i, int(q["path"]), int(q["id"])), {} - if path == "/api/crops": - a = store.crops( - i, - int(q["path"]), - int(q["id"]), - q["image"], - q.get("view", "image"), - q.get("vs", "average"), - ) - return "bin", a, {"X-Shape": json.dumps(list(a.shape))} - raise LookupError(path) - - -class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of store (set by :func:`make_handler`). - - Every request must name a trusted host (allowed, set by - :func:`make_server`: the loopback names and the bound host at the - server's port), so that a page reaching the server through DNS - rebinding (its own name resolving to 127.0.0.1) gets nothing; marks - must also come as JSON from a trusted origin. - """ - - store: SpineStore - allowed: frozenset = frozenset() - - def log_message(self, *a: object) -> None: - """Quiet.""" - - def _send( - self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None - ) -> None: - """Send one response.""" - self.send_response(code) - self.send_header("Content-Type", ctype) - self.send_header("Content-Length", str(len(body))) - self.send_header("Cache-Control", "no-store") - for k, v in (headers or {}).items(): - self.send_header(k, v) - self.end_headers() - self.wfile.write(body) - - def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: - """Send JSON (non-finite floats as null).""" - body = json.dumps(json_safe(obj), allow_nan=False).encode() - self._send(code, body, "application/json", headers) - - def _guard(self, fn: Callable[[], None]) -> None: - """Run fn and answer errors as JSON.""" - try: - fn() - except (KeyError, ValueError) as e: - self._json({"error": f"{type(e).__name__}: {e}"}, 400) - except LookupError as e: - self._json({"error": f"not found: {e}"}, 404) - except (BrokenPipeError, ConnectionResetError): - pass - except Exception as e: # noqa: BLE001 (shown on the page) - self._json({"error": f"{type(e).__name__}: {e}"}, 500) - - def _untrusted_host(self) -> bool: - """Whether the request's Host is not one of allowed. - - An empty allowed trusts every host: a server bound to all - interfaces. - - Returns - ------- - bool - True if allowed is non-empty and the request's Host is not in it. - """ - if not self.allowed: - return False - return self.headers.get("Host", "").lower() not in self.allowed - - 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() -> None: - """Answer it.""" - if self._untrusted_host(): - self._json({"error": "untrusted Host"}, 403) - return - if u.path in ("/", "/index.html"): - self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") - return - kind, payload, headers = route(self.store, u.path, q) - if kind == "json": - self._json(payload, headers=headers) - return - body = np.ascontiguousarray(payload, np.float32).tobytes() - self._send(200, body, "application/octet-stream", headers) - - self._guard(go) - - def _cross_origin(self) -> bool: - """Whether the request comes from a page of another origin. - - That is, its Origin (or Referer) is not http:// and a - trusted host (with allowed empty, not the request's own Host). - - Returns - ------- - bool - True if the request has an Origin or Referer from another origin. - """ - src = self.headers.get("Origin") or self.headers.get("Referer") - if not src: - return False - o = urlparse(src) - if o.scheme != "http": - return True - if self.allowed: - return o.netloc.lower() not in self.allowed - return o.netloc.lower() != self.headers.get("Host", "").lower() - - def do_POST(self) -> None: - """Set a mark (JSON from a page of this server only). - - A page of another origin cannot send JSON without a preflight, which - this server does not answer, and its Origin is refused. - """ - u = urlparse(self.path) - - def go() -> None: - """Answer it. - - Raises - ------ - LookupError - If the path is not /api/mark. - """ - if self._untrusted_host(): - self._json({"error": "untrusted Host"}, 403) - return - if u.path != "/api/mark": - raise LookupError(u.path) - ctype = self.headers.get("Content-Type", "") - if ctype.split(";")[0].strip().lower() != "application/json": - self._json({"error": "marks take application/json"}, 415) - return - if self._cross_origin(): - self._json({"error": "marks only from this server's page"}, 403) - return - n = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(n) or b"{}") - marks = self.store.set_mark( - int(body.get("prod", 0)), - int(body["path"]), - int(body["id"]), - (None if body.get("label", "") is None else str(body.get("label", ""))), - str(body.get("note", "")), - row=body.get("row"), - col=body.get("col"), - ) - self._json(marks) - - self._guard(go) - - -def make_handler(store: SpineStore) -> type[_Handler]: - """Build the request handler class serving store. - - Returns - ------- - type[_Handler] - A subclass of the handler with store set. - """ - return type("Handler", (_Handler,), {"store": store}) - - -_LOOPBACK = ("127.0.0.1", "localhost", "[::1]") - - -def make_server( - store: SpineStore, host: str = "127.0.0.1", port: int = DEFAULT_PORT -) -> ThreadingHTTPServer: - """Create an HTTP server for store (not started). - - It answers only requests whose Host is a loopback name or host - at the bound port; bound to all interfaces (0.0.0.0, ::), it - trusts every host name. - - Returns - ------- - ThreadingHTTPServer - The server, bound but not serving. - """ - handler = make_handler(store) - cls = _Server6 if ":" in host else ThreadingHTTPServer - srv = cls((host.strip("[]"), port), handler) - handler.allowed = allowed_hosts(host, srv.server_address[1]) - return srv - - -def allowed_hosts(host: str, port: int) -> frozenset: - """Return the Host values a server bound to host and port trusts. - - These are the loopback names and host, with the port (and without - it at port 80, which browsers leave out); empty (every name) when - bound to all interfaces. - - Returns - ------- - frozenset - The trusted Host header values, lower case; empty when every name is trusted. - """ - if host in ("0.0.0.0", "::", "[::]", ""): - return frozenset() - names = {_bracket(h) for h in set(_LOOPBACK) | {host.lower()}} - allowed = {f"{h}:{port}" for h in names} - if port == 80: - allowed |= names - return frozenset(allowed) - - -class _Server6(ThreadingHTTPServer): - """The threading server on an IPv6 address.""" - - address_family = socket.AF_INET6 - - -def _bracket(host: str) -> str: - """Put an IPv6 literal in brackets, as URLs and Host headers write it. - - Returns - ------- - str - host in brackets if it is an IPv6 literal, otherwise host unchanged. - """ - host = host.strip("[]") - return f"[{host}]" if ":" in host else host - - -def product_args(items: Iterable[str | Path]) -> list[tuple[str | None, str | Path]]: - """NAME=FILE or FILE arguments as (name, file). - - Returns - ------- - list[tuple[str | None, str | Path]] - One (name, file) pair per argument; name is None when the argument has no - NAME= prefix (or is an existing file path containing =). - """ - out = [] - for item in items: - name, sep, f = str(item).partition("=") - if sep and name and not Path(item).exists(): - out.append((name, f)) - else: - out.append((None, item)) - return out - - -def add_arguments(p: argparse.ArgumentParser) -> None: - """``giant spine view``'s options.""" - p.add_argument( - "products", - nargs="+", - metavar="PRODUCT", - help="spine_summary_.h5 files of one session, optionally as " - "NAME=FILE; several are compared", - ) - p.add_argument( - "--marks", - default=None, - help="spine_marks.csv to read and write (created on the first " - "mark; without it the page cannot mark)", - ) - p.add_argument( - "--crop-half", - type=int, - default=9, - help="half-width of the per-trial crops, px (default 9)", - ) - 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") - - -def serve(args: argparse.Namespace) -> int: - """Run giant spine view until interrupted. - - Returns - ------- - int - Exit status, 0 once the server has stopped. - """ - store = SpineStore(product_args(args.products), args.marks, crop_half=args.crop_half) - server = make_server(store, args.host, args.port) - url = f"http://{_bracket(args.host)}:{server.server_address[1]}/" - names = ", ".join(p.name for p in store.products) - print(f"spine viewer: {names}; serving {url} (Ctrl+C to stop)", flush=True) - if not args.no_browser: - threading.Timer(0.5, lambda: webbrowser.open(url)).start() - try: - server.serve_forever() - except KeyboardInterrupt: - pass - finally: - server.server_close() - return 0 +"""giant spine view: a local page for spine sizes, trends and marks. + +giant spine view PRODUCT [PRODUCT ...] --marks spine_marks.csv serves +http://127.0.0.1:8790 (one page, :data:`PAGE`) for one or more +spine_summary files of a session (:mod:`.data`): the field with the +sources, per-trial crops of the selected source, its size over the trials +in every image with the shared trend and its activity, a sortable table of +the trend tests, and marks written at once to the CSV. Several products +(runs or readout variants) are compared by switching between them at the +same path, trial, view and nearest source. + +API (used by the page): GET /api/meta, /api/sources?prod=&path=, +``/api/field?prod=&path=&image=&trial=&view=image|change|activity&vs=`` +(float32 layers x rows x cols, shape in X-Shape), +/api/roi?prod=&path=&id= (JSON), /api/crops?prod=&path=&id=&image= +&view=&vs= (float32 layers x tiles x s x s); POST /api/mark +(JSON {prod, path, id, label, note}; label null keeps the +source's label and sets the note). +""" + +from __future__ import annotations + +import argparse +import json +import socket +import threading +import webbrowser +from collections.abc import Callable, Iterable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +import numpy as np + +from .data import SpineStore + +PAGE = Path(__file__).with_name("page.html") +DEFAULT_PORT = 8790 + + +def json_safe(o: object) -> object: + """``o`` with non-finite floats as None (the browser rejects NaN). + + Returns + ------- + object + o with non-finite floats replaced by None, and dicts, lists, tuples and numpy + scalars converted to JSON-compatible Python values (recursively). + """ + if isinstance(o, float): + return o if np.isfinite(o) else None + if isinstance(o, dict): + return {str(k): json_safe(v) for k, v in o.items()} + if isinstance(o, (list, tuple)): + return [json_safe(v) for v in o] + if isinstance(o, np.generic): + return json_safe(o.item()) + return o + + +def route( + store: SpineStore, path: str, q: dict[str, str] +) -> tuple[str, dict | np.ndarray, dict[str, str]]: + """Answer one GET request: (kind, payload, headers). + + Returns + ------- + kind : str + "json" or "bin". + payload : dict or np.ndarray + The JSON-serializable answer for "json", or the float32 array for "bin". + headers : dict[str, str] + Extra response headers (X-Shape for arrays). + + Raises + ------ + LookupError + If the path is not one of the API's GET routes. + """ + if path == "/api/meta": + return "json", store.meta(), {} + i = int(q.get("prod", 0)) + if path == "/api/sources": + return "json", store.sources(i, int(q["path"])), {} + if path == "/api/field": + img = store.product(i).field( + int(q["path"]), + q.get("image", ""), + int(q.get("trial", -1)), + q.get("view", "image"), + q.get("vs", "average"), + ) + return "bin", img, {"X-Shape": json.dumps(list(img.shape))} + if path == "/api/roi": + return "json", store.roi(i, int(q["path"]), int(q["id"])), {} + if path == "/api/crops": + a = store.crops( + i, + int(q["path"]), + int(q["id"]), + q["image"], + q.get("view", "image"), + q.get("vs", "average"), + ) + return "bin", a, {"X-Shape": json.dumps(list(a.shape))} + raise LookupError(path) + + +class _Handler(BaseHTTPRequestHandler): + """Serves the page and the API of store (set by :func:`make_handler`). + + Every request must name a trusted host (allowed, set by + :func:`make_server`: the loopback names and the bound host at the + server's port), so that a page reaching the server through DNS + rebinding (its own name resolving to 127.0.0.1) gets nothing; marks + must also come as JSON from a trusted origin. + """ + + store: SpineStore + allowed: frozenset = frozenset() + + def log_message(self, *a: object) -> None: + """Quiet.""" + + def _send( + self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None + ) -> None: + """Send one response.""" + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: + """Send JSON (non-finite floats as null).""" + body = json.dumps(json_safe(obj), allow_nan=False).encode() + self._send(code, body, "application/json", headers) + + def _guard(self, fn: Callable[[], None]) -> None: + """Run fn and answer errors as JSON.""" + try: + fn() + except (KeyError, ValueError) as e: + self._json({"error": f"{type(e).__name__}: {e}"}, 400) + except LookupError as e: + self._json({"error": f"not found: {e}"}, 404) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception as e: # noqa: BLE001 (shown on the page) + self._json({"error": f"{type(e).__name__}: {e}"}, 500) + + def _untrusted_host(self) -> bool: + """Whether the request's Host is not one of allowed. + + An empty allowed trusts every host: a server bound to all + interfaces. + + Returns + ------- + bool + True if allowed is non-empty and the request's Host is not in it. + """ + if not self.allowed: + return False + return self.headers.get("Host", "").lower() not in self.allowed + + 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() -> None: + """Answer it.""" + if self._untrusted_host(): + self._json({"error": "untrusted Host"}, 403) + return + if u.path in ("/", "/index.html"): + self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") + return + kind, payload, headers = route(self.store, u.path, q) + if kind == "json": + self._json(payload, headers=headers) + return + body = np.ascontiguousarray(payload, np.float32).tobytes() + self._send(200, body, "application/octet-stream", headers) + + self._guard(go) + + def _cross_origin(self) -> bool: + """Whether the request comes from a page of another origin. + + That is, its Origin (or Referer) is not http:// and a + trusted host (with allowed empty, not the request's own Host). + + Returns + ------- + bool + True if the request has an Origin or Referer from another origin. + """ + src = self.headers.get("Origin") or self.headers.get("Referer") + if not src: + return False + o = urlparse(src) + if o.scheme != "http": + return True + if self.allowed: + return o.netloc.lower() not in self.allowed + return o.netloc.lower() != self.headers.get("Host", "").lower() + + def do_POST(self) -> None: + """Set a mark (JSON from a page of this server only). + + A page of another origin cannot send JSON without a preflight, which + this server does not answer, and its Origin is refused. + """ + u = urlparse(self.path) + + def go() -> None: + """Answer it. + + Raises + ------ + LookupError + If the path is not /api/mark. + """ + if self._untrusted_host(): + self._json({"error": "untrusted Host"}, 403) + return + if u.path != "/api/mark": + raise LookupError(u.path) + ctype = self.headers.get("Content-Type", "") + if ctype.split(";")[0].strip().lower() != "application/json": + self._json({"error": "marks take application/json"}, 415) + return + if self._cross_origin(): + self._json({"error": "marks only from this server's page"}, 403) + return + n = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(n) or b"{}") + marks = self.store.set_mark( + int(body.get("prod", 0)), + int(body["path"]), + int(body["id"]), + (None if body.get("label", "") is None else str(body.get("label", ""))), + str(body.get("note", "")), + row=body.get("row"), + col=body.get("col"), + ) + self._json(marks) + + self._guard(go) + + +def make_handler(store: SpineStore) -> type[_Handler]: + """Build the request handler class serving store. + + Returns + ------- + type[_Handler] + A subclass of the handler with store set. + """ + return type("Handler", (_Handler,), {"store": store}) + + +_LOOPBACK = ("127.0.0.1", "localhost", "[::1]") + + +def make_server( + store: SpineStore, host: str = "127.0.0.1", port: int = DEFAULT_PORT +) -> ThreadingHTTPServer: + """Create an HTTP server for store (not started). + + It answers only requests whose Host is a loopback name or host + at the bound port; bound to all interfaces (0.0.0.0, ::), it + trusts every host name. + + Returns + ------- + ThreadingHTTPServer + The server, bound but not serving. + """ + handler = make_handler(store) + cls = _Server6 if ":" in host else ThreadingHTTPServer + srv = cls((host.strip("[]"), port), handler) + handler.allowed = allowed_hosts(host, srv.server_address[1]) + return srv + + +def allowed_hosts(host: str, port: int) -> frozenset: + """Return the Host values a server bound to host and port trusts. + + These are the loopback names and host, with the port (and without + it at port 80, which browsers leave out); empty (every name) when + bound to all interfaces. + + Returns + ------- + frozenset + The trusted Host header values, lower case; empty when every name is trusted. + """ + if host in ("0.0.0.0", "::", "[::]", ""): + return frozenset() + names = {_bracket(h) for h in set(_LOOPBACK) | {host.lower()}} + allowed = {f"{h}:{port}" for h in names} + if port == 80: + allowed |= names + return frozenset(allowed) + + +class _Server6(ThreadingHTTPServer): + """The threading server on an IPv6 address.""" + + address_family = socket.AF_INET6 + + +def _bracket(host: str) -> str: + """Put an IPv6 literal in brackets, as URLs and Host headers write it. + + Returns + ------- + str + host in brackets if it is an IPv6 literal, otherwise host unchanged. + """ + host = host.strip("[]") + return f"[{host}]" if ":" in host else host + + +def product_args(items: Iterable[str | Path]) -> list[tuple[str | None, str | Path]]: + """NAME=FILE or FILE arguments as (name, file). + + Returns + ------- + list[tuple[str | None, str | Path]] + One (name, file) pair per argument; name is None when the argument has no + NAME= prefix (or is an existing file path containing =). + """ + out = [] + for item in items: + name, sep, f = str(item).partition("=") + if sep and name and not Path(item).exists(): + out.append((name, f)) + else: + out.append((None, item)) + return out + + +def add_arguments(p: argparse.ArgumentParser) -> None: + """``giant spine view``'s options.""" + p.add_argument( + "products", + nargs="+", + metavar="PRODUCT", + help="spine_summary_.h5 files of one session, optionally as " + "NAME=FILE; several are compared", + ) + p.add_argument( + "--marks", + default=None, + help="spine_marks.csv to read and write (created on the first " + "mark; without it the page cannot mark)", + ) + p.add_argument( + "--crop-half", + type=int, + default=9, + help="half-width of the per-trial crops, px (default 9)", + ) + 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") + + +def serve(args: argparse.Namespace) -> int: + """Run giant spine view until interrupted. + + Returns + ------- + int + Exit status, 0 once the server has stopped. + """ + store = SpineStore(product_args(args.products), args.marks, crop_half=args.crop_half) + server = make_server(store, args.host, args.port) + url = f"http://{_bracket(args.host)}:{server.server_address[1]}/" + names = ", ".join(p.name for p in store.products) + print(f"spine viewer: {names}; serving {url} (Ctrl+C to stop)", flush=True) + if not args.no_browser: + threading.Timer(0.5, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 diff --git a/src/giant_python/viewer/__init__.py b/src/giant_python/viewer/__init__.py index e880bba2..985b1fe6 100644 --- a/src/giant_python/viewer/__init__.py +++ b/src/giant_python/viewer/__init__.py @@ -1,7 +1,7 @@ -"""Browser viewer of SILo runs (giant view). - -:mod:`~giant_python.viewer.run` reads a run's summaries, -:mod:`~giant_python.viewer.render` renders its fitted activity in a -trial's registered 80 Hz movie, and :mod:`~giant_python.viewer.server` -serves the page (page.html). -""" +"""Browser viewer of SILo runs (giant view). + +:mod:`~giant_python.viewer.run` reads a run's summaries, +:mod:`~giant_python.viewer.render` renders its fitted activity in a +trial's registered 80 Hz movie, and :mod:`~giant_python.viewer.server` +serves the page (page.html). +""" diff --git a/src/giant_python/viewer/page.html b/src/giant_python/viewer/page.html index 16533dbf..815d4733 100644 --- a/src/giant_python/viewer/page.html +++ b/src/giant_python/viewer/page.html @@ -1,1086 +1,1086 @@ - - - - - -SILo run viewer - - - -
-
-

SILo run viewer

- - - - - loading… - -
-
- -
- - - - - - - - - - -
-
Over the images: scroll zooms · drag pans · click a marker for the source · double-click fits. - Markers:
- - - - - - - -
-
-
-
-
-
-

Source

Click a marker or a table row.

-
-
-
-
Source tracespick a kept source - 200 Hz, all trials (grey lines: trial boundaries) · scroll zooms time · drag pans · double-click shows everything
-
-
dF: least squares and denoised (the fit) (raw counts, footprint units)
-
-
Events (the denoised dF is their convolution with the indicator kernel)
-
-
F0 (raw counts, footprint units)
-
-
-
-
- -
- What the panels show -
    -
  • Activity image (Sources view): SILo's combined activity image of the path on its consensus canvas (all trials), or one trial's, as in experiment_summary.h5 and per_trial_summary.h5. Markers sit at the kept sources' footprint centroids, the kinetics-rejected sources' pixels and, when the run kept its plan, the seeds whose pixel got no source.
  • -
  • Aligned movie (Movie view): the trial's registered 80 Hz movie (*_REGISTERED_DOWNSAMPLED-80Hz, activity channel) in the trial's own registered frame, not resampled. Blank (NaN) at SILo's motion discards and at frames whose kernel weight lies mostly on SILo's discarded 200 Hz frames; only pixels missing in less than nanThresh of the frames, counting the motion discards (as SILo's trial loader and the exporter count them), are shown.
  • -
  • Fitted activity: every kept source's footprint times its denoised trace (dF_denoised), rendered in the movie's pixels and frames following the F0 network's training-data exporter. Time: each 80 Hz frame averages SILo's 200 Hz traces at its frame lines with weights exp(−|Δline| / dt) within max(3 dt, P) lines (P: lines per cycle), leaving out SILo's discarded frames. With the exporter's kernel (the one the current F0 training targets were made with) dt is the movie's own (ceil(mean(diff(DSframes))), 134 lines on these rigs), as the training-data exporter does; but the 200 Hz frames are themselves averages (dt200 = 54 lines), so this smooths fast events twice and keeps 93–95% of an event's 80 Hz peak on noiseless injected events. The matched kernel (the default) uses √(dt² − dt200²) (≈ 123 lines) and keeps 97–99%. The Time kernel menu switches between them. Space: the trial's footprints are moved from the consensus canvas into the trial's frame through the trial's across-trial map (rigid, affine or patchwise), bilinearly; the exporter instead searched a rigid offset per trial by correlation and blurred the footprints to match the movie's shape (here a fixed blur, 0 unless the server was started with --blur). Kinetics-rejected sources are not included (their traces are not in the summary).
  • -
  • Residual = aligned movie − fitted activity: what a training target made from this run would be. Residual − baseline = movie − activity − the F0 network's baseline (only with --baseline-dir).
  • -
  • Units: raw counts of the registered movie (each pixel's weighted mean of its raw SLAP2 samples); SILo's traces and F0 are in the same units (footprints sum to 1, so a trace is the source's total over its footprint).
  • -
-
-
-
- - - + + + + + +SILo run viewer + + + +
+
+

SILo run viewer

+ + + + + loading… + +
+
+ +
+ + + + + + + + + + +
+
Over the images: scroll zooms · drag pans · click a marker for the source · double-click fits. + Markers:
+ + + + + + + +
+
+
+
+
+
+

Source

Click a marker or a table row.

+
+
+
+
Source tracespick a kept source + 200 Hz, all trials (grey lines: trial boundaries) · scroll zooms time · drag pans · double-click shows everything
+
+
dF: least squares and denoised (the fit) (raw counts, footprint units)
+
+
Events (the denoised dF is their convolution with the indicator kernel)
+
+
F0 (raw counts, footprint units)
+
+
+
+
+ +
+ What the panels show +
    +
  • Activity image (Sources view): SILo's combined activity image of the path on its consensus canvas (all trials), or one trial's, as in experiment_summary.h5 and per_trial_summary.h5. Markers sit at the kept sources' footprint centroids, the kinetics-rejected sources' pixels and, when the run kept its plan, the seeds whose pixel got no source.
  • +
  • Aligned movie (Movie view): the trial's registered 80 Hz movie (*_REGISTERED_DOWNSAMPLED-80Hz, activity channel) in the trial's own registered frame, not resampled. Blank (NaN) at SILo's motion discards and at frames whose kernel weight lies mostly on SILo's discarded 200 Hz frames; only pixels missing in less than nanThresh of the frames, counting the motion discards (as SILo's trial loader and the exporter count them), are shown.
  • +
  • Fitted activity: every kept source's footprint times its denoised trace (dF_denoised), rendered in the movie's pixels and frames following the F0 network's training-data exporter. Time: each 80 Hz frame averages SILo's 200 Hz traces at its frame lines with weights exp(−|Δline| / dt) within max(3 dt, P) lines (P: lines per cycle), leaving out SILo's discarded frames. With the exporter's kernel (the one the current F0 training targets were made with) dt is the movie's own (ceil(mean(diff(DSframes))), 134 lines on these rigs), as the training-data exporter does; but the 200 Hz frames are themselves averages (dt200 = 54 lines), so this smooths fast events twice and keeps 93–95% of an event's 80 Hz peak on noiseless injected events. The matched kernel (the default) uses √(dt² − dt200²) (≈ 123 lines) and keeps 97–99%. The Time kernel menu switches between them. Space: the trial's footprints are moved from the consensus canvas into the trial's frame through the trial's across-trial map (rigid, affine or patchwise), bilinearly; the exporter instead searched a rigid offset per trial by correlation and blurred the footprints to match the movie's shape (here a fixed blur, 0 unless the server was started with --blur). Kinetics-rejected sources are not included (their traces are not in the summary).
  • +
  • Residual = aligned movie − fitted activity: what a training target made from this run would be. Residual − baseline = movie − activity − the F0 network's baseline (only with --baseline-dir).
  • +
  • Units: raw counts of the registered movie (each pixel's weighted mean of its raw SLAP2 samples); SILo's traces and F0 are in the same units (footprints sum to 1, so a trace is the source's total over its footprint).
  • +
+
+
+
+ + + diff --git a/src/giant_python/viewer/render.py b/src/giant_python/viewer/render.py index 6cffa85d..2ebac199 100644 --- a/src/giant_python/viewer/render.py +++ b/src/giant_python/viewer/render.py @@ -1,518 +1,518 @@ -"""SILo's fitted activity rendered in a trial's registered 80 Hz movie. - -The rendering follows the F0 network's training-data exporter -(exportF0TrainingData.m in slap2-F0-network), so that the movie minus -the rendered activity is what a training target made from the run would -be, with these changes: - -* **Time.** An 80 Hz frame is the registration's weighted mean of the - samples within max(3 dt, P) lines of its line, with weights - ``exp(-|dline| / dt)``, dt = ceil(mean(diff(DSframes))) lines and - P the recording's lines per cycle. The 200 Hz traces are averaged - at SILo's frame lines with such weights, leaving out SILo's discarded - frames (:func:`frame_weights`); an 80 Hz frame whose weight falls more - than half on discarded 200 Hz frames is discarded. The exporter uses - the movie's dt; since the 200 Hz frames are already averages, the - viewer's default narrows it to sqrt(dt**2 - dt200**2) - (:func:`~giant_python.viewer.trial.render_dt`). The exact kernel - (:func:`exact_weights`) undoes the double smoothing exactly for - densely sampled frames: r x200(line) + (1 - r) times the exporter's - average, r = (dt200 / dt80)**2 (:func:`kernel_weights` chooses). -* **Space.** Footprints live on SILo's consensus canvas; each trial's - footprints are moved into the trial's registered frame through the - trial's across-trial map (rigid, affine or patchwise), the one SILo read - the trial's data with: the trial-frame footprint at pixel q is the - canvas footprint at the map's inverse of q, interpolated bilinearly - (:class:`TrialMap`, :func:`place_footprints`). The exporter instead - searches each trial's offset (integer offset of the mean images plus a - sub-pixel search that maximizes the movie-activity correlation at the - source peaks) and applies it to the canvas as a rigid shift. -* **Blur.** Optionally a Gaussian blur of the moved footprints (the - exporter chooses one per trial by matching the movie's core and ring - slopes; here it is a fixed setting, 0 by default). -* **Scale.** None: the activity is SILo's footprints (each sums to 1) - times its denoised traces (dF_denoised, movie units), as the - exporter writes it (activityGain 1). -""" - -from __future__ import annotations - -import math - -import numpy as np -from numpy.typing import ArrayLike -from scipy import sparse -from scipy.ndimage import gaussian_filter, map_coordinates - - -def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float) -> int: - """Return the kernel's time constant in lines (the exporter's dt). - - ceil(mean(diff(DSframes))); with one registered frame, the 200 Hz - frame spacing times ratio (analysis rate over movie rate). - - Returns - ------- - int - The kernel's time constant in lines. - """ - ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel() - if ds_lines.size > 1: - return math.ceil(np.mean(np.diff(ds_lines))) - step = np.median(np.diff(np.asarray(lines200, dtype=np.float64))) - return math.ceil(step * ratio) - - -def frame_weights( - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt: int, - reach: float, -) -> tuple[sparse.csc_matrix, np.ndarray]: - """Weights that average 200 Hz frames into the movie's 80 Hz frames. - - Parameters - ---------- - lines200 : ndarray, shape (n200,) - SILo's frame lines of the trial (one-based, increasing). - discard200 : ndarray of bool, shape (n200,) - SILo's discarded frames. - ds_lines : ndarray, shape (n80,) - The registered frames' lines (DSframes). - dt : int - Kernel time constant in lines. - reach : float - Frames within this many lines count (max(3 dt, P)). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - Each 80 Hz frame's weights over the kept 200 Hz frames (columns sum - to 1, or are empty). - discard_share : ndarray, shape (n80,) - Share of each frame's weight on discarded 200 Hz frames (1 where - no 200 Hz frame is within reach). - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - disc = np.asarray(discard200, dtype=bool).ravel() - ds = np.asarray(ds_lines, dtype=np.float64).ravel() - lo = np.searchsorted(lines200, ds - reach, side="left") - hi = np.searchsorted(lines200, ds + reach, side="right") - ii, jj, ww = [], [], [] - share = np.ones(ds.size) - for j in range(ds.size): - idx = np.arange(lo[j], hi[j]) - if idx.size == 0: - continue - w = np.exp(-np.abs(lines200[idx] - ds[j]) / dt) - share[j] = w[disc[idx]].sum() / max(w.sum(), np.finfo(float).eps) - keep = ~disc[idx] - if keep.any(): - ii.append(idx[keep]) - jj.append(np.full(int(keep.sum()), j)) - ww.append(w[keep] / w[keep].sum()) - if ii: - ii, jj, ww = map(np.concatenate, (ii, jj, ww)) - m = sparse.csc_matrix((ww, (ii, jj)), shape=(lines200.size, ds.size)) - return m, share - - -def interp_weights( - lines200: np.ndarray, keep: np.ndarray, ds_lines: np.ndarray -) -> sparse.csc_matrix: - """Linear interpolation of the kept 200 Hz frames at the 80 Hz lines. - - Each 80 Hz frame takes the two kept 200 Hz frames around its line - (discarded frames are skipped, so a gap is bridged by its kept - neighbours); before the first or after the last kept frame, the - nearest kept frame. - - Parameters - ---------- - lines200 : ndarray, shape (n200,) - SILo's frame lines (increasing). - keep : ndarray of bool, shape (n200,) - Frames that may be used. - ds_lines : ndarray, shape (n80,) - The registered frames' lines. - - Returns - ------- - scipy.sparse.csc_matrix, shape (n200, n80) - Columns sum to 1 (all empty without a kept frame). - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - ds = np.asarray(ds_lines, dtype=np.float64).ravel() - k = np.flatnonzero(np.asarray(keep, dtype=bool).ravel()) - shape = (lines200.size, ds.size) - j = np.arange(ds.size) - if k.size == 0: - return sparse.csc_matrix(shape) - if k.size == 1: - return sparse.csc_matrix((np.ones(ds.size), (np.full(ds.size, k[0]), j)), shape=shape) - lk = lines200[k] - i = np.clip(np.searchsorted(lk, ds, side="right") - 1, 0, k.size - 2) - f = np.clip((ds - lk[i]) / (lk[i + 1] - lk[i]), 0.0, 1.0) - return sparse.csc_matrix((np.r_[1 - f, f], (np.r_[k[i], k[i + 1]], np.r_[j, j])), shape=shape) - - -def frame_dt200(lines200: np.ndarray, default: float) -> float: - """Return the 200 Hz frames' own kernel dt in lines. - - ceil(mean(diff(lines))) (default with fewer than 2 frames). - - Returns - ------- - float - The 200 Hz frames' kernel dt in lines. - """ - lines200 = np.asarray(lines200, dtype=np.float64).ravel() - if lines200.size < 2: - return float(default) - return float(math.ceil(float(np.mean(np.diff(lines200))))) - - -def exact_weights( - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt80: float, - dt200: float, - reach: float, -) -> tuple[sparse.csc_matrix, np.ndarray, float]: - """Weights that turn 200 Hz frames into the movie's 80 Hz frames without smoothing twice. - - Both frame rates are weighted means of the same samples with - ``exp(-|dline| / dt)``, whose spectrum is 1 / (1 + dt**2 w**2). - The 80 Hz frame over the 200 Hz frame is therefore (1 + dt200**2 - w**2) / (1 + dt80**2 w**2) = r + (1 - r) / (1 + dt80**2 w**2), - r = (dt200 / dt80)**2: the 80 Hz frame is r times the 200 Hz - frames interpolated at its line (:func:`interp_weights`) plus 1 - - r times their average with the movie's own kernel - (:func:`frame_weights`, the exporter's weights). Exact for densely - sampled pixels and untruncated kernels (on such data fast events keep - 0.99-1.01 of their 80 Hz peak); kernels cut at 3 dt put them 1-2% - high, and pixels sampled once per cycle deviate by about 1% either - way (noiseless injected SLAP2 events: 0.99 and 1.01 on the two paths - of the GFP copy). Discarded 200 Hz frames are left out of both terms. - - Parameters - ---------- - lines200, discard200, ds_lines, reach - As :func:`frame_weights`. - dt80, dt200 : float - The movie's and the 200 Hz frames' kernel dt (lines). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - Columns sum to 1, or are empty where no kept 200 Hz frame lies - within reach. - discard_share : ndarray, shape (n80,) - As :func:`frame_weights` (of the movie's kernel). - r : float - The interpolated term's weight. - """ - wk, share = frame_weights(lines200, discard200, ds_lines, dt80, reach) - r = min(1.0, (float(dt200) / float(dt80)) ** 2) - keep = ~np.asarray(discard200, dtype=bool).ravel() - wi = interp_weights(lines200, keep, ds_lines) - empty = np.asarray(wk.sum(0)).ravel() == 0 - if empty.any(): # nothing within reach: no activity, as frame_weights - wi = wi @ sparse.diags((~empty).astype(np.float64)) - w = (r * wi + (1.0 - r) * wk).tocsc() - w.eliminate_zeros() - return w, share, r - - -KERNELS = ("exporter", "matched", "exact") - - -def kernel_weights( - kernel: str, - lines200: np.ndarray, - discard200: np.ndarray, - ds_lines: np.ndarray, - dt80: float, - lines_per_cycle: float = 0, -) -> tuple[sparse.csc_matrix, np.ndarray, dict[str, float]]: - """Compute a time kernel's weights from a trial's 200 Hz frames to its 80 Hz frames. - - Parameters - ---------- - kernel : {"exporter", "matched", "exact"} - exporter: ``exp(-|dline| / dt80)``, the training-data - exporter's (smooths fast events twice); matched: the same with - dt = sqrt(dt80**2 - dt200**2); exact: - :func:`exact_weights`. dt200 comes from the frame lines - (:func:`frame_dt200`). - lines200, discard200, ds_lines - As :func:`frame_weights`. - dt80 : float - The movie's kernel dt (:func:`kernel_dt`). - lines_per_cycle : float - P; the kernels reach max(3 dt, P) lines (0: unknown). - - Returns - ------- - weights : scipy.sparse.csc_matrix, shape (n200, n80) - discard_share : ndarray, shape (n80,) - Share of each frame's weight on discarded 200 Hz frames under the - movie's kernel (dt80) for exporter and exact, under - the narrower kernel for matched. - info : dict - dt (the averaging kernel's), reach, dt200 and r - (the interpolated share; 0 except for exact). - - Raises - ------ - ValueError - If kernel is not one of the accepted kernels. - """ - if kernel not in KERNELS: - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - dt200 = frame_dt200(lines200, dt80) - if kernel == "matched" and np.size(lines200) >= 2: - dt = math.sqrt(max(float(dt80) ** 2 - dt200**2, 1.0)) - else: # (with fewer than 2 frames the movie's dt, as render_dt) - dt = float(dt80) - reach = max(3 * dt, float(lines_per_cycle)) - info = {"dt": dt, "reach": reach, "dt200": dt200, "r": 0.0} - if kernel == "exact": - w, share, r = exact_weights(lines200, discard200, ds_lines, dt80, dt200, reach) - info["r"] = r - return w, share, info - w, share = frame_weights(lines200, discard200, ds_lines, dt, reach) - return w, share, info - - -def _bilinear( - img: np.ndarray, r: ArrayLike, c: ArrayLike, mode: str = "nearest", cval: float = 0.0 -) -> np.ndarray: - """Bilinear samples of img at zero-based (r, c). - - Returns - ------- - np.ndarray - The samples, in the shape of r. - """ - return map_coordinates(img, [np.ravel(r), np.ravel(c)], order=1, mode=mode, cval=cval).reshape( - np.shape(r) - ) - - -class TrialMap: - """A trial's map from the consensus canvas to its registered frame. - - Zero-based pixel coordinates, as GIAnT-Python's summaries store them - (frame_info/trial_alignment_affine: [row_t, col_t] = A @ [row, - col, 1]; frame_info/trial_alignment_displacement for patchwise - maps: canvas pixel (r, c) lies at (r, c) + displacement in the - trial). With a displacement field, the field (sampled on the canvas, - interpolated bilinearly, edge values beyond it) is the map; without, - the affine map. - - Parameters - ---------- - affine : ndarray of shape (2, 3) - field : ndarray of shape (2, rows, cols), optional - """ - - def __init__(self, affine: np.ndarray, field: np.ndarray | None = None) -> None: - """Store the map.""" - self.affine = np.asarray(affine, dtype=np.float64).reshape(2, 3) - self.field = None if field is None else np.asarray(field, np.float64) - - @property - def valid(self) -> bool: - """Whether the trial has a map (it was aligned).""" - if self.field is not None: - return bool(np.isfinite(self.field).all()) - return bool(np.isfinite(self.affine).all()) - - def forward(self, r: ArrayLike, c: ArrayLike) -> tuple[np.ndarray, np.ndarray]: - """Trial-frame position of canvas positions (r, c). - - Returns - ------- - tuple[np.ndarray, np.ndarray] - The trial-frame (rows, cols) of the canvas positions. - """ - r = np.asarray(r, dtype=np.float64) - c = np.asarray(c, dtype=np.float64) - if self.field is not None: - return ( - r + _bilinear(self.field[0], r, c), - c + _bilinear(self.field[1], r, c), - ) - a = self.affine - return ( - a[0, 0] * r + a[0, 1] * c + a[0, 2], - a[1, 0] * r + a[1, 1] * c + a[1, 2], - ) - - def inverse( - self, rt: ArrayLike, ct: ArrayLike, iters: int = 20, tol: float = 1e-6 - ) -> tuple[np.ndarray, np.ndarray]: - """Canvas position of trial-frame positions (rt, ct). - - Exact for an affine map; for a displacement field the fixed point - of p = q - d(p), started at the affine map's inverse. - - Returns - ------- - tuple[np.ndarray, np.ndarray] - The canvas (rows, cols) of the trial-frame positions. - """ - rt = np.asarray(rt, dtype=np.float64) - ct = np.asarray(ct, dtype=np.float64) - a = self.affine - if not np.isfinite(a).all(): - a = np.array([[1.0, 0, 0], [0, 1.0, 0]]) - m = np.linalg.inv(a[:, :2]) - dr, dc = rt - a[0, 2], ct - a[1, 2] - r = m[0, 0] * dr + m[0, 1] * dc - c = m[1, 0] * dr + m[1, 1] * dc - if self.field is None: - return r, c - for _ in range(iters): - r_new = rt - _bilinear(self.field[0], r, c) - c_new = ct - _bilinear(self.field[1], r, c) - step = max( - float(np.max(np.abs(r_new - r), initial=0)), - float(np.max(np.abs(c_new - c), initial=0)), - ) - r, c = r_new, c_new - if step < tol: - break - return r, c - - -def _patch( - rows: np.ndarray, cols: np.ndarray, vals: np.ndarray, margin: int -) -> tuple[np.ndarray, int, int]: - """Build a footprint's dense canvas patch with a zero margin. - - Returns the patch and its origin (row, col). - - Returns - ------- - patch : np.ndarray - The dense patch of the footprint's values. - row0 : int - Canvas row of the patch's origin. - col0 : int - Canvas column of the patch's origin. - """ - r0, c0 = int(rows.min()) - margin, int(cols.min()) - margin - h = int(rows.max()) - r0 + margin + 1 - w = int(cols.max()) - c0 + margin + 1 - patch = np.zeros((h, w)) - patch[rows - r0, cols - c0] = vals - return patch, r0, c0 - - -def _place_one( - rows: np.ndarray, - cols: np.ndarray, - vals: np.ndarray, - tmap: TrialMap, - shape: tuple, - sigma: float, - interp: int = 1, -) -> tuple[np.ndarray, np.ndarray]: - """One footprint in the trial frame: flat pixel indices and values. - - Returns - ------- - indices : np.ndarray - Flat pixel indices (row-major) in the trial frame. - values : np.ndarray - The footprint's values at those pixels. - """ - margin = 2 + math.ceil(3 * sigma) + int(interp > 1) - patch, r0, c0 = _patch(rows, cols, vals, margin) - h, w = patch.shape - pr, pc = np.mgrid[r0 : r0 + h, c0 : c0 + w] - tr, tc = tmap.forward(pr, pc) - lo_r = max(0, math.floor(np.min(tr))) - hi_r = min(shape[0] - 1, math.ceil(np.max(tr))) - lo_c = max(0, math.floor(np.min(tc))) - hi_c = min(shape[1] - 1, math.ceil(np.max(tc))) - if hi_r < lo_r or hi_c < lo_c: - return np.zeros(0, np.int64), np.zeros(0) - qr, qc = np.mgrid[lo_r : hi_r + 1, lo_c : hi_c + 1] - sr, sc = tmap.inverse(qr, qc) - if interp == 1: - out = _bilinear(patch, sr - r0, sc - c0, mode="constant", cval=0.0) - else: # spline of the zero-padded patch (small negative lobes kept) - out = map_coordinates( - patch, - [np.ravel(sr - r0), np.ravel(sc - c0)], - order=interp, - mode="grid-constant", - cval=0.0, - ).reshape(sr.shape) - if sigma > 0: - out = gaussian_filter(out, sigma, mode="constant", cval=0.0) - peak = float(out.max(initial=0.0)) - if peak > 0: - ok = np.abs(out) > 1e-6 * peak - else: - ok = np.zeros(out.shape, bool) - return (qr[ok] * shape[1] + qc[ok]).astype(np.int64), out[ok] - - -def place_footprints( - footprints: tuple, - n_sources: int, - tmap: TrialMap, - shape: tuple, - sigma: float = 0.0, - interp_order: int = 1, -) -> sparse.csr_matrix: - """Move a trial's footprints into its registered frame. - - Parameters - ---------- - footprints : tuple of ndarray - (rows, cols, sources, values): the trial's footprints on the - canvas, one entry per nonzero pixel (zero-based). - n_sources : int - Number of sources (columns of the result). - tmap : TrialMap - The trial's map. - shape : tuple of int - (rows, cols) of the registered frame. - sigma : float - Gaussian blur (px) after the move; 0 for none. - interp_order : int - Interpolation of the canvas footprint at the map's inverse of each - trial pixel: 1 bilinear (the viewer's; it blurs a footprint moved - by a fraction of a pixel, by up to ~10% at the peak pixel of a - 1.3 px footprint), 3 cubic spline (keeps the shape; small negative - lobes at the edge are kept so the flux is unchanged). - - Returns - ------- - scipy.sparse.csr_matrix, shape (rows * cols, n_sources) - Row-major flat pixel index by source. - """ - rows, cols, src, vals = (np.asarray(x) for x in footprints) - order = np.argsort(src, kind="stable") - rows, cols, src, vals = rows[order], cols[order], src[order], vals[order] - edges = np.flatnonzero(np.diff(src)) + 1 - ii, jj, vv = [], [], [] - for k in np.split(np.arange(src.size), edges): - if k.size == 0: - continue - idx, val = _place_one(rows[k], cols[k], vals[k], tmap, shape, sigma, interp_order) - ii.append(idx) - jj.append(np.full(idx.size, int(src[k[0]]))) - vv.append(val) - n_px = int(shape[0]) * int(shape[1]) - if not ii: - return sparse.csr_matrix((n_px, n_sources)) - ii, jj, vv = map(np.concatenate, (ii, jj, vv)) - return sparse.csr_matrix((vv, (ii, jj)), shape=(n_px, n_sources)) +"""SILo's fitted activity rendered in a trial's registered 80 Hz movie. + +The rendering follows the F0 network's training-data exporter +(exportF0TrainingData.m in slap2-F0-network), so that the movie minus +the rendered activity is what a training target made from the run would +be, with these changes: + +* **Time.** An 80 Hz frame is the registration's weighted mean of the + samples within max(3 dt, P) lines of its line, with weights + ``exp(-|dline| / dt)``, dt = ceil(mean(diff(DSframes))) lines and + P the recording's lines per cycle. The 200 Hz traces are averaged + at SILo's frame lines with such weights, leaving out SILo's discarded + frames (:func:`frame_weights`); an 80 Hz frame whose weight falls more + than half on discarded 200 Hz frames is discarded. The exporter uses + the movie's dt; since the 200 Hz frames are already averages, the + viewer's default narrows it to sqrt(dt**2 - dt200**2) + (:func:`~giant_python.viewer.trial.render_dt`). The exact kernel + (:func:`exact_weights`) undoes the double smoothing exactly for + densely sampled frames: r x200(line) + (1 - r) times the exporter's + average, r = (dt200 / dt80)**2 (:func:`kernel_weights` chooses). +* **Space.** Footprints live on SILo's consensus canvas; each trial's + footprints are moved into the trial's registered frame through the + trial's across-trial map (rigid, affine or patchwise), the one SILo read + the trial's data with: the trial-frame footprint at pixel q is the + canvas footprint at the map's inverse of q, interpolated bilinearly + (:class:`TrialMap`, :func:`place_footprints`). The exporter instead + searches each trial's offset (integer offset of the mean images plus a + sub-pixel search that maximizes the movie-activity correlation at the + source peaks) and applies it to the canvas as a rigid shift. +* **Blur.** Optionally a Gaussian blur of the moved footprints (the + exporter chooses one per trial by matching the movie's core and ring + slopes; here it is a fixed setting, 0 by default). +* **Scale.** None: the activity is SILo's footprints (each sums to 1) + times its denoised traces (dF_denoised, movie units), as the + exporter writes it (activityGain 1). +""" + +from __future__ import annotations + +import math + +import numpy as np +from numpy.typing import ArrayLike +from scipy import sparse +from scipy.ndimage import gaussian_filter, map_coordinates + + +def kernel_dt(ds_lines: np.ndarray, lines200: np.ndarray, ratio: float) -> int: + """Return the kernel's time constant in lines (the exporter's dt). + + ceil(mean(diff(DSframes))); with one registered frame, the 200 Hz + frame spacing times ratio (analysis rate over movie rate). + + Returns + ------- + int + The kernel's time constant in lines. + """ + ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel() + if ds_lines.size > 1: + return math.ceil(np.mean(np.diff(ds_lines))) + step = np.median(np.diff(np.asarray(lines200, dtype=np.float64))) + return math.ceil(step * ratio) + + +def frame_weights( + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt: int, + reach: float, +) -> tuple[sparse.csc_matrix, np.ndarray]: + """Weights that average 200 Hz frames into the movie's 80 Hz frames. + + Parameters + ---------- + lines200 : ndarray, shape (n200,) + SILo's frame lines of the trial (one-based, increasing). + discard200 : ndarray of bool, shape (n200,) + SILo's discarded frames. + ds_lines : ndarray, shape (n80,) + The registered frames' lines (DSframes). + dt : int + Kernel time constant in lines. + reach : float + Frames within this many lines count (max(3 dt, P)). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + Each 80 Hz frame's weights over the kept 200 Hz frames (columns sum + to 1, or are empty). + discard_share : ndarray, shape (n80,) + Share of each frame's weight on discarded 200 Hz frames (1 where + no 200 Hz frame is within reach). + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + disc = np.asarray(discard200, dtype=bool).ravel() + ds = np.asarray(ds_lines, dtype=np.float64).ravel() + lo = np.searchsorted(lines200, ds - reach, side="left") + hi = np.searchsorted(lines200, ds + reach, side="right") + ii, jj, ww = [], [], [] + share = np.ones(ds.size) + for j in range(ds.size): + idx = np.arange(lo[j], hi[j]) + if idx.size == 0: + continue + w = np.exp(-np.abs(lines200[idx] - ds[j]) / dt) + share[j] = w[disc[idx]].sum() / max(w.sum(), np.finfo(float).eps) + keep = ~disc[idx] + if keep.any(): + ii.append(idx[keep]) + jj.append(np.full(int(keep.sum()), j)) + ww.append(w[keep] / w[keep].sum()) + if ii: + ii, jj, ww = map(np.concatenate, (ii, jj, ww)) + m = sparse.csc_matrix((ww, (ii, jj)), shape=(lines200.size, ds.size)) + return m, share + + +def interp_weights( + lines200: np.ndarray, keep: np.ndarray, ds_lines: np.ndarray +) -> sparse.csc_matrix: + """Linear interpolation of the kept 200 Hz frames at the 80 Hz lines. + + Each 80 Hz frame takes the two kept 200 Hz frames around its line + (discarded frames are skipped, so a gap is bridged by its kept + neighbours); before the first or after the last kept frame, the + nearest kept frame. + + Parameters + ---------- + lines200 : ndarray, shape (n200,) + SILo's frame lines (increasing). + keep : ndarray of bool, shape (n200,) + Frames that may be used. + ds_lines : ndarray, shape (n80,) + The registered frames' lines. + + Returns + ------- + scipy.sparse.csc_matrix, shape (n200, n80) + Columns sum to 1 (all empty without a kept frame). + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + ds = np.asarray(ds_lines, dtype=np.float64).ravel() + k = np.flatnonzero(np.asarray(keep, dtype=bool).ravel()) + shape = (lines200.size, ds.size) + j = np.arange(ds.size) + if k.size == 0: + return sparse.csc_matrix(shape) + if k.size == 1: + return sparse.csc_matrix((np.ones(ds.size), (np.full(ds.size, k[0]), j)), shape=shape) + lk = lines200[k] + i = np.clip(np.searchsorted(lk, ds, side="right") - 1, 0, k.size - 2) + f = np.clip((ds - lk[i]) / (lk[i + 1] - lk[i]), 0.0, 1.0) + return sparse.csc_matrix((np.r_[1 - f, f], (np.r_[k[i], k[i + 1]], np.r_[j, j])), shape=shape) + + +def frame_dt200(lines200: np.ndarray, default: float) -> float: + """Return the 200 Hz frames' own kernel dt in lines. + + ceil(mean(diff(lines))) (default with fewer than 2 frames). + + Returns + ------- + float + The 200 Hz frames' kernel dt in lines. + """ + lines200 = np.asarray(lines200, dtype=np.float64).ravel() + if lines200.size < 2: + return float(default) + return float(math.ceil(float(np.mean(np.diff(lines200))))) + + +def exact_weights( + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt80: float, + dt200: float, + reach: float, +) -> tuple[sparse.csc_matrix, np.ndarray, float]: + """Weights that turn 200 Hz frames into the movie's 80 Hz frames without smoothing twice. + + Both frame rates are weighted means of the same samples with + ``exp(-|dline| / dt)``, whose spectrum is 1 / (1 + dt**2 w**2). + The 80 Hz frame over the 200 Hz frame is therefore (1 + dt200**2 + w**2) / (1 + dt80**2 w**2) = r + (1 - r) / (1 + dt80**2 w**2), + r = (dt200 / dt80)**2: the 80 Hz frame is r times the 200 Hz + frames interpolated at its line (:func:`interp_weights`) plus 1 - + r times their average with the movie's own kernel + (:func:`frame_weights`, the exporter's weights). Exact for densely + sampled pixels and untruncated kernels (on such data fast events keep + 0.99-1.01 of their 80 Hz peak); kernels cut at 3 dt put them 1-2% + high, and pixels sampled once per cycle deviate by about 1% either + way (noiseless injected SLAP2 events: 0.99 and 1.01 on the two paths + of the GFP copy). Discarded 200 Hz frames are left out of both terms. + + Parameters + ---------- + lines200, discard200, ds_lines, reach + As :func:`frame_weights`. + dt80, dt200 : float + The movie's and the 200 Hz frames' kernel dt (lines). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + Columns sum to 1, or are empty where no kept 200 Hz frame lies + within reach. + discard_share : ndarray, shape (n80,) + As :func:`frame_weights` (of the movie's kernel). + r : float + The interpolated term's weight. + """ + wk, share = frame_weights(lines200, discard200, ds_lines, dt80, reach) + r = min(1.0, (float(dt200) / float(dt80)) ** 2) + keep = ~np.asarray(discard200, dtype=bool).ravel() + wi = interp_weights(lines200, keep, ds_lines) + empty = np.asarray(wk.sum(0)).ravel() == 0 + if empty.any(): # nothing within reach: no activity, as frame_weights + wi = wi @ sparse.diags((~empty).astype(np.float64)) + w = (r * wi + (1.0 - r) * wk).tocsc() + w.eliminate_zeros() + return w, share, r + + +KERNELS = ("exporter", "matched", "exact") + + +def kernel_weights( + kernel: str, + lines200: np.ndarray, + discard200: np.ndarray, + ds_lines: np.ndarray, + dt80: float, + lines_per_cycle: float = 0, +) -> tuple[sparse.csc_matrix, np.ndarray, dict[str, float]]: + """Compute a time kernel's weights from a trial's 200 Hz frames to its 80 Hz frames. + + Parameters + ---------- + kernel : {"exporter", "matched", "exact"} + exporter: ``exp(-|dline| / dt80)``, the training-data + exporter's (smooths fast events twice); matched: the same with + dt = sqrt(dt80**2 - dt200**2); exact: + :func:`exact_weights`. dt200 comes from the frame lines + (:func:`frame_dt200`). + lines200, discard200, ds_lines + As :func:`frame_weights`. + dt80 : float + The movie's kernel dt (:func:`kernel_dt`). + lines_per_cycle : float + P; the kernels reach max(3 dt, P) lines (0: unknown). + + Returns + ------- + weights : scipy.sparse.csc_matrix, shape (n200, n80) + discard_share : ndarray, shape (n80,) + Share of each frame's weight on discarded 200 Hz frames under the + movie's kernel (dt80) for exporter and exact, under + the narrower kernel for matched. + info : dict + dt (the averaging kernel's), reach, dt200 and r + (the interpolated share; 0 except for exact). + + Raises + ------ + ValueError + If kernel is not one of the accepted kernels. + """ + if kernel not in KERNELS: + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + dt200 = frame_dt200(lines200, dt80) + if kernel == "matched" and np.size(lines200) >= 2: + dt = math.sqrt(max(float(dt80) ** 2 - dt200**2, 1.0)) + else: # (with fewer than 2 frames the movie's dt, as render_dt) + dt = float(dt80) + reach = max(3 * dt, float(lines_per_cycle)) + info = {"dt": dt, "reach": reach, "dt200": dt200, "r": 0.0} + if kernel == "exact": + w, share, r = exact_weights(lines200, discard200, ds_lines, dt80, dt200, reach) + info["r"] = r + return w, share, info + w, share = frame_weights(lines200, discard200, ds_lines, dt, reach) + return w, share, info + + +def _bilinear( + img: np.ndarray, r: ArrayLike, c: ArrayLike, mode: str = "nearest", cval: float = 0.0 +) -> np.ndarray: + """Bilinear samples of img at zero-based (r, c). + + Returns + ------- + np.ndarray + The samples, in the shape of r. + """ + return map_coordinates(img, [np.ravel(r), np.ravel(c)], order=1, mode=mode, cval=cval).reshape( + np.shape(r) + ) + + +class TrialMap: + """A trial's map from the consensus canvas to its registered frame. + + Zero-based pixel coordinates, as GIAnT-Python's summaries store them + (frame_info/trial_alignment_affine: [row_t, col_t] = A @ [row, + col, 1]; frame_info/trial_alignment_displacement for patchwise + maps: canvas pixel (r, c) lies at (r, c) + displacement in the + trial). With a displacement field, the field (sampled on the canvas, + interpolated bilinearly, edge values beyond it) is the map; without, + the affine map. + + Parameters + ---------- + affine : ndarray of shape (2, 3) + field : ndarray of shape (2, rows, cols), optional + """ + + def __init__(self, affine: np.ndarray, field: np.ndarray | None = None) -> None: + """Store the map.""" + self.affine = np.asarray(affine, dtype=np.float64).reshape(2, 3) + self.field = None if field is None else np.asarray(field, np.float64) + + @property + def valid(self) -> bool: + """Whether the trial has a map (it was aligned).""" + if self.field is not None: + return bool(np.isfinite(self.field).all()) + return bool(np.isfinite(self.affine).all()) + + def forward(self, r: ArrayLike, c: ArrayLike) -> tuple[np.ndarray, np.ndarray]: + """Trial-frame position of canvas positions (r, c). + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The trial-frame (rows, cols) of the canvas positions. + """ + r = np.asarray(r, dtype=np.float64) + c = np.asarray(c, dtype=np.float64) + if self.field is not None: + return ( + r + _bilinear(self.field[0], r, c), + c + _bilinear(self.field[1], r, c), + ) + a = self.affine + return ( + a[0, 0] * r + a[0, 1] * c + a[0, 2], + a[1, 0] * r + a[1, 1] * c + a[1, 2], + ) + + def inverse( + self, rt: ArrayLike, ct: ArrayLike, iters: int = 20, tol: float = 1e-6 + ) -> tuple[np.ndarray, np.ndarray]: + """Canvas position of trial-frame positions (rt, ct). + + Exact for an affine map; for a displacement field the fixed point + of p = q - d(p), started at the affine map's inverse. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + The canvas (rows, cols) of the trial-frame positions. + """ + rt = np.asarray(rt, dtype=np.float64) + ct = np.asarray(ct, dtype=np.float64) + a = self.affine + if not np.isfinite(a).all(): + a = np.array([[1.0, 0, 0], [0, 1.0, 0]]) + m = np.linalg.inv(a[:, :2]) + dr, dc = rt - a[0, 2], ct - a[1, 2] + r = m[0, 0] * dr + m[0, 1] * dc + c = m[1, 0] * dr + m[1, 1] * dc + if self.field is None: + return r, c + for _ in range(iters): + r_new = rt - _bilinear(self.field[0], r, c) + c_new = ct - _bilinear(self.field[1], r, c) + step = max( + float(np.max(np.abs(r_new - r), initial=0)), + float(np.max(np.abs(c_new - c), initial=0)), + ) + r, c = r_new, c_new + if step < tol: + break + return r, c + + +def _patch( + rows: np.ndarray, cols: np.ndarray, vals: np.ndarray, margin: int +) -> tuple[np.ndarray, int, int]: + """Build a footprint's dense canvas patch with a zero margin. + + Returns the patch and its origin (row, col). + + Returns + ------- + patch : np.ndarray + The dense patch of the footprint's values. + row0 : int + Canvas row of the patch's origin. + col0 : int + Canvas column of the patch's origin. + """ + r0, c0 = int(rows.min()) - margin, int(cols.min()) - margin + h = int(rows.max()) - r0 + margin + 1 + w = int(cols.max()) - c0 + margin + 1 + patch = np.zeros((h, w)) + patch[rows - r0, cols - c0] = vals + return patch, r0, c0 + + +def _place_one( + rows: np.ndarray, + cols: np.ndarray, + vals: np.ndarray, + tmap: TrialMap, + shape: tuple, + sigma: float, + interp: int = 1, +) -> tuple[np.ndarray, np.ndarray]: + """One footprint in the trial frame: flat pixel indices and values. + + Returns + ------- + indices : np.ndarray + Flat pixel indices (row-major) in the trial frame. + values : np.ndarray + The footprint's values at those pixels. + """ + margin = 2 + math.ceil(3 * sigma) + int(interp > 1) + patch, r0, c0 = _patch(rows, cols, vals, margin) + h, w = patch.shape + pr, pc = np.mgrid[r0 : r0 + h, c0 : c0 + w] + tr, tc = tmap.forward(pr, pc) + lo_r = max(0, math.floor(np.min(tr))) + hi_r = min(shape[0] - 1, math.ceil(np.max(tr))) + lo_c = max(0, math.floor(np.min(tc))) + hi_c = min(shape[1] - 1, math.ceil(np.max(tc))) + if hi_r < lo_r or hi_c < lo_c: + return np.zeros(0, np.int64), np.zeros(0) + qr, qc = np.mgrid[lo_r : hi_r + 1, lo_c : hi_c + 1] + sr, sc = tmap.inverse(qr, qc) + if interp == 1: + out = _bilinear(patch, sr - r0, sc - c0, mode="constant", cval=0.0) + else: # spline of the zero-padded patch (small negative lobes kept) + out = map_coordinates( + patch, + [np.ravel(sr - r0), np.ravel(sc - c0)], + order=interp, + mode="grid-constant", + cval=0.0, + ).reshape(sr.shape) + if sigma > 0: + out = gaussian_filter(out, sigma, mode="constant", cval=0.0) + peak = float(out.max(initial=0.0)) + if peak > 0: + ok = np.abs(out) > 1e-6 * peak + else: + ok = np.zeros(out.shape, bool) + return (qr[ok] * shape[1] + qc[ok]).astype(np.int64), out[ok] + + +def place_footprints( + footprints: tuple, + n_sources: int, + tmap: TrialMap, + shape: tuple, + sigma: float = 0.0, + interp_order: int = 1, +) -> sparse.csr_matrix: + """Move a trial's footprints into its registered frame. + + Parameters + ---------- + footprints : tuple of ndarray + (rows, cols, sources, values): the trial's footprints on the + canvas, one entry per nonzero pixel (zero-based). + n_sources : int + Number of sources (columns of the result). + tmap : TrialMap + The trial's map. + shape : tuple of int + (rows, cols) of the registered frame. + sigma : float + Gaussian blur (px) after the move; 0 for none. + interp_order : int + Interpolation of the canvas footprint at the map's inverse of each + trial pixel: 1 bilinear (the viewer's; it blurs a footprint moved + by a fraction of a pixel, by up to ~10% at the peak pixel of a + 1.3 px footprint), 3 cubic spline (keeps the shape; small negative + lobes at the edge are kept so the flux is unchanged). + + Returns + ------- + scipy.sparse.csr_matrix, shape (rows * cols, n_sources) + Row-major flat pixel index by source. + """ + rows, cols, src, vals = (np.asarray(x) for x in footprints) + order = np.argsort(src, kind="stable") + rows, cols, src, vals = rows[order], cols[order], src[order], vals[order] + edges = np.flatnonzero(np.diff(src)) + 1 + ii, jj, vv = [], [], [] + for k in np.split(np.arange(src.size), edges): + if k.size == 0: + continue + idx, val = _place_one(rows[k], cols[k], vals[k], tmap, shape, sigma, interp_order) + ii.append(idx) + jj.append(np.full(idx.size, int(src[k[0]]))) + vv.append(val) + n_px = int(shape[0]) * int(shape[1]) + if not ii: + return sparse.csr_matrix((n_px, n_sources)) + ii, jj, vv = map(np.concatenate, (ii, jj, vv)) + return sparse.csr_matrix((vv, (ii, jj)), shape=(n_px, n_sources)) diff --git a/src/giant_python/viewer/run.py b/src/giant_python/viewer/run.py index 4a997956..4dbc8a37 100644 --- a/src/giant_python/viewer/run.py +++ b/src/giant_python/viewer/run.py @@ -1,606 +1,606 @@ -"""A SILo run's outputs as the viewer reads them. - -A run is a folder with experiment_summary.h5 and per_trial_summary.h5 -(directly or in source_extraction/), as giant silo writes them -(GIAnT-MATLAB's schema). The viewer reads only these two files, so runs -whose work folder is gone (Code Ocean results) work too; the plan files -(work/plan/path.h5, or source_extraction/silo/plan), when -present, add the seeds that did not become sources. - -The summaries are written in MATLAB's orientation (h5py shows the -dimensions reversed); everything here is returned in MATLAB's orientation -with zero-based pixel coordinates. Arrays of one path are read when the -path is first used and kept. -""" - -from __future__ import annotations - -import math -import threading -from dataclasses import dataclass, field -from pathlib import Path - -import h5py -import numpy as np -from numpy.typing import ArrayLike - -from .render import TrialMap - -_Scalar = str | int | float | bool | list -"""What an HDF5 parameter becomes (see :func:`_scalar`).""" - - -def _mat(f: h5py.File, name: str) -> np.ndarray | None: - """Read a summary dataset in MATLAB orientation, or None. - - Returns - ------- - np.ndarray or None - The dataset (transposed when it has more than one dimension); None when name is not in - the file. - """ - if name not in f: - return None - a = f[name][()] - return a.T if getattr(a, "ndim", 0) > 1 else a - - -def _scalar(v: object) -> _Scalar: - """Convert an HDF5 value to a Python scalar or string. - - Returns - ------- - str or int or float or bool or list - A string for text values, a Python scalar for a single value, otherwise the values as a - list. - """ - a = np.asarray(v) - if a.dtype.kind in "SO": - x = a.ravel()[0] if a.size else "" - return x.decode() if isinstance(x, bytes) else str(x) - if a.dtype.kind in "U": - return str(a.ravel()[0]) if a.size else "" - return a.ravel()[0].item() if a.size == 1 else a.tolist() - - -def find_summaries(run_dir: str | Path) -> Path: - """Find the folder holding a run's experiment_summary.h5. - - Returns - ------- - Path - The folder with experiment_summary.h5: the run folder, its source_extraction folder, - or the only folder below it that has one. - - Raises - ------ - FileNotFoundError - If no experiment_summary.h5 is found, or several are found below the run folder. - """ - run_dir = Path(run_dir) - for d in (run_dir, run_dir / "source_extraction"): - if (d / "experiment_summary.h5").exists(): - return d - found = sorted(run_dir.glob("**/experiment_summary.h5")) - if len(found) == 1: - return found[0].parent - raise FileNotFoundError( - f"{run_dir}: no experiment_summary.h5" + (" (several below it; give one)" if found else "") - ) - - -def _plan_file(run_dir: Path, summaries: Path, d: int) -> Path | None: - """Find the plan file of path d (one-based), if the run kept it. - - Returns - ------- - Path or None - The plan file; None when the run has none. - """ - for p in ( - run_dir / "work" / "plan" / f"path{d}.h5", - summaries / "silo" / "plan" / f"path{d}.h5", - ): - if p.exists(): - return p - return None - - -def footprint_width(profile: np.ndarray, r0: float, c0: float, radius: int = 6) -> float: - """RMS width per axis (px) of a footprint image around its source pixel. - - It is taken over the disk of radius px around (r0, c0), values - clipped at 0 (the measure of the footprint-support comparisons). - - Returns - ------- - float - The RMS width in px; NaN when the footprint has no positive value in the disk. - """ - r0, c0 = int(round(r0)), int(round(c0)) - rr, cc = np.mgrid[-radius : radius + 1, -radius : radius + 1] - m = rr**2 + cc**2 <= radius**2 - rr, cc = rr[m] + r0, cc[m] + c0 - ok = (rr >= 0) & (rr < profile.shape[0]) & (cc >= 0) & (cc < profile.shape[1]) - rr, cc = rr[ok], cc[ok] - x = np.clip(np.nan_to_num(profile[rr, cc]), 0, None) - if x.sum() <= 0: - return float("nan") - mr, mc = (x * rr).sum() / x.sum(), (x * cc).sum() / x.sum() - var = (x * ((rr - mr) ** 2 + (cc - mc) ** 2)).sum() / x.sum() / 2 - return float(math.sqrt(var)) - - -@dataclass -class Sources: - """One path's sources in a run (consensus canvas, zero-based). - - Attributes - ---------- - rc : ndarray (n, 2) - Kept sources' footprint centroids (sources/spatial/coords). - pixel : ndarray (n, 2) - Their source pixels (visualizations/act_im_peaks). - snr, kinetic_score, kinetic_n_events, width : ndarray (n,) - rejected_rc : ndarray (m, 2) - Sources the kinetics test rejected (their pixels). - rejected_score, rejected_n_events : ndarray (m,) - unused_seeds : ndarray (k, 2) or None - Seeds without a source (from the plan file; None without it). - """ - - rc: np.ndarray - pixel: np.ndarray - snr: np.ndarray - kinetic_score: np.ndarray - kinetic_n_events: np.ndarray - width: np.ndarray - rejected_rc: np.ndarray - rejected_score: np.ndarray - rejected_n_events: np.ndarray - unused_seeds: np.ndarray | None = None - - @property - def n(self) -> int: - """Number of kept sources.""" - return int(self.rc.shape[0]) - - -def _vec(a: ArrayLike | None, n: int, fill: float = np.nan) -> np.ndarray: - """Return a summary vector as float64 of length n. - - Returns - ------- - np.ndarray - The first n values as float64; n values of fill when a is None. - """ - if a is None: - return np.full(n, fill) - return np.asarray(a, dtype=np.float64).ravel()[:n] - - -def _rc(a: ArrayLike | None) -> np.ndarray: - """[0, row, col] rows as (n, 2) (empty when missing). - - Returns - ------- - np.ndarray - The (n, 2) row and column of each entry; shape (0, 2) when a is None. - """ - if a is None: - return np.zeros((0, 2)) - return np.asarray(a, dtype=np.float64).reshape(-1, 3)[:, 1:3] - - -@dataclass -class PathData: - """One path of a run: images, sources, traces, footprints, maps. - - Attributes - ---------- - path : int - One-based imaging path. - shape : tuple of int - (rows, cols) of the consensus canvas. - act_im, mean_im : ndarray (rows, cols) - Combined activity image; mean image of the activity channel. - trial_act, trial_mean : ndarray (trials, rows, cols) or None - n_frames : ndarray of int (trials,) - SILo's 200 Hz frames per trial (0: not analysed). - lines, discard : ndarray (total,) - SILo's frame lines and discarded frames, trials concatenated. - maps : list of (TrialMap or None) - Each trial's map from the canvas to its registered frame. - sources : Sources - """ - - path: int - shape: tuple - act_im: np.ndarray - mean_im: np.ndarray - trial_act: np.ndarray | None - trial_mean: np.ndarray | None - n_frames: np.ndarray - lines: np.ndarray - discard: np.ndarray - maps: list - sources: Sources - alignment: str = "rigid" - _traces: dict = field(default_factory=dict, repr=False) - _footprints: list | None = field(default=None, repr=False) - _trial_rc: np.ndarray | None = field(default=None, repr=False) - - @property - def offsets(self) -> np.ndarray: - """First 200 Hz frame of each trial in the concatenated traces.""" - return np.concatenate([[0], np.cumsum(self.n_frames)]).astype(int) - - def trial_span(self, t: int) -> slice: - """Return the concatenated frames of trial t (zero-based). - - Returns - ------- - slice - The span of trial t in the concatenated frames. - """ - o = self.offsets - return slice(int(o[t]), int(o[t + 1])) - - -TRACES = ("dF_denoised", "dF_ls", "events", "F0") - - -class SiloRun: - """A SILo run's summaries, read path by path on demand. - - Parameters - ---------- - run_dir : str or Path - The run folder (or its source_extraction folder). - name : str, optional - Label shown on the page (default: the folder's name). - """ - - def __init__(self, run_dir: str | Path, name: str | None = None) -> None: - """Open the run and read its parameters.""" - self.run_dir = Path(run_dir) - self.summaries = find_summaries(self.run_dir) - self.experiment = self.summaries / "experiment_summary.h5" - self.per_trial = self.summaries / "per_trial_summary.h5" - self.name = name or self.run_dir.name - with h5py.File(self.experiment, "r") as f: - # scalars and short vectors; validKernel is the kernel itself - # (a width x width matrix), kept whatever its size - self.params = { - k: _scalar(f["params"][k][()]) - for k in f.get("params", {}) - if f["params"][k].size <= 64 or k == "validKernel" - } - self.attrs = {k: _scalar(v) for k, v in f.attrs.items()} - self.paths = sorted(int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()) - self._paths: dict = {} - self._lock = threading.Lock() - - def param(self, name: str, default: _Scalar | None = None) -> _Scalar | None: - """Return a value of the run's params (MATLAB names). - - Returns - ------- - str or int or float or bool or list or None - The parameter's value; default when it is missing, None or empty. - """ - v = self.params.get(name, default) - return default if v is None or v == "" else v - - @property - def activity_channel(self) -> int: - """Zero-based file channel of the activity signal.""" - return int(self.param("activityChannel", 1)) - 1 - - def describe(self) -> dict: - """Return the run's settings that the page shows. - - Returns - ------- - dict - The settings by MATLAB name; validKernel is its width, and baselineSource - defaults to "median". - """ - keys = ( - "baselineSource", - "baselineMode", - "localizationBaseline", - "interTrialAlignment", - "validKernel", - "peakth", - "minSourceEventRate", - "footprintVariance", - "seedFit", - "seedMergePx", - "minKineticScore", - "photonScale", - "alignHz", - "analyzeHz", - ) - out = {k: self.params[k] for k in keys if k in self.params} - out.setdefault("baselineSource", "median") - vk = out.get("validKernel") - if isinstance(vk, list): # the kernel itself: report its width - out["validKernel"] = int(round(math.sqrt(len(np.ravel(vk))))) - return out - - def path(self, d: int) -> PathData: - """Path d (one-based), read on first use. - - Returns - ------- - PathData - The path's images, sources, frames and maps. - """ - with self._lock: - if d not in self._paths: - self._paths[d] = self._read_path(d) - return self._paths[d] - - def _read_path(self, d: int) -> PathData: - """Read one path's images, frames, maps and sources. - - Returns - ------- - PathData - The path's data, read from the summaries. - """ - g = f"Path{d}" - ch = self.activity_channel - with h5py.File(self.experiment, "r") as f: - act = _mat(f, f"{g}/visualizations/act_im")[0] - mean = _mat(f, f"{g}/visualizations/mean_im") - mean = mean[min(ch, mean.shape[0] - 1), 0] - fi = f"{g}/frame_info" - n_frames = np.asarray(_mat(f, f"{fi}/trial_num_frames")).ravel() - lines = _vec(_mat(f, f"{fi}/frame_line_idxs"), int(n_frames.sum())) - disc = _vec(_mat(f, f"{fi}/discard_frames"), lines.size, 0) - maps, mode = _read_maps(f, fi, n_frames.size) - sources = _read_sources(f, g, act.shape) - trial_act = trial_mean = None - if self.per_trial.exists(): - with h5py.File(self.per_trial, "r") as f: - ta = _mat(f, f"{g}/visualizations/per_trial_act_im") - tm = _mat(f, f"{g}/visualizations/per_trial_mean_im") - trial_act = None if ta is None else ta[:, 0].astype(np.float32) - if tm is not None: - trial_mean = tm[:, min(ch, tm.shape[1] - 1), 0] - trial_mean = trial_mean.astype(np.float32) - plan = _plan_file(self.run_dir, self.summaries, d) - if plan is not None: - sources.unused_seeds = _unused_seeds(plan) - return PathData( - path=d, - shape=tuple(act.shape), - act_im=act.astype(np.float32), - mean_im=mean.astype(np.float32), - trial_act=trial_act, - trial_mean=trial_mean, - n_frames=n_frames.astype(int), - lines=lines, - discard=disc.astype(bool), - maps=maps, - sources=sources, - alignment=mode, - ) - - def traces(self, d: int) -> dict: - """Return the activity channel's traces of path d. - - A dict from name to array (total frames, kept sources) (dF_denoised, - dF_ls, events, F0). - - Returns - ------- - dict - The traces by name, each (total frames, kept sources); read on first use. - """ - p = self.path(d) - with self._lock: - if not p._traces: - p._traces = self._read_traces(d) - return p._traces - - def _read_traces(self, d: int) -> dict: - """Read the four trace datasets of one path (activity channel). - - Returns - ------- - dict - The float32 trace arrays by name (those present in the file). - """ - out = {} - ch = self.activity_channel - with h5py.File(self.experiment, "r") as f: - for name in TRACES: - key = f"Path{d}/sources/temporal/{name}" - if key in f: # h5py: (frames, channels, sources) - ds = f[key] - c = min(ch, ds.shape[1] - 1) - out[name] = np.asarray(ds[:, c, :], np.float32) - return out - - def profile_patch(self, d: int, s: int, half: int = 7) -> tuple[np.ndarray, int, int]: - """Source s's mean footprint (sources/spatial/profiles) around its pixel. - - Returned as (patch, row0, col0). - - Returns - ------- - patch : np.ndarray - The footprint's (rows, cols) patch, up to 2 * half + 1 px square. - row0 : int - Canvas row of the patch's first row. - col0 : int - Canvas column of the patch's first column. - """ - p = self.path(d) - r0, c0 = (int(v) for v in p.sources.pixel[s]) - ra = slice(max(0, r0 - half), min(p.shape[0], r0 + half + 1)) - ca = slice(max(0, c0 - half), min(p.shape[1], c0 + half + 1)) - with h5py.File(self.experiment, "r") as f: - prof = f[f"Path{d}/sources/spatial/profiles"] # (c, r, 1, n) - patch = np.asarray(prof[ca, ra, 0, s], np.float32).T - return patch, ra.start, ca.start - - def footprints(self, d: int) -> list: - """Each trial's footprints of path d on the canvas. - - Given as (rows, cols, sources, values) (None for a trial without). - - Returns - ------- - list - One entry per trial: the tuple (rows, cols, sources, values) of its footprints, or - None for a trial without; read on first use. - """ - p = self.path(d) - with self._lock: - if p._footprints is None: - p._footprints, p._trial_rc = self._read_footprints(d, p) - return p._footprints - - def trial_centroids(self, d: int) -> np.ndarray: - """Per-trial footprint centroids (trials, sources, 2). - - NaN where a trial has none. - - Returns - ------- - np.ndarray - The (trials, sources, 2) row and column of each source's footprint in each trial. - """ - self.footprints(d) - return self.path(d)._trial_rc - - def _read_footprints(self, d: int, p: PathData) -> tuple[list, np.ndarray]: - """Read per_trial_profiles in blocks of columns. - - Returns - ------- - footprints : list - One entry per trial: (rows, cols, sources, values), or None for a trial without. - trial_rc : np.ndarray - The (trials, sources, 2) per-trial footprint centroids (NaN where missing). - """ - n_t, n_s = p.n_frames.size, p.sources.n - parts: list = [[] for _ in range(n_t)] - rc = np.full((n_t, n_s, 2), np.nan) - if not self.per_trial.exists() or n_s == 0: - return [None] * n_t, rc - g = f"Path{d}/sources" - with h5py.File(self.per_trial, "r") as f: - if f"{g}/spatial/per_trial_profiles" not in f: - return [None] * n_t, rc - ds = f[f"{g}/spatial/per_trial_profiles"] # (cols, rows, 1, s, t) - step = max(1, int(2e8 // max(1, ds.shape[1] * n_s * n_t * 4))) - for c0 in range(0, ds.shape[0], step): - blk = np.nan_to_num(ds[c0 : c0 + step, :, 0]) - c, r, s, t = np.nonzero(blk) - v = blk[c, r, s, t] - for k in np.unique(t): - m = t == k - parts[k].append((r[m], c[m] + c0, s[m], v[m])) - coords = _mat(f, f"{g}/spatial/per_trial_coords") - if coords is not None: # MATLAB (trials, sources, 3) - rc[:] = np.asarray(coords, np.float64)[:n_t, :n_s, 1:3] - out = [] - for k in range(n_t): - if not parts[k]: - out.append(None) - continue - out.append(tuple(np.concatenate(x) for x in zip(*parts[k]))) - return out, rc - - -def _read_maps(f: h5py.File, fi: str, n_trials: int) -> tuple[list[TrialMap | None], str]: - """Each trial's TrialMap and the alignment mode. - - Returns - ------- - maps : list - One TrialMap per trial, None where it is not valid (or unknown). - mode : str - "patchwise", "rigid" or "affine"; "unknown" with only offline shifts. - """ - affine = _mat(f, f"{fi}/trial_alignment_affine") - disp = _mat(f, f"{fi}/trial_alignment_displacement") - if affine is None: # only offline shifts: unknown - return [None] * n_trials, "unknown" - affine = np.asarray(affine, np.float64).reshape(-1, 2, 3) - maps = [] - for t in range(n_trials): - a = affine[t] if t < affine.shape[0] else np.full((2, 3), np.nan) - fld = None - if disp is not None and t < disp.shape[0]: - fld = np.asarray(disp[t], np.float64) # (2, rows, cols) - m = TrialMap(a, fld) - maps.append(m if m.valid else None) - if disp is not None: - return maps, "patchwise" - eye = np.isfinite(affine[:, 0, 0]) - rigid = np.allclose(affine[eye][:, :, :2], np.eye(2)) if eye.any() else 1 - return maps, "rigid" if rigid else "affine" - - -def _read_sources(f: h5py.File, g: str, shape: tuple[int, ...]) -> Sources: - """Read a path's kept and rejected sources from the experiment summary. - - Returns - ------- - Sources - The path's kept and rejected sources. - """ - rc = _rc(_mat(f, f"{g}/sources/spatial/coords")) - n = rc.shape[0] - pixel = _rc(_mat(f, f"{g}/visualizations/act_im_peaks")) - if pixel.shape[0] != n: - pixel = np.round(rc) - temporal = f"{g}/sources/temporal" - width = np.full(n, np.nan) - if n and f"{g}/sources/spatial/profiles" in f: - prof = f[f"{g}/sources/spatial/profiles"] # (cols, rows, 1, n) - for s in range(n): - r0, c0 = pixel[s] - ra = slice(max(0, int(r0) - 7), min(shape[0], int(r0) + 8)) - ca = slice(max(0, int(c0) - 7), min(shape[1], int(c0) + 8)) - img = prof[ca, ra, 0, s].T - width[s] = footprint_width(img, r0 - ra.start, c0 - ca.start) - rej = f"{g}/sources/rejected" - rej_rc = _rc(_mat(f, f"{rej}/seed_coords")) - m = rej_rc.shape[0] - return Sources( - rc=rc, - pixel=pixel, - snr=_vec(_mat(f, f"{temporal}/SNR"), n), - kinetic_score=_vec(_mat(f, f"{temporal}/kinetic_score"), n), - kinetic_n_events=_vec(_mat(f, f"{temporal}/kinetic_n_events"), n), - width=width, - rejected_rc=rej_rc, - rejected_score=_vec(_mat(f, f"{rej}/kinetic_score"), m), - rejected_n_events=_vec(_mat(f, f"{rej}/kinetic_n_events"), m), - ) - - -def _unused_seeds(plan_path: Path) -> np.ndarray: - """Seeds of a plan whose rounded pixel has no source. - - Returns - ------- - np.ndarray - The (k, 2) row and column of each such seed. - """ - with h5py.File(plan_path, "r") as f: - g = f.get("sources", f) - seeds = np.asarray(g["seeds"][()], np.float64).reshape(-1, 4) - rows = np.asarray(g["rows"][()]).ravel() - cols = np.asarray(g["cols"][()]).ravel() - have = set(zip(rows.tolist(), cols.tolist())) - pix = np.floor(seeds[:, 1:3] + 0.5).astype(int) - keep = [(int(r), int(c)) not in have for r, c in pix] - return seeds[np.asarray(keep, bool)][:, 1:3] +"""A SILo run's outputs as the viewer reads them. + +A run is a folder with experiment_summary.h5 and per_trial_summary.h5 +(directly or in source_extraction/), as giant silo writes them +(GIAnT-MATLAB's schema). The viewer reads only these two files, so runs +whose work folder is gone (Code Ocean results) work too; the plan files +(work/plan/path.h5, or source_extraction/silo/plan), when +present, add the seeds that did not become sources. + +The summaries are written in MATLAB's orientation (h5py shows the +dimensions reversed); everything here is returned in MATLAB's orientation +with zero-based pixel coordinates. Arrays of one path are read when the +path is first used and kept. +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass, field +from pathlib import Path + +import h5py +import numpy as np +from numpy.typing import ArrayLike + +from .render import TrialMap + +_Scalar = str | int | float | bool | list +"""What an HDF5 parameter becomes (see :func:`_scalar`).""" + + +def _mat(f: h5py.File, name: str) -> np.ndarray | None: + """Read a summary dataset in MATLAB orientation, or None. + + Returns + ------- + np.ndarray or None + The dataset (transposed when it has more than one dimension); None when name is not in + the file. + """ + if name not in f: + return None + a = f[name][()] + return a.T if getattr(a, "ndim", 0) > 1 else a + + +def _scalar(v: object) -> _Scalar: + """Convert an HDF5 value to a Python scalar or string. + + Returns + ------- + str or int or float or bool or list + A string for text values, a Python scalar for a single value, otherwise the values as a + list. + """ + a = np.asarray(v) + if a.dtype.kind in "SO": + x = a.ravel()[0] if a.size else "" + return x.decode() if isinstance(x, bytes) else str(x) + if a.dtype.kind in "U": + return str(a.ravel()[0]) if a.size else "" + return a.ravel()[0].item() if a.size == 1 else a.tolist() + + +def find_summaries(run_dir: str | Path) -> Path: + """Find the folder holding a run's experiment_summary.h5. + + Returns + ------- + Path + The folder with experiment_summary.h5: the run folder, its source_extraction folder, + or the only folder below it that has one. + + Raises + ------ + FileNotFoundError + If no experiment_summary.h5 is found, or several are found below the run folder. + """ + run_dir = Path(run_dir) + for d in (run_dir, run_dir / "source_extraction"): + if (d / "experiment_summary.h5").exists(): + return d + found = sorted(run_dir.glob("**/experiment_summary.h5")) + if len(found) == 1: + return found[0].parent + raise FileNotFoundError( + f"{run_dir}: no experiment_summary.h5" + (" (several below it; give one)" if found else "") + ) + + +def _plan_file(run_dir: Path, summaries: Path, d: int) -> Path | None: + """Find the plan file of path d (one-based), if the run kept it. + + Returns + ------- + Path or None + The plan file; None when the run has none. + """ + for p in ( + run_dir / "work" / "plan" / f"path{d}.h5", + summaries / "silo" / "plan" / f"path{d}.h5", + ): + if p.exists(): + return p + return None + + +def footprint_width(profile: np.ndarray, r0: float, c0: float, radius: int = 6) -> float: + """RMS width per axis (px) of a footprint image around its source pixel. + + It is taken over the disk of radius px around (r0, c0), values + clipped at 0 (the measure of the footprint-support comparisons). + + Returns + ------- + float + The RMS width in px; NaN when the footprint has no positive value in the disk. + """ + r0, c0 = int(round(r0)), int(round(c0)) + rr, cc = np.mgrid[-radius : radius + 1, -radius : radius + 1] + m = rr**2 + cc**2 <= radius**2 + rr, cc = rr[m] + r0, cc[m] + c0 + ok = (rr >= 0) & (rr < profile.shape[0]) & (cc >= 0) & (cc < profile.shape[1]) + rr, cc = rr[ok], cc[ok] + x = np.clip(np.nan_to_num(profile[rr, cc]), 0, None) + if x.sum() <= 0: + return float("nan") + mr, mc = (x * rr).sum() / x.sum(), (x * cc).sum() / x.sum() + var = (x * ((rr - mr) ** 2 + (cc - mc) ** 2)).sum() / x.sum() / 2 + return float(math.sqrt(var)) + + +@dataclass +class Sources: + """One path's sources in a run (consensus canvas, zero-based). + + Attributes + ---------- + rc : ndarray (n, 2) + Kept sources' footprint centroids (sources/spatial/coords). + pixel : ndarray (n, 2) + Their source pixels (visualizations/act_im_peaks). + snr, kinetic_score, kinetic_n_events, width : ndarray (n,) + rejected_rc : ndarray (m, 2) + Sources the kinetics test rejected (their pixels). + rejected_score, rejected_n_events : ndarray (m,) + unused_seeds : ndarray (k, 2) or None + Seeds without a source (from the plan file; None without it). + """ + + rc: np.ndarray + pixel: np.ndarray + snr: np.ndarray + kinetic_score: np.ndarray + kinetic_n_events: np.ndarray + width: np.ndarray + rejected_rc: np.ndarray + rejected_score: np.ndarray + rejected_n_events: np.ndarray + unused_seeds: np.ndarray | None = None + + @property + def n(self) -> int: + """Number of kept sources.""" + return int(self.rc.shape[0]) + + +def _vec(a: ArrayLike | None, n: int, fill: float = np.nan) -> np.ndarray: + """Return a summary vector as float64 of length n. + + Returns + ------- + np.ndarray + The first n values as float64; n values of fill when a is None. + """ + if a is None: + return np.full(n, fill) + return np.asarray(a, dtype=np.float64).ravel()[:n] + + +def _rc(a: ArrayLike | None) -> np.ndarray: + """[0, row, col] rows as (n, 2) (empty when missing). + + Returns + ------- + np.ndarray + The (n, 2) row and column of each entry; shape (0, 2) when a is None. + """ + if a is None: + return np.zeros((0, 2)) + return np.asarray(a, dtype=np.float64).reshape(-1, 3)[:, 1:3] + + +@dataclass +class PathData: + """One path of a run: images, sources, traces, footprints, maps. + + Attributes + ---------- + path : int + One-based imaging path. + shape : tuple of int + (rows, cols) of the consensus canvas. + act_im, mean_im : ndarray (rows, cols) + Combined activity image; mean image of the activity channel. + trial_act, trial_mean : ndarray (trials, rows, cols) or None + n_frames : ndarray of int (trials,) + SILo's 200 Hz frames per trial (0: not analysed). + lines, discard : ndarray (total,) + SILo's frame lines and discarded frames, trials concatenated. + maps : list of (TrialMap or None) + Each trial's map from the canvas to its registered frame. + sources : Sources + """ + + path: int + shape: tuple + act_im: np.ndarray + mean_im: np.ndarray + trial_act: np.ndarray | None + trial_mean: np.ndarray | None + n_frames: np.ndarray + lines: np.ndarray + discard: np.ndarray + maps: list + sources: Sources + alignment: str = "rigid" + _traces: dict = field(default_factory=dict, repr=False) + _footprints: list | None = field(default=None, repr=False) + _trial_rc: np.ndarray | None = field(default=None, repr=False) + + @property + def offsets(self) -> np.ndarray: + """First 200 Hz frame of each trial in the concatenated traces.""" + return np.concatenate([[0], np.cumsum(self.n_frames)]).astype(int) + + def trial_span(self, t: int) -> slice: + """Return the concatenated frames of trial t (zero-based). + + Returns + ------- + slice + The span of trial t in the concatenated frames. + """ + o = self.offsets + return slice(int(o[t]), int(o[t + 1])) + + +TRACES = ("dF_denoised", "dF_ls", "events", "F0") + + +class SiloRun: + """A SILo run's summaries, read path by path on demand. + + Parameters + ---------- + run_dir : str or Path + The run folder (or its source_extraction folder). + name : str, optional + Label shown on the page (default: the folder's name). + """ + + def __init__(self, run_dir: str | Path, name: str | None = None) -> None: + """Open the run and read its parameters.""" + self.run_dir = Path(run_dir) + self.summaries = find_summaries(self.run_dir) + self.experiment = self.summaries / "experiment_summary.h5" + self.per_trial = self.summaries / "per_trial_summary.h5" + self.name = name or self.run_dir.name + with h5py.File(self.experiment, "r") as f: + # scalars and short vectors; validKernel is the kernel itself + # (a width x width matrix), kept whatever its size + self.params = { + k: _scalar(f["params"][k][()]) + for k in f.get("params", {}) + if f["params"][k].size <= 64 or k == "validKernel" + } + self.attrs = {k: _scalar(v) for k, v in f.attrs.items()} + self.paths = sorted(int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()) + self._paths: dict = {} + self._lock = threading.Lock() + + def param(self, name: str, default: _Scalar | None = None) -> _Scalar | None: + """Return a value of the run's params (MATLAB names). + + Returns + ------- + str or int or float or bool or list or None + The parameter's value; default when it is missing, None or empty. + """ + v = self.params.get(name, default) + return default if v is None or v == "" else v + + @property + def activity_channel(self) -> int: + """Zero-based file channel of the activity signal.""" + return int(self.param("activityChannel", 1)) - 1 + + def describe(self) -> dict: + """Return the run's settings that the page shows. + + Returns + ------- + dict + The settings by MATLAB name; validKernel is its width, and baselineSource + defaults to "median". + """ + keys = ( + "baselineSource", + "baselineMode", + "localizationBaseline", + "interTrialAlignment", + "validKernel", + "peakth", + "minSourceEventRate", + "footprintVariance", + "seedFit", + "seedMergePx", + "minKineticScore", + "photonScale", + "alignHz", + "analyzeHz", + ) + out = {k: self.params[k] for k in keys if k in self.params} + out.setdefault("baselineSource", "median") + vk = out.get("validKernel") + if isinstance(vk, list): # the kernel itself: report its width + out["validKernel"] = int(round(math.sqrt(len(np.ravel(vk))))) + return out + + def path(self, d: int) -> PathData: + """Path d (one-based), read on first use. + + Returns + ------- + PathData + The path's images, sources, frames and maps. + """ + with self._lock: + if d not in self._paths: + self._paths[d] = self._read_path(d) + return self._paths[d] + + def _read_path(self, d: int) -> PathData: + """Read one path's images, frames, maps and sources. + + Returns + ------- + PathData + The path's data, read from the summaries. + """ + g = f"Path{d}" + ch = self.activity_channel + with h5py.File(self.experiment, "r") as f: + act = _mat(f, f"{g}/visualizations/act_im")[0] + mean = _mat(f, f"{g}/visualizations/mean_im") + mean = mean[min(ch, mean.shape[0] - 1), 0] + fi = f"{g}/frame_info" + n_frames = np.asarray(_mat(f, f"{fi}/trial_num_frames")).ravel() + lines = _vec(_mat(f, f"{fi}/frame_line_idxs"), int(n_frames.sum())) + disc = _vec(_mat(f, f"{fi}/discard_frames"), lines.size, 0) + maps, mode = _read_maps(f, fi, n_frames.size) + sources = _read_sources(f, g, act.shape) + trial_act = trial_mean = None + if self.per_trial.exists(): + with h5py.File(self.per_trial, "r") as f: + ta = _mat(f, f"{g}/visualizations/per_trial_act_im") + tm = _mat(f, f"{g}/visualizations/per_trial_mean_im") + trial_act = None if ta is None else ta[:, 0].astype(np.float32) + if tm is not None: + trial_mean = tm[:, min(ch, tm.shape[1] - 1), 0] + trial_mean = trial_mean.astype(np.float32) + plan = _plan_file(self.run_dir, self.summaries, d) + if plan is not None: + sources.unused_seeds = _unused_seeds(plan) + return PathData( + path=d, + shape=tuple(act.shape), + act_im=act.astype(np.float32), + mean_im=mean.astype(np.float32), + trial_act=trial_act, + trial_mean=trial_mean, + n_frames=n_frames.astype(int), + lines=lines, + discard=disc.astype(bool), + maps=maps, + sources=sources, + alignment=mode, + ) + + def traces(self, d: int) -> dict: + """Return the activity channel's traces of path d. + + A dict from name to array (total frames, kept sources) (dF_denoised, + dF_ls, events, F0). + + Returns + ------- + dict + The traces by name, each (total frames, kept sources); read on first use. + """ + p = self.path(d) + with self._lock: + if not p._traces: + p._traces = self._read_traces(d) + return p._traces + + def _read_traces(self, d: int) -> dict: + """Read the four trace datasets of one path (activity channel). + + Returns + ------- + dict + The float32 trace arrays by name (those present in the file). + """ + out = {} + ch = self.activity_channel + with h5py.File(self.experiment, "r") as f: + for name in TRACES: + key = f"Path{d}/sources/temporal/{name}" + if key in f: # h5py: (frames, channels, sources) + ds = f[key] + c = min(ch, ds.shape[1] - 1) + out[name] = np.asarray(ds[:, c, :], np.float32) + return out + + def profile_patch(self, d: int, s: int, half: int = 7) -> tuple[np.ndarray, int, int]: + """Source s's mean footprint (sources/spatial/profiles) around its pixel. + + Returned as (patch, row0, col0). + + Returns + ------- + patch : np.ndarray + The footprint's (rows, cols) patch, up to 2 * half + 1 px square. + row0 : int + Canvas row of the patch's first row. + col0 : int + Canvas column of the patch's first column. + """ + p = self.path(d) + r0, c0 = (int(v) for v in p.sources.pixel[s]) + ra = slice(max(0, r0 - half), min(p.shape[0], r0 + half + 1)) + ca = slice(max(0, c0 - half), min(p.shape[1], c0 + half + 1)) + with h5py.File(self.experiment, "r") as f: + prof = f[f"Path{d}/sources/spatial/profiles"] # (c, r, 1, n) + patch = np.asarray(prof[ca, ra, 0, s], np.float32).T + return patch, ra.start, ca.start + + def footprints(self, d: int) -> list: + """Each trial's footprints of path d on the canvas. + + Given as (rows, cols, sources, values) (None for a trial without). + + Returns + ------- + list + One entry per trial: the tuple (rows, cols, sources, values) of its footprints, or + None for a trial without; read on first use. + """ + p = self.path(d) + with self._lock: + if p._footprints is None: + p._footprints, p._trial_rc = self._read_footprints(d, p) + return p._footprints + + def trial_centroids(self, d: int) -> np.ndarray: + """Per-trial footprint centroids (trials, sources, 2). + + NaN where a trial has none. + + Returns + ------- + np.ndarray + The (trials, sources, 2) row and column of each source's footprint in each trial. + """ + self.footprints(d) + return self.path(d)._trial_rc + + def _read_footprints(self, d: int, p: PathData) -> tuple[list, np.ndarray]: + """Read per_trial_profiles in blocks of columns. + + Returns + ------- + footprints : list + One entry per trial: (rows, cols, sources, values), or None for a trial without. + trial_rc : np.ndarray + The (trials, sources, 2) per-trial footprint centroids (NaN where missing). + """ + n_t, n_s = p.n_frames.size, p.sources.n + parts: list = [[] for _ in range(n_t)] + rc = np.full((n_t, n_s, 2), np.nan) + if not self.per_trial.exists() or n_s == 0: + return [None] * n_t, rc + g = f"Path{d}/sources" + with h5py.File(self.per_trial, "r") as f: + if f"{g}/spatial/per_trial_profiles" not in f: + return [None] * n_t, rc + ds = f[f"{g}/spatial/per_trial_profiles"] # (cols, rows, 1, s, t) + step = max(1, int(2e8 // max(1, ds.shape[1] * n_s * n_t * 4))) + for c0 in range(0, ds.shape[0], step): + blk = np.nan_to_num(ds[c0 : c0 + step, :, 0]) + c, r, s, t = np.nonzero(blk) + v = blk[c, r, s, t] + for k in np.unique(t): + m = t == k + parts[k].append((r[m], c[m] + c0, s[m], v[m])) + coords = _mat(f, f"{g}/spatial/per_trial_coords") + if coords is not None: # MATLAB (trials, sources, 3) + rc[:] = np.asarray(coords, np.float64)[:n_t, :n_s, 1:3] + out = [] + for k in range(n_t): + if not parts[k]: + out.append(None) + continue + out.append(tuple(np.concatenate(x) for x in zip(*parts[k]))) + return out, rc + + +def _read_maps(f: h5py.File, fi: str, n_trials: int) -> tuple[list[TrialMap | None], str]: + """Each trial's TrialMap and the alignment mode. + + Returns + ------- + maps : list + One TrialMap per trial, None where it is not valid (or unknown). + mode : str + "patchwise", "rigid" or "affine"; "unknown" with only offline shifts. + """ + affine = _mat(f, f"{fi}/trial_alignment_affine") + disp = _mat(f, f"{fi}/trial_alignment_displacement") + if affine is None: # only offline shifts: unknown + return [None] * n_trials, "unknown" + affine = np.asarray(affine, np.float64).reshape(-1, 2, 3) + maps = [] + for t in range(n_trials): + a = affine[t] if t < affine.shape[0] else np.full((2, 3), np.nan) + fld = None + if disp is not None and t < disp.shape[0]: + fld = np.asarray(disp[t], np.float64) # (2, rows, cols) + m = TrialMap(a, fld) + maps.append(m if m.valid else None) + if disp is not None: + return maps, "patchwise" + eye = np.isfinite(affine[:, 0, 0]) + rigid = np.allclose(affine[eye][:, :, :2], np.eye(2)) if eye.any() else 1 + return maps, "rigid" if rigid else "affine" + + +def _read_sources(f: h5py.File, g: str, shape: tuple[int, ...]) -> Sources: + """Read a path's kept and rejected sources from the experiment summary. + + Returns + ------- + Sources + The path's kept and rejected sources. + """ + rc = _rc(_mat(f, f"{g}/sources/spatial/coords")) + n = rc.shape[0] + pixel = _rc(_mat(f, f"{g}/visualizations/act_im_peaks")) + if pixel.shape[0] != n: + pixel = np.round(rc) + temporal = f"{g}/sources/temporal" + width = np.full(n, np.nan) + if n and f"{g}/sources/spatial/profiles" in f: + prof = f[f"{g}/sources/spatial/profiles"] # (cols, rows, 1, n) + for s in range(n): + r0, c0 = pixel[s] + ra = slice(max(0, int(r0) - 7), min(shape[0], int(r0) + 8)) + ca = slice(max(0, int(c0) - 7), min(shape[1], int(c0) + 8)) + img = prof[ca, ra, 0, s].T + width[s] = footprint_width(img, r0 - ra.start, c0 - ca.start) + rej = f"{g}/sources/rejected" + rej_rc = _rc(_mat(f, f"{rej}/seed_coords")) + m = rej_rc.shape[0] + return Sources( + rc=rc, + pixel=pixel, + snr=_vec(_mat(f, f"{temporal}/SNR"), n), + kinetic_score=_vec(_mat(f, f"{temporal}/kinetic_score"), n), + kinetic_n_events=_vec(_mat(f, f"{temporal}/kinetic_n_events"), n), + width=width, + rejected_rc=rej_rc, + rejected_score=_vec(_mat(f, f"{rej}/kinetic_score"), m), + rejected_n_events=_vec(_mat(f, f"{rej}/kinetic_n_events"), m), + ) + + +def _unused_seeds(plan_path: Path) -> np.ndarray: + """Seeds of a plan whose rounded pixel has no source. + + Returns + ------- + np.ndarray + The (k, 2) row and column of each such seed. + """ + with h5py.File(plan_path, "r") as f: + g = f.get("sources", f) + seeds = np.asarray(g["seeds"][()], np.float64).reshape(-1, 4) + rows = np.asarray(g["rows"][()]).ravel() + cols = np.asarray(g["cols"][()]).ravel() + have = set(zip(rows.tolist(), cols.tolist())) + pix = np.floor(seeds[:, 1:3] + 0.5).astype(int) + keep = [(int(r), int(c)) not in have for r, c in pix] + return seeds[np.asarray(keep, bool)][:, 1:3] diff --git a/src/giant_python/viewer/server.py b/src/giant_python/viewer/server.py index 80df5e03..ed50282f 100644 --- a/src/giant_python/viewer/server.py +++ b/src/giant_python/viewer/server.py @@ -1,712 +1,712 @@ -"""giant view: a local page for inspecting SILo runs by eye. - -giant view RUN [RUN ...] serves http://127.0.0.1:8766 with two views: - -* **Sources**: per path, the combined activity image, each trial's - activity image and the mean image of one or two runs, with the runs' - sources overlaid (kept, kinetics-rejected and, when the run kept its - plan files, seeds without a source), synchronized zoom and pan, a - flicker between two panels, and a source's footprint, traces (denoised - and least-squares dF, events, F0 over all trials), SNR, kinetic score - and footprint width. With two runs, sources are marked by whether the - other run has one within 1.5 px (one to one, closest first). -* **Movie**: one trial-path at a time, frame by frame: the registered - 80 Hz movie, each run's fitted activity rendered into it - (:mod:`~giant_python.viewer.render`) and the residual movie - activity; - with --baseline-dir also the network's baseline and movie - - activity - baseline. Scroll or play through time, average frames, zoom - and pan with all panels in step, traces of a pixel or small region. - -A trial-path is loaded when it is shown (--cache-trials at once). -Memory: the movie (float32) and baseline (float16) at the valid pixels, -about 6 bytes x frames x valid pixels (0.5 GB for a 780125 trial of 2254 -frames x 36k pixels); the activity is computed per request from sparse -footprints. - -API (GET; used by the page): /api/meta, /api/sources?path=, -``/api/image?path=&run=&kind=act|mean|trial_act|trial_mean&trial=`` -(float32 rows x cols), /api/source?path=&run=&id= (JSON), -/api/source_traces?path=&run=&id= (float32 4 x frames), -/api/trial?path=&trial= (JSON), -/api/frame?path=&trial=&t=&avg=&kernel= (float32 layers x valid -pixels), /api/trace?path=&trial=&r=&c=&rad=&kernel= (float32 layers x -frames; kernel exporter, matched or exact, default --kernel), -/api/progress?key=. -""" - -from __future__ import annotations - -import argparse -import json -import threading -import time -import webbrowser -from collections import OrderedDict -from collections.abc import Iterable -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse - -import numpy as np -import numpy.typing as npt - -from .run import TRACES, SiloRun -from .trial import Session, TrialMovie, load_trial, source_events - -PAGE = Path(__file__).with_name("page.html") -DEFAULT_PORT = 8766 - - -def _json_safe(o: object) -> object: - """``o`` with non-finite floats as None (the browser rejects NaN). - - Returns - ------- - object - o with dicts, lists, tuples (as lists) and numpy values converted - recursively to JSON-safe Python values. - """ - if isinstance(o, float): - return o if np.isfinite(o) else None - if isinstance(o, dict): - return {k: _json_safe(v) for k, v in o.items()} - if isinstance(o, (list, tuple)): - return [_json_safe(v) for v in o] - if isinstance(o, np.ndarray): - return _json_safe(o.tolist()) - if isinstance(o, np.generic): - return _json_safe(o.item()) - return o - - -def _r(a: npt.ArrayLike, nd: int = 3) -> list: - """Round an array to nd decimals as nested lists. - - Returns - ------- - list - The rounded values of a as nested lists. - """ - return np.round(np.asarray(a, dtype=np.float64), nd).tolist() - - -class Store: - """The runs of one session and the trial-paths loaded from them. - - Parameters - ---------- - runs : list of SiloRun - One or more runs of the same session (same paths and trials). - session : Session - The trial table and folders. - label : str - Session label for the page. - cache_trials : int - Trial-paths kept in memory. - blur : float - Gaussian blur (px) of the rendered footprints. - """ - - def __init__( - self, - runs: list[SiloRun], - session: Session, - label: str = "", - cache_trials: int = 2, - blur: float = 0.0, - kernel: str = "matched", - ) -> None: - """Check that the runs fit together. - - Raises - ------ - ValueError - If there are no runs, the run names are not unique, or the runs differ in their paths, - channel count, or activity channel. - """ - if not runs: - raise ValueError("give at least one run") - names = [r.name for r in runs] - if len(set(names)) != len(names): - raise ValueError(f"run names must differ: {names}") - self.runs, self.session, self.label = runs, session, label - self.cache_trials, self.blur = max(1, int(cache_trials)), blur - self.kernel = kernel - self.paths = runs[0].paths - for r in runs[1:]: - if r.paths != self.paths: - raise ValueError( - f"runs have different paths: {runs[0].name} {self.paths}, {r.name} {r.paths}" - ) - # the movie is read once, as the first run's activity channel - # with the trial loader's defaults (trial._settings) - for key, default in (("numChannels", 2), ("activityChannel", 1)): - v0, v = runs[0].param(key, default), r.param(key, default) - if int(v) != int(v0): - raise ValueError(f"runs differ in {key}: {runs[0].name} {v0}, {r.name} {v}") - self._cache: OrderedDict = OrderedDict() - self._loading: dict = {} - # one trial-path loads at a time: each needs a whole movie in memory - self._load_slot = threading.Semaphore(1) - self._lock = threading.Lock() - self.progress: dict = {} - - def run(self, name: str) -> SiloRun: - """Return the run called name. - - Returns - ------- - SiloRun - The run with that name. - - Raises - ------ - KeyError - If no run has that name. - """ - for r in self.runs: - if r.name == name: - return r - raise KeyError(name) - - def meta(self) -> dict: - """List what the page shows: runs, paths, trials. - - Returns - ------- - dict - The session label, blur_px, kernel, the runs (name, folder, - settings), the table, moco_dir and baseline_dir, and per paths - entry its shape, trials and alignment. - """ - paths = [] - for d in self.paths: - p = self.runs[0].path(d) - trials = [] - for t in range(p.n_frames.size): - trials.append({ - "trial": t, - "frames200": int(p.n_frames[t]), - "movie": bool(self.session.has_movie(d - 1, t)), - "baseline": self.session.baseline_file(d - 1, t) is not None, - "aligned": [r.path(d).maps[t] is not None for r in self.runs], - }) - paths.append({ - "path": d, - "shape": list(p.shape), - "trials": trials, - "alignment": [r.path(d).alignment for r in self.runs], - }) - return { - "label": self.label, - "blur_px": self.blur, - "kernel": self.kernel, - "runs": [ - { - "name": r.name, - "dir": str(r.run_dir), - "settings": r.describe(), - } - for r in self.runs - ], - "table": str(self.session.table), - "moco_dir": str(self.session.moco_dir), - "baseline_dir": str(self.session.baseline_dir or ""), - "paths": paths, - } - - def sources(self, d: int) -> dict: - """Every run's sources of path d (canvas, zero-based). - - Returns - ------- - dict - shape of the path's canvas and runs: per run name its kept and - rejected sources, unused seeds (or None) and number of trials. - """ - out = {} - for r in self.runs: - s = r.path(d).sources - kept = ( - np.column_stack([ - s.rc, - s.snr, - s.kinetic_score, - s.kinetic_n_events, - s.width, - s.pixel, - ]) - if s.n - else np.zeros((0, 8)) - ) - rej = np.column_stack([s.rejected_rc, s.rejected_score, s.rejected_n_events]) - seeds = None if s.unused_seeds is None else _r(s.unused_seeds, 2) - out[r.name] = { - "kept": _r(kept), - "rejected": _r(rej), - "seeds": seeds, - "trials": int(r.path(d).n_frames.size), - } - return {"shape": list(self.runs[0].path(d).shape), "runs": out} - - def image(self, d: int, run: str, kind: str, trial: int) -> np.ndarray: - """Return an image of the canvas as float32 (rows, cols). - - Returns - ------- - np.ndarray - The requested image (kind act, mean, trial_act or trial_mean). - - Raises - ------ - KeyError - If kind is unknown, or a per-trial image is asked for a trial it does not have. - """ - p = self.run(run).path(d) - if kind == "act": - img = p.act_im - elif kind == "mean": - img = p.mean_im - elif kind in ("trial_act", "trial_mean"): - stack = p.trial_act if kind == "trial_act" else p.trial_mean - if stack is None or not 0 <= trial < stack.shape[0]: - raise KeyError(f"{kind} of trial {trial}") - img = stack[trial] - else: - raise KeyError(kind) - return np.ascontiguousarray(img, np.float32) - - def source(self, d: int, run: str, s: int) -> dict: - """One kept source: values, footprint, trial positions, events. - - Returns - ------- - dict - The source's id, canvas position rc, pixel, snr, kinetic - scores, width, footprint patch, per-trial positions trial_rc, - offsets, hz and events. - - Raises - ------ - KeyError - If s is not a source index of the path. - """ - r = self.run(run) - p = r.path(d) - src = p.sources - if not 0 <= s < src.n: - raise KeyError(f"source {s}") - patch, r0, c0 = r.profile_patch(d, s) - trc = r.trial_centroids(d) - pos = [] - for t, m in enumerate(p.maps): - rc = trc[t, s] if t < trc.shape[0] else src.rc[s] - if np.isnan(rc).any(): - rc = src.rc[s] - pos.append(None if m is None else _r(m.forward(*rc), 2)) - return { - "id": s, - "rc": _r(src.rc[s], 2), - "pixel": _r(src.pixel[s]), - "snr": float(src.snr[s]), - "kinetic_score": float(src.kinetic_score[s]), - "kinetic_n_events": float(src.kinetic_n_events[s]), - "width": float(src.width[s]), - "footprint": {"r0": r0, "c0": c0, "values": _r(patch, 5)}, - "trial_rc": pos, - "offsets": p.offsets.tolist(), - "hz": float(r.param("analyzeHz", 200.0)), - "events": source_events(r, self.session, d, s), - } - - def source_traces(self, d: int, run: str, s: int) -> np.ndarray: - """Return a source's four traces (4, frames) float32. - - Returns - ------- - np.ndarray - One row per trace in TRACES; NaN where the run has no value. - """ - tr = self.run(run).traces(d) - n = self.run(run).path(d).lines.size - out = np.full((len(TRACES), n), np.nan, np.float32) - for i, name in enumerate(TRACES): - if name in tr and 0 <= s < tr[name].shape[1]: - out[i] = tr[name][:, s] - return out - - def trial(self, d: int, t: int) -> TrialMovie: - """Trial-path (d, t), loaded once (a second request waits). - - Returns - ------- - TrialMovie - The loaded trial-path (from the cache when it is there). - """ - key = (d, t) - while True: - with self._lock: - if key in self._cache: - self._cache.move_to_end(key) - return self._cache[key] - ev = self._loading.get(key) - mine = ev is None - if mine: - ev = self._loading[key] = threading.Event() - if not mine: - ev.wait() - continue - try: - with self._load_slot: - tr = self._load(d, t) - with self._lock: - self._cache[key] = tr - while len(self._cache) > self.cache_trials: - self._cache.popitem(last=False) - finally: - with self._lock: - self._loading.pop(key, None) - ev.set() - return tr - - def _load(self, d: int, t: int) -> TrialMovie: - """Load a trial-path and report the time. - - Returns - ------- - TrialMovie - The loaded trial-path. - - Raises - ------ - KeyError - If the session has no movie for the trial-path. - """ - if not self.session.has_movie(d - 1, t): - raise KeyError(f"no movie for path {d} trial {t + 1}") - key = f"{d}/{t}" - self.progress[key] = "reading the movie and rendering" - t0 = time.time() - try: - tr = load_trial(self.runs, self.session, d, t, self.blur, self.kernel) - finally: - self.progress.pop(key, None) - print( - f"loaded path {d} trial {t + 1}: {tr.T} frames x {tr.N} px in {time.time() - t0:.1f} s", - flush=True, - ) - return tr - - def trial_static(self, d: int, t: int) -> dict: - """Return what the page needs once per trial-path. - - Returns - ------- - dict - The trial's rows, cols, mean image, discard frames, layers, - shape, per-run markers, info and busiest frame of each run. - """ - tr = self.trial(d, t) - runs = {} - for r in tr.runs: - runs[r.name] = { - "kept": _r(r.kept_rc, 2), - "rejected": _r(r.rejected_rc, 2), - "seeds": _r(r.seeds_rc, 2), - "rendered": r.rendered, - } - return { - "rows": tr.rows.tolist(), - "cols": tr.cols.tolist(), - "mean": _r(tr.mean, 2), - "discard": np.flatnonzero(tr.discard).tolist(), - "layers": tr.layers, - "shape": [tr.T, *tr.shape], - "markers": runs, - "info": tr.info, - "busiest": [tr.busiest_frame(i) for i in range(len(tr.runs))], - } - - -def _ints(q: dict, *names: str) -> list: - """Integer query values. - - Returns - ------- - list - int(q[n]) for each name, in order. - """ - return [int(q[n]) for n in names] - - -def _route(store: Store, path: str, q: dict) -> tuple[str, dict | np.ndarray, dict[str, str]]: - """Answer one API request: (kind, payload, headers). - - Returns - ------- - kind : str - "json" or "bin". - payload : dict or np.ndarray - The JSON-able dict, or the array to send as float32 bytes. - headers : dict of str to str - Extra response headers. - - Raises - ------ - LookupError - If path is not an API route. - """ - if path == "/api/meta": - return "json", store.meta(), {} - if path == "/api/sources": - return "json", store.sources(int(q["path"])), {} - if path == "/api/image": - img = store.image(int(q["path"]), q["run"], q["kind"], int(q.get("trial", -1))) - return "bin", img, {"X-Shape": json.dumps(list(img.shape))} - if path == "/api/source": - d, s = _ints(q, "path", "id") - return "json", store.source(d, q["run"], s), {} - if path == "/api/source_traces": - d, s = _ints(q, "path", "id") - return ( - "bin", - store.source_traces(d, q["run"], s), - {"X-Names": json.dumps(list(TRACES))}, - ) - if path == "/api/trial": - d, t = _ints(q, "path", "trial") - return "json", store.trial_static(d, t), {} - if path == "/api/frame": - d, t, f = _ints(q, "path", "trial", "t") - tr = store.trial(d, t) - f = min(max(f, 0), tr.T - 1) - a = tr.frame(f, max(1, int(q.get("avg", 1))), q.get("kernel")) - return "bin", a, {"X-Frame": str(f)} - if path == "/api/trace": - d, t, r, c = _ints(q, "path", "trial", "r", "c") - rad = max(0, int(q.get("rad", 0))) - a, n = store.trial(d, t).trace(r, c, rad, q.get("kernel")) - return "bin", a, {"X-Pixels": str(n)} - if path == "/api/progress": - return "json", {"msg": store.progress.get(q.get("key", ""), "")}, {} - raise LookupError(path) - - -class _Handler(BaseHTTPRequestHandler): - """Serves the page and the API of store. - - The store is set by :func:`make_handler`. - """ - - store: Store - - def log_message(self, *a: object) -> None: - """Quiet.""" - - def _send( - self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None - ) -> None: - """Send one response.""" - self.send_response(code) - self.send_header("Content-Type", ctype) - self.send_header("Content-Length", str(len(body))) - self.send_header("Cache-Control", "no-store") - for k, v in (headers or {}).items(): - self.send_header(k, v) - self.end_headers() - self.wfile.write(body) - - def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: - """Send JSON (non-finite floats as null).""" - body = json.dumps(_json_safe(obj), allow_nan=False).encode() - self._send(code, body, "application/json", headers) - - 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()} - try: - if u.path in ("/", "/index.html"): - self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") - return - kind, payload, headers = _route(self.store, u.path, q) - if kind == "json": - self._json(payload, headers=headers) - return - body = np.ascontiguousarray(payload, np.float32).tobytes() - self._send(200, body, "application/octet-stream", headers) - except KeyError as e: - self._json({"error": f"missing or unknown {e}"}, 400) - except LookupError: - self._json({"error": f"not found: {u.path}"}, 404) - except (BrokenPipeError, ConnectionResetError): - pass - except Exception as e: # noqa: BLE001 (shown on the page) - self._json({"error": f"{type(e).__name__}: {e}"}, 500) - - -def make_handler(store: Store) -> type[_Handler]: - """Build the request handler class serving store. - - Returns - ------- - type[_Handler] - A handler class whose store is the given store. - """ - return type("Handler", (_Handler,), {"store": store}) - - -def _run_args(items: Iterable[str]) -> list: - """NAME=DIR or DIR arguments as (name, dir). - - Returns - ------- - list - One (name, dir) tuple per item; name is None for a plain DIR. - """ - out = [] - for item in items: - name, sep, d = str(item).partition("=") - if sep and name and not Path(item).exists(): - out.append((name, d)) - else: - out.append((None, item)) - return out - - -def _default_table(run_dir: Path) -> Path | None: - """Find a trial table in or above a run folder. - - Returns - ------- - Path or None - The nearest trial_table.h5 (in the folder or up to two levels above), or None. - """ - for d in (run_dir, run_dir.parent, run_dir.parent.parent): - if (d / "trial_table.h5").exists(): - return d / "trial_table.h5" - return None - - -def make_store(args: argparse.Namespace) -> Store: - """Build the store for parsed giant view arguments. - - Returns - ------- - Store - The store of the given runs and session. - - Raises - ------ - ValueError - If no trial table was given and none is found in or above the first run folder. - """ - runs = [SiloRun(d, name) for name, d in _run_args(args.runs)] - table = args.table or _default_table(runs[0].run_dir) - if table is None: - raise ValueError(f"no trial_table.h5 in or above {runs[0].run_dir}: give --table") - session = Session(table, args.moco_dir, args.baseline_dir, args.data_dir) - label = args.label or Path(session.table).parent.name - return Store(runs, session, label, args.cache_trials, args.blur, args.kernel) - - -def make_server( - store: Store, host: str = "127.0.0.1", port: int = DEFAULT_PORT -) -> ThreadingHTTPServer: - """Build an HTTP server for store (not started). - - Returns - ------- - ThreadingHTTPServer - The server bound to host and port. - """ - return ThreadingHTTPServer((host, port), make_handler(store)) - - -def add_arguments(p: argparse.ArgumentParser) -> None: - """``giant view``'s options.""" - p.add_argument( - "runs", - nargs="+", - metavar="RUN", - help="SILo run folders (holding experiment_summary.h5, " - "directly or in source_extraction/), optionally as " - "NAME=FOLDER; two or more runs of the same session are " - "compared", - ) - p.add_argument( - "--table", - default=None, - help="the session's trial_table.h5 (default: in or above the first run's folder)", - ) - p.add_argument( - "--moco-dir", - default=None, - help="registered movies and alignment files (default: " - "the table's savedr/motion_correction)", - ) - p.add_argument( - "--baseline-dir", - default=None, - help="F0 network baselines (_BASELINE-80Hz.h5); adds the baseline layers", - ) - p.add_argument( - "--data-dir", - default=None, - help="raw .dat/.meta folder, for the lines per cycle " - "(default: the table's datadr; without it the frame " - "kernel reaches 3 dt)", - ) - p.add_argument("--label", default="", help="session label on the page") - p.add_argument( - "--blur", - type=float, - default=0.0, - help="Gaussian blur (px) of the rendered footprints (default 0)", - ) - p.add_argument( - "--kernel", - choices=("matched", "exporter", "exact"), - default="matched", - help="how SILo's 200 Hz traces become the movie's 80 Hz " - "frames: matched (default; sqrt(dt80^2 - dt200^2), for the " - "200 Hz frames' own smoothing), the exporter's weights (the " - "movie's dt), or exact (r x200 + (1 - r) exporter's, r = " - "(dt200/dt80)^2); the page switches between them", - ) - p.add_argument( - "--cache-trials", - type=int, - default=2, - help="trial-paths kept in memory", - ) - 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") - - -def serve(args: argparse.Namespace) -> int: - """Run giant view until interrupted. - - Returns - ------- - int - The exit code, 0. - """ - store = make_store(args) - server = make_server(store, args.host, args.port) - url = f"http://{args.host}:{server.server_address[1]}/" - names = ", ".join(r.name for r in store.runs) - print( - f"{store.label}: runs {names}; paths {store.paths}; serving {url} (Ctrl+C to stop)", - flush=True, - ) - if not args.no_browser: - threading.Timer(0.5, lambda: webbrowser.open(url)).start() - try: - server.serve_forever() - except KeyboardInterrupt: - pass - finally: - server.server_close() - return 0 +"""giant view: a local page for inspecting SILo runs by eye. + +giant view RUN [RUN ...] serves http://127.0.0.1:8766 with two views: + +* **Sources**: per path, the combined activity image, each trial's + activity image and the mean image of one or two runs, with the runs' + sources overlaid (kept, kinetics-rejected and, when the run kept its + plan files, seeds without a source), synchronized zoom and pan, a + flicker between two panels, and a source's footprint, traces (denoised + and least-squares dF, events, F0 over all trials), SNR, kinetic score + and footprint width. With two runs, sources are marked by whether the + other run has one within 1.5 px (one to one, closest first). +* **Movie**: one trial-path at a time, frame by frame: the registered + 80 Hz movie, each run's fitted activity rendered into it + (:mod:`~giant_python.viewer.render`) and the residual movie - activity; + with --baseline-dir also the network's baseline and movie - + activity - baseline. Scroll or play through time, average frames, zoom + and pan with all panels in step, traces of a pixel or small region. + +A trial-path is loaded when it is shown (--cache-trials at once). +Memory: the movie (float32) and baseline (float16) at the valid pixels, +about 6 bytes x frames x valid pixels (0.5 GB for a 780125 trial of 2254 +frames x 36k pixels); the activity is computed per request from sparse +footprints. + +API (GET; used by the page): /api/meta, /api/sources?path=, +``/api/image?path=&run=&kind=act|mean|trial_act|trial_mean&trial=`` +(float32 rows x cols), /api/source?path=&run=&id= (JSON), +/api/source_traces?path=&run=&id= (float32 4 x frames), +/api/trial?path=&trial= (JSON), +/api/frame?path=&trial=&t=&avg=&kernel= (float32 layers x valid +pixels), /api/trace?path=&trial=&r=&c=&rad=&kernel= (float32 layers x +frames; kernel exporter, matched or exact, default --kernel), +/api/progress?key=. +""" + +from __future__ import annotations + +import argparse +import json +import threading +import time +import webbrowser +from collections import OrderedDict +from collections.abc import Iterable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +import numpy as np +import numpy.typing as npt + +from .run import TRACES, SiloRun +from .trial import Session, TrialMovie, load_trial, source_events + +PAGE = Path(__file__).with_name("page.html") +DEFAULT_PORT = 8766 + + +def _json_safe(o: object) -> object: + """``o`` with non-finite floats as None (the browser rejects NaN). + + Returns + ------- + object + o with dicts, lists, tuples (as lists) and numpy values converted + recursively to JSON-safe Python values. + """ + if isinstance(o, float): + return o if np.isfinite(o) else None + if isinstance(o, dict): + return {k: _json_safe(v) for k, v in o.items()} + if isinstance(o, (list, tuple)): + return [_json_safe(v) for v in o] + if isinstance(o, np.ndarray): + return _json_safe(o.tolist()) + if isinstance(o, np.generic): + return _json_safe(o.item()) + return o + + +def _r(a: npt.ArrayLike, nd: int = 3) -> list: + """Round an array to nd decimals as nested lists. + + Returns + ------- + list + The rounded values of a as nested lists. + """ + return np.round(np.asarray(a, dtype=np.float64), nd).tolist() + + +class Store: + """The runs of one session and the trial-paths loaded from them. + + Parameters + ---------- + runs : list of SiloRun + One or more runs of the same session (same paths and trials). + session : Session + The trial table and folders. + label : str + Session label for the page. + cache_trials : int + Trial-paths kept in memory. + blur : float + Gaussian blur (px) of the rendered footprints. + """ + + def __init__( + self, + runs: list[SiloRun], + session: Session, + label: str = "", + cache_trials: int = 2, + blur: float = 0.0, + kernel: str = "matched", + ) -> None: + """Check that the runs fit together. + + Raises + ------ + ValueError + If there are no runs, the run names are not unique, or the runs differ in their paths, + channel count, or activity channel. + """ + if not runs: + raise ValueError("give at least one run") + names = [r.name for r in runs] + if len(set(names)) != len(names): + raise ValueError(f"run names must differ: {names}") + self.runs, self.session, self.label = runs, session, label + self.cache_trials, self.blur = max(1, int(cache_trials)), blur + self.kernel = kernel + self.paths = runs[0].paths + for r in runs[1:]: + if r.paths != self.paths: + raise ValueError( + f"runs have different paths: {runs[0].name} {self.paths}, {r.name} {r.paths}" + ) + # the movie is read once, as the first run's activity channel + # with the trial loader's defaults (trial._settings) + for key, default in (("numChannels", 2), ("activityChannel", 1)): + v0, v = runs[0].param(key, default), r.param(key, default) + if int(v) != int(v0): + raise ValueError(f"runs differ in {key}: {runs[0].name} {v0}, {r.name} {v}") + self._cache: OrderedDict = OrderedDict() + self._loading: dict = {} + # one trial-path loads at a time: each needs a whole movie in memory + self._load_slot = threading.Semaphore(1) + self._lock = threading.Lock() + self.progress: dict = {} + + def run(self, name: str) -> SiloRun: + """Return the run called name. + + Returns + ------- + SiloRun + The run with that name. + + Raises + ------ + KeyError + If no run has that name. + """ + for r in self.runs: + if r.name == name: + return r + raise KeyError(name) + + def meta(self) -> dict: + """List what the page shows: runs, paths, trials. + + Returns + ------- + dict + The session label, blur_px, kernel, the runs (name, folder, + settings), the table, moco_dir and baseline_dir, and per paths + entry its shape, trials and alignment. + """ + paths = [] + for d in self.paths: + p = self.runs[0].path(d) + trials = [] + for t in range(p.n_frames.size): + trials.append({ + "trial": t, + "frames200": int(p.n_frames[t]), + "movie": bool(self.session.has_movie(d - 1, t)), + "baseline": self.session.baseline_file(d - 1, t) is not None, + "aligned": [r.path(d).maps[t] is not None for r in self.runs], + }) + paths.append({ + "path": d, + "shape": list(p.shape), + "trials": trials, + "alignment": [r.path(d).alignment for r in self.runs], + }) + return { + "label": self.label, + "blur_px": self.blur, + "kernel": self.kernel, + "runs": [ + { + "name": r.name, + "dir": str(r.run_dir), + "settings": r.describe(), + } + for r in self.runs + ], + "table": str(self.session.table), + "moco_dir": str(self.session.moco_dir), + "baseline_dir": str(self.session.baseline_dir or ""), + "paths": paths, + } + + def sources(self, d: int) -> dict: + """Every run's sources of path d (canvas, zero-based). + + Returns + ------- + dict + shape of the path's canvas and runs: per run name its kept and + rejected sources, unused seeds (or None) and number of trials. + """ + out = {} + for r in self.runs: + s = r.path(d).sources + kept = ( + np.column_stack([ + s.rc, + s.snr, + s.kinetic_score, + s.kinetic_n_events, + s.width, + s.pixel, + ]) + if s.n + else np.zeros((0, 8)) + ) + rej = np.column_stack([s.rejected_rc, s.rejected_score, s.rejected_n_events]) + seeds = None if s.unused_seeds is None else _r(s.unused_seeds, 2) + out[r.name] = { + "kept": _r(kept), + "rejected": _r(rej), + "seeds": seeds, + "trials": int(r.path(d).n_frames.size), + } + return {"shape": list(self.runs[0].path(d).shape), "runs": out} + + def image(self, d: int, run: str, kind: str, trial: int) -> np.ndarray: + """Return an image of the canvas as float32 (rows, cols). + + Returns + ------- + np.ndarray + The requested image (kind act, mean, trial_act or trial_mean). + + Raises + ------ + KeyError + If kind is unknown, or a per-trial image is asked for a trial it does not have. + """ + p = self.run(run).path(d) + if kind == "act": + img = p.act_im + elif kind == "mean": + img = p.mean_im + elif kind in ("trial_act", "trial_mean"): + stack = p.trial_act if kind == "trial_act" else p.trial_mean + if stack is None or not 0 <= trial < stack.shape[0]: + raise KeyError(f"{kind} of trial {trial}") + img = stack[trial] + else: + raise KeyError(kind) + return np.ascontiguousarray(img, np.float32) + + def source(self, d: int, run: str, s: int) -> dict: + """One kept source: values, footprint, trial positions, events. + + Returns + ------- + dict + The source's id, canvas position rc, pixel, snr, kinetic + scores, width, footprint patch, per-trial positions trial_rc, + offsets, hz and events. + + Raises + ------ + KeyError + If s is not a source index of the path. + """ + r = self.run(run) + p = r.path(d) + src = p.sources + if not 0 <= s < src.n: + raise KeyError(f"source {s}") + patch, r0, c0 = r.profile_patch(d, s) + trc = r.trial_centroids(d) + pos = [] + for t, m in enumerate(p.maps): + rc = trc[t, s] if t < trc.shape[0] else src.rc[s] + if np.isnan(rc).any(): + rc = src.rc[s] + pos.append(None if m is None else _r(m.forward(*rc), 2)) + return { + "id": s, + "rc": _r(src.rc[s], 2), + "pixel": _r(src.pixel[s]), + "snr": float(src.snr[s]), + "kinetic_score": float(src.kinetic_score[s]), + "kinetic_n_events": float(src.kinetic_n_events[s]), + "width": float(src.width[s]), + "footprint": {"r0": r0, "c0": c0, "values": _r(patch, 5)}, + "trial_rc": pos, + "offsets": p.offsets.tolist(), + "hz": float(r.param("analyzeHz", 200.0)), + "events": source_events(r, self.session, d, s), + } + + def source_traces(self, d: int, run: str, s: int) -> np.ndarray: + """Return a source's four traces (4, frames) float32. + + Returns + ------- + np.ndarray + One row per trace in TRACES; NaN where the run has no value. + """ + tr = self.run(run).traces(d) + n = self.run(run).path(d).lines.size + out = np.full((len(TRACES), n), np.nan, np.float32) + for i, name in enumerate(TRACES): + if name in tr and 0 <= s < tr[name].shape[1]: + out[i] = tr[name][:, s] + return out + + def trial(self, d: int, t: int) -> TrialMovie: + """Trial-path (d, t), loaded once (a second request waits). + + Returns + ------- + TrialMovie + The loaded trial-path (from the cache when it is there). + """ + key = (d, t) + while True: + with self._lock: + if key in self._cache: + self._cache.move_to_end(key) + return self._cache[key] + ev = self._loading.get(key) + mine = ev is None + if mine: + ev = self._loading[key] = threading.Event() + if not mine: + ev.wait() + continue + try: + with self._load_slot: + tr = self._load(d, t) + with self._lock: + self._cache[key] = tr + while len(self._cache) > self.cache_trials: + self._cache.popitem(last=False) + finally: + with self._lock: + self._loading.pop(key, None) + ev.set() + return tr + + def _load(self, d: int, t: int) -> TrialMovie: + """Load a trial-path and report the time. + + Returns + ------- + TrialMovie + The loaded trial-path. + + Raises + ------ + KeyError + If the session has no movie for the trial-path. + """ + if not self.session.has_movie(d - 1, t): + raise KeyError(f"no movie for path {d} trial {t + 1}") + key = f"{d}/{t}" + self.progress[key] = "reading the movie and rendering" + t0 = time.time() + try: + tr = load_trial(self.runs, self.session, d, t, self.blur, self.kernel) + finally: + self.progress.pop(key, None) + print( + f"loaded path {d} trial {t + 1}: {tr.T} frames x {tr.N} px in {time.time() - t0:.1f} s", + flush=True, + ) + return tr + + def trial_static(self, d: int, t: int) -> dict: + """Return what the page needs once per trial-path. + + Returns + ------- + dict + The trial's rows, cols, mean image, discard frames, layers, + shape, per-run markers, info and busiest frame of each run. + """ + tr = self.trial(d, t) + runs = {} + for r in tr.runs: + runs[r.name] = { + "kept": _r(r.kept_rc, 2), + "rejected": _r(r.rejected_rc, 2), + "seeds": _r(r.seeds_rc, 2), + "rendered": r.rendered, + } + return { + "rows": tr.rows.tolist(), + "cols": tr.cols.tolist(), + "mean": _r(tr.mean, 2), + "discard": np.flatnonzero(tr.discard).tolist(), + "layers": tr.layers, + "shape": [tr.T, *tr.shape], + "markers": runs, + "info": tr.info, + "busiest": [tr.busiest_frame(i) for i in range(len(tr.runs))], + } + + +def _ints(q: dict, *names: str) -> list: + """Integer query values. + + Returns + ------- + list + int(q[n]) for each name, in order. + """ + return [int(q[n]) for n in names] + + +def _route(store: Store, path: str, q: dict) -> tuple[str, dict | np.ndarray, dict[str, str]]: + """Answer one API request: (kind, payload, headers). + + Returns + ------- + kind : str + "json" or "bin". + payload : dict or np.ndarray + The JSON-able dict, or the array to send as float32 bytes. + headers : dict of str to str + Extra response headers. + + Raises + ------ + LookupError + If path is not an API route. + """ + if path == "/api/meta": + return "json", store.meta(), {} + if path == "/api/sources": + return "json", store.sources(int(q["path"])), {} + if path == "/api/image": + img = store.image(int(q["path"]), q["run"], q["kind"], int(q.get("trial", -1))) + return "bin", img, {"X-Shape": json.dumps(list(img.shape))} + if path == "/api/source": + d, s = _ints(q, "path", "id") + return "json", store.source(d, q["run"], s), {} + if path == "/api/source_traces": + d, s = _ints(q, "path", "id") + return ( + "bin", + store.source_traces(d, q["run"], s), + {"X-Names": json.dumps(list(TRACES))}, + ) + if path == "/api/trial": + d, t = _ints(q, "path", "trial") + return "json", store.trial_static(d, t), {} + if path == "/api/frame": + d, t, f = _ints(q, "path", "trial", "t") + tr = store.trial(d, t) + f = min(max(f, 0), tr.T - 1) + a = tr.frame(f, max(1, int(q.get("avg", 1))), q.get("kernel")) + return "bin", a, {"X-Frame": str(f)} + if path == "/api/trace": + d, t, r, c = _ints(q, "path", "trial", "r", "c") + rad = max(0, int(q.get("rad", 0))) + a, n = store.trial(d, t).trace(r, c, rad, q.get("kernel")) + return "bin", a, {"X-Pixels": str(n)} + if path == "/api/progress": + return "json", {"msg": store.progress.get(q.get("key", ""), "")}, {} + raise LookupError(path) + + +class _Handler(BaseHTTPRequestHandler): + """Serves the page and the API of store. + + The store is set by :func:`make_handler`. + """ + + store: Store + + def log_message(self, *a: object) -> None: + """Quiet.""" + + def _send( + self, code: int, body: bytes, ctype: str, headers: dict[str, str] | None = None + ) -> None: + """Send one response.""" + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def _json(self, obj: object, code: int = 200, headers: dict[str, str] | None = None) -> None: + """Send JSON (non-finite floats as null).""" + body = json.dumps(_json_safe(obj), allow_nan=False).encode() + self._send(code, body, "application/json", headers) + + 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()} + try: + if u.path in ("/", "/index.html"): + self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8") + return + kind, payload, headers = _route(self.store, u.path, q) + if kind == "json": + self._json(payload, headers=headers) + return + body = np.ascontiguousarray(payload, np.float32).tobytes() + self._send(200, body, "application/octet-stream", headers) + except KeyError as e: + self._json({"error": f"missing or unknown {e}"}, 400) + except LookupError: + self._json({"error": f"not found: {u.path}"}, 404) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception as e: # noqa: BLE001 (shown on the page) + self._json({"error": f"{type(e).__name__}: {e}"}, 500) + + +def make_handler(store: Store) -> type[_Handler]: + """Build the request handler class serving store. + + Returns + ------- + type[_Handler] + A handler class whose store is the given store. + """ + return type("Handler", (_Handler,), {"store": store}) + + +def _run_args(items: Iterable[str]) -> list: + """NAME=DIR or DIR arguments as (name, dir). + + Returns + ------- + list + One (name, dir) tuple per item; name is None for a plain DIR. + """ + out = [] + for item in items: + name, sep, d = str(item).partition("=") + if sep and name and not Path(item).exists(): + out.append((name, d)) + else: + out.append((None, item)) + return out + + +def _default_table(run_dir: Path) -> Path | None: + """Find a trial table in or above a run folder. + + Returns + ------- + Path or None + The nearest trial_table.h5 (in the folder or up to two levels above), or None. + """ + for d in (run_dir, run_dir.parent, run_dir.parent.parent): + if (d / "trial_table.h5").exists(): + return d / "trial_table.h5" + return None + + +def make_store(args: argparse.Namespace) -> Store: + """Build the store for parsed giant view arguments. + + Returns + ------- + Store + The store of the given runs and session. + + Raises + ------ + ValueError + If no trial table was given and none is found in or above the first run folder. + """ + runs = [SiloRun(d, name) for name, d in _run_args(args.runs)] + table = args.table or _default_table(runs[0].run_dir) + if table is None: + raise ValueError(f"no trial_table.h5 in or above {runs[0].run_dir}: give --table") + session = Session(table, args.moco_dir, args.baseline_dir, args.data_dir) + label = args.label or Path(session.table).parent.name + return Store(runs, session, label, args.cache_trials, args.blur, args.kernel) + + +def make_server( + store: Store, host: str = "127.0.0.1", port: int = DEFAULT_PORT +) -> ThreadingHTTPServer: + """Build an HTTP server for store (not started). + + Returns + ------- + ThreadingHTTPServer + The server bound to host and port. + """ + return ThreadingHTTPServer((host, port), make_handler(store)) + + +def add_arguments(p: argparse.ArgumentParser) -> None: + """``giant view``'s options.""" + p.add_argument( + "runs", + nargs="+", + metavar="RUN", + help="SILo run folders (holding experiment_summary.h5, " + "directly or in source_extraction/), optionally as " + "NAME=FOLDER; two or more runs of the same session are " + "compared", + ) + p.add_argument( + "--table", + default=None, + help="the session's trial_table.h5 (default: in or above the first run's folder)", + ) + p.add_argument( + "--moco-dir", + default=None, + help="registered movies and alignment files (default: " + "the table's savedr/motion_correction)", + ) + p.add_argument( + "--baseline-dir", + default=None, + help="F0 network baselines (_BASELINE-80Hz.h5); adds the baseline layers", + ) + p.add_argument( + "--data-dir", + default=None, + help="raw .dat/.meta folder, for the lines per cycle " + "(default: the table's datadr; without it the frame " + "kernel reaches 3 dt)", + ) + p.add_argument("--label", default="", help="session label on the page") + p.add_argument( + "--blur", + type=float, + default=0.0, + help="Gaussian blur (px) of the rendered footprints (default 0)", + ) + p.add_argument( + "--kernel", + choices=("matched", "exporter", "exact"), + default="matched", + help="how SILo's 200 Hz traces become the movie's 80 Hz " + "frames: matched (default; sqrt(dt80^2 - dt200^2), for the " + "200 Hz frames' own smoothing), the exporter's weights (the " + "movie's dt), or exact (r x200 + (1 - r) exporter's, r = " + "(dt200/dt80)^2); the page switches between them", + ) + p.add_argument( + "--cache-trials", + type=int, + default=2, + help="trial-paths kept in memory", + ) + 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") + + +def serve(args: argparse.Namespace) -> int: + """Run giant view until interrupted. + + Returns + ------- + int + The exit code, 0. + """ + store = make_store(args) + server = make_server(store, args.host, args.port) + url = f"http://{args.host}:{server.server_address[1]}/" + names = ", ".join(r.name for r in store.runs) + print( + f"{store.label}: runs {names}; paths {store.paths}; serving {url} (Ctrl+C to stop)", + flush=True, + ) + if not args.no_browser: + threading.Timer(0.5, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 diff --git a/src/giant_python/viewer/trial.py b/src/giant_python/viewer/trial.py index 6462f4c7..c9f682a7 100644 --- a/src/giant_python/viewer/trial.py +++ b/src/giant_python/viewer/trial.py @@ -1,757 +1,757 @@ -"""One trial-path in the viewer's movie view. - -The registered 80 Hz movie of the trial (the activity channel, in the -trial's own registered frame, not resampled), the runs' fitted activity -rendered into it (:mod:`~giant_python.viewer.render`), and the F0 -network's baseline when a baseline folder is given. Arrays are held for -the valid pixels only, as the exporter defines them: missing in less than -nanThresh of the frames with SILo's motion discards counted as -missing. The frames blanked afterwards because their kernel weight lies -mostly on discarded 200 Hz frames do not count (they are blank at every -pixel, and the exporter's training targets cover the same pixels). The -activity is not stored per frame: a frame or a trace is the footprints -(sparse) times the sources' 80 Hz traces. -""" - -from __future__ import annotations - -import math -import threading -from dataclasses import dataclass, field -from pathlib import Path, PurePath - -import h5py -import numpy as np - -from ..extraction.raster.trial import discard_frames -from ..pipeline.silo_session import _grid, _read -from .render import ( - KERNELS, - TrialMap, - frame_dt200, - kernel_dt, - kernel_weights, - place_footprints, -) -from .run import SiloRun - - -class Session: - """The trial table and folders the runs of one session share. - - Parameters - ---------- - table : str or Path - trial_table.h5 (or its folder). - moco_dir : str or Path, optional - Folder of the registered movies and alignment files (default: - /motion_correction, else next to the table). - baseline_dir : str or Path, optional - Folder of _BASELINE-80Hz.h5 (slap2-f0 - predict-registered); optional. - data_dir : str or Path, optional - Folder of the raw files, to read the lines per cycle (default: the - table's datadr; without them the kernel reaches 3 dt). - """ - - def __init__( - self, - table: str | Path, - moco_dir: str | Path | None = None, - baseline_dir: str | Path | None = None, - data_dir: str | Path | None = None, - ) -> None: - """Read the table's file names. - - Raises - ------ - ValueError - If the table has no registration (fn_reg_ds or fn_adata is missing). - """ - table = Path(table) - if table.is_dir(): - table = table / "trial_table.h5" - self.table = table - with h5py.File(table, "r") as f: - rm = "row_major" in f and bool(np.ravel(f["row_major"][()])[0]) - filename = np.atleast_2d(_read(f, "filename", rm)) - shape = filename.shape - reg = _read(f, "motion_correction/fn_reg_ds", rm) - adata = _read(f, "motion_correction/fn_adata", rm) - savedr = _read(f, "savedr", rm) - datadr = _read(f, "datadr", rm) - if reg is None or adata is None: - raise ValueError(f"{table} has no registration") - self.filename = filename - self.fn_reg_ds = _grid(reg, shape) - self.fn_adata = _grid(adata, shape) - savedr = Path(str(np.ravel(savedr)[0])) if savedr is not None else None - if moco_dir is None: - moco_dir = (savedr / "motion_correction") if savedr else None - if moco_dir is None or not moco_dir.exists(): - moco_dir = table.parent / "motion_correction" - self.moco_dir = Path(moco_dir) - self.baseline_dir = Path(baseline_dir) if baseline_dir else None - if data_dir is None and datadr is not None: - data_dir = str(np.ravel(datadr)[0]) - self.data_dir = Path(data_dir) if data_dir else None - self._ds: dict = {} - self._lpc: dict = {} - - @staticmethod - def _name(value: object) -> str: - """Return a table file name without its folder. - - Returns - ------- - str - The file name, without its folder. - """ - return PurePath(str(value).replace("\\", "/")).name - - def movie_file(self, d: int, t: int) -> Path: - """Find the registered movie of path d, trial t (zero-based). - - It is found by its stem as .tif or .h5, as SILo finds it - (:meth:`SiloSession.movie`); the table's name if neither exists. - - Returns - ------- - Path - The movie's path in the motion-correction folder. - """ - name = self._name(self.fn_reg_ds[d, t]) - stem = PurePath(name).stem - for ext in (".tif", ".h5"): - p = self.moco_dir / (stem + ext) - if p.exists(): - return p - return self.moco_dir / name - - def alignment_file(self, d: int, t: int) -> Path: - """Return the alignment file of path d, trial t (zero-based). - - Returns - ------- - Path - The alignment file's path in the motion-correction folder. - """ - return self.moco_dir / self._name(self.fn_adata[d, t]) - - def has_movie(self, d: int, t: int) -> bool: - """Whether the trial's movie and alignment file are here. - - Returns - ------- - bool - True when the table names a movie and both files exist. - """ - if not str(self.fn_reg_ds[d, t]).strip(): - return False - return self.movie_file(d, t).exists() and self.alignment_file(d, t).exists() - - def baseline_file(self, d: int, t: int) -> Path | None: - """Find the trial's network baseline, if there is one. - - Returns - ------- - Path or None - The baseline file; None when there is no baseline folder or file for the trial. - """ - if self.baseline_dir is None: - return None - name = self._name(self.fn_reg_ds[d, t]) - if "_REGISTERED" not in name: - return None - stem = name[: name.index("_REGISTERED")] - p = self.baseline_dir / f"{stem}_BASELINE-80Hz.h5" - return p if p.exists() else None - - def ds_lines(self, d: int, t: int) -> np.ndarray: - """Read the registered frames' lines (DSframes) of a trial. - - Returns - ------- - np.ndarray - The lines of the trial's registered frames, as a flat float vector. - """ - key = (d, t) - if key not in self._ds: - with h5py.File(self.alignment_file(d, t), "r") as f: - self._ds[key] = np.asarray(f["DSframes"][()], float).ravel() - return self._ds[key] - - def lines_per_cycle(self, d: int, t: int) -> int: - """Lines per cycle from the raw file's header (0 if unreadable). - - Returns - ------- - int - The lines per cycle; 0 when there is no raw data or its header is unreadable. - """ - key = (d, t) - if key not in self._lpc: - self._lpc[key] = 0 - if self.data_dir is not None: - try: - from ..io.slap2_raster import raster_layout - - fn = self.data_dir / self._name(self.filename[d, t]) - self._lpc[key] = int(raster_layout(fn).lines_per_cycle) - except Exception: # noqa: BLE001 (no raw data: 3 dt) - self._lpc[key] = 0 - return self._lpc[key] - - -def read_channel(path: Path, num_channels: int, channel: int) -> np.ndarray: - """One channel of a registered movie as (frames, rows, cols) float32. - - Zero-based channel; channels interleaved by frame. - - Returns - ------- - np.ndarray - The channel's frames, (frames, rows, cols) float32. - """ - if path.suffix == ".h5": - with h5py.File(path, "r") as f: - ds = f[next(iter(f.keys()))] # (pages, MATLAB cols, rows) - n = ds.shape[0] // num_channels - # whole frames at a time: twice as fast as a strided selection - # of the (one page per chunk, compressed) dataset - step = 128 * num_channels - raw = np.concatenate([ - ds[a : min(a + step, n * num_channels)][channel::num_channels] - for a in range(0, n * num_channels, step) - ]) - else: - import tifffile - - with tifffile.TiffFile(path) as tf: - pages = tf.pages - n = len(pages) // num_channels - first = pages[channel].asarray() - raw = np.empty((n,) + first.shape, first.dtype) - raw[0] = first - for k in range(1, n): - raw[k] = pages[channel + k * num_channels].asarray() - return np.ascontiguousarray(np.asarray(raw, np.float32).transpose(0, 2, 1)) - - -@dataclass -class RunLayer: - """One run's activity in a trial. - - Attributes - ---------- - name : str - footprints : scipy.sparse.csr_matrix (valid pixels, sources) - x80 : dict - Time kernel (:data:`KERNELS`) to the sources' denoised traces at - the movie's frames, (sources, frames). - kept_rc, rejected_rc, seeds_rc : ndarray (n, 2) - Marker positions in the trial's registered frame. - kernels : dict - Time kernel to its (dt, reach) in lines, from this run's own - 200 Hz frame lines (:func:`render_dt`). - rendered : bool - False when the run has no footprints or no map for the trial. - """ - - name: str - footprints: object - x80: dict - kept_rc: np.ndarray - rejected_rc: np.ndarray - seeds_rc: np.ndarray - rendered: bool = True - kernels: dict = field(default_factory=dict) - - -@dataclass -class TrialMovie: - """A loaded trial-path: movie, baseline and each run's activity. - - kernel is the time kernel (:data:`KERNELS`) that :meth:`frame` and - :meth:`trace` use unless they are given another. - """ - - path: int - trial: int - shape: tuple - rows: np.ndarray - cols: np.ndarray - mean: np.ndarray - discard: np.ndarray - movie: np.ndarray - baseline: np.ndarray | None - runs: list - info: dict = field(default_factory=dict) - kernel: str = "matched" - lock: threading.Lock = field(default_factory=threading.Lock, repr=False) - - @property - def T(self) -> int: - """Frames.""" - return int(self.movie.shape[0]) - - @property - def N(self) -> int: - """Valid pixels.""" - return int(self.movie.shape[1]) - - @property - def layers(self) -> list: - """Layer names in the order of :meth:`frame` and :meth:`trace`.""" - out = ["movie"] - for r in self.runs: - out += [f"activity:{r.name}", f"residual:{r.name}"] - if self.baseline is not None: - out.append("baseline") - out += [f"residual-baseline:{r.name}" for r in self.runs] - return out - - def span(self, t: int, avg: int) -> tuple: - """Return the frames [lo, hi) a mean of avg frames at t uses. - - Returns - ------- - tuple - (lo, hi): the first frame and the end (exclusive) of the span. - """ - lo = min(max(t - (avg - 1) // 2, 0), self.T - 1) - return lo, min(max(lo + avg, lo + 1), self.T) - - def _stack(self, frames: slice, pixels: np.ndarray | slice, kernel: str | None = None) -> list: - """Every layer's values (frames, pixels) at the given frames and pixels. - - The frames are a slice; the pixels an index array or a slice. - - Returns - ------- - list - One (frames, pixels) array per layer, in the order of :attr:`layers`. - - Raises - ------ - KeyError - If kernel is not one of the known kernels. - """ - kernel = kernel or self.kernel - if kernel not in KERNELS: - raise KeyError(f"kernel {kernel}") - m = self.movie[frames][:, pixels] - miss = np.isnan(m) - out = [m] - acts = [] - for r in self.runs: - h = r.footprints[pixels] if r.rendered else None - a = ( - np.asarray((h @ r.x80[kernel][:, frames]).T, np.float32) - if h is not None - else np.zeros_like(m) - ) - a[miss] = np.nan - acts.append(a) - out += [a, m - a] - if self.baseline is not None: - b = self.baseline[frames][:, pixels].astype(np.float32) - out.append(b) - out += [m - a - b for a in acts] - return out - - def frame(self, t: int, avg: int, kernel: str | None = None) -> np.ndarray: - """Each layer's mean over avg frames at t. - - (layers, valid pixels) float32, NaN-aware. - - Returns - ------- - np.ndarray - The means, (layers, valid pixels) float32. - """ - lo, hi = self.span(t, avg) - blocks = self._stack(slice(lo, hi), slice(None), kernel) - out = np.empty((len(blocks), self.N), np.float32) - with np.errstate(invalid="ignore"), _quiet(): - for i, b in enumerate(blocks): - out[i] = b[0] if hi - lo == 1 else np.nanmean(b, 0) - return out - - def trace(self, r: int, c: int, rad: int, kernel: str | None = None) -> tuple: - """Each layer's mean over the valid pixels within rad rows and columns of (r, c). - - Returns (layers, frames) float32, and the number of pixels. - - Returns - ------- - trace : np.ndarray - Each layer's mean trace, (layers, frames) float32. - n_pixels : int - The number of valid pixels averaged. - """ - near = (np.abs(self.rows - r) <= rad) & (np.abs(self.cols - c) <= rad) - k = np.flatnonzero(near) - out = np.full((len(self.layers), self.T), np.nan, np.float32) - if k.size: - with _quiet(): - for i, b in enumerate(self._stack(slice(None), k, kernel)): - out[i] = np.nanmean(b, 1) - return out, int(k.size) - - def busiest_frame(self, run: int = 0) -> int: - """Find the frame with the most rendered activity of a run. - - Returns - ------- - int - The frame index; 0 when the run is not rendered or has no activity. - """ - r = self.runs[run] - x = r.x80[self.kernel] - if not r.rendered or x.size == 0: - return 0 - total = np.asarray(r.footprints.sum(0)).ravel() @ x - total[self.discard] = -np.inf - return int(np.argmax(total)) - - -class _quiet: - """Silence NumPy's all-NaN warnings inside a block.""" - - def __enter__(self) -> None: - """Start ignoring RuntimeWarnings.""" - import warnings - - self._w = warnings.catch_warnings() - self._w.__enter__() - warnings.simplefilter("ignore", RuntimeWarning) - - def __exit__(self, *exc: object) -> None: - """Restore the warning filters.""" - self._w.__exit__(*exc) - - -def _marker_rc(tmap: TrialMap | None, rc: np.ndarray) -> np.ndarray: - """Canvas positions moved into the trial frame (NaN rows stay NaN). - - Returns - ------- - np.ndarray - The positions (n, 2) in the trial's registered frame; a copy of rc when there - is no map. - """ - rc = np.asarray(rc, np.float64).reshape(-1, 2) - if tmap is None or rc.size == 0: - return rc.copy() - r, c = tmap.forward(np.nan_to_num(rc[:, 0]), np.nan_to_num(rc[:, 1])) - out = np.column_stack([r, c]) - out[np.isnan(rc).any(1)] = np.nan - return out - - -def run_layer(run: SiloRun, session: Session, d: int, t: int, ctx: dict) -> RunLayer: - """One run's activity in trial t of path d (one-based path, zero-based trial). - - ctx holds the trial's shape, valid flat pixel indices flat, - ds_lines, the movie's kernel dt, the lines per cycle lpc and - blur; the time kernels come from the run's own 200 Hz frame lines - (:func:`render_dt`), and the run's 80 Hz discard share under the - exporter's kernel is added to ctx. - - Returns - ------- - RunLayer - The run's footprints, denoised traces per time kernel and marker positions in the trial. - """ - p = run.path(d) - n = p.sources.n - tmap = p.maps[t] if t < len(p.maps) else None - fps = run.footprints(d) - fp = fps[t] if t < len(fps) else None - span = p.trial_span(t) if t < p.n_frames.size else slice(0, 0) - lines200 = p.lines[span] - rendered = bool(tmap is not None and fp is not None and lines200.size) - T = ctx["ds_lines"].size - kernels = {} - for k in KERNELS: - dtr = render_dt(k, ctx["dt"], lines200) - kernels[k] = (dtr, max(3 * dtr, ctx["lpc"])) - x80 = {k: np.zeros((n, T), np.float32) for k in kernels} - h = None - if rendered: - x200 = np.nan_to_num(run.traces(d)["dF_denoised"][span]) # (n200, n) - for k in kernels: - w, share, _ = kernel_weights( - k, - lines200, - p.discard[span], - ctx["ds_lines"], - ctx["dt"], - ctx["lpc"], - ) - if k == "exporter": - ctx.setdefault("shares", []).append(share) - x80[k] = np.asarray((w.T @ x200).T, np.float32) - h = place_footprints(fp, n, tmap, ctx["shape"], ctx["blur"]) - h = h[ctx["flat"]] - trc = run.trial_centroids(d) - rc = trc[t] if t < trc.shape[0] else np.full((n, 2), np.nan) - rc = np.where(np.isnan(rc), p.sources.rc, rc) - seeds = p.sources.unused_seeds - return RunLayer( - name=run.name, - footprints=h, - x80=x80, - kept_rc=_marker_rc(tmap, rc), - rejected_rc=_marker_rc(tmap, p.sources.rejected_rc), - seeds_rc=_marker_rc(tmap, seeds if seeds is not None else []), - rendered=rendered, - kernels=kernels, - ) - - -def _settings(run: SiloRun) -> dict: - """SILo's frame settings of a run (defaults: SILo's for SLAP2). - - Returns - ------- - dict - num_channels, channel, motion_thresh, discard_initial_s, - nan_thresh and ratio (analysis to alignment frame rate). - """ - return { - "num_channels": int(run.param("numChannels", 2)), - "channel": run.activity_channel, - "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)), - } - - -def _read_alignment(path: Path, n_frames: int) -> tuple[float, np.ndarray]: - """Return alignHz and recNegErr from a trial's alignment file. - - Returns - ------- - hz : float - The alignment frame rate, alignHz. - rne : np.ndarray - recNegErr of the first n_frames frames. - """ - with h5py.File(path, "r") as f: - hz = float(np.ravel(f["alignHz"][()])[0]) - rne = np.asarray(f["recNegErr"][()], np.float64).ravel()[:n_frames] - return hz, rne - - -def render_dt(kernel: str, dt80: int, lines200: np.ndarray) -> float: - """Return the time constant (lines) the 200 Hz traces are averaged with. - - exporter: the movie's own dt, as the exporter does. The 200 Hz - frames are already averaged with their own kernel (dt200 = - ceil(mean(diff(lines)))), so this smooths fast events twice; - matched uses sqrt(dt80**2 - dt200**2), the kernel whose - variance added to the 200 Hz frames' gives the movie's; exact - averages with the movie's dt and adds the interpolated 200 Hz - frames (:func:`~giant_python.viewer.render.exact_weights`). - - Returns - ------- - float - The time constant, in lines. - - Raises - ------ - ValueError - If kernel is not one of the known kernels. - """ - if kernel in ("exporter", "exact"): - return float(dt80) - if kernel != "matched": - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - lines200 = np.asarray(lines200, dtype=np.float64) - if lines200.size < 2: - return float(dt80) - dt200 = frame_dt200(lines200, dt80) - return math.sqrt(max(dt80**2 - dt200**2, 1.0)) - - -def load_trial( - runs: list, - session: Session, - d: int, - t: int, - blur: float = 0.0, - kernel: str = "matched", -) -> TrialMovie: - """Load trial t (zero-based) of path d (one-based) with every run's activity. - - The movie is NaN at SILo's motion discards (recNegErr, as - loadAndProcessTrialAsync) and at the frames whose kernel weight - falls mostly on SILo's discarded 200 Hz frames (the exporter's rule). - Valid pixels are decided on the motion discards alone, as the - exporter decides them (see the module docstring). - Both time kernels (:func:`render_dt`) are rendered; kernel is the - one :meth:`TrialMovie.frame` uses by default. - - Returns - ------- - TrialMovie - The trial's movie, baseline, valid-pixel layout, every run's activity and an info - dict of the settings used. - - Raises - ------ - ValueError - If kernel is not one of the known kernels. - """ - if kernel not in KERNELS: - raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") - st = _settings(runs[0]) - movie = read_channel(session.movie_file(d - 1, t), st["num_channels"], st["channel"]) - T, R, C = movie.shape - hz, rne = _read_alignment(session.alignment_file(d - 1, t), T) - disc = discard_frames(rne, hz, st["motion_thresh"], st["discard_initial_s"]) - movie[disc] = np.nan - with np.errstate(invalid="ignore"): - valid = np.isnan(movie).mean(0) < st["nan_thresh"] - rows, cols = np.nonzero(valid) - flat = rows * C + cols - ds = session.ds_lines(d - 1, t)[:T] - lines0 = runs[0].path(d).lines - dt = kernel_dt(ds, lines0, st["ratio"]) - lpc = session.lines_per_cycle(d - 1, t) - ctx = { - "shape": (R, C), - "flat": flat, - "ds_lines": ds, - "dt": dt, - "lpc": lpc, - "blur": float(blur), - } - layers = [run_layer(r, session, d, t, ctx) for r in runs] - for share in ctx.get("shares", []): - disc = disc | (share > 0.5) - mov = movie.reshape(T, R * C)[:, flat] - del movie - mov[disc] = np.nan - base = _read_baseline(session.baseline_file(d - 1, t), (T, R, C), flat) - if base is not None: - base[disc] = np.nan - with np.errstate(invalid="ignore"), _quiet(): - mean = np.nanmean(mov, 0) - info = { - "dt_lines": dt, - "render_dt_lines": { - r.name: {k: round(v[0], 2) for k, v in r.kernels.items()} for r in layers - }, - "reach_lines": {r.name: {k: round(v[1], 1) for k, v in r.kernels.items()} for r in layers}, - "lines_per_cycle": lpc, - "blur_px": float(blur), - "align_hz": hz, - "movie": session.movie_file(d - 1, t).name, - "baseline": (session.baseline_file(d - 1, t) or Path("")).name, - "discarded": int(disc.sum()), - } - return TrialMovie( - path=d, - trial=t, - shape=(R, C), - rows=rows, - cols=cols, - mean=mean, - discard=disc, - movie=mov, - baseline=base, - runs=layers, - info=info, - kernel=kernel, - ) - - -def _read_baseline(path: Path | None, shape: tuple, flat: np.ndarray) -> np.ndarray | None: - """Read a network baseline at the valid pixels, float16 (frames, N). - - Returns - ------- - np.ndarray or None - The baseline, float16 (frames, N); None when path is None. - - Raises - ------ - ValueError - If the baseline's shape does not match the movie's. - """ - if path is None: - return None - T, R, C = shape - with h5py.File(path, "r") as f: - b = np.asarray(f["baseline"][()]) # (frames, MATLAB cols, rows) - if b.shape != (T, C, R): - raise ValueError(f"{path.name}: baseline {b.shape}, movie {shape}") - b = b.transpose(0, 2, 1).reshape(T, R * C)[:, flat] - return np.ascontiguousarray(b.astype(np.float16)) - - -def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: - """Return indices of the n largest local maxima of x at least gap samples apart. - - The indices are ordered largest first. - - Returns - ------- - np.ndarray - The indices of the largest local maxima, largest first. - """ - x = np.nan_to_num(np.asarray(x, np.float64), nan=-np.inf) - if x.size < 3: - return np.zeros(0, int) - peak = np.flatnonzero((x[1:-1] > x[:-2]) & (x[1:-1] >= x[2:])) + 1 - peak = peak[x[peak] > 0] - order = peak[np.argsort(-x[peak], kind="stable")] - taken: list = [] - for i in order: - if all(abs(i - j) >= gap for j in taken): - taken.append(int(i)) - if len(taken) >= n: - break - return np.asarray(taken, int) - - -def source_events( - run: SiloRun, session: Session, d: int, s: int, n: int = 30 -) -> list[dict[str, float]]: - """Find a source's largest denoised events over all trials, as movie frames. - - Returns a list of {trial, frame, line, value} (largest first). - - Returns - ------- - list[dict[str, float]] - Up to n events, largest first, each with the trial, the movie frame, the - acquisition line and the value of the denoised trace. - """ - p = run.path(d) - x = run.traces(d)["dF_denoised"][:, s] - hz = float(run.param("analyzeHz", 200.0)) - gap = max(1, math.ceil(0.25 * hz)) - out = [] - for t in range(p.n_frames.size): - span = p.trial_span(t) - if span.stop <= span.start or not session.has_movie(d - 1, t): - continue - xs = x[span] - ds = session.ds_lines(d - 1, t) - for i in largest_events(xs, n, gap): - line = float(p.lines[span][i]) - frame = int(np.argmin(np.abs(ds - line))) - out.append({ - "trial": t, - "frame": frame, - "value": float(xs[i]), - "line": line, - }) - out.sort(key=lambda e: -e["value"]) - return out[:n] +"""One trial-path in the viewer's movie view. + +The registered 80 Hz movie of the trial (the activity channel, in the +trial's own registered frame, not resampled), the runs' fitted activity +rendered into it (:mod:`~giant_python.viewer.render`), and the F0 +network's baseline when a baseline folder is given. Arrays are held for +the valid pixels only, as the exporter defines them: missing in less than +nanThresh of the frames with SILo's motion discards counted as +missing. The frames blanked afterwards because their kernel weight lies +mostly on discarded 200 Hz frames do not count (they are blank at every +pixel, and the exporter's training targets cover the same pixels). The +activity is not stored per frame: a frame or a trace is the footprints +(sparse) times the sources' 80 Hz traces. +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass, field +from pathlib import Path, PurePath + +import h5py +import numpy as np + +from ..extraction.raster.trial import discard_frames +from ..pipeline.silo_session import _grid, _read +from .render import ( + KERNELS, + TrialMap, + frame_dt200, + kernel_dt, + kernel_weights, + place_footprints, +) +from .run import SiloRun + + +class Session: + """The trial table and folders the runs of one session share. + + Parameters + ---------- + table : str or Path + trial_table.h5 (or its folder). + moco_dir : str or Path, optional + Folder of the registered movies and alignment files (default: + /motion_correction, else next to the table). + baseline_dir : str or Path, optional + Folder of _BASELINE-80Hz.h5 (slap2-f0 + predict-registered); optional. + data_dir : str or Path, optional + Folder of the raw files, to read the lines per cycle (default: the + table's datadr; without them the kernel reaches 3 dt). + """ + + def __init__( + self, + table: str | Path, + moco_dir: str | Path | None = None, + baseline_dir: str | Path | None = None, + data_dir: str | Path | None = None, + ) -> None: + """Read the table's file names. + + Raises + ------ + ValueError + If the table has no registration (fn_reg_ds or fn_adata is missing). + """ + table = Path(table) + if table.is_dir(): + table = table / "trial_table.h5" + self.table = table + with h5py.File(table, "r") as f: + rm = "row_major" in f and bool(np.ravel(f["row_major"][()])[0]) + filename = np.atleast_2d(_read(f, "filename", rm)) + shape = filename.shape + reg = _read(f, "motion_correction/fn_reg_ds", rm) + adata = _read(f, "motion_correction/fn_adata", rm) + savedr = _read(f, "savedr", rm) + datadr = _read(f, "datadr", rm) + if reg is None or adata is None: + raise ValueError(f"{table} has no registration") + self.filename = filename + self.fn_reg_ds = _grid(reg, shape) + self.fn_adata = _grid(adata, shape) + savedr = Path(str(np.ravel(savedr)[0])) if savedr is not None else None + if moco_dir is None: + moco_dir = (savedr / "motion_correction") if savedr else None + if moco_dir is None or not moco_dir.exists(): + moco_dir = table.parent / "motion_correction" + self.moco_dir = Path(moco_dir) + self.baseline_dir = Path(baseline_dir) if baseline_dir else None + if data_dir is None and datadr is not None: + data_dir = str(np.ravel(datadr)[0]) + self.data_dir = Path(data_dir) if data_dir else None + self._ds: dict = {} + self._lpc: dict = {} + + @staticmethod + def _name(value: object) -> str: + """Return a table file name without its folder. + + Returns + ------- + str + The file name, without its folder. + """ + return PurePath(str(value).replace("\\", "/")).name + + def movie_file(self, d: int, t: int) -> Path: + """Find the registered movie of path d, trial t (zero-based). + + It is found by its stem as .tif or .h5, as SILo finds it + (:meth:`SiloSession.movie`); the table's name if neither exists. + + Returns + ------- + Path + The movie's path in the motion-correction folder. + """ + name = self._name(self.fn_reg_ds[d, t]) + stem = PurePath(name).stem + for ext in (".tif", ".h5"): + p = self.moco_dir / (stem + ext) + if p.exists(): + return p + return self.moco_dir / name + + def alignment_file(self, d: int, t: int) -> Path: + """Return the alignment file of path d, trial t (zero-based). + + Returns + ------- + Path + The alignment file's path in the motion-correction folder. + """ + return self.moco_dir / self._name(self.fn_adata[d, t]) + + def has_movie(self, d: int, t: int) -> bool: + """Whether the trial's movie and alignment file are here. + + Returns + ------- + bool + True when the table names a movie and both files exist. + """ + if not str(self.fn_reg_ds[d, t]).strip(): + return False + return self.movie_file(d, t).exists() and self.alignment_file(d, t).exists() + + def baseline_file(self, d: int, t: int) -> Path | None: + """Find the trial's network baseline, if there is one. + + Returns + ------- + Path or None + The baseline file; None when there is no baseline folder or file for the trial. + """ + if self.baseline_dir is None: + return None + name = self._name(self.fn_reg_ds[d, t]) + if "_REGISTERED" not in name: + return None + stem = name[: name.index("_REGISTERED")] + p = self.baseline_dir / f"{stem}_BASELINE-80Hz.h5" + return p if p.exists() else None + + def ds_lines(self, d: int, t: int) -> np.ndarray: + """Read the registered frames' lines (DSframes) of a trial. + + Returns + ------- + np.ndarray + The lines of the trial's registered frames, as a flat float vector. + """ + key = (d, t) + if key not in self._ds: + with h5py.File(self.alignment_file(d, t), "r") as f: + self._ds[key] = np.asarray(f["DSframes"][()], float).ravel() + return self._ds[key] + + def lines_per_cycle(self, d: int, t: int) -> int: + """Lines per cycle from the raw file's header (0 if unreadable). + + Returns + ------- + int + The lines per cycle; 0 when there is no raw data or its header is unreadable. + """ + key = (d, t) + if key not in self._lpc: + self._lpc[key] = 0 + if self.data_dir is not None: + try: + from ..io.slap2_raster import raster_layout + + fn = self.data_dir / self._name(self.filename[d, t]) + self._lpc[key] = int(raster_layout(fn).lines_per_cycle) + except Exception: # noqa: BLE001 (no raw data: 3 dt) + self._lpc[key] = 0 + return self._lpc[key] + + +def read_channel(path: Path, num_channels: int, channel: int) -> np.ndarray: + """One channel of a registered movie as (frames, rows, cols) float32. + + Zero-based channel; channels interleaved by frame. + + Returns + ------- + np.ndarray + The channel's frames, (frames, rows, cols) float32. + """ + if path.suffix == ".h5": + with h5py.File(path, "r") as f: + ds = f[next(iter(f.keys()))] # (pages, MATLAB cols, rows) + n = ds.shape[0] // num_channels + # whole frames at a time: twice as fast as a strided selection + # of the (one page per chunk, compressed) dataset + step = 128 * num_channels + raw = np.concatenate([ + ds[a : min(a + step, n * num_channels)][channel::num_channels] + for a in range(0, n * num_channels, step) + ]) + else: + import tifffile + + with tifffile.TiffFile(path) as tf: + pages = tf.pages + n = len(pages) // num_channels + first = pages[channel].asarray() + raw = np.empty((n,) + first.shape, first.dtype) + raw[0] = first + for k in range(1, n): + raw[k] = pages[channel + k * num_channels].asarray() + return np.ascontiguousarray(np.asarray(raw, np.float32).transpose(0, 2, 1)) + + +@dataclass +class RunLayer: + """One run's activity in a trial. + + Attributes + ---------- + name : str + footprints : scipy.sparse.csr_matrix (valid pixels, sources) + x80 : dict + Time kernel (:data:`KERNELS`) to the sources' denoised traces at + the movie's frames, (sources, frames). + kept_rc, rejected_rc, seeds_rc : ndarray (n, 2) + Marker positions in the trial's registered frame. + kernels : dict + Time kernel to its (dt, reach) in lines, from this run's own + 200 Hz frame lines (:func:`render_dt`). + rendered : bool + False when the run has no footprints or no map for the trial. + """ + + name: str + footprints: object + x80: dict + kept_rc: np.ndarray + rejected_rc: np.ndarray + seeds_rc: np.ndarray + rendered: bool = True + kernels: dict = field(default_factory=dict) + + +@dataclass +class TrialMovie: + """A loaded trial-path: movie, baseline and each run's activity. + + kernel is the time kernel (:data:`KERNELS`) that :meth:`frame` and + :meth:`trace` use unless they are given another. + """ + + path: int + trial: int + shape: tuple + rows: np.ndarray + cols: np.ndarray + mean: np.ndarray + discard: np.ndarray + movie: np.ndarray + baseline: np.ndarray | None + runs: list + info: dict = field(default_factory=dict) + kernel: str = "matched" + lock: threading.Lock = field(default_factory=threading.Lock, repr=False) + + @property + def T(self) -> int: + """Frames.""" + return int(self.movie.shape[0]) + + @property + def N(self) -> int: + """Valid pixels.""" + return int(self.movie.shape[1]) + + @property + def layers(self) -> list: + """Layer names in the order of :meth:`frame` and :meth:`trace`.""" + out = ["movie"] + for r in self.runs: + out += [f"activity:{r.name}", f"residual:{r.name}"] + if self.baseline is not None: + out.append("baseline") + out += [f"residual-baseline:{r.name}" for r in self.runs] + return out + + def span(self, t: int, avg: int) -> tuple: + """Return the frames [lo, hi) a mean of avg frames at t uses. + + Returns + ------- + tuple + (lo, hi): the first frame and the end (exclusive) of the span. + """ + lo = min(max(t - (avg - 1) // 2, 0), self.T - 1) + return lo, min(max(lo + avg, lo + 1), self.T) + + def _stack(self, frames: slice, pixels: np.ndarray | slice, kernel: str | None = None) -> list: + """Every layer's values (frames, pixels) at the given frames and pixels. + + The frames are a slice; the pixels an index array or a slice. + + Returns + ------- + list + One (frames, pixels) array per layer, in the order of :attr:`layers`. + + Raises + ------ + KeyError + If kernel is not one of the known kernels. + """ + kernel = kernel or self.kernel + if kernel not in KERNELS: + raise KeyError(f"kernel {kernel}") + m = self.movie[frames][:, pixels] + miss = np.isnan(m) + out = [m] + acts = [] + for r in self.runs: + h = r.footprints[pixels] if r.rendered else None + a = ( + np.asarray((h @ r.x80[kernel][:, frames]).T, np.float32) + if h is not None + else np.zeros_like(m) + ) + a[miss] = np.nan + acts.append(a) + out += [a, m - a] + if self.baseline is not None: + b = self.baseline[frames][:, pixels].astype(np.float32) + out.append(b) + out += [m - a - b for a in acts] + return out + + def frame(self, t: int, avg: int, kernel: str | None = None) -> np.ndarray: + """Each layer's mean over avg frames at t. + + (layers, valid pixels) float32, NaN-aware. + + Returns + ------- + np.ndarray + The means, (layers, valid pixels) float32. + """ + lo, hi = self.span(t, avg) + blocks = self._stack(slice(lo, hi), slice(None), kernel) + out = np.empty((len(blocks), self.N), np.float32) + with np.errstate(invalid="ignore"), _quiet(): + for i, b in enumerate(blocks): + out[i] = b[0] if hi - lo == 1 else np.nanmean(b, 0) + return out + + def trace(self, r: int, c: int, rad: int, kernel: str | None = None) -> tuple: + """Each layer's mean over the valid pixels within rad rows and columns of (r, c). + + Returns (layers, frames) float32, and the number of pixels. + + Returns + ------- + trace : np.ndarray + Each layer's mean trace, (layers, frames) float32. + n_pixels : int + The number of valid pixels averaged. + """ + near = (np.abs(self.rows - r) <= rad) & (np.abs(self.cols - c) <= rad) + k = np.flatnonzero(near) + out = np.full((len(self.layers), self.T), np.nan, np.float32) + if k.size: + with _quiet(): + for i, b in enumerate(self._stack(slice(None), k, kernel)): + out[i] = np.nanmean(b, 1) + return out, int(k.size) + + def busiest_frame(self, run: int = 0) -> int: + """Find the frame with the most rendered activity of a run. + + Returns + ------- + int + The frame index; 0 when the run is not rendered or has no activity. + """ + r = self.runs[run] + x = r.x80[self.kernel] + if not r.rendered or x.size == 0: + return 0 + total = np.asarray(r.footprints.sum(0)).ravel() @ x + total[self.discard] = -np.inf + return int(np.argmax(total)) + + +class _quiet: + """Silence NumPy's all-NaN warnings inside a block.""" + + def __enter__(self) -> None: + """Start ignoring RuntimeWarnings.""" + import warnings + + self._w = warnings.catch_warnings() + self._w.__enter__() + warnings.simplefilter("ignore", RuntimeWarning) + + def __exit__(self, *exc: object) -> None: + """Restore the warning filters.""" + self._w.__exit__(*exc) + + +def _marker_rc(tmap: TrialMap | None, rc: np.ndarray) -> np.ndarray: + """Canvas positions moved into the trial frame (NaN rows stay NaN). + + Returns + ------- + np.ndarray + The positions (n, 2) in the trial's registered frame; a copy of rc when there + is no map. + """ + rc = np.asarray(rc, np.float64).reshape(-1, 2) + if tmap is None or rc.size == 0: + return rc.copy() + r, c = tmap.forward(np.nan_to_num(rc[:, 0]), np.nan_to_num(rc[:, 1])) + out = np.column_stack([r, c]) + out[np.isnan(rc).any(1)] = np.nan + return out + + +def run_layer(run: SiloRun, session: Session, d: int, t: int, ctx: dict) -> RunLayer: + """One run's activity in trial t of path d (one-based path, zero-based trial). + + ctx holds the trial's shape, valid flat pixel indices flat, + ds_lines, the movie's kernel dt, the lines per cycle lpc and + blur; the time kernels come from the run's own 200 Hz frame lines + (:func:`render_dt`), and the run's 80 Hz discard share under the + exporter's kernel is added to ctx. + + Returns + ------- + RunLayer + The run's footprints, denoised traces per time kernel and marker positions in the trial. + """ + p = run.path(d) + n = p.sources.n + tmap = p.maps[t] if t < len(p.maps) else None + fps = run.footprints(d) + fp = fps[t] if t < len(fps) else None + span = p.trial_span(t) if t < p.n_frames.size else slice(0, 0) + lines200 = p.lines[span] + rendered = bool(tmap is not None and fp is not None and lines200.size) + T = ctx["ds_lines"].size + kernels = {} + for k in KERNELS: + dtr = render_dt(k, ctx["dt"], lines200) + kernels[k] = (dtr, max(3 * dtr, ctx["lpc"])) + x80 = {k: np.zeros((n, T), np.float32) for k in kernels} + h = None + if rendered: + x200 = np.nan_to_num(run.traces(d)["dF_denoised"][span]) # (n200, n) + for k in kernels: + w, share, _ = kernel_weights( + k, + lines200, + p.discard[span], + ctx["ds_lines"], + ctx["dt"], + ctx["lpc"], + ) + if k == "exporter": + ctx.setdefault("shares", []).append(share) + x80[k] = np.asarray((w.T @ x200).T, np.float32) + h = place_footprints(fp, n, tmap, ctx["shape"], ctx["blur"]) + h = h[ctx["flat"]] + trc = run.trial_centroids(d) + rc = trc[t] if t < trc.shape[0] else np.full((n, 2), np.nan) + rc = np.where(np.isnan(rc), p.sources.rc, rc) + seeds = p.sources.unused_seeds + return RunLayer( + name=run.name, + footprints=h, + x80=x80, + kept_rc=_marker_rc(tmap, rc), + rejected_rc=_marker_rc(tmap, p.sources.rejected_rc), + seeds_rc=_marker_rc(tmap, seeds if seeds is not None else []), + rendered=rendered, + kernels=kernels, + ) + + +def _settings(run: SiloRun) -> dict: + """SILo's frame settings of a run (defaults: SILo's for SLAP2). + + Returns + ------- + dict + num_channels, channel, motion_thresh, discard_initial_s, + nan_thresh and ratio (analysis to alignment frame rate). + """ + return { + "num_channels": int(run.param("numChannels", 2)), + "channel": run.activity_channel, + "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)), + } + + +def _read_alignment(path: Path, n_frames: int) -> tuple[float, np.ndarray]: + """Return alignHz and recNegErr from a trial's alignment file. + + Returns + ------- + hz : float + The alignment frame rate, alignHz. + rne : np.ndarray + recNegErr of the first n_frames frames. + """ + with h5py.File(path, "r") as f: + hz = float(np.ravel(f["alignHz"][()])[0]) + rne = np.asarray(f["recNegErr"][()], np.float64).ravel()[:n_frames] + return hz, rne + + +def render_dt(kernel: str, dt80: int, lines200: np.ndarray) -> float: + """Return the time constant (lines) the 200 Hz traces are averaged with. + + exporter: the movie's own dt, as the exporter does. The 200 Hz + frames are already averaged with their own kernel (dt200 = + ceil(mean(diff(lines)))), so this smooths fast events twice; + matched uses sqrt(dt80**2 - dt200**2), the kernel whose + variance added to the 200 Hz frames' gives the movie's; exact + averages with the movie's dt and adds the interpolated 200 Hz + frames (:func:`~giant_python.viewer.render.exact_weights`). + + Returns + ------- + float + The time constant, in lines. + + Raises + ------ + ValueError + If kernel is not one of the known kernels. + """ + if kernel in ("exporter", "exact"): + return float(dt80) + if kernel != "matched": + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + lines200 = np.asarray(lines200, dtype=np.float64) + if lines200.size < 2: + return float(dt80) + dt200 = frame_dt200(lines200, dt80) + return math.sqrt(max(dt80**2 - dt200**2, 1.0)) + + +def load_trial( + runs: list, + session: Session, + d: int, + t: int, + blur: float = 0.0, + kernel: str = "matched", +) -> TrialMovie: + """Load trial t (zero-based) of path d (one-based) with every run's activity. + + The movie is NaN at SILo's motion discards (recNegErr, as + loadAndProcessTrialAsync) and at the frames whose kernel weight + falls mostly on SILo's discarded 200 Hz frames (the exporter's rule). + Valid pixels are decided on the motion discards alone, as the + exporter decides them (see the module docstring). + Both time kernels (:func:`render_dt`) are rendered; kernel is the + one :meth:`TrialMovie.frame` uses by default. + + Returns + ------- + TrialMovie + The trial's movie, baseline, valid-pixel layout, every run's activity and an info + dict of the settings used. + + Raises + ------ + ValueError + If kernel is not one of the known kernels. + """ + if kernel not in KERNELS: + raise ValueError(f"kernel must be one of {KERNELS}, not {kernel!r}") + st = _settings(runs[0]) + movie = read_channel(session.movie_file(d - 1, t), st["num_channels"], st["channel"]) + T, R, C = movie.shape + hz, rne = _read_alignment(session.alignment_file(d - 1, t), T) + disc = discard_frames(rne, hz, st["motion_thresh"], st["discard_initial_s"]) + movie[disc] = np.nan + with np.errstate(invalid="ignore"): + valid = np.isnan(movie).mean(0) < st["nan_thresh"] + rows, cols = np.nonzero(valid) + flat = rows * C + cols + ds = session.ds_lines(d - 1, t)[:T] + lines0 = runs[0].path(d).lines + dt = kernel_dt(ds, lines0, st["ratio"]) + lpc = session.lines_per_cycle(d - 1, t) + ctx = { + "shape": (R, C), + "flat": flat, + "ds_lines": ds, + "dt": dt, + "lpc": lpc, + "blur": float(blur), + } + layers = [run_layer(r, session, d, t, ctx) for r in runs] + for share in ctx.get("shares", []): + disc = disc | (share > 0.5) + mov = movie.reshape(T, R * C)[:, flat] + del movie + mov[disc] = np.nan + base = _read_baseline(session.baseline_file(d - 1, t), (T, R, C), flat) + if base is not None: + base[disc] = np.nan + with np.errstate(invalid="ignore"), _quiet(): + mean = np.nanmean(mov, 0) + info = { + "dt_lines": dt, + "render_dt_lines": { + r.name: {k: round(v[0], 2) for k, v in r.kernels.items()} for r in layers + }, + "reach_lines": {r.name: {k: round(v[1], 1) for k, v in r.kernels.items()} for r in layers}, + "lines_per_cycle": lpc, + "blur_px": float(blur), + "align_hz": hz, + "movie": session.movie_file(d - 1, t).name, + "baseline": (session.baseline_file(d - 1, t) or Path("")).name, + "discarded": int(disc.sum()), + } + return TrialMovie( + path=d, + trial=t, + shape=(R, C), + rows=rows, + cols=cols, + mean=mean, + discard=disc, + movie=mov, + baseline=base, + runs=layers, + info=info, + kernel=kernel, + ) + + +def _read_baseline(path: Path | None, shape: tuple, flat: np.ndarray) -> np.ndarray | None: + """Read a network baseline at the valid pixels, float16 (frames, N). + + Returns + ------- + np.ndarray or None + The baseline, float16 (frames, N); None when path is None. + + Raises + ------ + ValueError + If the baseline's shape does not match the movie's. + """ + if path is None: + return None + T, R, C = shape + with h5py.File(path, "r") as f: + b = np.asarray(f["baseline"][()]) # (frames, MATLAB cols, rows) + if b.shape != (T, C, R): + raise ValueError(f"{path.name}: baseline {b.shape}, movie {shape}") + b = b.transpose(0, 2, 1).reshape(T, R * C)[:, flat] + return np.ascontiguousarray(b.astype(np.float16)) + + +def largest_events(x: np.ndarray, n: int, gap: int) -> np.ndarray: + """Return indices of the n largest local maxima of x at least gap samples apart. + + The indices are ordered largest first. + + Returns + ------- + np.ndarray + The indices of the largest local maxima, largest first. + """ + x = np.nan_to_num(np.asarray(x, np.float64), nan=-np.inf) + if x.size < 3: + return np.zeros(0, int) + peak = np.flatnonzero((x[1:-1] > x[:-2]) & (x[1:-1] >= x[2:])) + 1 + peak = peak[x[peak] > 0] + order = peak[np.argsort(-x[peak], kind="stable")] + taken: list = [] + for i in order: + if all(abs(i - j) >= gap for j in taken): + taken.append(int(i)) + if len(taken) >= n: + break + return np.asarray(taken, int) + + +def source_events( + run: SiloRun, session: Session, d: int, s: int, n: int = 30 +) -> list[dict[str, float]]: + """Find a source's largest denoised events over all trials, as movie frames. + + Returns a list of {trial, frame, line, value} (largest first). + + Returns + ------- + list[dict[str, float]] + Up to n events, largest first, each with the trial, the movie frame, the + acquisition line and the value of the denoised trace. + """ + p = run.path(d) + x = run.traces(d)["dF_denoised"][:, s] + hz = float(run.param("analyzeHz", 200.0)) + gap = max(1, math.ceil(0.25 * hz)) + out = [] + for t in range(p.n_frames.size): + span = p.trial_span(t) + if span.stop <= span.start or not session.has_movie(d - 1, t): + continue + xs = x[span] + ds = session.ds_lines(d - 1, t) + for i in largest_events(xs, n, gap): + line = float(p.lines[span][i]) + frame = int(np.argmin(np.abs(ds - line))) + out.append({ + "trial": t, + "frame": frame, + "value": float(xs[i]), + "line": line, + }) + out.sort(key=lambda e: -e["value"]) + return out[:n] diff --git a/tests/__init__.py b/tests/__init__.py index d4d2ae53..48622532 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1 @@ -"""Tests for giant_python.""" +"""Tests for giant_python.""" diff --git a/tests/export/__init__.py b/tests/export/__init__.py index ee894a2a..f052d76c 100644 --- a/tests/export/__init__.py +++ b/tests/export/__init__.py @@ -1 +1 @@ -"""Tests of the F0 training-data export (giant export-f0).""" +"""Tests of the F0 training-data export (giant export-f0).""" diff --git a/tests/export/test_f0_injected.py b/tests/export/test_f0_injected.py index c42f64c3..22623b9e 100644 --- a/tests/export/test_f0_injected.py +++ b/tests/export/test_f0_injected.py @@ -1,279 +1,279 @@ -"""GFP kind of the F0 training data (giant export-f0-injected). - -The tests run on a synthetic recording with injected events. -""" - -from collections.abc import Iterator -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.export.f0_injected import export_injected -from giant_python.export.f0_training import ExportOptions -from giant_python.io import slap2_raster -from giant_python.io.slap2_raster import RasterLayout -from giant_python.pipeline.register import register_multiroi -from giant_python.registration import multiroi -from giant_python.simulation import injection as inj - -from ..registration.synthetic import ( - make_layout, - online_offsets, - write_recording, -) -from ..simulation.test_injection import ( - BRIGHT, - BRIGHT_AT, - N_CYCLES, - registered_table, -) - - -@pytest.fixture(scope="module") -def copy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Path]: - """Build a synthetic recording and a registered copy with injected events. - - The recording is registered as two trials; the copy gets bright injected - events and is registered and compared (positions on the copy's grid). The - raster layouts stay patched while the module's tests run (the synthetic - files have no real header). - - Yields - ------ - Path - The copy's folder. - """ - root = tmp_path_factory.mktemp("gfpkind") - path = root / "rec" / "inj_DMD1-TRIAL000001.dat" - path.parent.mkdir() - layout = make_layout(path, n_cycles=N_CYCLES, seed=5) - offs = online_offsets(layout.total_lines) - write_recording(layout, seed=6, online=offs) - path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) - mp = pytest.MonkeyPatch() - mp.setattr(multiroi, "raster_layout", lambda p: layout) - reg = root / "reg" - reg.mkdir() - table = registered_table(layout, reg, True, [(1, 4800), (4801, 9700)]) - out = root / "copy" - mp.setattr(inj, "raster_layout", lambda p: layout) - inj.inject_session(table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT) - copy_layout = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - mp.setattr(multiroi, "raster_layout", lambda p: copy_layout) - register_multiroi( - out / "trial_table.h5", - {"maxshift": 6, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert inj.main(["compare", str(out)]) == 0 - # f0_injected reads the original's layout and replaces its files - mp.setattr(slap2_raster, "raster_layout", lambda p: layout) - yield out - mp.undo() - - -def test_activity_is_the_injected_photons(copy: Path, tmp_path: Path) -> None: - """The activity holds the injected photons as drawn. - - Their sum matches the noiseless expectation within Poisson noise, nothing - is injected far from the sources, and the file has the training layout. - """ - s = export_injected(copy, tmp_path / "out", ExportOptions(label="syn"), expected=True) - assert [q["trial"] for q in s["trials"]] == [1, 2] - truth = inj.read_truth(copy / inj.TRUTH_NAME)["paths"][1] - for q in s["trials"]: - assert "error" not in q, q - assert q["kind"] == "gfp_injected" and q["nSources"] == 3 - assert q["drawnOverExpected"] == pytest.approx(1.0, abs=0.05) - with h5py.File(q["file"], "r") as f: - a, m = f["activity"][0], f["movie"][0] - e = f["activity_expected"][0] - sup = f["mask/footprint_support"][()].astype(bool) - r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) - assert a.shape == m.shape and e.shape == a.shape - assert f.attrs["kind"] == "gfp_injected" - assert int(f.attrs["originalTrial"]) == q["trial"] - assert f.attrs["registrationStem"] == q["registrationStem"] - assert f"DMD{q['path']}" in q["registrationStem"] - pr, pc = f["sources/peak_row"][()], f["sources/peak_col"][()] - pos = truth["trials_detail"][q["trial"]]["positions_copy_rc"] - np.testing.assert_array_equal(pr, np.rint(pos[:, 0]).astype(int) - r0) - np.testing.assert_array_equal(pc, np.rint(pos[:, 1]).astype(int) - c0) - assert sup.any() and np.abs(a[:, ~sup]).max() < 1e-2 * a.max() - assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx(e[:, sup].sum(), rel=0.05) - - -def test_cli_and_selection(copy: Path, tmp_path: Path) -> None: - """Giant export-f0-injected writes the chosen trial. - - Trials the copy does not have are refused. - """ - out = tmp_path / "out" - rc = main(["export-f0-injected", str(copy), str(out), "--trials", "2"]) - assert rc == 0 - assert (out / "Path1" / "trial_002.h5").exists() - assert not (out / "Path1" / "trial_001.h5").exists() - with pytest.raises(SystemExit) as e: - main(["export-f0-injected", str(copy), str(out), "--trials", "3"]) - assert e.value.code == 2 - - -def test_target_is_the_original_on_the_copys_grid(copy: Path, tmp_path: Path) -> None: - """Movie - activity equals the original's samples on the copy's grid. - - The samples are formed with the copy's registration (its kernel and - resampling weights): the injected events leave nothing in the target. - """ - from giant_python.export.f0_injected import kernel_lines - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.simulation.render import iter_registered_frames - - s = export_injected(copy, tmp_path / "out", ExportOptions(trials=(1,))) - q = s["trials"][0] - truth = inj.read_truth(copy / inj.TRUTH_NAME) - layout = slap2_raster.raster_layout("unused") # the patched layout - al = inj.read_alignment(copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - with h5py.File(q["file"], "r") as f: - m, a = f["movie"][0], f["activity"][0] - r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) - dt = float(f.attrs["movieDtLines"]) - disc = f["frame/discard"][()].astype(bool) - assert dt == kernel_lines(layout, 80.0) - orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype(np.float32) - times = np.asarray(al.ds_frames, np.int64)[: m.shape[0]] - ref = np.full((times.size,) + al.shape, np.nan, np.float32) - for idx, frames, _ in iter_registered_frames(layout, orig, 0, al, times, int(dt)): - ref[idx] = frames[0].numpy() - R, C = m.shape[1:] - ref = ref[:, r0 : r0 + R, c0 : c0 + C] - ok = np.isfinite(m) & np.isfinite(ref) & ~disc[:, None, None] - assert ok.mean() > 0.5 - np.testing.assert_allclose((m - a)[ok], ref[ok], atol=1e-2 * np.nanmax(a)) - assert truth["paths"][1]["events"]["source"].size > 0 - - -@pytest.mark.parametrize("channels", [(0,), (3,)]) -def test_channels_outside_the_movie_are_refused( - copy: Path, tmp_path: Path, channels: tuple[int, ...] -) -> None: - """Channels are one-based and within the alignment file's numChannels.""" - with pytest.raises(ValueError, match="channels"): - export_injected(copy, tmp_path / "out", ExportOptions(channels=channels)) - - -def test_footprints_rebuilt_from_the_truth() -> None: - """Gaussian footprints come back with their recorded widths and radius. - - An image footprint is refused when its model is needed. - """ - from giant_python.export.f0_injected import injected_footprints - - g = {"kind": "gaussian", "sigma_rc": [1.0, 2.0], "radius_px": 8.0} - fp = injected_footprints({"footprint": {"params": [g]}}, True)[0] - assert fp.sigma == (1.0, 2.0) and fp.radius == pytest.approx(8.0) - img = {"kind": "image", "center_rc": [1.0, 1.0], "radius_px": 3.0} - assert injected_footprints({"footprint": {"params": [img]}}, False) == [None] - with pytest.raises(ValueError, match="image"): - injected_footprints({"footprint": {"params": [img]}}, True) - - -def test_default_export_reconciles_and_selection_keeps(copy: Path, tmp_path: Path) -> None: - """A default export removes earlier trial files it does not write. - - An export of chosen trials leaves them. - """ - out = tmp_path / "out" - (out / "Path1").mkdir(parents=True) - (out / "Path1" / "trial_007.h5").write_bytes(b"old") - s = export_injected(copy, out, ExportOptions(trials=(2,))) - assert "removed" not in s and (out / "Path1" / "trial_007.h5").exists() - s = export_injected(copy, out) - assert s["removed"] == {"Path1": ["trial_007.h5"]} - assert sorted(f.name for f in (out / "Path1").iterdir()) == [ - "trial_001.h5", - "trial_002.h5", - ] - - -def test_ragged_copy_and_bounded_reads( - copy: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A column without a recording on the path is skipped (no error). - - A trial reads only the cycles its frames' kernels reach. - """ - import giant_python.export.f0_injected as fi - - real = inj.read_truth - - def ragged(path: str | Path) -> dict: - """Read the truth without trial 1 on path 1. - - Returns - ------- - dict - The truth, with trial 1 removed from path 1's trials_detail. - """ - t = real(path) - t["paths"][1]["trials_detail"].pop(1) # trial 1 not on this path - return t - - monkeypatch.setattr(inj, "read_truth", ragged) - ranges = [] - real_read = slap2_raster.read_raster_samples - - def spy(layout: RasterLayout, cycles: tuple[int, int], *a: object, **k: object) -> np.ndarray: - """Record the cycles read. - - Returns - ------- - np.ndarray - The samples from the real read_raster_samples. - """ - ranges.append(tuple(cycles)) - return real_read(layout, cycles, *a, **k) - - monkeypatch.setattr(slap2_raster, "read_raster_samples", spy) - s = fi.export_injected(copy, tmp_path / "out") - assert [q["trial"] for q in s["trials"]] == [2] - assert "error" not in s["trials"][0] - layout = slap2_raster.raster_layout("unused") - assert ranges and all(c0 > 0 for c0, _ in ranges) # trial 2 starts later - assert all(c1 - c0 < layout.num_cycles for c0, c1 in ranges) - - -def test_peaks_of_an_empty_source_list() -> None: - """A copy without placed sources has no peaks (no index error).""" - from giant_python.export.f0_injected import peak_positions - - pth = { - "peak_pixel_rc": np.zeros((0, 2)), - "positions_rc": np.zeros((0, 2)), - "footprint": {"params": []}, - } - assert peak_positions(pth, np.zeros((0, 2))).shape == (0, 2) - - -def test_moved_copy_duplicate_channels_and_stale_paths(copy: Path, tmp_path: Path) -> None: - """A copy moved to another folder exports from its own raw files. - - A repeated injected channel gets the activity in every occurrence; a full - export clears trial files of paths the copy does not have. - """ - import shutil - - moved = tmp_path / "moved" - shutil.copytree(copy, moved) - out = tmp_path / "out" - (out / "Path2").mkdir(parents=True) - (out / "Path2" / "trial_001.h5").write_bytes(b"old") - s = export_injected(moved, out, ExportOptions(channels=(1, 1))) - assert all("error" not in q for q in s["trials"]) - assert s["removed"]["Path2"] == ["trial_001.h5"] - with h5py.File(s["trials"][0]["file"], "r") as f: - a = f["activity"][()] - assert a.shape[0] == 2 and np.array_equal(a[0], a[1]) and a[0].max() > 0 +"""GFP kind of the F0 training data (giant export-f0-injected). + +The tests run on a synthetic recording with injected events. +""" + +from collections.abc import Iterator +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.export.f0_injected import export_injected +from giant_python.export.f0_training import ExportOptions +from giant_python.io import slap2_raster +from giant_python.io.slap2_raster import RasterLayout +from giant_python.pipeline.register import register_multiroi +from giant_python.registration import multiroi +from giant_python.simulation import injection as inj + +from ..registration.synthetic import ( + make_layout, + online_offsets, + write_recording, +) +from ..simulation.test_injection import ( + BRIGHT, + BRIGHT_AT, + N_CYCLES, + registered_table, +) + + +@pytest.fixture(scope="module") +def copy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Path]: + """Build a synthetic recording and a registered copy with injected events. + + The recording is registered as two trials; the copy gets bright injected + events and is registered and compared (positions on the copy's grid). The + raster layouts stay patched while the module's tests run (the synthetic + files have no real header). + + Yields + ------ + Path + The copy's folder. + """ + root = tmp_path_factory.mktemp("gfpkind") + path = root / "rec" / "inj_DMD1-TRIAL000001.dat" + path.parent.mkdir() + layout = make_layout(path, n_cycles=N_CYCLES, seed=5) + offs = online_offsets(layout.total_lines) + write_recording(layout, seed=6, online=offs) + path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) + mp = pytest.MonkeyPatch() + mp.setattr(multiroi, "raster_layout", lambda p: layout) + reg = root / "reg" + reg.mkdir() + table = registered_table(layout, reg, True, [(1, 4800), (4801, 9700)]) + out = root / "copy" + mp.setattr(inj, "raster_layout", lambda p: layout) + inj.inject_session(table, out, paths=(1,), settings=BRIGHT, positions=BRIGHT_AT) + copy_layout = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + mp.setattr(multiroi, "raster_layout", lambda p: copy_layout) + register_multiroi( + out / "trial_table.h5", + {"maxshift": 6, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert inj.main(["compare", str(out)]) == 0 + # f0_injected reads the original's layout and replaces its files + mp.setattr(slap2_raster, "raster_layout", lambda p: layout) + yield out + mp.undo() + + +def test_activity_is_the_injected_photons(copy: Path, tmp_path: Path) -> None: + """The activity holds the injected photons as drawn. + + Their sum matches the noiseless expectation within Poisson noise, nothing + is injected far from the sources, and the file has the training layout. + """ + s = export_injected(copy, tmp_path / "out", ExportOptions(label="syn"), expected=True) + assert [q["trial"] for q in s["trials"]] == [1, 2] + truth = inj.read_truth(copy / inj.TRUTH_NAME)["paths"][1] + for q in s["trials"]: + assert "error" not in q, q + assert q["kind"] == "gfp_injected" and q["nSources"] == 3 + assert q["drawnOverExpected"] == pytest.approx(1.0, abs=0.05) + with h5py.File(q["file"], "r") as f: + a, m = f["activity"][0], f["movie"][0] + e = f["activity_expected"][0] + sup = f["mask/footprint_support"][()].astype(bool) + r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) + assert a.shape == m.shape and e.shape == a.shape + assert f.attrs["kind"] == "gfp_injected" + assert int(f.attrs["originalTrial"]) == q["trial"] + assert f.attrs["registrationStem"] == q["registrationStem"] + assert f"DMD{q['path']}" in q["registrationStem"] + pr, pc = f["sources/peak_row"][()], f["sources/peak_col"][()] + pos = truth["trials_detail"][q["trial"]]["positions_copy_rc"] + np.testing.assert_array_equal(pr, np.rint(pos[:, 0]).astype(int) - r0) + np.testing.assert_array_equal(pc, np.rint(pos[:, 1]).astype(int) - c0) + assert sup.any() and np.abs(a[:, ~sup]).max() < 1e-2 * a.max() + assert e[:, sup].sum() > 0 and a[:, sup].sum() == pytest.approx(e[:, sup].sum(), rel=0.05) + + +def test_cli_and_selection(copy: Path, tmp_path: Path) -> None: + """Giant export-f0-injected writes the chosen trial. + + Trials the copy does not have are refused. + """ + out = tmp_path / "out" + rc = main(["export-f0-injected", str(copy), str(out), "--trials", "2"]) + assert rc == 0 + assert (out / "Path1" / "trial_002.h5").exists() + assert not (out / "Path1" / "trial_001.h5").exists() + with pytest.raises(SystemExit) as e: + main(["export-f0-injected", str(copy), str(out), "--trials", "3"]) + assert e.value.code == 2 + + +def test_target_is_the_original_on_the_copys_grid(copy: Path, tmp_path: Path) -> None: + """Movie - activity equals the original's samples on the copy's grid. + + The samples are formed with the copy's registration (its kernel and + resampling weights): the injected events leave nothing in the target. + """ + from giant_python.export.f0_injected import kernel_lines + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.simulation.render import iter_registered_frames + + s = export_injected(copy, tmp_path / "out", ExportOptions(trials=(1,))) + q = s["trials"][0] + truth = inj.read_truth(copy / inj.TRUTH_NAME) + layout = slap2_raster.raster_layout("unused") # the patched layout + al = inj.read_alignment(copy / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + with h5py.File(q["file"], "r") as f: + m, a = f["movie"][0], f["activity"][0] + r0, c0 = (int(v) for v in np.ravel(f.attrs["cropOriginRC"])) + dt = float(f.attrs["movieDtLines"]) + disc = f["frame/discard"][()].astype(bool) + assert dt == kernel_lines(layout, 80.0) + orig = read_raster_samples(layout, (0, layout.num_cycles))[:1].astype(np.float32) + times = np.asarray(al.ds_frames, np.int64)[: m.shape[0]] + ref = np.full((times.size,) + al.shape, np.nan, np.float32) + for idx, frames, _ in iter_registered_frames(layout, orig, 0, al, times, int(dt)): + ref[idx] = frames[0].numpy() + R, C = m.shape[1:] + ref = ref[:, r0 : r0 + R, c0 : c0 + C] + ok = np.isfinite(m) & np.isfinite(ref) & ~disc[:, None, None] + assert ok.mean() > 0.5 + np.testing.assert_allclose((m - a)[ok], ref[ok], atol=1e-2 * np.nanmax(a)) + assert truth["paths"][1]["events"]["source"].size > 0 + + +@pytest.mark.parametrize("channels", [(0,), (3,)]) +def test_channels_outside_the_movie_are_refused( + copy: Path, tmp_path: Path, channels: tuple[int, ...] +) -> None: + """Channels are one-based and within the alignment file's numChannels.""" + with pytest.raises(ValueError, match="channels"): + export_injected(copy, tmp_path / "out", ExportOptions(channels=channels)) + + +def test_footprints_rebuilt_from_the_truth() -> None: + """Gaussian footprints come back with their recorded widths and radius. + + An image footprint is refused when its model is needed. + """ + from giant_python.export.f0_injected import injected_footprints + + g = {"kind": "gaussian", "sigma_rc": [1.0, 2.0], "radius_px": 8.0} + fp = injected_footprints({"footprint": {"params": [g]}}, True)[0] + assert fp.sigma == (1.0, 2.0) and fp.radius == pytest.approx(8.0) + img = {"kind": "image", "center_rc": [1.0, 1.0], "radius_px": 3.0} + assert injected_footprints({"footprint": {"params": [img]}}, False) == [None] + with pytest.raises(ValueError, match="image"): + injected_footprints({"footprint": {"params": [img]}}, True) + + +def test_default_export_reconciles_and_selection_keeps(copy: Path, tmp_path: Path) -> None: + """A default export removes earlier trial files it does not write. + + An export of chosen trials leaves them. + """ + out = tmp_path / "out" + (out / "Path1").mkdir(parents=True) + (out / "Path1" / "trial_007.h5").write_bytes(b"old") + s = export_injected(copy, out, ExportOptions(trials=(2,))) + assert "removed" not in s and (out / "Path1" / "trial_007.h5").exists() + s = export_injected(copy, out) + assert s["removed"] == {"Path1": ["trial_007.h5"]} + assert sorted(f.name for f in (out / "Path1").iterdir()) == [ + "trial_001.h5", + "trial_002.h5", + ] + + +def test_ragged_copy_and_bounded_reads( + copy: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A column without a recording on the path is skipped (no error). + + A trial reads only the cycles its frames' kernels reach. + """ + import giant_python.export.f0_injected as fi + + real = inj.read_truth + + def ragged(path: str | Path) -> dict: + """Read the truth without trial 1 on path 1. + + Returns + ------- + dict + The truth, with trial 1 removed from path 1's trials_detail. + """ + t = real(path) + t["paths"][1]["trials_detail"].pop(1) # trial 1 not on this path + return t + + monkeypatch.setattr(inj, "read_truth", ragged) + ranges = [] + real_read = slap2_raster.read_raster_samples + + def spy(layout: RasterLayout, cycles: tuple[int, int], *a: object, **k: object) -> np.ndarray: + """Record the cycles read. + + Returns + ------- + np.ndarray + The samples from the real read_raster_samples. + """ + ranges.append(tuple(cycles)) + return real_read(layout, cycles, *a, **k) + + monkeypatch.setattr(slap2_raster, "read_raster_samples", spy) + s = fi.export_injected(copy, tmp_path / "out") + assert [q["trial"] for q in s["trials"]] == [2] + assert "error" not in s["trials"][0] + layout = slap2_raster.raster_layout("unused") + assert ranges and all(c0 > 0 for c0, _ in ranges) # trial 2 starts later + assert all(c1 - c0 < layout.num_cycles for c0, c1 in ranges) + + +def test_peaks_of_an_empty_source_list() -> None: + """A copy without placed sources has no peaks (no index error).""" + from giant_python.export.f0_injected import peak_positions + + pth = { + "peak_pixel_rc": np.zeros((0, 2)), + "positions_rc": np.zeros((0, 2)), + "footprint": {"params": []}, + } + assert peak_positions(pth, np.zeros((0, 2))).shape == (0, 2) + + +def test_moved_copy_duplicate_channels_and_stale_paths(copy: Path, tmp_path: Path) -> None: + """A copy moved to another folder exports from its own raw files. + + A repeated injected channel gets the activity in every occurrence; a full + export clears trial files of paths the copy does not have. + """ + import shutil + + moved = tmp_path / "moved" + shutil.copytree(copy, moved) + out = tmp_path / "out" + (out / "Path2").mkdir(parents=True) + (out / "Path2" / "trial_001.h5").write_bytes(b"old") + s = export_injected(moved, out, ExportOptions(channels=(1, 1))) + assert all("error" not in q for q in s["trials"]) + assert s["removed"]["Path2"] == ["trial_001.h5"] + with h5py.File(s["trials"][0]["file"], "r") as f: + a = f["activity"][()] + assert a.shape[0] == 2 and np.array_equal(a[0], a[1]) and a[0].max() > 0 diff --git a/tests/export/test_f0_layout.py b/tests/export/test_f0_layout.py index 22f4c6ad..807b6695 100644 --- a/tests/export/test_f0_layout.py +++ b/tests/export/test_f0_layout.py @@ -1,843 +1,843 @@ -"""The raster layout files of the F0 network's simulator.""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.export import f0_layout -from giant_python.export.f0_layout import ( - HEIGHT_BINS, - SPLIT_BINS, - export_layouts, - layout_path, - pulse_statistics, - read_layout, - reference_frames, - slot_statistics, -) -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import ( - INVALID_SAMPLE, - RasterLayout, - read_raster_samples, -) -from giant_python.registration import multiroi -from giant_python.registration.stats.gain import next_slots - -from ..registration.synthetic import make_layout, online_offsets, write_recording - -MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - -Registered = tuple[RasterLayout, Path, Path] -"""The layout of a registered synthetic trial, its trial table and its folder.""" - - -def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: - """Write a one-trial trial table of the recording dat. - - Returns - ------- - Path - The path of the written trial table. - """ - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[1.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[last]]), - }, - }, - ) - return table - - -@pytest.fixture(scope="module") -def registered(tmp_path_factory: pytest.TempPathFactory) -> Registered: - """Register a synthetic trial (moving scene, some invalid samples). - - Gives the layout, its trial table and its output folder. - - Returns - ------- - Registered - The layout, its trial table and its output folder, as (layout, table, root). - """ - from giant_python.pipeline.register import register_multiroi - - root = tmp_path_factory.mktemp("layout") - layout = make_layout(root / "synthetic_DMD1-TRIAL000001.dat", 1400) - write_recording(layout, invalid=0.02) - table = _table(root, Path(layout.files[0])) - with pytest.MonkeyPatch.context() as mp: - mp.setattr(multiroi, "raster_layout", lambda path: layout) - register_multiroi( - table, - {"maxshift": 5}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - return layout, table, root - - -@pytest.fixture -def patched(registered: Registered, monkeypatch: pytest.MonkeyPatch) -> Registered: - """Serve the recording's layout to the exporter. - - Returns - ------- - Registered - The registered fixture's value, unchanged. - """ - monkeypatch.setattr(multiroi, "raster_layout", lambda path: registered[0]) - return registered - - -def _movie(path: Path, n_channels: int) -> np.ndarray: - """Read a registered movie as (channels, frames, rows, cols). - - Returns - ------- - np.ndarray - The movie's pages, reshaped and transposed to (channels, frames, rows, cols). - """ - with h5py.File(path, "r") as f: - pages = f[next(iter(f.keys()))][()] - pages = pages.reshape(-1, n_channels, *pages.shape[1:]) - return np.swapaxes(pages, -1, -2).transpose(1, 0, 2, 3) - - -def test_file_reproduces_the_registered_movie(patched: Registered, tmp_path: Path) -> None: - """Frames formed from the file and its slots' raw samples are registration's. - - Missing pixels included. - """ - layout, table, root = patched - out = tmp_path / "layouts" - res = export_layouts(table, out) - assert [r["error"] for r in res] == [None] - lay = read_layout(out / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - assert at["path"] == 1 and at["trial"] == 1 and not at["compensated"] - assert at["lines_per_cycle"] == layout.lines_per_cycle - assert at["margin"] == 5 - c0, n = at["cycle0"], at["n_cycles"] - raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) - samples = raw[:, lay["slots/index"]] - movie = _movie(root / "motion_correction" / MOVIE, at["num_channels"]) - assert movie.shape[1] == lay["frames/lines"].size - frames = np.r_[0, 1, 7, 40, movie.shape[1] - 1] - got = reference_frames(lay, samples, frames) - want = movie[:, frames] - assert got.shape == want.shape - assert np.array_equal(np.isnan(got), np.isnan(want)) - assert np.isfinite(want).mean() > 0.2 - np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) - - -def test_slots_and_their_statistics(patched: Registered, tmp_path: Path) -> None: - """The file's slots are the window's, with their means and zeros.""" - layout, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - idx = lay["slots/index"] - # every slot of the raster block is in the window (one plane) - assert idx.size == layout.slot_line.size - assert np.array_equal(lay["slots/line"], layout.slot_line[idx]) - rows = (layout.slot_pixel[idx] - 1) // layout.n_cols - at["window_row0"] - cols = (layout.slot_pixel[idx] - 1) % layout.n_cols - at["window_col0"] - assert np.array_equal(lay["pixels/row"][lay["slots/pixel"]], rows) - assert np.array_equal(lay["pixels/col"][lay["slots/pixel"]], cols) - nxt = lay["slots/next"] - has = nxt >= 0 - # the synthetic lines visit their pixels in random order: only some - # consecutive samples are neighbouring pixels and share pulses - assert 0 < has.sum() < 0.5 * has.size - step_r = np.abs(rows[nxt[has]] - rows[has]) - step_c = np.abs(cols[nxt[has]] - cols[has]) - assert step_r.max() <= 1 and step_c.max() <= 1 - assert np.array_equal(lay["slots/line"][nxt[has]], lay["slots/line"][has]) - assert np.array_equal(lay["slots/pos"][nxt[has]], lay["slots/pos"][has] + 1) - c0, n = at["cycle0"], at["n_cycles"] - raw = read_raster_samples(layout, (c0, c0 + n))[:, idx].astype(float) - ok = raw != INVALID_SAMPLE - mean = np.where(ok, raw, 0).sum(2) / ok.sum(2) - np.testing.assert_allclose(lay["slots/mean"], mean, rtol=1e-6) - zero = (ok & (raw == 0)).sum(2) / ok.sum(2) - np.testing.assert_allclose(lay["slots/zero_share"], zero, atol=1e-6) - np.testing.assert_allclose(lay["slots/valid_share"], ok.mean(2), atol=1e-6) - assert 0.97 < lay["slots/valid_share"].mean() < 0.99 - - -def test_existing_files_are_kept_and_selection(patched: Registered, tmp_path: Path) -> None: - """A second run keeps the file; --overwrite and the selection.""" - from giant_python.cli import main - - _, table, _ = patched - args = ["export-f0-layout", str(table), "--out", str(tmp_path)] - assert main(args) == 0 - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - stamp = out.stat().st_mtime_ns - assert main(args) == 0 - assert out.stat().st_mtime_ns == stamp - assert main(args + ["--overwrite"]) == 0 - assert out.stat().st_mtime_ns != stamp - assert export_layouts(table, tmp_path / "none", trials=[2]) == [] - assert layout_path("a/E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif") == Path( - "a/E1T1DMD1_F0LAYOUT.h5" - ) - assert layout_path("a/movie.h5") == Path("a/movie_F0LAYOUT.h5") - - -def test_missing_alignment_and_old_versions(patched: Registered, tmp_path: Path) -> None: - """A trial without its alignment file fails. - - Other versions are refused. - """ - from giant_python.cli import main - - _, table, _ = patched - moved = ["--out", str(tmp_path), "--moco", str(tmp_path / "moved")] - assert main(["export-f0-layout", str(table)] + moved) == 1 - assert not (tmp_path / "E1T1DMD1_F0LAYOUT.h5").exists() - export_layouts(table, tmp_path) - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - with h5py.File(out, "r+") as f: - f.attrs["layout_version"] = 0 - with pytest.raises(ValueError, match="layout version"): - read_layout(out) - - -def test_compensated_registration_is_reproduced( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A registration that undid the online correction is reproduced. - - The file holds the lines' offsets and the frames' own, and frames formed - from it, every sample moved by its line's offset, are registration's. - """ - from giant_python.pipeline.register import register_multiroi - - layout = make_layout(tmp_path / "comp_DMD1-TRIAL000001.dat", 500) - x, _, y_dmd = online_offsets(layout.total_lines) - write_recording(layout, seed=6, online=(x, _, y_dmd)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = _table(tmp_path, Path(layout.files[0]), last=2000.0) - register_multiroi( - table, - {"maxshift": 5, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - res = export_layouts(table, tmp_path / "out") - assert [r["error"] for r in res] == [None] - lay = read_layout(tmp_path / "out" / "E1T1DMD1_F0LAYOUT.h5") - at = lay["attrs"] - assert at["compensated"] and at["layout_version"] == 4 - assert list(at["y_lead"]) == [2, 6] - p, c0, n = at["lines_per_cycle"], at["cycle0"], at["n_cycles"] - # the offsets of the lines of the file's cycles: x as the header has - # it, y as it was on the DMD - lines = slice(c0 * p, (c0 + n) * p) - assert lay["lines/x"].shape == (n * p,) - np.testing.assert_array_equal(lay["lines/x"], x[lines]) - np.testing.assert_array_equal(lay["lines/y_eff"], y_dmd[lines]) - assert np.unique(lay["lines/x"]).size > 1 - assert np.unique(lay["lines/y_eff"]).size > 1 - ref = lay["frames/ref_xy"] - assert ref.shape == (lay["frames/lines"].size, 2) - assert np.unique(ref, axis=0).shape[0] > 1 - # the slots' raster positions; a slot whose own pixel is among the - # pixels that frames report points at it - w = at["window_cols"] - slot_flat = lay["slots/row"].astype(np.int64) * w + lay["slots/col"] - pix_flat = lay["pixels/row"].astype(np.int64) * w + lay["pixels/col"] - listed = lay["slots/pixel"] >= 0 - np.testing.assert_array_equal(pix_flat[lay["slots/pixel"][listed]], slot_flat[listed]) - assert np.isin(slot_flat[listed], pix_flat).all() and listed.mean() > 0.9 - raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) - samples = raw[:, lay["slots/index"]] - movie = _movie(tmp_path / "motion_correction" / MOVIE, at["num_channels"]) - assert movie.shape[1] == lay["frames/lines"].size - # frames whose lines span an offset switch among them - changed = np.flatnonzero(np.any(np.diff(ref, axis=0) != 0, axis=1)) - frames = np.unique(np.r_[0, 1, changed[:6], changed[:6] + 1, movie.shape[1] - 1]) - got = reference_frames(lay, samples, frames) - want = movie[:, frames] - assert np.array_equal(np.isnan(got), np.isnan(want)) - assert np.isfinite(want).mean() > 0.2 - np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) - # without the offsets the frames are others: the samples are moved - plain = dict(lay, attrs=dict(at, compensated=False)) - off = reference_frames(plain, samples, frames) - both = np.isfinite(off) & np.isfinite(want) - assert np.abs(off - want)[both].max() > 1.0 - - -def test_version_3_files_are_read(patched: Registered, tmp_path: Path) -> None: - """A file of version 3 is read with its slots' positions. - - Version 3 has no slot positions (registrations without online - compensation); such a file gives the same frames. - """ - layout, table, _root = patched - export_layouts(table, tmp_path) - out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" - new = read_layout(out) - assert new["attrs"]["layout_version"] == 4 - assert not new["attrs"]["compensated"] and "lines/x" not in new - np.testing.assert_array_equal(new["slots/row"], new["pixels/row"][new["slots/pixel"]]) - with h5py.File(out, "r+") as f: - f.attrs["layout_version"] = 3 - del f["slots/row"], f["slots/col"] - old = read_layout(out) - assert old["attrs"]["layout_version"] == 3 - np.testing.assert_array_equal(old["slots/row"], new["slots/row"]) - np.testing.assert_array_equal(old["slots/col"], new["slots/col"]) - at = new["attrs"] - raw = read_raster_samples( - layout, - (at["cycle0"], at["cycle0"] + at["n_cycles"]), - mask_unlit=at["unlit_masked"], - ) - samples = raw[:, new["slots/index"]] - np.testing.assert_array_equal( - reference_frames(old, samples, [3, 20]), - reference_frames(new, samples, [3, 20]), - ) - - -def _shared_pulses( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - p_split: float = 0.35, - k: float = 5.0, - theta: float = 22.0, -) -> np.ndarray: - """Compound-Poisson samples (slots, cycles) with pulses shared with the next slot. - - The pulses (gamma heights) are split with the next slot on the line with - probability p_split, by a uniform fraction. - - Returns - ------- - np.ndarray - Rounded samples of shape (slots, cycles). - """ - n_slots, n_cycles = rate.shape - out = np.zeros((n_slots, n_cycles)) - counts = rng.poisson(rate) - s, c = np.nonzero(counts) - s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) - height = rng.gamma(k, theta, s.size) - split = (rng.random(s.size) < p_split) & (nxt[s] >= 0) - frac = np.where(split, rng.random(s.size), 1.0) - np.add.at(out, (s, c), height * frac) - np.add.at(out, (nxt[s[split]], c[split]), height[split] * (1 - frac[split])) - return np.round(out) - - -def test_pulse_statistics_recover_the_pulses() -> None: - """Heights, split probability and split fractions of simulated shared pulses. - - Measured on the dim pairs only. - """ - rng = np.random.default_rng(0) - n_lines, per_line, n_cycles = 40, 30, 4000 - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - nxt = next_slots(slot_line, slot_pos) - # dim lines and bright lines; only the dim ones should be used - level = np.where(slot_line <= 30, 0.01, 1.5) - rate = np.repeat(level[:, None], n_cycles, 1) - x = _shared_pulses(rate, nxt, rng) - x[5, :50] = INVALID_SAMPLE - samples = torch.from_numpy(x.astype(np.int16))[None] - out = pulse_statistics(samples, nxt) - single, split = out["height_single"][0], out["height_split"][0] - assert out["pairs"][0] == 30 * (per_line - 2) - n1, n2 = single.sum(), split.sum() - assert n1 + n2 > 6_000 - # only the pulses of each pair's first slot are counted, and 0.35 of - # them are split into the pair - assert abs(n2 / (n1 + n2) - 0.35) < 0.02 - heights = np.arange(1, HEIGHT_BINS + 1) - mean_height = ((single + split) * heights).sum() / (n1 + n2) - assert abs(mean_height - 5.0 * 22.0) < 3.0 - frac = out["split_fraction"][0] - assert frac.sum() == n2 - joint = out["split_joint"][0] - assert joint.shape == (f0_layout.JOINT_BINS, SPLIT_BINS) - assert np.array_equal(joint.sum(0), frac) - width = HEIGHT_BINS // f0_layout.JOINT_BINS - assert np.array_equal(joint.sum(1), split.reshape(-1, width).sum(1)) - assert np.abs(frac / n2 - 1 / SPLIT_BINS).max() < 0.02 - # isolated pair-cycles: both slots valid, their neighbours zero - assert 0.9 < out["pair_cycles"][0] / (out["pairs"][0] * n_cycles) < 1.0 - stats = slot_statistics(samples) - assert abs(stats["valid_share"][0, 5] - (1 - 50 / n_cycles)) < 1e-6 - assert abs(np.nanmean(stats["mean"][0, slot_line <= 30]) - 1.1) < 0.1 - - -def test_pairs_next_to_unseen_samples_are_left_out() -> None: - """A line with a sample that is not a raster slot. - - A pulse split with it would be counted truncated, so the pair before the - gap is not used; a pair needs a slot before it, so none starts a run - either. - """ - rng = np.random.default_rng(2) - # one line of eight samples; the one at position 4 is not a raster slot - slot_line = np.ones(7, dtype=np.int64) - slot_pos = np.array([0, 1, 2, 3, 5, 6, 7]) - nxt = next_slots(slot_line, slot_pos) - assert list(nxt) == [1, 2, 3, -1, 5, 6, -1] - x = (rng.random((7, 2000)) < 0.02) * 100 - samples = torch.from_numpy(x.astype(np.int16))[None] - # without line ends, a slot without a next ends its run: pairs (1, 2), - # (2, 3) and (5, 6); (0, 1) and (4, 5) start a run - naive = pulse_statistics(samples, nxt) - assert naive["pairs"][0] == 3 - out = pulse_statistics(samples, nxt, slot_pos == 7) - # the sample after 3 is unseen: (2, 3) goes - assert out["pairs"][0] == 2 - alone = (x[0] == 0) & (x[3] == 0) - one = (x[1] > 0) & (x[2] == 0) - both = (x[1] > 0) & (x[2] > 0) - alone2 = x[4] == 0 # the pair (5, 6): slot 4 before it, nothing after it - one2 = (x[5] > 0) & (x[6] == 0) - both2 = (x[5] > 0) & (x[6] > 0) - assert out["pair_cycles"][0] == alone.sum() + alone2.sum() - assert out["height_single"][0].sum() == (one & alone).sum() + (one2 & alone2).sum() - assert out["height_split"][0].sum() == (both & alone).sum() + (both2 & alone2).sum() - - -def test_run_starts_are_not_measured() -> None: - """The sample before a run is not recorded but passes parts of its pulses on. - - Counted on the run's first slot they would look like small unsplit - pulses. - """ - rng = np.random.default_rng(6) - n_cycles = 6000 - # the recorded run is the last six samples of a line of eight - slot_line = np.ones(8, dtype=np.int64) - slot_pos = np.arange(8) - full = next_slots(slot_line, slot_pos) - x = _shared_pulses(np.full((8, n_cycles), 0.01), full, rng, p_split=0.5) - seen = x[2:] # slots 0 and 1 are not recorded - nxt = np.array([1, 2, 3, 4, 5, -1]) - out = pulse_statistics(torch.from_numpy(seen.astype(np.int16))[None], nxt) - assert out["pairs"][0] == 4 # the pair starting the run is not used - low = out["height_single"][0][:25].sum() / out["height_single"][0].sum() - assert low < 0.02 # the simulated pulses are rarely below 25 - # the run's first slot alone: many small "pulses" - first = seen[0][(seen[0] > 0) & (seen[1] == 0)] - assert (first < 25).mean() > 5 * max(low, 0.01) - - -def test_layout_file_marks_line_ends(patched: Registered, tmp_path: Path) -> None: - """slots/next links consecutive samples of neighbouring pixels. - - slots/line_end marks the slots that nothing follows which could share - a pulse: a line's last sample, or one before a jump. - """ - from giant_python.export.f0_layout import LAYOUT_VERSION, sharing_slots - - layout, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - assert lay["attrs"]["layout_version"] == LAYOUT_VERSION - idx = lay["slots/index"] - consecutive = next_slots(layout.slot_line, layout.slot_pos) - nxt, start, end = sharing_slots(layout) - row = (layout.slot_pixel - 1) // layout.n_cols - col = (layout.slot_pixel - 1) % layout.n_cols - to = np.maximum(consecutive, 0) - near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) - assert np.array_equal(nxt >= 0, (consecutive >= 0) & near) - assert np.array_equal(nxt[nxt >= 0], consecutive[nxt >= 0]) - last = layout.slot_pos == layout.n_per_channel[layout.slot_line - 1] - 1 - assert np.array_equal(end, last | ((consecutive >= 0) & ~near)) - # a slot starts a run when it starts its line or follows a jump - follows_jump = np.zeros(nxt.size, bool) - follows_jump[consecutive[(consecutive >= 0) & ~near]] = True - assert np.array_equal(start, (layout.slot_pos == 0) | follows_jump) - # the synthetic lines hold raster slots only: every slot is in the file - assert np.array_equal(lay["slots/line_end"].astype(bool), end[idx]) - assert np.array_equal(lay["slots/next"] < 0, end[idx]) - - -def test_pulses_are_not_measured_across_jumps() -> None: - """A pair whose samples are not neighbouring pixels shares no pulse. - - It is not a pair; the slots on either side of the jump are measured as the - ends of their runs. - """ - rng = np.random.default_rng(4) - n_cycles = 4000 - # one line of 8 samples: pixels 0-3 of a row, then a jump to 20-23 - slot_line = np.ones(8, dtype=np.int64) - slot_pos = np.arange(8) - cols = np.array([0, 1, 2, 3, 20, 21, 22, 23]) - - class Layout: - """One line of 8 samples: pixels 0-3 of a row, then a jump to 20-23.""" - - n_cols = 50 - slot_pixel = 5 * 50 + cols + 1 - n_per_channel = np.array([8]) - - Layout.slot_line, Layout.slot_pos = slot_line, slot_pos - from giant_python.export.f0_layout import sharing_slots - - nxt, start, end = sharing_slots(Layout) - assert list(nxt) == [1, 2, 3, -1, 5, 6, 7, -1] - assert list(start) == [ - True, - False, - False, - False, - True, - False, - False, - False, - ] - assert list(end) == [False, False, False, True, False, False, False, True] - # pulses split with probability 0.4 inside each run, none across the jump - x = _shared_pulses(np.full((8, n_cycles), 0.01), nxt, rng, p_split=0.4) - samples = torch.from_numpy(x.astype(np.int16))[None] - out = pulse_statistics(samples, nxt, end) - assert out["pairs"][0] == 4 # two per run: none starts a run - n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() - assert abs(n2 / (n1 + n2) - 0.4) < 0.07 - # counting the jump as a pair adds a slot whose pulses are never split - naive = pulse_statistics(samples, next_slots(slot_line, slot_pos)) - assert naive["pairs"][0] == 6 - m1, m2 = naive["height_single"][0].sum(), naive["height_split"][0].sum() - assert m2 / (m1 + m2) < n2 / (n1 + n2) - - -def test_pulse_statistics_without_dim_pairs() -> None: - """Bright pairs, in which pulses coincide, are never used. - - A recording without dim pairs gets empty histograms. - """ - rng = np.random.default_rng(1) - slot_line = np.repeat(np.arange(1, 21), 20) - slot_pos = np.tile(np.arange(20), 20) - nxt = next_slots(slot_line, slot_pos) - # no sharing at all: any split pulse would be a coincidence - x = _shared_pulses(np.full((400, 500), 0.8), nxt, rng, p_split=0.0) - out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - assert out["pairs"][0] == 0 and out["pair_cycles"][0] == 0 - for key in ("height_single", "height_split", "split_fraction"): - assert out[key].sum() == 0 - # dim pairs without sharing: almost no pulse is counted as split - x = _shared_pulses(np.full((400, 4000), 0.005), nxt, rng, p_split=0.0) - out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() - assert out["pairs"][0] == 360 and n1 > 5000 and n2 / (n1 + n2) < 0.01 - rate = (n1 + n2) / out["pair_cycles"][0] - assert abs(n2 / (n1 + n2) - rate) < 0.004 # the coincidences - none = pulse_statistics(torch.zeros((1, 3, 10), dtype=torch.int16), np.full(3, -1)) - assert none["pairs"][0] == 0 and none["height_single"].sum() == 0 - - -def _bursts( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - lengths: tuple[float, ...] = (0.5, 0.35, 0.12, 0.03), -) -> np.ndarray: - """Draw samples (slots, cycles) of events that occupy 1-4 consecutive slots. - - The lengths have the given probabilities, every part 40 + 10 x its place - in the burst (so that a part tells where in its burst it is). - - Returns - ------- - np.ndarray - Samples of shape (slots, cycles). - """ - n_slots, n_cycles = rate.shape - out = np.zeros((n_slots, n_cycles)) - counts = rng.poisson(rate) - s, c = np.nonzero(counts) - s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) - length = rng.choice(4, s.size, p=lengths) + 1 - slot = s.copy() - for k in range(4): - on = (length > k) & (slot >= 0) - np.add.at(out, (slot[on], c[on]), 40 + 10 * k) - slot = np.where(slot >= 0, nxt[np.maximum(slot, 0)], -1) - return out - - -def test_burst_cells() -> None: - """The type of a burst. - - Its length, total and, for two samples, the smaller part's share. - """ - from giant_python.export.f0_layout import N_CELLS, burst_cells - - assert N_CELLS == 162 - one = burst_cells(np.array([[35], [100], [405], [9000]])) - assert one.tolist() == [3, 10, 40, 40] - two = burst_cells(np.array([[10, 90], [90, 10], [50, 50], [300, 400]])) - assert two.tolist() == [41 + 15, 41 + 15, 41 + 17, 41 + 30 * 3 + 2] - assert burst_cells(np.array([[100, 100, 100]])).tolist() == [134 + 6] - assert burst_cells(np.array([[250, 250, 250, 250]])).tolist() == [161] - assert burst_cells(np.zeros((0, 2))).shape == (0,) - - -def test_burst_library_and_counts_by_stratum(patched: Registered, tmp_path: Path) -> None: - """The library's counts are the events' length distribution. - - Its examples are whole events, part by part; the counts by stratum tell - events whose rate follows brightness from events at a constant rate; the - file holds both. - """ - from giant_python.export.f0_layout import ( - BURST_EXAMPLES, - N_CELLS, - STRATA_EDGES, - burst_cells, - burst_statistics, - ) - - rng = np.random.default_rng(3) - n_lines, per_line, n_cycles = 16, 40, 6000 - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - nxt = next_slots(slot_line, slot_pos) - # lines of four brightnesses (events per sample) and four bright lines - levels = np.array([0.006, 0.016, 0.033, 0.066, 1.0]) - level = levels[np.minimum((slot_line - 1) // 3, 4)] - x = _bursts(np.repeat(level[:, None], n_cycles, 1), nxt, rng) - # events at one rate everywhere: one sample of 60 - extra = rng.random(x.shape) < 0.002 - x = x + 60 * extra - x[7, :100] = INVALID_SAMPLE - out = burst_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) - counts = out["burst_counts"][0] - assert counts[:4].sum() > 5000 - assert counts[4] < 0.01 * counts[:4].sum() - for n in range(1, 5): - kept = out["burst_examples"][0, n - 1] - assert kept == min(BURST_EXAMPLES, counts[n - 1]) - parts = out[f"burst_{n}"][0, :kept] - assert parts.shape[1] == n and (parts > 0).all() - # almost all are one event: part k is 40 + 10 k, or the one of 60 - clean = (parts == 40 + 10 * np.arange(n)).all(1) - if n == 1: - clean |= parts[:, 0] == 60 - # (a long burst is more often two events that touch) - assert clean.mean() > (0.9 if n < 3 else 0.7) - assert (out[f"burst_{n}"][0, kept:] == 0).all() - cells = out[f"burst_cell_{n}"][0, :kept] - np.testing.assert_array_equal(cells, burst_cells(parts)) - # strata: the mean sample rises, the bright lines are not counted - free, mean = out["strata_free"][0], out["strata_mean"][0] - assert out["strata_edges"].tolist() == list(STRATA_EDGES) - assert out["strata_bursts"].shape == (1, len(STRATA_EDGES) - 1, N_CELLS) - used = free > 2e5 - assert used.sum() >= 4 and (np.diff(mean[used]) > 0).all() - assert mean[used].max() < 8 and free.sum() <= 12 * 35 * n_cycles - rate = out["strata_bursts"][0][used] / free[used][:, None] - # one-sample events of 40 follow the mean; those of 60 do not - photon = rate[:, 4] / mean[used] - assert photon.max() < 1.2 * photon.min() - np.testing.assert_allclose(rate[:, 6], 0.002, rtol=0.2) - assert out["strata_longer"][0].sum() < 0.02 * out["strata_bursts"].sum() - # nothing without dim chains - bright = burst_statistics( - torch.from_numpy(x[slot_line > 12].astype(np.int16))[None], - next_slots(slot_line[slot_line > 12], slot_pos[slot_line > 12]), - ) - assert bright["strata_free"].sum() == 0 - assert bright["burst_counts"].sum() == 0 - # the layout file carries the library and the tables - _, table, _ = patched - export_layouts(table, tmp_path) - lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") - assert lay["photon/burst_counts"].shape == (2, 5) - assert lay["photon/burst_3"].shape == (2, BURST_EXAMPLES, 3) - assert lay["photon/burst_cell_2"].shape == (2, BURST_EXAMPLES) - assert lay["photon/strata_bursts"].shape == (2, 8, N_CELLS) - assert lay["photon/level_moments"].shape == (2, 18, 9) - assert lay["photon/level_revisits"] in (0, 1) - assert lay["attrs"]["burst_level"] == 2.0 - - -def _level_case( - rng: np.random.Generator, visits: int, n_cycles: int = 3000 -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Simulate a raster whose pixels are sampled visits times per cycle. - - It has lines of two brightnesses that change together from cycle to cycle; - also returns the moments its events have per unit of mean. - - Returns - ------- - x : np.ndarray - Simulated samples of shape (slots, cycles). - nxt : np.ndarray - Index of the next slot on the line for each slot. - pixel : np.ndarray - Pixel index of each slot. - slot_line : np.ndarray - Line number of each slot. - moments : np.ndarray - The moments the events have per unit of mean. - """ - per_line, n_pairs = 60, 24 - n_lines = n_pairs * visits - slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) - slot_pos = np.tile(np.arange(per_line), n_lines) - pair = (slot_line - 1) // visits - pixel = pair * per_line + slot_pos - nxt = next_slots(slot_line, slot_pos) - rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] - if visits > 1: # brightness that changes slowly: both visits see it - wave = 1 + 0.6 * np.sin(np.arange(n_cycles) / 40.0) - rate = rate * wave[None, :] - else: - rate = np.repeat(rate, n_cycles, 1) - x = _bursts(rate, nxt, rng) - lengths = np.array([0.5, 0.35, 0.12, 0.03]) - parts = 40.0 + 10 * np.arange(4) - total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) - want = np.zeros(9) - for k in range(4): - want[k] = sum( - lengths[n] * (parts[: n + 1 - k] * parts[k : n + 1]).sum() for n in range(k, 4) - ) - return x, nxt, pixel, slot_line, want / total - - -@pytest.mark.parametrize("visits", [2, 1]) -def test_level_statistics_measure_the_events(visits: int) -> None: - """The moments by level are those of the events, per unit of mean. - - At every brightness, also where the brightness changes between cycles (two - visits per cycle) and for a raster without second visits. - """ - from giant_python.export.f0_layout import LEVEL_EDGES, level_statistics - - rng = np.random.default_rng(5 + visits) - x, nxt, pixel, line, want = _level_case(rng, visits) - x[3, :50] = INVALID_SAMPLE - out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, line) - assert out["level_revisits"] == (1 if visits > 1 else 0) - assert out["level_edges"].tolist() == list(LEVEL_EDGES) - n = out["level_samples"][0] - full = np.flatnonzero(n > 2e5) - assert full.size >= 2 - mean = out["level_mean"][0][full] - assert mean.min() < 8 and mean.max() > 20 - per_mean = out["level_moments"][0][full] / mean[:, None] - np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) - np.testing.assert_allclose(per_mean[:, 2], want[2], rtol=0.15) - assert np.abs(per_mean[:, 4:]).max() < 0.03 * want[0] - # zeros: no event covers the sample - cover = 0.5 + 0.35 * 2 + 0.12 * 3 + 0.03 * 4 - total = 0.5 * 40 + 0.35 * 90 + 0.12 * 150 + 0.03 * 220 - dim = full[np.argmin(mean)] - zero = np.exp(-out["level_mean"][0][dim] / total * cover) - assert abs(out["level_zero"][0][dim] - zero) < 0.03 - if visits > 1: # against the next cycle, the changing brightness counts - naive = x.astype(np.float64).var(1).sum() / x.sum() * x.shape[1] - assert naive > 1.15 * want[0] - empty = level_statistics( - torch.zeros((1, 4, 10), dtype=torch.int16), - np.full(4, -1), - np.arange(4), - np.ones(4, dtype=np.int64), - ) - assert empty["level_samples"].sum() == 0 - - -def test_level_statistics_second_observation_is_on_a_later_line() -> None: - """A line that samples its pixels twice in a row. - - The second sample of a pixel on the same line can share pulses with the - first, so it is not taken as the second observation; the next line's is. - """ - from giant_python.export.f0_layout import _second_visits, level_statistics - - rng = np.random.default_rng(13) - n_lines, half, n_cycles = 48, 30, 3000 - slot_line = np.repeat(np.arange(1, n_lines + 1), 2 * half) - slot_pos = np.tile(np.arange(2 * half), n_lines) - pair = (slot_line - 1) // 2 # two lines sample the same pixels - pixel = pair * half + slot_pos % half - nxt = next_slots(slot_line, slot_pos) - chain, other = _second_visits(nxt, pixel, slot_line) - assert other is not None and chain[0].size > 1000 - assert (slot_line[other[0]] == slot_line[chain[0]] + 1).all() - assert (pixel[other[0]] == pixel[chain[0]]).all() - # the first of the later line's two samples, whichever copy asks - assert (slot_pos[other[0]] == slot_pos[chain[0]] % half).all() - # one line per pixel set: no second observation within the cycle - _, none = _second_visits(nxt, slot_line * half + slot_pos % half, slot_line) - assert none is None - rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] - x = _bursts(np.repeat(rate, n_cycles, 1), nxt, rng) - out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, slot_line) - lengths = np.array([0.5, 0.35, 0.12, 0.03]) - parts = 40.0 + 10 * np.arange(4) - total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) - var = sum(lengths[n] * (parts[: n + 1] ** 2).sum() for n in range(4)) - cov = sum(lengths[n] * (parts[:n] * parts[1 : n + 1]).sum() for n in range(1, 4)) - assert out["level_revisits"] == 1 - full = np.flatnonzero(out["level_samples"][0] > 2e5) - per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] - np.testing.assert_allclose(per_mean[:, 0], var / total, rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], cov / total, rtol=0.06) - - -def test_level_statistics_skip_the_visits_of_another_plane() -> None: - """Lines of another plane between a pixel's two visits are no visits. - - Those lines sample the same pixels; marked by a negative pixel, they do not - stand in as the next visit (which would leave no revisits and send the - measurement to the next cycle). - """ - from giant_python.export.f0_layout import _second_visits, level_statistics - - rng = np.random.default_rng(9) - x, nxt, pixel, line, want = _level_case(rng, 3) - # the middle line of each three is another plane: its slots link to - # nothing, as sharing_slots restricted to the plane leaves them - off = (line - 1) % 3 == 1 - nxt = np.where(off | off[np.maximum(nxt, 0)], -1, nxt) - _, other = _second_visits(nxt, pixel, line) - assert other is None # the other plane's visit is taken and fails - chain, other = _second_visits(nxt, np.where(off, -1, pixel), line) - assert other is not None and chain[0].size > 1000 - assert not off[chain[0]].any() and not off[other[0]].any() - assert (line[other[0]] - line[chain[0]] == 2).all() - out = level_statistics( - torch.from_numpy(x.astype(np.int16))[None], - nxt, - np.where(off, -1, pixel), - line, - ) - assert out["level_revisits"] == 1 - full = np.flatnonzero(out["level_samples"][0] > 2e5) - per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] - np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) - np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) +"""The raster layout files of the F0 network's simulator.""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.export import f0_layout +from giant_python.export.f0_layout import ( + HEIGHT_BINS, + SPLIT_BINS, + export_layouts, + layout_path, + pulse_statistics, + read_layout, + reference_frames, + slot_statistics, +) +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + read_raster_samples, +) +from giant_python.registration import multiroi +from giant_python.registration.stats.gain import next_slots + +from ..registration.synthetic import make_layout, online_offsets, write_recording + +MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + +Registered = tuple[RasterLayout, Path, Path] +"""The layout of a registered synthetic trial, its trial table and its folder.""" + + +def _table(tmp_path: Path, dat: Path, last: float = 3000.0) -> Path: + """Write a one-trial trial table of the recording dat. + + Returns + ------- + Path + The path of the written trial table. + """ + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[1.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[last]]), + }, + }, + ) + return table + + +@pytest.fixture(scope="module") +def registered(tmp_path_factory: pytest.TempPathFactory) -> Registered: + """Register a synthetic trial (moving scene, some invalid samples). + + Gives the layout, its trial table and its output folder. + + Returns + ------- + Registered + The layout, its trial table and its output folder, as (layout, table, root). + """ + from giant_python.pipeline.register import register_multiroi + + root = tmp_path_factory.mktemp("layout") + layout = make_layout(root / "synthetic_DMD1-TRIAL000001.dat", 1400) + write_recording(layout, invalid=0.02) + table = _table(root, Path(layout.files[0])) + with pytest.MonkeyPatch.context() as mp: + mp.setattr(multiroi, "raster_layout", lambda path: layout) + register_multiroi( + table, + {"maxshift": 5}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + return layout, table, root + + +@pytest.fixture +def patched(registered: Registered, monkeypatch: pytest.MonkeyPatch) -> Registered: + """Serve the recording's layout to the exporter. + + Returns + ------- + Registered + The registered fixture's value, unchanged. + """ + monkeypatch.setattr(multiroi, "raster_layout", lambda path: registered[0]) + return registered + + +def _movie(path: Path, n_channels: int) -> np.ndarray: + """Read a registered movie as (channels, frames, rows, cols). + + Returns + ------- + np.ndarray + The movie's pages, reshaped and transposed to (channels, frames, rows, cols). + """ + with h5py.File(path, "r") as f: + pages = f[next(iter(f.keys()))][()] + pages = pages.reshape(-1, n_channels, *pages.shape[1:]) + return np.swapaxes(pages, -1, -2).transpose(1, 0, 2, 3) + + +def test_file_reproduces_the_registered_movie(patched: Registered, tmp_path: Path) -> None: + """Frames formed from the file and its slots' raw samples are registration's. + + Missing pixels included. + """ + layout, table, root = patched + out = tmp_path / "layouts" + res = export_layouts(table, out) + assert [r["error"] for r in res] == [None] + lay = read_layout(out / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + assert at["path"] == 1 and at["trial"] == 1 and not at["compensated"] + assert at["lines_per_cycle"] == layout.lines_per_cycle + assert at["margin"] == 5 + c0, n = at["cycle0"], at["n_cycles"] + raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) + samples = raw[:, lay["slots/index"]] + movie = _movie(root / "motion_correction" / MOVIE, at["num_channels"]) + assert movie.shape[1] == lay["frames/lines"].size + frames = np.r_[0, 1, 7, 40, movie.shape[1] - 1] + got = reference_frames(lay, samples, frames) + want = movie[:, frames] + assert got.shape == want.shape + assert np.array_equal(np.isnan(got), np.isnan(want)) + assert np.isfinite(want).mean() > 0.2 + np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) + + +def test_slots_and_their_statistics(patched: Registered, tmp_path: Path) -> None: + """The file's slots are the window's, with their means and zeros.""" + layout, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + idx = lay["slots/index"] + # every slot of the raster block is in the window (one plane) + assert idx.size == layout.slot_line.size + assert np.array_equal(lay["slots/line"], layout.slot_line[idx]) + rows = (layout.slot_pixel[idx] - 1) // layout.n_cols - at["window_row0"] + cols = (layout.slot_pixel[idx] - 1) % layout.n_cols - at["window_col0"] + assert np.array_equal(lay["pixels/row"][lay["slots/pixel"]], rows) + assert np.array_equal(lay["pixels/col"][lay["slots/pixel"]], cols) + nxt = lay["slots/next"] + has = nxt >= 0 + # the synthetic lines visit their pixels in random order: only some + # consecutive samples are neighbouring pixels and share pulses + assert 0 < has.sum() < 0.5 * has.size + step_r = np.abs(rows[nxt[has]] - rows[has]) + step_c = np.abs(cols[nxt[has]] - cols[has]) + assert step_r.max() <= 1 and step_c.max() <= 1 + assert np.array_equal(lay["slots/line"][nxt[has]], lay["slots/line"][has]) + assert np.array_equal(lay["slots/pos"][nxt[has]], lay["slots/pos"][has] + 1) + c0, n = at["cycle0"], at["n_cycles"] + raw = read_raster_samples(layout, (c0, c0 + n))[:, idx].astype(float) + ok = raw != INVALID_SAMPLE + mean = np.where(ok, raw, 0).sum(2) / ok.sum(2) + np.testing.assert_allclose(lay["slots/mean"], mean, rtol=1e-6) + zero = (ok & (raw == 0)).sum(2) / ok.sum(2) + np.testing.assert_allclose(lay["slots/zero_share"], zero, atol=1e-6) + np.testing.assert_allclose(lay["slots/valid_share"], ok.mean(2), atol=1e-6) + assert 0.97 < lay["slots/valid_share"].mean() < 0.99 + + +def test_existing_files_are_kept_and_selection(patched: Registered, tmp_path: Path) -> None: + """A second run keeps the file; --overwrite and the selection.""" + from giant_python.cli import main + + _, table, _ = patched + args = ["export-f0-layout", str(table), "--out", str(tmp_path)] + assert main(args) == 0 + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + stamp = out.stat().st_mtime_ns + assert main(args) == 0 + assert out.stat().st_mtime_ns == stamp + assert main(args + ["--overwrite"]) == 0 + assert out.stat().st_mtime_ns != stamp + assert export_layouts(table, tmp_path / "none", trials=[2]) == [] + assert layout_path("a/E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif") == Path( + "a/E1T1DMD1_F0LAYOUT.h5" + ) + assert layout_path("a/movie.h5") == Path("a/movie_F0LAYOUT.h5") + + +def test_missing_alignment_and_old_versions(patched: Registered, tmp_path: Path) -> None: + """A trial without its alignment file fails. + + Other versions are refused. + """ + from giant_python.cli import main + + _, table, _ = patched + moved = ["--out", str(tmp_path), "--moco", str(tmp_path / "moved")] + assert main(["export-f0-layout", str(table)] + moved) == 1 + assert not (tmp_path / "E1T1DMD1_F0LAYOUT.h5").exists() + export_layouts(table, tmp_path) + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + with h5py.File(out, "r+") as f: + f.attrs["layout_version"] = 0 + with pytest.raises(ValueError, match="layout version"): + read_layout(out) + + +def test_compensated_registration_is_reproduced( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A registration that undid the online correction is reproduced. + + The file holds the lines' offsets and the frames' own, and frames formed + from it, every sample moved by its line's offset, are registration's. + """ + from giant_python.pipeline.register import register_multiroi + + layout = make_layout(tmp_path / "comp_DMD1-TRIAL000001.dat", 500) + x, _, y_dmd = online_offsets(layout.total_lines) + write_recording(layout, seed=6, online=(x, _, y_dmd)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = _table(tmp_path, Path(layout.files[0]), last=2000.0) + register_multiroi( + table, + {"maxshift": 5, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + res = export_layouts(table, tmp_path / "out") + assert [r["error"] for r in res] == [None] + lay = read_layout(tmp_path / "out" / "E1T1DMD1_F0LAYOUT.h5") + at = lay["attrs"] + assert at["compensated"] and at["layout_version"] == 4 + assert list(at["y_lead"]) == [2, 6] + p, c0, n = at["lines_per_cycle"], at["cycle0"], at["n_cycles"] + # the offsets of the lines of the file's cycles: x as the header has + # it, y as it was on the DMD + lines = slice(c0 * p, (c0 + n) * p) + assert lay["lines/x"].shape == (n * p,) + np.testing.assert_array_equal(lay["lines/x"], x[lines]) + np.testing.assert_array_equal(lay["lines/y_eff"], y_dmd[lines]) + assert np.unique(lay["lines/x"]).size > 1 + assert np.unique(lay["lines/y_eff"]).size > 1 + ref = lay["frames/ref_xy"] + assert ref.shape == (lay["frames/lines"].size, 2) + assert np.unique(ref, axis=0).shape[0] > 1 + # the slots' raster positions; a slot whose own pixel is among the + # pixels that frames report points at it + w = at["window_cols"] + slot_flat = lay["slots/row"].astype(np.int64) * w + lay["slots/col"] + pix_flat = lay["pixels/row"].astype(np.int64) * w + lay["pixels/col"] + listed = lay["slots/pixel"] >= 0 + np.testing.assert_array_equal(pix_flat[lay["slots/pixel"][listed]], slot_flat[listed]) + assert np.isin(slot_flat[listed], pix_flat).all() and listed.mean() > 0.9 + raw = read_raster_samples(layout, (c0, c0 + n), mask_unlit=at["unlit_masked"]) + samples = raw[:, lay["slots/index"]] + movie = _movie(tmp_path / "motion_correction" / MOVIE, at["num_channels"]) + assert movie.shape[1] == lay["frames/lines"].size + # frames whose lines span an offset switch among them + changed = np.flatnonzero(np.any(np.diff(ref, axis=0) != 0, axis=1)) + frames = np.unique(np.r_[0, 1, changed[:6], changed[:6] + 1, movie.shape[1] - 1]) + got = reference_frames(lay, samples, frames) + want = movie[:, frames] + assert np.array_equal(np.isnan(got), np.isnan(want)) + assert np.isfinite(want).mean() > 0.2 + np.testing.assert_allclose(got, want, rtol=2e-5, atol=1e-4, equal_nan=True) + # without the offsets the frames are others: the samples are moved + plain = dict(lay, attrs=dict(at, compensated=False)) + off = reference_frames(plain, samples, frames) + both = np.isfinite(off) & np.isfinite(want) + assert np.abs(off - want)[both].max() > 1.0 + + +def test_version_3_files_are_read(patched: Registered, tmp_path: Path) -> None: + """A file of version 3 is read with its slots' positions. + + Version 3 has no slot positions (registrations without online + compensation); such a file gives the same frames. + """ + layout, table, _root = patched + export_layouts(table, tmp_path) + out = tmp_path / "E1T1DMD1_F0LAYOUT.h5" + new = read_layout(out) + assert new["attrs"]["layout_version"] == 4 + assert not new["attrs"]["compensated"] and "lines/x" not in new + np.testing.assert_array_equal(new["slots/row"], new["pixels/row"][new["slots/pixel"]]) + with h5py.File(out, "r+") as f: + f.attrs["layout_version"] = 3 + del f["slots/row"], f["slots/col"] + old = read_layout(out) + assert old["attrs"]["layout_version"] == 3 + np.testing.assert_array_equal(old["slots/row"], new["slots/row"]) + np.testing.assert_array_equal(old["slots/col"], new["slots/col"]) + at = new["attrs"] + raw = read_raster_samples( + layout, + (at["cycle0"], at["cycle0"] + at["n_cycles"]), + mask_unlit=at["unlit_masked"], + ) + samples = raw[:, new["slots/index"]] + np.testing.assert_array_equal( + reference_frames(old, samples, [3, 20]), + reference_frames(new, samples, [3, 20]), + ) + + +def _shared_pulses( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + p_split: float = 0.35, + k: float = 5.0, + theta: float = 22.0, +) -> np.ndarray: + """Compound-Poisson samples (slots, cycles) with pulses shared with the next slot. + + The pulses (gamma heights) are split with the next slot on the line with + probability p_split, by a uniform fraction. + + Returns + ------- + np.ndarray + Rounded samples of shape (slots, cycles). + """ + n_slots, n_cycles = rate.shape + out = np.zeros((n_slots, n_cycles)) + counts = rng.poisson(rate) + s, c = np.nonzero(counts) + s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) + height = rng.gamma(k, theta, s.size) + split = (rng.random(s.size) < p_split) & (nxt[s] >= 0) + frac = np.where(split, rng.random(s.size), 1.0) + np.add.at(out, (s, c), height * frac) + np.add.at(out, (nxt[s[split]], c[split]), height[split] * (1 - frac[split])) + return np.round(out) + + +def test_pulse_statistics_recover_the_pulses() -> None: + """Heights, split probability and split fractions of simulated shared pulses. + + Measured on the dim pairs only. + """ + rng = np.random.default_rng(0) + n_lines, per_line, n_cycles = 40, 30, 4000 + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + nxt = next_slots(slot_line, slot_pos) + # dim lines and bright lines; only the dim ones should be used + level = np.where(slot_line <= 30, 0.01, 1.5) + rate = np.repeat(level[:, None], n_cycles, 1) + x = _shared_pulses(rate, nxt, rng) + x[5, :50] = INVALID_SAMPLE + samples = torch.from_numpy(x.astype(np.int16))[None] + out = pulse_statistics(samples, nxt) + single, split = out["height_single"][0], out["height_split"][0] + assert out["pairs"][0] == 30 * (per_line - 2) + n1, n2 = single.sum(), split.sum() + assert n1 + n2 > 6_000 + # only the pulses of each pair's first slot are counted, and 0.35 of + # them are split into the pair + assert abs(n2 / (n1 + n2) - 0.35) < 0.02 + heights = np.arange(1, HEIGHT_BINS + 1) + mean_height = ((single + split) * heights).sum() / (n1 + n2) + assert abs(mean_height - 5.0 * 22.0) < 3.0 + frac = out["split_fraction"][0] + assert frac.sum() == n2 + joint = out["split_joint"][0] + assert joint.shape == (f0_layout.JOINT_BINS, SPLIT_BINS) + assert np.array_equal(joint.sum(0), frac) + width = HEIGHT_BINS // f0_layout.JOINT_BINS + assert np.array_equal(joint.sum(1), split.reshape(-1, width).sum(1)) + assert np.abs(frac / n2 - 1 / SPLIT_BINS).max() < 0.02 + # isolated pair-cycles: both slots valid, their neighbours zero + assert 0.9 < out["pair_cycles"][0] / (out["pairs"][0] * n_cycles) < 1.0 + stats = slot_statistics(samples) + assert abs(stats["valid_share"][0, 5] - (1 - 50 / n_cycles)) < 1e-6 + assert abs(np.nanmean(stats["mean"][0, slot_line <= 30]) - 1.1) < 0.1 + + +def test_pairs_next_to_unseen_samples_are_left_out() -> None: + """A line with a sample that is not a raster slot. + + A pulse split with it would be counted truncated, so the pair before the + gap is not used; a pair needs a slot before it, so none starts a run + either. + """ + rng = np.random.default_rng(2) + # one line of eight samples; the one at position 4 is not a raster slot + slot_line = np.ones(7, dtype=np.int64) + slot_pos = np.array([0, 1, 2, 3, 5, 6, 7]) + nxt = next_slots(slot_line, slot_pos) + assert list(nxt) == [1, 2, 3, -1, 5, 6, -1] + x = (rng.random((7, 2000)) < 0.02) * 100 + samples = torch.from_numpy(x.astype(np.int16))[None] + # without line ends, a slot without a next ends its run: pairs (1, 2), + # (2, 3) and (5, 6); (0, 1) and (4, 5) start a run + naive = pulse_statistics(samples, nxt) + assert naive["pairs"][0] == 3 + out = pulse_statistics(samples, nxt, slot_pos == 7) + # the sample after 3 is unseen: (2, 3) goes + assert out["pairs"][0] == 2 + alone = (x[0] == 0) & (x[3] == 0) + one = (x[1] > 0) & (x[2] == 0) + both = (x[1] > 0) & (x[2] > 0) + alone2 = x[4] == 0 # the pair (5, 6): slot 4 before it, nothing after it + one2 = (x[5] > 0) & (x[6] == 0) + both2 = (x[5] > 0) & (x[6] > 0) + assert out["pair_cycles"][0] == alone.sum() + alone2.sum() + assert out["height_single"][0].sum() == (one & alone).sum() + (one2 & alone2).sum() + assert out["height_split"][0].sum() == (both & alone).sum() + (both2 & alone2).sum() + + +def test_run_starts_are_not_measured() -> None: + """The sample before a run is not recorded but passes parts of its pulses on. + + Counted on the run's first slot they would look like small unsplit + pulses. + """ + rng = np.random.default_rng(6) + n_cycles = 6000 + # the recorded run is the last six samples of a line of eight + slot_line = np.ones(8, dtype=np.int64) + slot_pos = np.arange(8) + full = next_slots(slot_line, slot_pos) + x = _shared_pulses(np.full((8, n_cycles), 0.01), full, rng, p_split=0.5) + seen = x[2:] # slots 0 and 1 are not recorded + nxt = np.array([1, 2, 3, 4, 5, -1]) + out = pulse_statistics(torch.from_numpy(seen.astype(np.int16))[None], nxt) + assert out["pairs"][0] == 4 # the pair starting the run is not used + low = out["height_single"][0][:25].sum() / out["height_single"][0].sum() + assert low < 0.02 # the simulated pulses are rarely below 25 + # the run's first slot alone: many small "pulses" + first = seen[0][(seen[0] > 0) & (seen[1] == 0)] + assert (first < 25).mean() > 5 * max(low, 0.01) + + +def test_layout_file_marks_line_ends(patched: Registered, tmp_path: Path) -> None: + """slots/next links consecutive samples of neighbouring pixels. + + slots/line_end marks the slots that nothing follows which could share + a pulse: a line's last sample, or one before a jump. + """ + from giant_python.export.f0_layout import LAYOUT_VERSION, sharing_slots + + layout, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + assert lay["attrs"]["layout_version"] == LAYOUT_VERSION + idx = lay["slots/index"] + consecutive = next_slots(layout.slot_line, layout.slot_pos) + nxt, start, end = sharing_slots(layout) + row = (layout.slot_pixel - 1) // layout.n_cols + col = (layout.slot_pixel - 1) % layout.n_cols + to = np.maximum(consecutive, 0) + near = (np.abs(row[to] - row) <= 1) & (np.abs(col[to] - col) <= 1) + assert np.array_equal(nxt >= 0, (consecutive >= 0) & near) + assert np.array_equal(nxt[nxt >= 0], consecutive[nxt >= 0]) + last = layout.slot_pos == layout.n_per_channel[layout.slot_line - 1] - 1 + assert np.array_equal(end, last | ((consecutive >= 0) & ~near)) + # a slot starts a run when it starts its line or follows a jump + follows_jump = np.zeros(nxt.size, bool) + follows_jump[consecutive[(consecutive >= 0) & ~near]] = True + assert np.array_equal(start, (layout.slot_pos == 0) | follows_jump) + # the synthetic lines hold raster slots only: every slot is in the file + assert np.array_equal(lay["slots/line_end"].astype(bool), end[idx]) + assert np.array_equal(lay["slots/next"] < 0, end[idx]) + + +def test_pulses_are_not_measured_across_jumps() -> None: + """A pair whose samples are not neighbouring pixels shares no pulse. + + It is not a pair; the slots on either side of the jump are measured as the + ends of their runs. + """ + rng = np.random.default_rng(4) + n_cycles = 4000 + # one line of 8 samples: pixels 0-3 of a row, then a jump to 20-23 + slot_line = np.ones(8, dtype=np.int64) + slot_pos = np.arange(8) + cols = np.array([0, 1, 2, 3, 20, 21, 22, 23]) + + class Layout: + """One line of 8 samples: pixels 0-3 of a row, then a jump to 20-23.""" + + n_cols = 50 + slot_pixel = 5 * 50 + cols + 1 + n_per_channel = np.array([8]) + + Layout.slot_line, Layout.slot_pos = slot_line, slot_pos + from giant_python.export.f0_layout import sharing_slots + + nxt, start, end = sharing_slots(Layout) + assert list(nxt) == [1, 2, 3, -1, 5, 6, 7, -1] + assert list(start) == [ + True, + False, + False, + False, + True, + False, + False, + False, + ] + assert list(end) == [False, False, False, True, False, False, False, True] + # pulses split with probability 0.4 inside each run, none across the jump + x = _shared_pulses(np.full((8, n_cycles), 0.01), nxt, rng, p_split=0.4) + samples = torch.from_numpy(x.astype(np.int16))[None] + out = pulse_statistics(samples, nxt, end) + assert out["pairs"][0] == 4 # two per run: none starts a run + n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() + assert abs(n2 / (n1 + n2) - 0.4) < 0.07 + # counting the jump as a pair adds a slot whose pulses are never split + naive = pulse_statistics(samples, next_slots(slot_line, slot_pos)) + assert naive["pairs"][0] == 6 + m1, m2 = naive["height_single"][0].sum(), naive["height_split"][0].sum() + assert m2 / (m1 + m2) < n2 / (n1 + n2) + + +def test_pulse_statistics_without_dim_pairs() -> None: + """Bright pairs, in which pulses coincide, are never used. + + A recording without dim pairs gets empty histograms. + """ + rng = np.random.default_rng(1) + slot_line = np.repeat(np.arange(1, 21), 20) + slot_pos = np.tile(np.arange(20), 20) + nxt = next_slots(slot_line, slot_pos) + # no sharing at all: any split pulse would be a coincidence + x = _shared_pulses(np.full((400, 500), 0.8), nxt, rng, p_split=0.0) + out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + assert out["pairs"][0] == 0 and out["pair_cycles"][0] == 0 + for key in ("height_single", "height_split", "split_fraction"): + assert out[key].sum() == 0 + # dim pairs without sharing: almost no pulse is counted as split + x = _shared_pulses(np.full((400, 4000), 0.005), nxt, rng, p_split=0.0) + out = pulse_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + n1, n2 = out["height_single"][0].sum(), out["height_split"][0].sum() + assert out["pairs"][0] == 360 and n1 > 5000 and n2 / (n1 + n2) < 0.01 + rate = (n1 + n2) / out["pair_cycles"][0] + assert abs(n2 / (n1 + n2) - rate) < 0.004 # the coincidences + none = pulse_statistics(torch.zeros((1, 3, 10), dtype=torch.int16), np.full(3, -1)) + assert none["pairs"][0] == 0 and none["height_single"].sum() == 0 + + +def _bursts( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + lengths: tuple[float, ...] = (0.5, 0.35, 0.12, 0.03), +) -> np.ndarray: + """Draw samples (slots, cycles) of events that occupy 1-4 consecutive slots. + + The lengths have the given probabilities, every part 40 + 10 x its place + in the burst (so that a part tells where in its burst it is). + + Returns + ------- + np.ndarray + Samples of shape (slots, cycles). + """ + n_slots, n_cycles = rate.shape + out = np.zeros((n_slots, n_cycles)) + counts = rng.poisson(rate) + s, c = np.nonzero(counts) + s, c = np.repeat(s, counts[s, c]), np.repeat(c, counts[s, c]) + length = rng.choice(4, s.size, p=lengths) + 1 + slot = s.copy() + for k in range(4): + on = (length > k) & (slot >= 0) + np.add.at(out, (slot[on], c[on]), 40 + 10 * k) + slot = np.where(slot >= 0, nxt[np.maximum(slot, 0)], -1) + return out + + +def test_burst_cells() -> None: + """The type of a burst. + + Its length, total and, for two samples, the smaller part's share. + """ + from giant_python.export.f0_layout import N_CELLS, burst_cells + + assert N_CELLS == 162 + one = burst_cells(np.array([[35], [100], [405], [9000]])) + assert one.tolist() == [3, 10, 40, 40] + two = burst_cells(np.array([[10, 90], [90, 10], [50, 50], [300, 400]])) + assert two.tolist() == [41 + 15, 41 + 15, 41 + 17, 41 + 30 * 3 + 2] + assert burst_cells(np.array([[100, 100, 100]])).tolist() == [134 + 6] + assert burst_cells(np.array([[250, 250, 250, 250]])).tolist() == [161] + assert burst_cells(np.zeros((0, 2))).shape == (0,) + + +def test_burst_library_and_counts_by_stratum(patched: Registered, tmp_path: Path) -> None: + """The library's counts are the events' length distribution. + + Its examples are whole events, part by part; the counts by stratum tell + events whose rate follows brightness from events at a constant rate; the + file holds both. + """ + from giant_python.export.f0_layout import ( + BURST_EXAMPLES, + N_CELLS, + STRATA_EDGES, + burst_cells, + burst_statistics, + ) + + rng = np.random.default_rng(3) + n_lines, per_line, n_cycles = 16, 40, 6000 + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + nxt = next_slots(slot_line, slot_pos) + # lines of four brightnesses (events per sample) and four bright lines + levels = np.array([0.006, 0.016, 0.033, 0.066, 1.0]) + level = levels[np.minimum((slot_line - 1) // 3, 4)] + x = _bursts(np.repeat(level[:, None], n_cycles, 1), nxt, rng) + # events at one rate everywhere: one sample of 60 + extra = rng.random(x.shape) < 0.002 + x = x + 60 * extra + x[7, :100] = INVALID_SAMPLE + out = burst_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt) + counts = out["burst_counts"][0] + assert counts[:4].sum() > 5000 + assert counts[4] < 0.01 * counts[:4].sum() + for n in range(1, 5): + kept = out["burst_examples"][0, n - 1] + assert kept == min(BURST_EXAMPLES, counts[n - 1]) + parts = out[f"burst_{n}"][0, :kept] + assert parts.shape[1] == n and (parts > 0).all() + # almost all are one event: part k is 40 + 10 k, or the one of 60 + clean = (parts == 40 + 10 * np.arange(n)).all(1) + if n == 1: + clean |= parts[:, 0] == 60 + # (a long burst is more often two events that touch) + assert clean.mean() > (0.9 if n < 3 else 0.7) + assert (out[f"burst_{n}"][0, kept:] == 0).all() + cells = out[f"burst_cell_{n}"][0, :kept] + np.testing.assert_array_equal(cells, burst_cells(parts)) + # strata: the mean sample rises, the bright lines are not counted + free, mean = out["strata_free"][0], out["strata_mean"][0] + assert out["strata_edges"].tolist() == list(STRATA_EDGES) + assert out["strata_bursts"].shape == (1, len(STRATA_EDGES) - 1, N_CELLS) + used = free > 2e5 + assert used.sum() >= 4 and (np.diff(mean[used]) > 0).all() + assert mean[used].max() < 8 and free.sum() <= 12 * 35 * n_cycles + rate = out["strata_bursts"][0][used] / free[used][:, None] + # one-sample events of 40 follow the mean; those of 60 do not + photon = rate[:, 4] / mean[used] + assert photon.max() < 1.2 * photon.min() + np.testing.assert_allclose(rate[:, 6], 0.002, rtol=0.2) + assert out["strata_longer"][0].sum() < 0.02 * out["strata_bursts"].sum() + # nothing without dim chains + bright = burst_statistics( + torch.from_numpy(x[slot_line > 12].astype(np.int16))[None], + next_slots(slot_line[slot_line > 12], slot_pos[slot_line > 12]), + ) + assert bright["strata_free"].sum() == 0 + assert bright["burst_counts"].sum() == 0 + # the layout file carries the library and the tables + _, table, _ = patched + export_layouts(table, tmp_path) + lay = read_layout(tmp_path / "E1T1DMD1_F0LAYOUT.h5") + assert lay["photon/burst_counts"].shape == (2, 5) + assert lay["photon/burst_3"].shape == (2, BURST_EXAMPLES, 3) + assert lay["photon/burst_cell_2"].shape == (2, BURST_EXAMPLES) + assert lay["photon/strata_bursts"].shape == (2, 8, N_CELLS) + assert lay["photon/level_moments"].shape == (2, 18, 9) + assert lay["photon/level_revisits"] in (0, 1) + assert lay["attrs"]["burst_level"] == 2.0 + + +def _level_case( + rng: np.random.Generator, visits: int, n_cycles: int = 3000 +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Simulate a raster whose pixels are sampled visits times per cycle. + + It has lines of two brightnesses that change together from cycle to cycle; + also returns the moments its events have per unit of mean. + + Returns + ------- + x : np.ndarray + Simulated samples of shape (slots, cycles). + nxt : np.ndarray + Index of the next slot on the line for each slot. + pixel : np.ndarray + Pixel index of each slot. + slot_line : np.ndarray + Line number of each slot. + moments : np.ndarray + The moments the events have per unit of mean. + """ + per_line, n_pairs = 60, 24 + n_lines = n_pairs * visits + slot_line = np.repeat(np.arange(1, n_lines + 1), per_line) + slot_pos = np.tile(np.arange(per_line), n_lines) + pair = (slot_line - 1) // visits + pixel = pair * per_line + slot_pos + nxt = next_slots(slot_line, slot_pos) + rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] + if visits > 1: # brightness that changes slowly: both visits see it + wave = 1 + 0.6 * np.sin(np.arange(n_cycles) / 40.0) + rate = rate * wave[None, :] + else: + rate = np.repeat(rate, n_cycles, 1) + x = _bursts(rate, nxt, rng) + lengths = np.array([0.5, 0.35, 0.12, 0.03]) + parts = 40.0 + 10 * np.arange(4) + total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) + want = np.zeros(9) + for k in range(4): + want[k] = sum( + lengths[n] * (parts[: n + 1 - k] * parts[k : n + 1]).sum() for n in range(k, 4) + ) + return x, nxt, pixel, slot_line, want / total + + +@pytest.mark.parametrize("visits", [2, 1]) +def test_level_statistics_measure_the_events(visits: int) -> None: + """The moments by level are those of the events, per unit of mean. + + At every brightness, also where the brightness changes between cycles (two + visits per cycle) and for a raster without second visits. + """ + from giant_python.export.f0_layout import LEVEL_EDGES, level_statistics + + rng = np.random.default_rng(5 + visits) + x, nxt, pixel, line, want = _level_case(rng, visits) + x[3, :50] = INVALID_SAMPLE + out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, line) + assert out["level_revisits"] == (1 if visits > 1 else 0) + assert out["level_edges"].tolist() == list(LEVEL_EDGES) + n = out["level_samples"][0] + full = np.flatnonzero(n > 2e5) + assert full.size >= 2 + mean = out["level_mean"][0][full] + assert mean.min() < 8 and mean.max() > 20 + per_mean = out["level_moments"][0][full] / mean[:, None] + np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) + np.testing.assert_allclose(per_mean[:, 2], want[2], rtol=0.15) + assert np.abs(per_mean[:, 4:]).max() < 0.03 * want[0] + # zeros: no event covers the sample + cover = 0.5 + 0.35 * 2 + 0.12 * 3 + 0.03 * 4 + total = 0.5 * 40 + 0.35 * 90 + 0.12 * 150 + 0.03 * 220 + dim = full[np.argmin(mean)] + zero = np.exp(-out["level_mean"][0][dim] / total * cover) + assert abs(out["level_zero"][0][dim] - zero) < 0.03 + if visits > 1: # against the next cycle, the changing brightness counts + naive = x.astype(np.float64).var(1).sum() / x.sum() * x.shape[1] + assert naive > 1.15 * want[0] + empty = level_statistics( + torch.zeros((1, 4, 10), dtype=torch.int16), + np.full(4, -1), + np.arange(4), + np.ones(4, dtype=np.int64), + ) + assert empty["level_samples"].sum() == 0 + + +def test_level_statistics_second_observation_is_on_a_later_line() -> None: + """A line that samples its pixels twice in a row. + + The second sample of a pixel on the same line can share pulses with the + first, so it is not taken as the second observation; the next line's is. + """ + from giant_python.export.f0_layout import _second_visits, level_statistics + + rng = np.random.default_rng(13) + n_lines, half, n_cycles = 48, 30, 3000 + slot_line = np.repeat(np.arange(1, n_lines + 1), 2 * half) + slot_pos = np.tile(np.arange(2 * half), n_lines) + pair = (slot_line - 1) // 2 # two lines sample the same pixels + pixel = pair * half + slot_pos % half + nxt = next_slots(slot_line, slot_pos) + chain, other = _second_visits(nxt, pixel, slot_line) + assert other is not None and chain[0].size > 1000 + assert (slot_line[other[0]] == slot_line[chain[0]] + 1).all() + assert (pixel[other[0]] == pixel[chain[0]]).all() + # the first of the later line's two samples, whichever copy asks + assert (slot_pos[other[0]] == slot_pos[chain[0]] % half).all() + # one line per pixel set: no second observation within the cycle + _, none = _second_visits(nxt, slot_line * half + slot_pos % half, slot_line) + assert none is None + rate = np.where(pair % 2 == 0, 0.05, 0.4)[:, None] + x = _bursts(np.repeat(rate, n_cycles, 1), nxt, rng) + out = level_statistics(torch.from_numpy(x.astype(np.int16))[None], nxt, pixel, slot_line) + lengths = np.array([0.5, 0.35, 0.12, 0.03]) + parts = 40.0 + 10 * np.arange(4) + total = sum(lengths[n] * parts[: n + 1].sum() for n in range(4)) + var = sum(lengths[n] * (parts[: n + 1] ** 2).sum() for n in range(4)) + cov = sum(lengths[n] * (parts[:n] * parts[1 : n + 1]).sum() for n in range(1, 4)) + assert out["level_revisits"] == 1 + full = np.flatnonzero(out["level_samples"][0] > 2e5) + per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] + np.testing.assert_allclose(per_mean[:, 0], var / total, rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], cov / total, rtol=0.06) + + +def test_level_statistics_skip_the_visits_of_another_plane() -> None: + """Lines of another plane between a pixel's two visits are no visits. + + Those lines sample the same pixels; marked by a negative pixel, they do not + stand in as the next visit (which would leave no revisits and send the + measurement to the next cycle). + """ + from giant_python.export.f0_layout import _second_visits, level_statistics + + rng = np.random.default_rng(9) + x, nxt, pixel, line, want = _level_case(rng, 3) + # the middle line of each three is another plane: its slots link to + # nothing, as sharing_slots restricted to the plane leaves them + off = (line - 1) % 3 == 1 + nxt = np.where(off | off[np.maximum(nxt, 0)], -1, nxt) + _, other = _second_visits(nxt, pixel, line) + assert other is None # the other plane's visit is taken and fails + chain, other = _second_visits(nxt, np.where(off, -1, pixel), line) + assert other is not None and chain[0].size > 1000 + assert not off[chain[0]].any() and not off[other[0]].any() + assert (line[other[0]] - line[chain[0]] == 2).all() + out = level_statistics( + torch.from_numpy(x.astype(np.int16))[None], + nxt, + np.where(off, -1, pixel), + line, + ) + assert out["level_revisits"] == 1 + full = np.flatnonzero(out["level_samples"][0] > 2e5) + per_mean = out["level_moments"][0][full] / out["level_mean"][0][full, None] + np.testing.assert_allclose(per_mean[:, 0], want[0], rtol=0.03) + np.testing.assert_allclose(per_mean[:, 1], want[1], rtol=0.06) diff --git a/tests/export/test_f0_training.py b/tests/export/test_f0_training.py index 35878e89..9505a278 100644 --- a/tests/export/test_f0_training.py +++ b/tests/export/test_f0_training.py @@ -1,976 +1,976 @@ -"""F0 training-data export (giant export-f0) on a synthetic SILo run.""" - -import json -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.export import f0_qc -from giant_python.export.f0_training import ExportOptions, export_run - -from ..viewer.synthetic import BASELINE, CENTRES, N_TRIALS, write_session - -N80 = 600 - - -@pytest.fixture(scope="module", params=["rigid", "patchwise"]) -def session( - request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory -) -> dict[str, Any]: - """Build a synthetic session (rigid or patchwise maps) of 600 frames. - - Returns - ------- - dict[str, Any] - The session written by write_session: its run, motion-correction and baseline - folders. - """ - root = tmp_path_factory.mktemp(f"syn_{request.param}") - return write_session(root, request.param, n80=N80) - - -def _export( - syn: dict[str, Any], - out: Path, - **kw: object, -) -> dict: - """Export the synthetic run with the given options. - - Returns - ------- - dict - The export summary from export_run, including the per-trial records (trials). - """ - return export_run( - syn["run"], - out, - syn["run"] / "trial_table.h5", - syn["moco"], - syn["base"], - options=ExportOptions(**kw), - log=lambda line: None, - ) - - -def test_layout_matches_the_training_reader(session: dict[str, Any], tmp_path: Path) -> None: - """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile reads them. - - The reader is not a dependency: its contract is checked here. - """ - s = _export(session, tmp_path, kernel="exporter") - assert [q["trial"] for q in s["trials"]] == [1, 2] - for q in s["trials"]: - assert "error" not in q - with h5py.File(q["file"], "r") as f: - n_ch, T, R, C = f["movie"].shape - assert (n_ch, T) == (1, N80) and f["movie"].dtype == np.float32 - assert f["activity"].shape == f["movie"].shape - for m in ("valid", "labeled", "footprint_support"): - assert f[f"mask/{m}"].shape == (R, C) - assert f[f"mask/{m}"].dtype == np.uint8 - assert f["mean_image"].shape == (1, R, C) - assert f["varfac"].shape == (R, C) - for k in ("discard", "valid_mean", "rec_neg_err"): - assert f[f"frame/{k}"].shape == (T,) - assert f["sources/peak_row"].shape == (CENTRES.shape[0],) - for k in ( - "label", - "path", - "trial", - "peakR", - "nSources", - "alignHz", - "channels", - "activityChannel", - "activityGain", - "kernel", - "exporter", - ): - assert k in f.attrs - assert int(f.attrs["trial"]) == q["trial"] - # the stem of the trial's registration files, as the summary - stem = f.attrs["registrationStem"] - assert stem == q["registrationStem"] - assert stem.endswith(f"T{q['trial']}DMD{q['path']}") - assert f["movie"].chunks == (1, 256, min(64, R), min(64, C)) - name = Path(q["file"]) - assert (name.parent.name, name.name) == ( - "Path1", - f"trial_{q['trial']:03d}.h5", - ) - - -def test_target_is_the_baseline(session: dict[str, Any], tmp_path: Path) -> None: - """With the movie's own kernel and cubic placement the noiseless target is the baseline. - - The target (movie - activity) is the baseline to 2% of the activity's - peak; QC says the activity matches the movie. - """ - s = _export(session, tmp_path, kernel="exporter", interp="cubic") - for q in s["trials"]: - with h5py.File(q["file"], "r") as f: - m, a = f["movie"][0], f["activity"][0] - sup = f["mask/footprint_support"][()].astype(bool) - res = (m - a - BASELINE)[:, sup] - assert np.nanmax(np.abs(res)) < 0.02 * a.max() - assert q["peakR"] > 0.99 and q["diskR"] > 0.99 - assert q["diskSlope"] == pytest.approx(1.0, abs=0.01) - assert q["peakSlope"] == pytest.approx(1.0, abs=0.02) - assert abs(q["eventResidualFraction"]) < 0.02 - assert q["blurShapeRatio"] == pytest.approx(1.0, abs=0.02) - assert q["targetOverBaselineSupport"] == pytest.approx(1.0, abs=1e-3) - - -def test_linear_placement_blurs_the_peaks(session: dict[str, Any], tmp_path: Path) -> None: - """Bilinear placement keeps the flux but lowers the peak pixels (the viewer's rendering). - - Cubic placement keeps both. - """ - lin = _export(session, tmp_path / "lin", kernel="exporter") - cub = _export(session, tmp_path / "cub", kernel="exporter", interp="cubic") - for a, b in zip(lin["trials"], cub["trials"]): - assert a["diskSlope"] == pytest.approx(b["diskSlope"], abs=0.02) - assert a["blurShapeRatio"] > b["blurShapeRatio"] - assert a["eventResidualFraction"] > b["eventResidualFraction"] - - -def test_exact_kernel_is_sharper(session: dict[str, Any], tmp_path: Path) -> None: - """The exact kernel keeps the activity's total and sharpens its peaks. - - The peaks are compared against the MATLAB exporter's kernel. - """ - e = _export(session, tmp_path / "e", kernel="exporter", interp="cubic") - x = _export(session, tmp_path / "x", kernel="exact", interp="cubic") - for qe, qx in zip(e["trials"], x["trials"]): - assert qx["kernelR"] == pytest.approx((54 / 134) ** 2) - assert np.isnan(qe["kernelR"]) or qe["kernelR"] == 0 - with ( - h5py.File(qe["file"], "r") as fe, - h5py.File(qx["file"], "r") as fx, - ): - ae, ax = fe["activity"][0], fx["activity"][0] - assert ax.sum() == pytest.approx(ae.sum(), rel=0.02) - assert ax.max() > ae.max() - - -def test_summary_and_skipped_trial(tmp_path: Path) -> None: - """export_summary.json holds every trial (NaN as null). - - A trial without an across-trial map is reported, not written. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - _export(syn, out) # a first export writes both trials - assert (out / "Path1" / "trial_002.h5").exists() - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - a = f["Path1/frame_info/trial_alignment_affine"][()] - a[..., 1] = np.nan # MATLAB orientation: trials last - f["Path1/frame_info/trial_alignment_affine"][...] = a - s = _export(syn, out) - by_trial = {q["trial"]: q for q in s["trials"]} - assert "error" not in by_trial[1] - assert "map" in by_trial[2]["error"] - assert "removed" in by_trial[2]["error"] # no stale file is left - assert not (out / "Path1" / "trial_002.h5").exists() - text = (out / "export_summary.json").read_text() - assert "NaN" not in text - j = json.loads(text) - assert len(j["trials"]) == N_TRIALS and j["options"]["kernel"] == "exact" - - -def test_default_export_reconciles_trial_files(tmp_path: Path) -> None: - """A default export removes earlier trial files it does not write and lists them. - - An export with chosen trials leaves other files alone. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - folder = out / "Path1" - folder.mkdir(parents=True) - for name in ("trial_009.h5", "trial_1000.h5", "notes.txt"): - (folder / name).write_bytes(b"old") - s = _export(syn, out, trials=(1,)) - assert "removed" not in s - assert (folder / "trial_009.h5").exists() - s = _export(syn, out) - assert s["removed"] == {"Path1": ["trial_009.h5", "trial_1000.h5"]} - assert sorted(f.name for f in folder.iterdir()) == [ - "notes.txt", - "trial_001.h5", - "trial_002.h5", - ] - j = json.loads((out / "export_summary.json").read_text()) - assert j["removed"] == s["removed"] - - -def test_repeated_selectors_export_once(tmp_path: Path) -> None: - """Repeated paths and trials give one job each. - - Two workers never write the same file. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", paths=(1, 1), trials=(2, 2, 1), workers=2) - assert [(q["path"], q["trial"]) for q in s["trials"]] == [(1, 1), (1, 2)] - assert all("error" not in q for q in s["trials"]) - - -@pytest.mark.parametrize( - "kw", - [ - {"trials": (0,)}, - {"trials": (-1,)}, - {"trials": (N_TRIALS + 1,)}, - {"paths": (2,)}, - ], -) -def test_selectors_outside_the_run_are_refused( - tmp_path: Path, kw: dict[str, tuple[int, ...]] -) -> None: - """Trials outside 1..the table's trials and paths the run does not have are refused. - - They are refused before any job starts; the CLI reports a usage error. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="trials|paths"): - _export(syn, tmp_path / "out", **kw) - assert not (tmp_path / "out" / "Path1").exists() - flag, values = next(iter(kw.items())) - with pytest.raises(SystemExit) as e: - main([ - "export-f0", - str(syn["run"]), - str(tmp_path / "o2"), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - f"--{flag}", - *[str(v) for v in values], - ]) - assert e.value.code == 2 - - -@pytest.fixture(scope="module") -def exported(tmp_path_factory: pytest.TempPathFactory) -> tuple[dict[str, Any], Path]: - """Export a synthetic session once (default options). - - Returns - ------- - syn : dict[str, Any] - The synthetic session. - out : Path - The folder the session was exported to. - """ - root = tmp_path_factory.mktemp("bad_options") - syn = write_session(root / "syn", "rigid", n80=200) - _export(syn, root / "out") - return syn, root / "out" - - -@pytest.mark.parametrize( - "kw, cli", - [ - ({"deflate": 10}, ["--deflate", "10"]), - ({"deflate": -1}, ["--deflate", "-1"]), - ({"blur": -1.0}, ["--blur", "-1"]), - ({"blur": float("nan")}, ["--blur", "nan"]), - ({"blur": float("inf")}, ["--blur", "inf"]), - ({"var_fac": "median"}, None), - ({"kernel": "box"}, None), - ({"interp": "nearest"}, None), - ], -) -def test_invalid_options_keep_earlier_files( - exported: tuple[dict[str, Any], Path], kw: dict[str, Any], cli: list[str] | None -) -> None: - """An option every trial would fail on is refused before any trial. - - So a rerun with it leaves the earlier export in place; the CLI reports a - usage error. - """ - syn, out = exported - files = sorted((out / "Path1").glob("trial_*.h5")) - assert len(files) == N_TRIALS - stamps = [f.stat().st_mtime_ns for f in files] - with pytest.raises(ValueError): - _export(syn, out, **kw) - assert [f.stat().st_mtime_ns for f in files] == stamps - if cli is None: # argparse's choices refuse these - return - with pytest.raises(SystemExit) as e: - main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - *cli, - ]) - assert e.value.code == 2 - assert [f.stat().st_mtime_ns for f in files] == stamps - - -def test_ignore_sources(tmp_path: Path) -> None: - """Without sources: zero activity, no sources group, no QC.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", ignore_sources=True) - for q in s["trials"]: - assert q["nSources"] == 0 and np.isnan(q["peakR"]) - with h5py.File(q["file"], "r") as f: - assert not f["activity"][()].any() - assert "sources" not in f - assert not f["mask/footprint_support"][()].any() - - -def test_cli(tmp_path: Path) -> None: - """Giant export-f0 writes the trials and returns 0.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - out = tmp_path / "out" - rc = main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--kernel", - "matched", - "--interp", - "cubic", - "--label", - "syn", - ]) - assert rc == 0 - with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: - assert f.attrs["label"] == "syn" and f.attrs["kernel"] == "matched" - - -def test_movmedian_omitnan() -> None: - """The running median ignores NaN and shrinks at the ends.""" - rng = np.random.default_rng(0) - x = rng.normal(size=(3, 300)) - x[0, 50:60] = np.nan - x[2, :] = np.nan - m = f0_qc.movmedian_omitnan(x, 81) - for i in range(2): - for t in (0, 10, 55, 150, 299): - w = x[i, max(0, t - 40) : t + 41] - assert m[i, t] == pytest.approx(np.median(w[~np.isnan(w)])) - assert np.isnan(m[2]).all() - - -def test_event_residual_and_peaks() -> None: - """The event-triggered residual is 0 when the activity is the movie's signal. - - It is 1 when no activity is removed. - """ - from scipy import sparse - - T = 400 - x = np.zeros((1, T)) - for e in (50, 150, 250, 350): - x[0, e : e + 20] += 10 * np.exp(-np.arange(20) / 4.0) - H = sparse.csr_matrix(np.array([[0.2], [0.5], [0.3]])) - Y = (np.asarray(H @ x).T + 5.0).astype(np.float64) - pk = f0_qc.peak_pixels(H) - assert pk.tolist() == [1] - frac, n = f0_qc.event_residual(H, x, Y, pk) - assert n > 0 and abs(frac) < 1e-9 - frac0, _ = f0_qc.event_residual(H, x, Y + np.asarray(H @ x).T, pk) - assert frac0 == pytest.approx(0.5) # half of the doubled movie left - sl, r = f0_qc.peak_fit(H, x, Y, pk) - assert sl[0] == pytest.approx(1.0) and r[0] == pytest.approx(1.0) - - -def _two_channels(syn: dict[str, Any]) -> None: - """Rewrite the synthetic movies with a second channel. - - The second channel is 2 x the first + 5, interleaved by frame; also set - numChannels 2. - """ - for mf in sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")): - with h5py.File(mf, "r+") as f: - a = f["mov"][()] # (pages, cols, rows) - del f["mov"] - st = np.empty((2 * a.shape[0],) + a.shape[1:], a.dtype) - st[0::2], st[1::2] = a, 2 * a + 5 - f["mov"] = st - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - f["params/numChannels"][...] = 2 - - -def test_written_channels_and_mean_image(tmp_path: Path) -> None: - """The mean image follows the written channels, as movie and activity do. - - The reader indexes all three alike. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - _two_channels(syn) - s = _export(syn, tmp_path / "c2", channels=(2,)) - with h5py.File(s["trials"][0]["file"], "r") as f: - m, mi = f["movie"][()], f["mean_image"][()] - valid = f["mask/valid"][()].astype(bool) - assert m.shape[0] == 1 and mi.shape[0] == 1 - np.testing.assert_allclose(mi[0][valid], np.nanmean(m[0], 0)[valid], rtol=1e-4) - assert int(f.attrs["activityChannel"]) == 1 - s = _export(syn, tmp_path / "c21", channels=(2, 1)) - with h5py.File(s["trials"][0]["file"], "r") as f: - mi = f["mean_image"][()] - np.testing.assert_allclose(mi[0], 2 * mi[1] + 5, rtol=1e-4) - - -def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path: Path) -> None: - """The mean image leaves out the discarded frames and is NaN outside the valid pixels. - - This is as slap2-f0 computes it at inference. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - alf = min(syn["moco"].glob("*_ALIGNMENTDATA.h5")) - with h5py.File(alf, "r+") as f: - rne = f["recNegErr"][()] - rne[100:110] = 1.0 # a motion spike: those frames are discarded - f["recNegErr"][...] = rne - stem = alf.name.replace("_ALIGNMENTDATA.h5", "") - mf = syn["moco"] / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" - with h5py.File(mf, "r+") as f: - key = next(iter(f.keys())) - a = f[key][()] # (frames, cols, rows), one channel - a[100:110] += 1000.0 # what a mean over every frame would show - col = a.shape[1] // 2 - a[:150, col, :] = np.nan # a column imaged in a quarter of the frames - f[key][...] = a - s = _export(syn, tmp_path / "out", trials=(1,)) - q = s["trials"][0] - assert "error" not in q - with h5py.File(q["file"], "r") as f: - disc = f["frame/discard"][()].astype(bool) - m, mi = f["movie"][0], f["mean_image"][0] - valid = f["mask/valid"][()].astype(bool) - c0 = int(np.ravel(f.attrs["cropOriginRC"])[1]) - assert disc[100:110].all() - np.testing.assert_allclose(mi[valid], np.nanmean(m, 0)[valid], rtol=1e-4) - assert np.nanmax(mi) < 500 # the bright discarded frames are not in it - assert not valid[:, col - c0].any() and np.isnan(mi[:, col - c0]).all() - - -def test_sources_without_traces_are_refused(tmp_path: Path) -> None: - """Sources without dF_denoised traces would give zero activity. - - The target would keep every event, so the trials are reported, not - written. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["Path1/sources/temporal/dF_denoised"] - s = _export(syn, tmp_path / "out") - for q in s["trials"]: - assert "dF_denoised" in q["error"] - assert not list((tmp_path / "out" / "Path1").glob("trial_*.h5")) - - -@pytest.mark.parametrize("channels", [(0,), (3,), (1, 2)]) -def test_channels_outside_the_movie_are_refused(tmp_path: Path, channels: tuple[int, ...]) -> None: - """Channels are one-based and within numChannels (1 here).""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="channels"): - _export(syn, tmp_path / "out", channels=channels) - with pytest.raises(SystemExit) as e: # the CLI reports it as a usage error - main([ - "export-f0", - str(syn["run"]), - str(tmp_path / "o2"), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--channels", - *[str(c) for c in channels], - ]) - assert e.value.code == 2 - - -# ------------------------------------------------- activity mask, events - - -def _noisy_traces(syn: dict[str, Any], sd: float = 2.0) -> None: - """Give the synthetic run noisy dF_ls (noise SD sd around dF_denoised). - - Also give it an events trace at the denoised trace's jumps. - """ - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - den = g["dF_denoised"][()] # (frames, channels, sources) - rng = np.random.default_rng(5) - g["dF_ls"][...] = den + rng.normal(0, sd, den.shape) - jump = np.diff(den, axis=0, prepend=den[:1]) - g["events"][...] = np.where(jump > 5, jump, 0.0) - - -def _plan_file( - syn: dict[str, Any], unused: tuple[tuple[float, float], ...] = ((8.0, 40.0),) -) -> None: - """Write a minimal SILo plan file for path 1. - - It holds the sources' seeds plus unused seeds without a source (as - giant silo keeps it in source_extraction/silo/plan). - """ - plan = syn["run"] / "source_extraction" / "silo" / "plan" / "path1.h5" - plan.parent.mkdir(parents=True, exist_ok=True) - rc = np.vstack([CENTRES, np.asarray(unused, float)]) - seeds = np.column_stack([np.ones(len(rc)), rc, np.ones(len(rc))]) - pix = np.floor(CENTRES + 0.5).astype(int) - with h5py.File(plan, "w") as f: - g = f.create_group("sources") - g["seeds"] = seeds - g["rows"] = pix[:, 0] - g["cols"] = pix[:, 1] - - -def test_temporal_mask_rule() -> None: - """A crossing masks its frames, the widening after it and the shared frames on both sides. - - Nothing else is masked. - """ - from giant_python.export.f0_mask import MaskRule, temporal_mask - - n200 = 500 - lines200 = np.arange(n200) * 54.0 - ds = np.arange(0, n200 * 54, 134.0) - den = np.zeros((n200, 2)) - den[200:210, 0] = 10.0 # above 2 x 1 for 10 frames - den[300:310, 1] = 1.5 # below the threshold - rule = MaskRule(k=2, margin_px=0, widen_tau=1, share_frames=6) - tm = temporal_mask(den, np.ones(2), lines200, np.zeros(n200, bool), ds, rule, 30) - assert not tm[1].any() - f = np.flatnonzero(tm[0]) - first = int(np.argmin(np.abs(ds - 200 * 54))) - 6 - last = int(np.argmin(np.abs(ds - (209 + 30) * 54))) + 6 - assert f.min() == first and f.max() == last and f.size == last - first + 1 - - -def test_mask_widening_uses_the_activity_channel_decay() -> None: - """The widening's decay constant is the activity channel's, not channel 2's tau2. - - The activity channel's is SILo's tau_full, else tau_s times the - frame rate. - """ - from types import SimpleNamespace - - from giant_python.export.f0_training import _mask_inputs - - class Run: - """A run with only the given params (as SiloRun.param reads them).""" - - def __init__(self, params: dict[str, object]) -> None: - """Keep the params.""" - self.params = params - - def param(self, name: str, default: object = None) -> object: - """Return a param, the default when missing or empty. - - Returns - ------- - object - The named param, or `default` if it is missing, None or an empty string. - """ - v = self.params.get(name, default) - return default if v is None or v == "" else v - - p = SimpleNamespace( - sources=SimpleNamespace(n=0, rejected_rc=np.zeros((0, 2)), unused_seeds=None) - ) - # tau_full overrides tau_s (6 frames, not 0.024 s x 200 Hz = 4.8) - both = { - "analyzeHz": 200.0, - "tau_s": 0.024, - "tau_full": 6.0, - "tau2_s": 0.15, - "tau2_samps": 30.0, - } - m = _mask_inputs(Run(both), p, {}, None) - assert m["tau200"] == 6.0 and m["tau_seconds"] == pytest.approx(0.03) - # tau_s in the run's frames; the recorded constant in seconds - no_full = {"analyzeHz": 100.0, "tau_s": 0.05, "tau2_s": 0.15} - m = _mask_inputs(Run(no_full), p, {}, None) - assert m["tau200"] == pytest.approx(5.0) - assert m["tau_seconds"] == pytest.approx(0.05) - m = _mask_inputs(Run({}), p, {}, None) - assert m["tau200"] == pytest.approx(4.8) - assert m["tau_seconds"] == pytest.approx(0.024) - - -def test_activity_mask_written(tmp_path: Path) -> None: - """mask/activity covers the sources' activity, never pixels far from a footprint. - - It also leaves quiet stretches; spots add to it; the rule and the masked - shares are recorded. - """ - from scipy import ndimage - - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - _plan_file(syn) - rule = MaskRule(k=2, margin_px=1, widen_tau=1, share_frames=6, spots="none") - s = _export(syn, tmp_path / "m", interp="cubic", activity_mask=rule) - s2 = _export( - syn, - tmp_path / "m2", - interp="cubic", - activity_mask=MaskRule(k=2, margin_px=1, spots="seeds"), - ) - for q, q2 in zip(s["trials"], s2["trials"]): - assert "error" not in q - assert 0 < q["activityMaskFractionSupport"] < 1 - assert q["activityMaskFraction"] < q["activityMaskFractionSupport"] - assert q2["activityMaskFraction"] >= q["activityMaskFraction"] - with h5py.File(q["file"], "r") as f: - am = f["mask/activity"][()].astype(bool) - a = f["activity"][0] - sup = f["mask/footprint_support"][()].astype(bool) - assert f["mask/activity"].dtype == np.uint8 - assert f.attrs["activityMaskK"] == 2.0 - assert f.attrs["activityMaskSpots"] == "none" - # SILo's tau_s default (24 ms) at 200 Hz: the activity channel's - assert f.attrs["activityMaskTauSeconds"] == pytest.approx(0.024) - with h5py.File(q2["file"], "r") as f: - assert f.attrs["activityMaskWidenTau"] == 2.0 # the default - assert am.shape == a.shape - big = a > 0.2 * a.max() - assert big.any() and am[big].all() # the events are masked - far = ~ndimage.binary_dilation(sup, iterations=3) - assert not am[:, far].any() # nothing beyond footprint + margin - act = a.reshape(a.shape[0], -1).max(1) > 0 - near = ndimage.binary_dilation(act, np.ones(41, bool)) - if (~near).any(): # quiet stretches stay in the loss - assert not am[~near][:, sup].any() - - -def test_mask_and_event_stats_off_by_default(tmp_path: Path) -> None: - """Without the options neither the mask nor the statistics file.""" - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out") - with h5py.File(s["trials"][0]["file"], "r") as f: - assert "mask/activity" not in f - assert not (tmp_path / "out" / "event_statistics.json").exists() - - -def test_event_statistics(tmp_path: Path) -> None: - """event_statistics.json: events are crossings of k noise SDs. - - SILo's small noise events in its events trace do not count; the file - also holds rate, sizes and the synchrony against chance. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - den = np.zeros(g["dF_denoised"].shape) # (frames, channels, sources) - T = den.shape[0] - kern = np.exp(-np.arange(40) / 4.8) - starts = np.arange(30, T - 60, 100) # well apart: one event each - for a in starts: - den[a : a + 40, 0, :] += 40.0 * kern[: min(40, T - a)][:, None] - rng = np.random.default_rng(3) - g["dF_denoised"][...] = den - g["dF_ls"][...] = den + rng.normal(0, 2.0, den.shape) - tiny = np.zeros_like(den) - tiny[::7] = 0.5 # SILo's small events: not activity - g["events"][...] = tiny - _export(syn, tmp_path / "out", event_stats=True) - j = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) - p = j["paths"][0] - assert p["path"] == 1 and len(p["sources"]) == CENTRES.shape[0] - assert p["thresholdSD"] == 6.0 - for src in p["sources"]: - assert src["noise"] == pytest.approx(2.0, rel=0.15) - assert src["events"] == starts.size - assert src["ratePerMin"] == pytest.approx(starts.size / p["keptMinutes"]) - assert src["sizeRaw"]["q50"] == pytest.approx(40.0) - assert src["sizeDff"]["q50"] == pytest.approx(40.0 / 50) - assert src["ratesPerMin"]["3"] == pytest.approx(src["ratePerMin"]) - sy = p["synchrony"] - assert 0 <= sy["observed"] <= 1 and 0 <= sy["expected"] <= 1 - - -@pytest.mark.parametrize( - "bad", - [{"k": 0}, {"margin_px": -1}, {"share_frames": 1.5}, {"spots": "all"}], -) -def test_invalid_mask_rule_refused(tmp_path: Path, bad: dict[str, Any]) -> None: - """An invalid mask rule is refused before any trial.""" - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - with pytest.raises(ValueError, match="mask"): - _export(syn, tmp_path / "out", activity_mask=MaskRule(**bad)) - - -def test_cli_mask_and_event_stats(tmp_path: Path) -> None: - """Giant export-f0 --activity-mask --event-stats writes both.""" - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - out = tmp_path / "out" - rc = main([ - "export-f0", - str(syn["run"]), - str(out), - "--table", - str(syn["run"] / "trial_table.h5"), - "--moco-dir", - str(syn["moco"]), - "--activity-mask", - "--mask-k", - "3", - "--mask-spots", - "none", - "--event-stats", - ]) - assert rc == 0 - with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: - assert "mask/activity" in f and f.attrs["activityMaskK"] == 3.0 - assert (out / "event_statistics.json").exists() - - -def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path: Path) -> None: - """The exact and matched kernels cannot match the movie when 200 Hz frames are wider. - - With 200 Hz frames wider than the movie's (dt200 > dt80) the trials are - reported, not written with interpolated (too smooth) activity; the - MATLAB exporter's kernel still exports. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - ds = f["Path1/frame_info/frame_line_idxs"] - ds[...] = ds[()] * 3 # 200 Hz frames every ~160 lines, dt80 134 - for kernel in ("exact", "matched"): - s = _export(syn, tmp_path / kernel, kernel=kernel) - for q in s["trials"]: - assert "wider than the movie's" in q["error"] - s = _export(syn, tmp_path / "exporter", kernel="exporter") - assert all("error" not in q for q in s["trials"]) - - -def _trial_frames(syn: dict[str, Any]) -> np.ndarray: - """SILo's 200 Hz frames per trial of the synthetic run. - - Returns - ------- - np.ndarray - Integer number of frames of each trial, from Path1/frame_info/trial_num_frames. - """ - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - return np.ravel(f["Path1/frame_info/trial_num_frames"][()]).astype(int) - - -def _set_traces(syn: dict[str, Any], den: np.ndarray, ls: np.ndarray | None = None) -> None: - """Replace dF_denoised (and dF_ls: den + noise SD 2 unless given).""" - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - g = f["Path1/sources/temporal"] - g["dF_denoised"][...] = den - if ls is None: - rng = np.random.default_rng(4) - ls = np.nan_to_num(den) + rng.normal(0, 2.0, den.shape) - g["dF_ls"][...] = ls - - -def test_event_statistics_per_trial_and_observed_time(tmp_path: Path) -> None: - """An event across a trial boundary counts once in each trial. - - A trial without traces adds no observation time. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - n1, n2 = _trial_frames(syn)[:2] - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = np.zeros(f["Path1/sources/temporal/dF_denoised"].shape) - den[n1 - 3 : n1 + 5, 0, :] = 40.0 # straddles the boundary - den[20:28, 0, :] = 40.0 # one more in trial 1 - den[n1:, 0, 1] = np.nan # source 1: trial 2 not extracted - _set_traces(syn, den) - _export(syn, tmp_path / "out", event_stats=True) - p = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) - s0, s1 = p["paths"][0]["sources"][:2] - assert s0["events"] == 3 # 2 in trial 1, 1 at the start of trial 2 - assert s1["events"] == 2 # trial 2 has no trace for it - assert s1["observedMinutes"] == pytest.approx(s0["observedMinutes"] * n1 / (n1 + n2), rel=0.02) - assert s1["ratePerMin"] == pytest.approx(2 / s1["observedMinutes"]) - - -def test_mask_refuses_active_sources_without_noise(tmp_path: Path) -> None: - """A source with activity but no dF_ls (no noise estimate) would stay unmasked. - - The trial is refused. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = f["Path1/sources/temporal/dF_denoised"][()] - ls = den + 0.0 - ls[:, 0, 0] = np.nan - _set_traces(syn, den, ls) - s = _export(syn, tmp_path / "out", activity_mask=MaskRule()) - for q in s["trials"]: - assert "no noise estimate" in q["error"] and "[0]" in q["error"] - - -def test_mask_fractions_count_finite_samples(tmp_path: Path) -> None: - """The masked shares count only finite samples of the activity channel. - - A valid pixel may miss some frames. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - mf = min(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")) - with h5py.File(mf, "r+") as f: - key = next(iter(f.keys())) - a = f[key][()] # (frames, cols, rows) - a[::5, :, :] = np.where( - np.random.default_rng(1).random(a[::5].shape) < 0.5, np.nan, a[::5] - ) # 10% of the samples missing: every pixel stays valid - f[key][...] = a - s = _export(syn, tmp_path / "out", trials=(1,), activity_mask=MaskRule(k=2)) - q = s["trials"][0] - with h5py.File(q["file"], "r") as f: - am = f["mask/activity"][()].astype(bool) - m = f["movie"][0] - valid = f["mask/valid"][()].astype(bool) - ok = np.isfinite(m) & valid[None] - assert valid.sum() > 0 and (~np.isfinite(m[:, valid])).any() - assert q["activityMaskFraction"] == pytest.approx(am[ok].mean()) - - -def test_event_statistics_unavailable_and_stale_file(tmp_path: Path) -> None: - """An active source without a noise estimate is reported as unavailable, not as zero events. - - A rerun without --event-stats removes the earlier statistics. - """ - syn = write_session(tmp_path / "syn", "rigid", n80=300) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r") as f: - den = f["Path1/sources/temporal/dF_denoised"][()] - ls = den + np.random.default_rng(2).normal(0, 2.0, den.shape) - ls[:, 0, 0] = np.nan - _set_traces(syn, den, ls) - out = tmp_path / "out" - _export(syn, out, event_stats=True) - j = json.loads((out / "event_statistics.json").read_text()) - s0, s1 = j["paths"][0]["sources"][:2] - assert s0["events"] is None and s0["ratePerMin"] is None - assert "no noise estimate" in s0["unavailable"] - assert s1["events"] > 0 and "unavailable" not in s1 - _export(syn, out) # statistics off: the earlier file is not this run's - assert not (out / "event_statistics.json").exists() - - -def test_mask_seeds_refused_without_a_map(tmp_path: Path) -> None: - """With --mask-spots seeds, a trial whose seeds cannot be placed is refused. - - Such a trial (no across-trial map) is refused rather than written - without them. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - a = f["Path1/frame_info/trial_alignment_affine"][()] - a[..., 1] = np.nan # trial 2 has no map - f["Path1/frame_info/trial_alignment_affine"][...] = a - _plan_file(syn) - s = _export( - syn, - tmp_path / "out", - ignore_sources=True, - activity_mask=MaskRule(spots="seeds"), - ) - by_trial = {q["trial"]: q for q in s["trials"]} - assert "error" not in by_trial[1] - assert "cannot be placed" in by_trial[2]["error"] - s = _export( - syn, - tmp_path / "none", - ignore_sources=True, - activity_mask=MaskRule(spots="none"), - ) - assert all("error" not in q for q in s["trials"]) - - -def test_mask_seeds_refused_without_a_plan_file(tmp_path: Path) -> None: - """Without SILo's plan file the unused seeds are unknown, not absent. - - --mask-spots seeds is refused; the default (no spots) exports. - """ - from giant_python.export.f0_mask import MaskRule - - syn = write_session(tmp_path / "syn", "rigid", n80=200) - s = _export(syn, tmp_path / "out", activity_mask=MaskRule(spots="seeds")) - for q in s["trials"]: - assert "plan file" in q["error"] - s = _export(syn, tmp_path / "none", activity_mask=MaskRule()) - assert all("error" not in q for q in s["trials"]) - - -def test_event_statistics_without_denoised_traces_or_f0(tmp_path: Path) -> None: - """Without dF_denoised the path is reported as unavailable. - - Without F0 the counts and raw sizes remain and dF/F is null. - """ - from giant_python.export.f0_events import path_statistics - from giant_python.viewer.run import SiloRun - - syn = write_session(tmp_path / "syn", "rigid", n80=300) - _noisy_traces(syn) - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["Path1/sources/temporal/F0"] - _export(syn, tmp_path / "a", event_stats=True) - j = json.loads((tmp_path / "a" / "event_statistics.json").read_text()) - src = j["paths"][0]["sources"][0] - assert src["events"] > 0 and src["sizeRaw"] is not None - assert src["sizeDff"] is None and src["f0Median"] is None - run = SiloRun(syn["run"]) - run.traces(1).pop("dF_denoised") - p = path_statistics(run, 1) - assert "dF_denoised" in p["unavailable"] and p["sources"] == [] - - -def test_synchrony_counts_only_observed_partners() -> None: - """A partner without a trace around an event neither coincides nor counts towards chance. - - With full traces chance follows the rates. - """ - from giant_python.export.f0_events import synchrony - - T = 1000 - a = np.array([100, 300, 500]) - b = np.array([101, 700]) - full = np.ones((2, T), bool) - r = synchrony([([a, b], full)], 2) - assert r["events"] == 5 and r["observed"] == pytest.approx(2 / 5) - gap = full.copy() - gap[1, :600] = False # b is not observed around a's events - b2 = b[1:] - r2 = synchrony([([a, b2], gap)], 2) - assert r2["events"] == 4 and r2["observed"] == 0.0 - # only b2's event has an observed partner (a, rate 3 x 5 / 1000) - assert r2["expected"] == pytest.approx((3 * 5 / 1000) / 4, rel=1e-6) +"""F0 training-data export (giant export-f0) on a synthetic SILo run.""" + +import json +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.export import f0_qc +from giant_python.export.f0_training import ExportOptions, export_run + +from ..viewer.synthetic import BASELINE, CENTRES, N_TRIALS, write_session + +N80 = 600 + + +@pytest.fixture(scope="module", params=["rigid", "patchwise"]) +def session( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> dict[str, Any]: + """Build a synthetic session (rigid or patchwise maps) of 600 frames. + + Returns + ------- + dict[str, Any] + The session written by write_session: its run, motion-correction and baseline + folders. + """ + root = tmp_path_factory.mktemp(f"syn_{request.param}") + return write_session(root, request.param, n80=N80) + + +def _export( + syn: dict[str, Any], + out: Path, + **kw: object, +) -> dict: + """Export the synthetic run with the given options. + + Returns + ------- + dict + The export summary from export_run, including the per-trial records (trials). + """ + return export_run( + syn["run"], + out, + syn["run"] / "trial_table.h5", + syn["moco"], + syn["base"], + options=ExportOptions(**kw), + log=lambda line: None, + ) + + +def test_layout_matches_the_training_reader(session: dict[str, Any], tmp_path: Path) -> None: + """Datasets, shapes, dtypes and attributes as slap2_f0.io.TrialFile reads them. + + The reader is not a dependency: its contract is checked here. + """ + s = _export(session, tmp_path, kernel="exporter") + assert [q["trial"] for q in s["trials"]] == [1, 2] + for q in s["trials"]: + assert "error" not in q + with h5py.File(q["file"], "r") as f: + n_ch, T, R, C = f["movie"].shape + assert (n_ch, T) == (1, N80) and f["movie"].dtype == np.float32 + assert f["activity"].shape == f["movie"].shape + for m in ("valid", "labeled", "footprint_support"): + assert f[f"mask/{m}"].shape == (R, C) + assert f[f"mask/{m}"].dtype == np.uint8 + assert f["mean_image"].shape == (1, R, C) + assert f["varfac"].shape == (R, C) + for k in ("discard", "valid_mean", "rec_neg_err"): + assert f[f"frame/{k}"].shape == (T,) + assert f["sources/peak_row"].shape == (CENTRES.shape[0],) + for k in ( + "label", + "path", + "trial", + "peakR", + "nSources", + "alignHz", + "channels", + "activityChannel", + "activityGain", + "kernel", + "exporter", + ): + assert k in f.attrs + assert int(f.attrs["trial"]) == q["trial"] + # the stem of the trial's registration files, as the summary + stem = f.attrs["registrationStem"] + assert stem == q["registrationStem"] + assert stem.endswith(f"T{q['trial']}DMD{q['path']}") + assert f["movie"].chunks == (1, 256, min(64, R), min(64, C)) + name = Path(q["file"]) + assert (name.parent.name, name.name) == ( + "Path1", + f"trial_{q['trial']:03d}.h5", + ) + + +def test_target_is_the_baseline(session: dict[str, Any], tmp_path: Path) -> None: + """With the movie's own kernel and cubic placement the noiseless target is the baseline. + + The target (movie - activity) is the baseline to 2% of the activity's + peak; QC says the activity matches the movie. + """ + s = _export(session, tmp_path, kernel="exporter", interp="cubic") + for q in s["trials"]: + with h5py.File(q["file"], "r") as f: + m, a = f["movie"][0], f["activity"][0] + sup = f["mask/footprint_support"][()].astype(bool) + res = (m - a - BASELINE)[:, sup] + assert np.nanmax(np.abs(res)) < 0.02 * a.max() + assert q["peakR"] > 0.99 and q["diskR"] > 0.99 + assert q["diskSlope"] == pytest.approx(1.0, abs=0.01) + assert q["peakSlope"] == pytest.approx(1.0, abs=0.02) + assert abs(q["eventResidualFraction"]) < 0.02 + assert q["blurShapeRatio"] == pytest.approx(1.0, abs=0.02) + assert q["targetOverBaselineSupport"] == pytest.approx(1.0, abs=1e-3) + + +def test_linear_placement_blurs_the_peaks(session: dict[str, Any], tmp_path: Path) -> None: + """Bilinear placement keeps the flux but lowers the peak pixels (the viewer's rendering). + + Cubic placement keeps both. + """ + lin = _export(session, tmp_path / "lin", kernel="exporter") + cub = _export(session, tmp_path / "cub", kernel="exporter", interp="cubic") + for a, b in zip(lin["trials"], cub["trials"]): + assert a["diskSlope"] == pytest.approx(b["diskSlope"], abs=0.02) + assert a["blurShapeRatio"] > b["blurShapeRatio"] + assert a["eventResidualFraction"] > b["eventResidualFraction"] + + +def test_exact_kernel_is_sharper(session: dict[str, Any], tmp_path: Path) -> None: + """The exact kernel keeps the activity's total and sharpens its peaks. + + The peaks are compared against the MATLAB exporter's kernel. + """ + e = _export(session, tmp_path / "e", kernel="exporter", interp="cubic") + x = _export(session, tmp_path / "x", kernel="exact", interp="cubic") + for qe, qx in zip(e["trials"], x["trials"]): + assert qx["kernelR"] == pytest.approx((54 / 134) ** 2) + assert np.isnan(qe["kernelR"]) or qe["kernelR"] == 0 + with ( + h5py.File(qe["file"], "r") as fe, + h5py.File(qx["file"], "r") as fx, + ): + ae, ax = fe["activity"][0], fx["activity"][0] + assert ax.sum() == pytest.approx(ae.sum(), rel=0.02) + assert ax.max() > ae.max() + + +def test_summary_and_skipped_trial(tmp_path: Path) -> None: + """export_summary.json holds every trial (NaN as null). + + A trial without an across-trial map is reported, not written. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + _export(syn, out) # a first export writes both trials + assert (out / "Path1" / "trial_002.h5").exists() + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + a = f["Path1/frame_info/trial_alignment_affine"][()] + a[..., 1] = np.nan # MATLAB orientation: trials last + f["Path1/frame_info/trial_alignment_affine"][...] = a + s = _export(syn, out) + by_trial = {q["trial"]: q for q in s["trials"]} + assert "error" not in by_trial[1] + assert "map" in by_trial[2]["error"] + assert "removed" in by_trial[2]["error"] # no stale file is left + assert not (out / "Path1" / "trial_002.h5").exists() + text = (out / "export_summary.json").read_text() + assert "NaN" not in text + j = json.loads(text) + assert len(j["trials"]) == N_TRIALS and j["options"]["kernel"] == "exact" + + +def test_default_export_reconciles_trial_files(tmp_path: Path) -> None: + """A default export removes earlier trial files it does not write and lists them. + + An export with chosen trials leaves other files alone. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + folder = out / "Path1" + folder.mkdir(parents=True) + for name in ("trial_009.h5", "trial_1000.h5", "notes.txt"): + (folder / name).write_bytes(b"old") + s = _export(syn, out, trials=(1,)) + assert "removed" not in s + assert (folder / "trial_009.h5").exists() + s = _export(syn, out) + assert s["removed"] == {"Path1": ["trial_009.h5", "trial_1000.h5"]} + assert sorted(f.name for f in folder.iterdir()) == [ + "notes.txt", + "trial_001.h5", + "trial_002.h5", + ] + j = json.loads((out / "export_summary.json").read_text()) + assert j["removed"] == s["removed"] + + +def test_repeated_selectors_export_once(tmp_path: Path) -> None: + """Repeated paths and trials give one job each. + + Two workers never write the same file. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", paths=(1, 1), trials=(2, 2, 1), workers=2) + assert [(q["path"], q["trial"]) for q in s["trials"]] == [(1, 1), (1, 2)] + assert all("error" not in q for q in s["trials"]) + + +@pytest.mark.parametrize( + "kw", + [ + {"trials": (0,)}, + {"trials": (-1,)}, + {"trials": (N_TRIALS + 1,)}, + {"paths": (2,)}, + ], +) +def test_selectors_outside_the_run_are_refused( + tmp_path: Path, kw: dict[str, tuple[int, ...]] +) -> None: + """Trials outside 1..the table's trials and paths the run does not have are refused. + + They are refused before any job starts; the CLI reports a usage error. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="trials|paths"): + _export(syn, tmp_path / "out", **kw) + assert not (tmp_path / "out" / "Path1").exists() + flag, values = next(iter(kw.items())) + with pytest.raises(SystemExit) as e: + main([ + "export-f0", + str(syn["run"]), + str(tmp_path / "o2"), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + f"--{flag}", + *[str(v) for v in values], + ]) + assert e.value.code == 2 + + +@pytest.fixture(scope="module") +def exported(tmp_path_factory: pytest.TempPathFactory) -> tuple[dict[str, Any], Path]: + """Export a synthetic session once (default options). + + Returns + ------- + syn : dict[str, Any] + The synthetic session. + out : Path + The folder the session was exported to. + """ + root = tmp_path_factory.mktemp("bad_options") + syn = write_session(root / "syn", "rigid", n80=200) + _export(syn, root / "out") + return syn, root / "out" + + +@pytest.mark.parametrize( + "kw, cli", + [ + ({"deflate": 10}, ["--deflate", "10"]), + ({"deflate": -1}, ["--deflate", "-1"]), + ({"blur": -1.0}, ["--blur", "-1"]), + ({"blur": float("nan")}, ["--blur", "nan"]), + ({"blur": float("inf")}, ["--blur", "inf"]), + ({"var_fac": "median"}, None), + ({"kernel": "box"}, None), + ({"interp": "nearest"}, None), + ], +) +def test_invalid_options_keep_earlier_files( + exported: tuple[dict[str, Any], Path], kw: dict[str, Any], cli: list[str] | None +) -> None: + """An option every trial would fail on is refused before any trial. + + So a rerun with it leaves the earlier export in place; the CLI reports a + usage error. + """ + syn, out = exported + files = sorted((out / "Path1").glob("trial_*.h5")) + assert len(files) == N_TRIALS + stamps = [f.stat().st_mtime_ns for f in files] + with pytest.raises(ValueError): + _export(syn, out, **kw) + assert [f.stat().st_mtime_ns for f in files] == stamps + if cli is None: # argparse's choices refuse these + return + with pytest.raises(SystemExit) as e: + main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + *cli, + ]) + assert e.value.code == 2 + assert [f.stat().st_mtime_ns for f in files] == stamps + + +def test_ignore_sources(tmp_path: Path) -> None: + """Without sources: zero activity, no sources group, no QC.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", ignore_sources=True) + for q in s["trials"]: + assert q["nSources"] == 0 and np.isnan(q["peakR"]) + with h5py.File(q["file"], "r") as f: + assert not f["activity"][()].any() + assert "sources" not in f + assert not f["mask/footprint_support"][()].any() + + +def test_cli(tmp_path: Path) -> None: + """Giant export-f0 writes the trials and returns 0.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + out = tmp_path / "out" + rc = main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--kernel", + "matched", + "--interp", + "cubic", + "--label", + "syn", + ]) + assert rc == 0 + with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: + assert f.attrs["label"] == "syn" and f.attrs["kernel"] == "matched" + + +def test_movmedian_omitnan() -> None: + """The running median ignores NaN and shrinks at the ends.""" + rng = np.random.default_rng(0) + x = rng.normal(size=(3, 300)) + x[0, 50:60] = np.nan + x[2, :] = np.nan + m = f0_qc.movmedian_omitnan(x, 81) + for i in range(2): + for t in (0, 10, 55, 150, 299): + w = x[i, max(0, t - 40) : t + 41] + assert m[i, t] == pytest.approx(np.median(w[~np.isnan(w)])) + assert np.isnan(m[2]).all() + + +def test_event_residual_and_peaks() -> None: + """The event-triggered residual is 0 when the activity is the movie's signal. + + It is 1 when no activity is removed. + """ + from scipy import sparse + + T = 400 + x = np.zeros((1, T)) + for e in (50, 150, 250, 350): + x[0, e : e + 20] += 10 * np.exp(-np.arange(20) / 4.0) + H = sparse.csr_matrix(np.array([[0.2], [0.5], [0.3]])) + Y = (np.asarray(H @ x).T + 5.0).astype(np.float64) + pk = f0_qc.peak_pixels(H) + assert pk.tolist() == [1] + frac, n = f0_qc.event_residual(H, x, Y, pk) + assert n > 0 and abs(frac) < 1e-9 + frac0, _ = f0_qc.event_residual(H, x, Y + np.asarray(H @ x).T, pk) + assert frac0 == pytest.approx(0.5) # half of the doubled movie left + sl, r = f0_qc.peak_fit(H, x, Y, pk) + assert sl[0] == pytest.approx(1.0) and r[0] == pytest.approx(1.0) + + +def _two_channels(syn: dict[str, Any]) -> None: + """Rewrite the synthetic movies with a second channel. + + The second channel is 2 x the first + 5, interleaved by frame; also set + numChannels 2. + """ + for mf in sorted(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")): + with h5py.File(mf, "r+") as f: + a = f["mov"][()] # (pages, cols, rows) + del f["mov"] + st = np.empty((2 * a.shape[0],) + a.shape[1:], a.dtype) + st[0::2], st[1::2] = a, 2 * a + 5 + f["mov"] = st + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + f["params/numChannels"][...] = 2 + + +def test_written_channels_and_mean_image(tmp_path: Path) -> None: + """The mean image follows the written channels, as movie and activity do. + + The reader indexes all three alike. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + _two_channels(syn) + s = _export(syn, tmp_path / "c2", channels=(2,)) + with h5py.File(s["trials"][0]["file"], "r") as f: + m, mi = f["movie"][()], f["mean_image"][()] + valid = f["mask/valid"][()].astype(bool) + assert m.shape[0] == 1 and mi.shape[0] == 1 + np.testing.assert_allclose(mi[0][valid], np.nanmean(m[0], 0)[valid], rtol=1e-4) + assert int(f.attrs["activityChannel"]) == 1 + s = _export(syn, tmp_path / "c21", channels=(2, 1)) + with h5py.File(s["trials"][0]["file"], "r") as f: + mi = f["mean_image"][()] + np.testing.assert_allclose(mi[0], 2 * mi[1] + 5, rtol=1e-4) + + +def test_mean_image_over_kept_frames_and_valid_pixels(tmp_path: Path) -> None: + """The mean image leaves out the discarded frames and is NaN outside the valid pixels. + + This is as slap2-f0 computes it at inference. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + alf = min(syn["moco"].glob("*_ALIGNMENTDATA.h5")) + with h5py.File(alf, "r+") as f: + rne = f["recNegErr"][()] + rne[100:110] = 1.0 # a motion spike: those frames are discarded + f["recNegErr"][...] = rne + stem = alf.name.replace("_ALIGNMENTDATA.h5", "") + mf = syn["moco"] / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5" + with h5py.File(mf, "r+") as f: + key = next(iter(f.keys())) + a = f[key][()] # (frames, cols, rows), one channel + a[100:110] += 1000.0 # what a mean over every frame would show + col = a.shape[1] // 2 + a[:150, col, :] = np.nan # a column imaged in a quarter of the frames + f[key][...] = a + s = _export(syn, tmp_path / "out", trials=(1,)) + q = s["trials"][0] + assert "error" not in q + with h5py.File(q["file"], "r") as f: + disc = f["frame/discard"][()].astype(bool) + m, mi = f["movie"][0], f["mean_image"][0] + valid = f["mask/valid"][()].astype(bool) + c0 = int(np.ravel(f.attrs["cropOriginRC"])[1]) + assert disc[100:110].all() + np.testing.assert_allclose(mi[valid], np.nanmean(m, 0)[valid], rtol=1e-4) + assert np.nanmax(mi) < 500 # the bright discarded frames are not in it + assert not valid[:, col - c0].any() and np.isnan(mi[:, col - c0]).all() + + +def test_sources_without_traces_are_refused(tmp_path: Path) -> None: + """Sources without dF_denoised traces would give zero activity. + + The target would keep every event, so the trials are reported, not + written. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["Path1/sources/temporal/dF_denoised"] + s = _export(syn, tmp_path / "out") + for q in s["trials"]: + assert "dF_denoised" in q["error"] + assert not list((tmp_path / "out" / "Path1").glob("trial_*.h5")) + + +@pytest.mark.parametrize("channels", [(0,), (3,), (1, 2)]) +def test_channels_outside_the_movie_are_refused(tmp_path: Path, channels: tuple[int, ...]) -> None: + """Channels are one-based and within numChannels (1 here).""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="channels"): + _export(syn, tmp_path / "out", channels=channels) + with pytest.raises(SystemExit) as e: # the CLI reports it as a usage error + main([ + "export-f0", + str(syn["run"]), + str(tmp_path / "o2"), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--channels", + *[str(c) for c in channels], + ]) + assert e.value.code == 2 + + +# ------------------------------------------------- activity mask, events + + +def _noisy_traces(syn: dict[str, Any], sd: float = 2.0) -> None: + """Give the synthetic run noisy dF_ls (noise SD sd around dF_denoised). + + Also give it an events trace at the denoised trace's jumps. + """ + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + den = g["dF_denoised"][()] # (frames, channels, sources) + rng = np.random.default_rng(5) + g["dF_ls"][...] = den + rng.normal(0, sd, den.shape) + jump = np.diff(den, axis=0, prepend=den[:1]) + g["events"][...] = np.where(jump > 5, jump, 0.0) + + +def _plan_file( + syn: dict[str, Any], unused: tuple[tuple[float, float], ...] = ((8.0, 40.0),) +) -> None: + """Write a minimal SILo plan file for path 1. + + It holds the sources' seeds plus unused seeds without a source (as + giant silo keeps it in source_extraction/silo/plan). + """ + plan = syn["run"] / "source_extraction" / "silo" / "plan" / "path1.h5" + plan.parent.mkdir(parents=True, exist_ok=True) + rc = np.vstack([CENTRES, np.asarray(unused, float)]) + seeds = np.column_stack([np.ones(len(rc)), rc, np.ones(len(rc))]) + pix = np.floor(CENTRES + 0.5).astype(int) + with h5py.File(plan, "w") as f: + g = f.create_group("sources") + g["seeds"] = seeds + g["rows"] = pix[:, 0] + g["cols"] = pix[:, 1] + + +def test_temporal_mask_rule() -> None: + """A crossing masks its frames, the widening after it and the shared frames on both sides. + + Nothing else is masked. + """ + from giant_python.export.f0_mask import MaskRule, temporal_mask + + n200 = 500 + lines200 = np.arange(n200) * 54.0 + ds = np.arange(0, n200 * 54, 134.0) + den = np.zeros((n200, 2)) + den[200:210, 0] = 10.0 # above 2 x 1 for 10 frames + den[300:310, 1] = 1.5 # below the threshold + rule = MaskRule(k=2, margin_px=0, widen_tau=1, share_frames=6) + tm = temporal_mask(den, np.ones(2), lines200, np.zeros(n200, bool), ds, rule, 30) + assert not tm[1].any() + f = np.flatnonzero(tm[0]) + first = int(np.argmin(np.abs(ds - 200 * 54))) - 6 + last = int(np.argmin(np.abs(ds - (209 + 30) * 54))) + 6 + assert f.min() == first and f.max() == last and f.size == last - first + 1 + + +def test_mask_widening_uses_the_activity_channel_decay() -> None: + """The widening's decay constant is the activity channel's, not channel 2's tau2. + + The activity channel's is SILo's tau_full, else tau_s times the + frame rate. + """ + from types import SimpleNamespace + + from giant_python.export.f0_training import _mask_inputs + + class Run: + """A run with only the given params (as SiloRun.param reads them).""" + + def __init__(self, params: dict[str, object]) -> None: + """Keep the params.""" + self.params = params + + def param(self, name: str, default: object = None) -> object: + """Return a param, the default when missing or empty. + + Returns + ------- + object + The named param, or `default` if it is missing, None or an empty string. + """ + v = self.params.get(name, default) + return default if v is None or v == "" else v + + p = SimpleNamespace( + sources=SimpleNamespace(n=0, rejected_rc=np.zeros((0, 2)), unused_seeds=None) + ) + # tau_full overrides tau_s (6 frames, not 0.024 s x 200 Hz = 4.8) + both = { + "analyzeHz": 200.0, + "tau_s": 0.024, + "tau_full": 6.0, + "tau2_s": 0.15, + "tau2_samps": 30.0, + } + m = _mask_inputs(Run(both), p, {}, None) + assert m["tau200"] == 6.0 and m["tau_seconds"] == pytest.approx(0.03) + # tau_s in the run's frames; the recorded constant in seconds + no_full = {"analyzeHz": 100.0, "tau_s": 0.05, "tau2_s": 0.15} + m = _mask_inputs(Run(no_full), p, {}, None) + assert m["tau200"] == pytest.approx(5.0) + assert m["tau_seconds"] == pytest.approx(0.05) + m = _mask_inputs(Run({}), p, {}, None) + assert m["tau200"] == pytest.approx(4.8) + assert m["tau_seconds"] == pytest.approx(0.024) + + +def test_activity_mask_written(tmp_path: Path) -> None: + """mask/activity covers the sources' activity, never pixels far from a footprint. + + It also leaves quiet stretches; spots add to it; the rule and the masked + shares are recorded. + """ + from scipy import ndimage + + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + _plan_file(syn) + rule = MaskRule(k=2, margin_px=1, widen_tau=1, share_frames=6, spots="none") + s = _export(syn, tmp_path / "m", interp="cubic", activity_mask=rule) + s2 = _export( + syn, + tmp_path / "m2", + interp="cubic", + activity_mask=MaskRule(k=2, margin_px=1, spots="seeds"), + ) + for q, q2 in zip(s["trials"], s2["trials"]): + assert "error" not in q + assert 0 < q["activityMaskFractionSupport"] < 1 + assert q["activityMaskFraction"] < q["activityMaskFractionSupport"] + assert q2["activityMaskFraction"] >= q["activityMaskFraction"] + with h5py.File(q["file"], "r") as f: + am = f["mask/activity"][()].astype(bool) + a = f["activity"][0] + sup = f["mask/footprint_support"][()].astype(bool) + assert f["mask/activity"].dtype == np.uint8 + assert f.attrs["activityMaskK"] == 2.0 + assert f.attrs["activityMaskSpots"] == "none" + # SILo's tau_s default (24 ms) at 200 Hz: the activity channel's + assert f.attrs["activityMaskTauSeconds"] == pytest.approx(0.024) + with h5py.File(q2["file"], "r") as f: + assert f.attrs["activityMaskWidenTau"] == 2.0 # the default + assert am.shape == a.shape + big = a > 0.2 * a.max() + assert big.any() and am[big].all() # the events are masked + far = ~ndimage.binary_dilation(sup, iterations=3) + assert not am[:, far].any() # nothing beyond footprint + margin + act = a.reshape(a.shape[0], -1).max(1) > 0 + near = ndimage.binary_dilation(act, np.ones(41, bool)) + if (~near).any(): # quiet stretches stay in the loss + assert not am[~near][:, sup].any() + + +def test_mask_and_event_stats_off_by_default(tmp_path: Path) -> None: + """Without the options neither the mask nor the statistics file.""" + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out") + with h5py.File(s["trials"][0]["file"], "r") as f: + assert "mask/activity" not in f + assert not (tmp_path / "out" / "event_statistics.json").exists() + + +def test_event_statistics(tmp_path: Path) -> None: + """event_statistics.json: events are crossings of k noise SDs. + + SILo's small noise events in its events trace do not count; the file + also holds rate, sizes and the synchrony against chance. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + den = np.zeros(g["dF_denoised"].shape) # (frames, channels, sources) + T = den.shape[0] + kern = np.exp(-np.arange(40) / 4.8) + starts = np.arange(30, T - 60, 100) # well apart: one event each + for a in starts: + den[a : a + 40, 0, :] += 40.0 * kern[: min(40, T - a)][:, None] + rng = np.random.default_rng(3) + g["dF_denoised"][...] = den + g["dF_ls"][...] = den + rng.normal(0, 2.0, den.shape) + tiny = np.zeros_like(den) + tiny[::7] = 0.5 # SILo's small events: not activity + g["events"][...] = tiny + _export(syn, tmp_path / "out", event_stats=True) + j = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) + p = j["paths"][0] + assert p["path"] == 1 and len(p["sources"]) == CENTRES.shape[0] + assert p["thresholdSD"] == 6.0 + for src in p["sources"]: + assert src["noise"] == pytest.approx(2.0, rel=0.15) + assert src["events"] == starts.size + assert src["ratePerMin"] == pytest.approx(starts.size / p["keptMinutes"]) + assert src["sizeRaw"]["q50"] == pytest.approx(40.0) + assert src["sizeDff"]["q50"] == pytest.approx(40.0 / 50) + assert src["ratesPerMin"]["3"] == pytest.approx(src["ratePerMin"]) + sy = p["synchrony"] + assert 0 <= sy["observed"] <= 1 and 0 <= sy["expected"] <= 1 + + +@pytest.mark.parametrize( + "bad", + [{"k": 0}, {"margin_px": -1}, {"share_frames": 1.5}, {"spots": "all"}], +) +def test_invalid_mask_rule_refused(tmp_path: Path, bad: dict[str, Any]) -> None: + """An invalid mask rule is refused before any trial.""" + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + with pytest.raises(ValueError, match="mask"): + _export(syn, tmp_path / "out", activity_mask=MaskRule(**bad)) + + +def test_cli_mask_and_event_stats(tmp_path: Path) -> None: + """Giant export-f0 --activity-mask --event-stats writes both.""" + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + out = tmp_path / "out" + rc = main([ + "export-f0", + str(syn["run"]), + str(out), + "--table", + str(syn["run"] / "trial_table.h5"), + "--moco-dir", + str(syn["moco"]), + "--activity-mask", + "--mask-k", + "3", + "--mask-spots", + "none", + "--event-stats", + ]) + assert rc == 0 + with h5py.File(out / "Path1" / "trial_001.h5", "r") as f: + assert "mask/activity" in f and f.attrs["activityMaskK"] == 3.0 + assert (out / "event_statistics.json").exists() + + +def test_exact_kernel_refused_when_200hz_frames_are_wider(tmp_path: Path) -> None: + """The exact and matched kernels cannot match the movie when 200 Hz frames are wider. + + With 200 Hz frames wider than the movie's (dt200 > dt80) the trials are + reported, not written with interpolated (too smooth) activity; the + MATLAB exporter's kernel still exports. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + ds = f["Path1/frame_info/frame_line_idxs"] + ds[...] = ds[()] * 3 # 200 Hz frames every ~160 lines, dt80 134 + for kernel in ("exact", "matched"): + s = _export(syn, tmp_path / kernel, kernel=kernel) + for q in s["trials"]: + assert "wider than the movie's" in q["error"] + s = _export(syn, tmp_path / "exporter", kernel="exporter") + assert all("error" not in q for q in s["trials"]) + + +def _trial_frames(syn: dict[str, Any]) -> np.ndarray: + """SILo's 200 Hz frames per trial of the synthetic run. + + Returns + ------- + np.ndarray + Integer number of frames of each trial, from Path1/frame_info/trial_num_frames. + """ + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + return np.ravel(f["Path1/frame_info/trial_num_frames"][()]).astype(int) + + +def _set_traces(syn: dict[str, Any], den: np.ndarray, ls: np.ndarray | None = None) -> None: + """Replace dF_denoised (and dF_ls: den + noise SD 2 unless given).""" + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + g = f["Path1/sources/temporal"] + g["dF_denoised"][...] = den + if ls is None: + rng = np.random.default_rng(4) + ls = np.nan_to_num(den) + rng.normal(0, 2.0, den.shape) + g["dF_ls"][...] = ls + + +def test_event_statistics_per_trial_and_observed_time(tmp_path: Path) -> None: + """An event across a trial boundary counts once in each trial. + + A trial without traces adds no observation time. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + n1, n2 = _trial_frames(syn)[:2] + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = np.zeros(f["Path1/sources/temporal/dF_denoised"].shape) + den[n1 - 3 : n1 + 5, 0, :] = 40.0 # straddles the boundary + den[20:28, 0, :] = 40.0 # one more in trial 1 + den[n1:, 0, 1] = np.nan # source 1: trial 2 not extracted + _set_traces(syn, den) + _export(syn, tmp_path / "out", event_stats=True) + p = json.loads((tmp_path / "out" / "event_statistics.json").read_text()) + s0, s1 = p["paths"][0]["sources"][:2] + assert s0["events"] == 3 # 2 in trial 1, 1 at the start of trial 2 + assert s1["events"] == 2 # trial 2 has no trace for it + assert s1["observedMinutes"] == pytest.approx(s0["observedMinutes"] * n1 / (n1 + n2), rel=0.02) + assert s1["ratePerMin"] == pytest.approx(2 / s1["observedMinutes"]) + + +def test_mask_refuses_active_sources_without_noise(tmp_path: Path) -> None: + """A source with activity but no dF_ls (no noise estimate) would stay unmasked. + + The trial is refused. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = f["Path1/sources/temporal/dF_denoised"][()] + ls = den + 0.0 + ls[:, 0, 0] = np.nan + _set_traces(syn, den, ls) + s = _export(syn, tmp_path / "out", activity_mask=MaskRule()) + for q in s["trials"]: + assert "no noise estimate" in q["error"] and "[0]" in q["error"] + + +def test_mask_fractions_count_finite_samples(tmp_path: Path) -> None: + """The masked shares count only finite samples of the activity channel. + + A valid pixel may miss some frames. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + mf = min(syn["moco"].glob("*_REGISTERED_DOWNSAMPLED-80Hz.h5")) + with h5py.File(mf, "r+") as f: + key = next(iter(f.keys())) + a = f[key][()] # (frames, cols, rows) + a[::5, :, :] = np.where( + np.random.default_rng(1).random(a[::5].shape) < 0.5, np.nan, a[::5] + ) # 10% of the samples missing: every pixel stays valid + f[key][...] = a + s = _export(syn, tmp_path / "out", trials=(1,), activity_mask=MaskRule(k=2)) + q = s["trials"][0] + with h5py.File(q["file"], "r") as f: + am = f["mask/activity"][()].astype(bool) + m = f["movie"][0] + valid = f["mask/valid"][()].astype(bool) + ok = np.isfinite(m) & valid[None] + assert valid.sum() > 0 and (~np.isfinite(m[:, valid])).any() + assert q["activityMaskFraction"] == pytest.approx(am[ok].mean()) + + +def test_event_statistics_unavailable_and_stale_file(tmp_path: Path) -> None: + """An active source without a noise estimate is reported as unavailable, not as zero events. + + A rerun without --event-stats removes the earlier statistics. + """ + syn = write_session(tmp_path / "syn", "rigid", n80=300) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r") as f: + den = f["Path1/sources/temporal/dF_denoised"][()] + ls = den + np.random.default_rng(2).normal(0, 2.0, den.shape) + ls[:, 0, 0] = np.nan + _set_traces(syn, den, ls) + out = tmp_path / "out" + _export(syn, out, event_stats=True) + j = json.loads((out / "event_statistics.json").read_text()) + s0, s1 = j["paths"][0]["sources"][:2] + assert s0["events"] is None and s0["ratePerMin"] is None + assert "no noise estimate" in s0["unavailable"] + assert s1["events"] > 0 and "unavailable" not in s1 + _export(syn, out) # statistics off: the earlier file is not this run's + assert not (out / "event_statistics.json").exists() + + +def test_mask_seeds_refused_without_a_map(tmp_path: Path) -> None: + """With --mask-spots seeds, a trial whose seeds cannot be placed is refused. + + Such a trial (no across-trial map) is refused rather than written + without them. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + a = f["Path1/frame_info/trial_alignment_affine"][()] + a[..., 1] = np.nan # trial 2 has no map + f["Path1/frame_info/trial_alignment_affine"][...] = a + _plan_file(syn) + s = _export( + syn, + tmp_path / "out", + ignore_sources=True, + activity_mask=MaskRule(spots="seeds"), + ) + by_trial = {q["trial"]: q for q in s["trials"]} + assert "error" not in by_trial[1] + assert "cannot be placed" in by_trial[2]["error"] + s = _export( + syn, + tmp_path / "none", + ignore_sources=True, + activity_mask=MaskRule(spots="none"), + ) + assert all("error" not in q for q in s["trials"]) + + +def test_mask_seeds_refused_without_a_plan_file(tmp_path: Path) -> None: + """Without SILo's plan file the unused seeds are unknown, not absent. + + --mask-spots seeds is refused; the default (no spots) exports. + """ + from giant_python.export.f0_mask import MaskRule + + syn = write_session(tmp_path / "syn", "rigid", n80=200) + s = _export(syn, tmp_path / "out", activity_mask=MaskRule(spots="seeds")) + for q in s["trials"]: + assert "plan file" in q["error"] + s = _export(syn, tmp_path / "none", activity_mask=MaskRule()) + assert all("error" not in q for q in s["trials"]) + + +def test_event_statistics_without_denoised_traces_or_f0(tmp_path: Path) -> None: + """Without dF_denoised the path is reported as unavailable. + + Without F0 the counts and raw sizes remain and dF/F is null. + """ + from giant_python.export.f0_events import path_statistics + from giant_python.viewer.run import SiloRun + + syn = write_session(tmp_path / "syn", "rigid", n80=300) + _noisy_traces(syn) + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["Path1/sources/temporal/F0"] + _export(syn, tmp_path / "a", event_stats=True) + j = json.loads((tmp_path / "a" / "event_statistics.json").read_text()) + src = j["paths"][0]["sources"][0] + assert src["events"] > 0 and src["sizeRaw"] is not None + assert src["sizeDff"] is None and src["f0Median"] is None + run = SiloRun(syn["run"]) + run.traces(1).pop("dF_denoised") + p = path_statistics(run, 1) + assert "dF_denoised" in p["unavailable"] and p["sources"] == [] + + +def test_synchrony_counts_only_observed_partners() -> None: + """A partner without a trace around an event neither coincides nor counts towards chance. + + With full traces chance follows the rates. + """ + from giant_python.export.f0_events import synchrony + + T = 1000 + a = np.array([100, 300, 500]) + b = np.array([101, 700]) + full = np.ones((2, T), bool) + r = synchrony([([a, b], full)], 2) + assert r["events"] == 5 and r["observed"] == pytest.approx(2 / 5) + gap = full.copy() + gap[1, :600] = False # b is not observed around a's events + b2 = b[1:] + r2 = synchrony([([a, b2], gap)], 2) + assert r2["events"] == 4 and r2["observed"] == 0.0 + # only b2's event has an observed partner (a, rate 3 x 5 / 1000) + assert r2["expected"] == pytest.approx((3 * 5 / 1000) / 4, rel=1e-6) diff --git a/tests/raster/__init__.py b/tests/raster/__init__.py index 548691c0..a7413461 100644 --- a/tests/raster/__init__.py +++ b/tests/raster/__init__.py @@ -1 +1 @@ -"""Tests of raster (multi-ROI) source extraction.""" +"""Tests of raster (multi-ROI) source extraction.""" diff --git a/tests/raster/alignment_synthetic.py b/tests/raster/alignment_synthetic.py index b9efd179..e132a41a 100644 --- a/tests/raster/alignment_synthetic.py +++ b/tests/raster/alignment_synthetic.py @@ -1,180 +1,180 @@ -"""Synthetic trials for the across-trial alignment tests. - -A port of the scenario of GIAnT-MATLAB's TestTrialAlignment.m, with numpy's -random numbers: a labeled neuron (dendrites with spines, an unscanned band and a -hole) seen through known affine maps and, optionally, smooth bends, with -shot-like noise in two halves per trial. -""" - -from __future__ import annotations - -from collections.abc import Callable - -import numpy as np -from scipy import ndimage - -from giant_python.extraction.raster.alignment import interp2_cubic - -SIZE = (180, 260) -N_TRIALS = 6 - - -def neuron(rng: np.random.Generator, size: tuple[int, int] = SIZE) -> tuple[np.ndarray, np.ndarray]: - """Mean image of a labeled neuron and its scanned pixels (NaN outside them). - - Returns - ------- - truth : np.ndarray - The neuron's mean image, NaN outside the scanned pixels. - scan : np.ndarray - Boolean mask of the scanned pixels. - """ - h, w = size - rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) - truth = np.full(size, 5.0) - for _ in range(6): - t = np.linspace(0, 1, 400)[:, None] - p0 = rng.random(2) * np.array(size) - ang = rng.random() * np.pi - length = 150 + 100 * rng.random() - along = np.array([np.sin(ang), np.cos(ang)]) - across = np.array([np.cos(ang), -np.sin(ang)]) - wiggle = 8 * np.sin(2 * np.pi * (t * (1 + rng.random()) + rng.random())) - path = p0 + t * length * along + wiggle * across - for q in range(0, path.shape[0], 20): - truth += 30 * np.exp(-((rr - path[q, 0]) ** 2 + (cc - path[q, 1]) ** 2) / (2 * 1.5**2)) - sp = path[q] + (3 + 2 * rng.random()) * across * np.sign(rng.standard_normal()) - truth += (40 + 80 * rng.random()) * np.exp( - -((rr - sp[0]) ** 2 + (cc - sp[1]) ** 2) / (2 * 1.1**2) - ) - scan = np.ones(size, bool) - scan[:, :12] = False - scan[79:100, 119:150] = False - truth[~scan] = np.nan - return truth, scan - - -def trials( - truth: np.ndarray, - scan: np.ndarray, - bends: bool, - rng: np.random.Generator, - n_trials: int = N_TRIALS, - bend_px: float = 0.25, - affine_sd: float = 0.003, -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Trial mean images, their halves, the true fields and the rigid starting maps. - - Mean images (trials, rows, cols), halves (trials, 2, rows, cols), - true fields (trials, 2, rows, cols) (consensus pixel x is at - x + U(x) in the trial) and rigid starting maps (trials, 2, 3). - - Returns - ------- - m : np.ndarray - Trial mean images (trials, rows, cols). - mh : np.ndarray - Each trial's two halves (trials, 2, rows, cols). - u : np.ndarray - The true fields (trials, 2, rows, cols). - a0 : np.ndarray - The rigid starting maps (trials, 2, 3). - """ - h, w = truth.shape - rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) - filled = np.where(np.isnan(truth), 5.0, truth) - m = np.full((n_trials, h, w), np.nan) - mh = np.full((n_trials, 2, h, w), np.nan) - u = np.zeros((n_trials, 2, h, w)) - a0 = np.zeros((n_trials, 2, 3)) - for t in range(n_trials): - lin = np.eye(2) + affine_sd * rng.standard_normal((2, 2)) - tr = 0.6 * rng.standard_normal(2) - u_r = (lin[0, 0] - 1) * rr + lin[0, 1] * cc + tr[0] - u_c = lin[1, 0] * rr + (lin[1, 1] - 1) * cc + tr[1] - if bends: - for comp in (0, 1): - b = ndimage.gaussian_filter( - rng.standard_normal((h, w)), 40, mode="nearest", truncate=5 - ) - b = bend_px * b / b.std() - if comp == 0: - u_r = u_r + b - else: - u_c = u_c + b - u[t, 0], u[t, 1] = u_r, u_c - # the consensus point each trial pixel shows: y = x - U(y) - y_r, y_c = rr.ravel().copy(), cc.ravel().copy() - for _ in range(8): - coords = np.vstack([y_r, y_c]) - ur = ndimage.map_coordinates(u_r, coords, order=1, mode="nearest") - uc = ndimage.map_coordinates(u_c, coords, order=1, mode="nearest") - y_r, y_c = rr.ravel() - ur, cc.ravel() - uc - img = interp2_cubic(filled, y_r, y_c) - img = np.where(np.isnan(img), 5.0, img).reshape(h, w) - for half in range(2): - x = img + 0.2 * np.sqrt(np.maximum(img, 0)) * rng.standard_normal((h, w)) - x[~scan] = np.nan # the scan mask is fixed in the trial's frame - mh[t, half] = x - m[t] = mh[t].mean(axis=0) - c0 = (h // 2 - 1, w // 2 - 1) # MATLAB's round(sz/2), zero-based - a0[t] = [[1, 0, np.round(u_r[c0])], [0, 1, np.round(u_c[c0])]] - return m, mh, u, a0 - - -def field_error( - coords: Callable[[int, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]], - u: np.ndarray, - a0: np.ndarray, - truth: np.ndarray, - scan: np.ndarray, -) -> tuple[float, float]: - """RMS error of fitted maps relative to the trials' mean map. - - Weighted by image structure; and the same for the rigid start. - coords(t, r, c) gives the fitted positions. - - Returns - ------- - fitted : float - Structure-weighted RMS error of the fitted maps. - rigid : float - The same for the rigid start. - """ - n_trials = u.shape[0] - sel = ndimage.binary_erosion(scan, np.ones((5, 5)), border_value=0) - rows, cols = np.nonzero(sel) - est = np.empty((n_trials, rows.size, 2)) - tru = np.empty_like(est) - rig = np.empty_like(est) - for t in range(n_trials): - r_t, c_t = coords(t, rows.astype(float), cols.astype(float)) - est[t] = np.column_stack([r_t - rows, c_t - cols]) - tru[t] = np.column_stack([u[t, 0][sel], u[t, 1][sel]]) - rig[t] = a0[t, :, 2] - sq = np.sqrt(np.fmax(truth, 0)) - g_r, g_c = np.gradient(sq, axis=0), np.gradient(sq, axis=1) - wgt = g_r[sel] ** 2 + g_c[sel] ** 2 - wgt[np.isnan(wgt)] = 0 - - def rel(x: np.ndarray) -> np.ndarray: - """Relative to the trials' mean. - - Returns - ------- - np.ndarray - x minus its mean over trials. - """ - return x - x.mean(axis=0) - - def wrms(e: np.ndarray) -> float: - """Structure-weighted RMS over trials and pixels. - - Returns - ------- - float - The RMS of e, weighted by image structure. - """ - return np.sqrt(np.sum((e**2).sum(axis=2).mean(axis=0) * wgt) / wgt.sum()) - - return wrms(rel(est) - rel(tru)), wrms(rel(rig) - rel(tru)) +"""Synthetic trials for the across-trial alignment tests. + +A port of the scenario of GIAnT-MATLAB's TestTrialAlignment.m, with numpy's +random numbers: a labeled neuron (dendrites with spines, an unscanned band and a +hole) seen through known affine maps and, optionally, smooth bends, with +shot-like noise in two halves per trial. +""" + +from __future__ import annotations + +from collections.abc import Callable + +import numpy as np +from scipy import ndimage + +from giant_python.extraction.raster.alignment import interp2_cubic + +SIZE = (180, 260) +N_TRIALS = 6 + + +def neuron(rng: np.random.Generator, size: tuple[int, int] = SIZE) -> tuple[np.ndarray, np.ndarray]: + """Mean image of a labeled neuron and its scanned pixels (NaN outside them). + + Returns + ------- + truth : np.ndarray + The neuron's mean image, NaN outside the scanned pixels. + scan : np.ndarray + Boolean mask of the scanned pixels. + """ + h, w = size + rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) + truth = np.full(size, 5.0) + for _ in range(6): + t = np.linspace(0, 1, 400)[:, None] + p0 = rng.random(2) * np.array(size) + ang = rng.random() * np.pi + length = 150 + 100 * rng.random() + along = np.array([np.sin(ang), np.cos(ang)]) + across = np.array([np.cos(ang), -np.sin(ang)]) + wiggle = 8 * np.sin(2 * np.pi * (t * (1 + rng.random()) + rng.random())) + path = p0 + t * length * along + wiggle * across + for q in range(0, path.shape[0], 20): + truth += 30 * np.exp(-((rr - path[q, 0]) ** 2 + (cc - path[q, 1]) ** 2) / (2 * 1.5**2)) + sp = path[q] + (3 + 2 * rng.random()) * across * np.sign(rng.standard_normal()) + truth += (40 + 80 * rng.random()) * np.exp( + -((rr - sp[0]) ** 2 + (cc - sp[1]) ** 2) / (2 * 1.1**2) + ) + scan = np.ones(size, bool) + scan[:, :12] = False + scan[79:100, 119:150] = False + truth[~scan] = np.nan + return truth, scan + + +def trials( + truth: np.ndarray, + scan: np.ndarray, + bends: bool, + rng: np.random.Generator, + n_trials: int = N_TRIALS, + bend_px: float = 0.25, + affine_sd: float = 0.003, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Trial mean images, their halves, the true fields and the rigid starting maps. + + Mean images (trials, rows, cols), halves (trials, 2, rows, cols), + true fields (trials, 2, rows, cols) (consensus pixel x is at + x + U(x) in the trial) and rigid starting maps (trials, 2, 3). + + Returns + ------- + m : np.ndarray + Trial mean images (trials, rows, cols). + mh : np.ndarray + Each trial's two halves (trials, 2, rows, cols). + u : np.ndarray + The true fields (trials, 2, rows, cols). + a0 : np.ndarray + The rigid starting maps (trials, 2, 3). + """ + h, w = truth.shape + rr, cc = np.mgrid[0:h, 0:w].astype(np.float64) + filled = np.where(np.isnan(truth), 5.0, truth) + m = np.full((n_trials, h, w), np.nan) + mh = np.full((n_trials, 2, h, w), np.nan) + u = np.zeros((n_trials, 2, h, w)) + a0 = np.zeros((n_trials, 2, 3)) + for t in range(n_trials): + lin = np.eye(2) + affine_sd * rng.standard_normal((2, 2)) + tr = 0.6 * rng.standard_normal(2) + u_r = (lin[0, 0] - 1) * rr + lin[0, 1] * cc + tr[0] + u_c = lin[1, 0] * rr + (lin[1, 1] - 1) * cc + tr[1] + if bends: + for comp in (0, 1): + b = ndimage.gaussian_filter( + rng.standard_normal((h, w)), 40, mode="nearest", truncate=5 + ) + b = bend_px * b / b.std() + if comp == 0: + u_r = u_r + b + else: + u_c = u_c + b + u[t, 0], u[t, 1] = u_r, u_c + # the consensus point each trial pixel shows: y = x - U(y) + y_r, y_c = rr.ravel().copy(), cc.ravel().copy() + for _ in range(8): + coords = np.vstack([y_r, y_c]) + ur = ndimage.map_coordinates(u_r, coords, order=1, mode="nearest") + uc = ndimage.map_coordinates(u_c, coords, order=1, mode="nearest") + y_r, y_c = rr.ravel() - ur, cc.ravel() - uc + img = interp2_cubic(filled, y_r, y_c) + img = np.where(np.isnan(img), 5.0, img).reshape(h, w) + for half in range(2): + x = img + 0.2 * np.sqrt(np.maximum(img, 0)) * rng.standard_normal((h, w)) + x[~scan] = np.nan # the scan mask is fixed in the trial's frame + mh[t, half] = x + m[t] = mh[t].mean(axis=0) + c0 = (h // 2 - 1, w // 2 - 1) # MATLAB's round(sz/2), zero-based + a0[t] = [[1, 0, np.round(u_r[c0])], [0, 1, np.round(u_c[c0])]] + return m, mh, u, a0 + + +def field_error( + coords: Callable[[int, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]], + u: np.ndarray, + a0: np.ndarray, + truth: np.ndarray, + scan: np.ndarray, +) -> tuple[float, float]: + """RMS error of fitted maps relative to the trials' mean map. + + Weighted by image structure; and the same for the rigid start. + coords(t, r, c) gives the fitted positions. + + Returns + ------- + fitted : float + Structure-weighted RMS error of the fitted maps. + rigid : float + The same for the rigid start. + """ + n_trials = u.shape[0] + sel = ndimage.binary_erosion(scan, np.ones((5, 5)), border_value=0) + rows, cols = np.nonzero(sel) + est = np.empty((n_trials, rows.size, 2)) + tru = np.empty_like(est) + rig = np.empty_like(est) + for t in range(n_trials): + r_t, c_t = coords(t, rows.astype(float), cols.astype(float)) + est[t] = np.column_stack([r_t - rows, c_t - cols]) + tru[t] = np.column_stack([u[t, 0][sel], u[t, 1][sel]]) + rig[t] = a0[t, :, 2] + sq = np.sqrt(np.fmax(truth, 0)) + g_r, g_c = np.gradient(sq, axis=0), np.gradient(sq, axis=1) + wgt = g_r[sel] ** 2 + g_c[sel] ** 2 + wgt[np.isnan(wgt)] = 0 + + def rel(x: np.ndarray) -> np.ndarray: + """Relative to the trials' mean. + + Returns + ------- + np.ndarray + x minus its mean over trials. + """ + return x - x.mean(axis=0) + + def wrms(e: np.ndarray) -> float: + """Structure-weighted RMS over trials and pixels. + + Returns + ------- + float + The RMS of e, weighted by image structure. + """ + return np.sqrt(np.sum((e**2).sum(axis=2).mean(axis=0) * wgt) / wgt.sum()) + + return wrms(rel(est) - rel(tru)), wrms(rel(rig) - rel(tru)) diff --git a/tests/raster/data/make_matlab_kinetics.m b/tests/raster/data/make_matlab_kinetics.m index a7514fc1..65a494b8 100644 --- a/tests/raster/data/make_matlab_kinetics.m +++ b/tests/raster/data/make_matlab_kinetics.m @@ -1,55 +1,55 @@ -function make_matlab_kinetics(out) -% Reference values of islocalmax and sourceKinetics/rejectFastSources for -% GIAnT-Python's tests (GIAnT-MATLAB main 5a0673b, read-only). -% Writes a v7.3 .mat; make_matlab_kinetics_h5.py turns it into the test's -% matlab_kinetics.h5: -% make_matlab_kinetics('kinetics_fixture.mat') (GIAnT-MATLAB dependencies on the path) -% python make_matlab_kinetics_h5.py kinetics_fixture.mat matlab_kinetics.h5 -rng(7); -% islocalmax with plateaus and MinSeparation -Y = randi([0 5], 300, 40); -Y(1:100, :) = Y(1:100, :) + 0.001 * randn(100, 40); -seps = [0 1 2 3 5 9.6]; -M = false(numel(seps), size(Y,1), size(Y,2)); -for i = 1:numel(seps) - M(i, :, :) = islocalmax(Y, 2, 'MinSeparation', seps(i)); -end -% kinetics: trials with sensor-like and fast transients, discards -params = struct('tau_s', 0.024, 'analyzeHz', 200, 'minKineticScore', 0.2); -nS = 10; nT = 600; nTr = 3; -tauF = params.tau_s * params.analyzeHz; -E = cell(nTr, 1); -LS = nan(nTr, nS, nT); -for t = 1:nTr - x = 0.3 * randn(nS, nT) + 0.05 * (1:nT) / nT; - for s = 1:nS - on = find(rand(1, nT) < 0.02); - for p = on - a = 3 + 3 * rand; - if s <= 4 - k = exp(-(0:min(40, nT - p)) / tauF); % sensor kinetics - elseif s <= 7 - k = [1 0.3]; % fast transients - k = k(1:min(2, nT - p + 1)); - else - k = exp(-(0:min(40, nT - p)) / (tauF / 3)); % between - end - x(s, p:p + numel(k) - 1) = x(s, p:p + numel(k) - 1) + a * k; - end - end - discard = rand(1, nT) < 0.05; - discard(100:120) = true; - x(:, discard) = nan; - if t == 2 - x(9, :) = nan; % a source without data in one trial - end - E{t}.dF.ls = cat(3, x, randn(nS, nT)); - LS(t, :, :) = x; -end -E{nTr + 1} = []; % a trial without traces -[score, nEvents] = sourceKinetics(E, params); -sources = struct('R', (1:nS)', 'C', (2:nS + 1)', 'V', ones(nS, 1)); -[~, kept, kin] = rejectFastSources(E, sources, params); -keep = ismember((1:nS)', kept.R); -save(out, 'Y', 'seps', 'M', 'LS', 'score', 'nEvents', 'keep', 'kin', '-v7.3'); -end +function make_matlab_kinetics(out) +% Reference values of islocalmax and sourceKinetics/rejectFastSources for +% GIAnT-Python's tests (GIAnT-MATLAB main 5a0673b, read-only). +% Writes a v7.3 .mat; make_matlab_kinetics_h5.py turns it into the test's +% matlab_kinetics.h5: +% make_matlab_kinetics('kinetics_fixture.mat') (GIAnT-MATLAB dependencies on the path) +% python make_matlab_kinetics_h5.py kinetics_fixture.mat matlab_kinetics.h5 +rng(7); +% islocalmax with plateaus and MinSeparation +Y = randi([0 5], 300, 40); +Y(1:100, :) = Y(1:100, :) + 0.001 * randn(100, 40); +seps = [0 1 2 3 5 9.6]; +M = false(numel(seps), size(Y,1), size(Y,2)); +for i = 1:numel(seps) + M(i, :, :) = islocalmax(Y, 2, 'MinSeparation', seps(i)); +end +% kinetics: trials with sensor-like and fast transients, discards +params = struct('tau_s', 0.024, 'analyzeHz', 200, 'minKineticScore', 0.2); +nS = 10; nT = 600; nTr = 3; +tauF = params.tau_s * params.analyzeHz; +E = cell(nTr, 1); +LS = nan(nTr, nS, nT); +for t = 1:nTr + x = 0.3 * randn(nS, nT) + 0.05 * (1:nT) / nT; + for s = 1:nS + on = find(rand(1, nT) < 0.02); + for p = on + a = 3 + 3 * rand; + if s <= 4 + k = exp(-(0:min(40, nT - p)) / tauF); % sensor kinetics + elseif s <= 7 + k = [1 0.3]; % fast transients + k = k(1:min(2, nT - p + 1)); + else + k = exp(-(0:min(40, nT - p)) / (tauF / 3)); % between + end + x(s, p:p + numel(k) - 1) = x(s, p:p + numel(k) - 1) + a * k; + end + end + discard = rand(1, nT) < 0.05; + discard(100:120) = true; + x(:, discard) = nan; + if t == 2 + x(9, :) = nan; % a source without data in one trial + end + E{t}.dF.ls = cat(3, x, randn(nS, nT)); + LS(t, :, :) = x; +end +E{nTr + 1} = []; % a trial without traces +[score, nEvents] = sourceKinetics(E, params); +sources = struct('R', (1:nS)', 'C', (2:nS + 1)', 'V', ones(nS, 1)); +[~, kept, kin] = rejectFastSources(E, sources, params); +keep = ismember((1:nS)', kept.R); +save(out, 'Y', 'seps', 'M', 'LS', 'score', 'nEvents', 'keep', 'kin', '-v7.3'); +end diff --git a/tests/raster/data/make_matlab_kinetics_h5.py b/tests/raster/data/make_matlab_kinetics_h5.py index 548b8267..4e3fb22a 100644 --- a/tests/raster/data/make_matlab_kinetics_h5.py +++ b/tests/raster/data/make_matlab_kinetics_h5.py @@ -1,42 +1,42 @@ -"""Convert make_matlab_kinetics.m's output into matlab_kinetics.h5. - -usage: python make_matlab_kinetics_h5.py kinetics_fixture.mat OUT.h5 - -The MATLAB script saves a v7.3 .mat (HDF5 with MATLAB's dimensions reversed -and vectors as 2-D arrays). This writes the flat datasets the test reads, -in numpy orientation: Y (rows, n), M (separations, rows, n), -seps, LS (trials, sources, frames), score, nEvents, -keep (vectors 1-D). A subset of the islocalmax rows is kept (60 with -noise, 60 of whole numbers) to keep the file small. -""" - -import sys - -import h5py -import numpy as np - - -def main(src: str, dst: str) -> None: - """Read the .mat and write the fixture.""" - with h5py.File(src, "r") as f, h5py.File(dst, "w") as g: - y = f["Y"][()].T - m = f["M"][()].transpose(2, 1, 0).astype(np.uint8) - rows = np.r_[0:60, 100:160] - g.attrs["source"] = "make_matlab_kinetics.m (GIAnT-MATLAB main 5a0673b, MATLAB R2024b)" - g["Y"] = y[rows] - g["M"] = m[:, rows] - g["seps"] = f["seps"][()].ravel() - g.create_dataset( - "LS", - data=f["LS"][()].transpose(2, 1, 0), - compression="gzip", - compression_opts=9, - shuffle=True, - ) - g["score"] = f["score"][()].ravel() - g["nEvents"] = f["nEvents"][()].ravel().astype(np.int64) - g["keep"] = f["keep"][()].ravel().astype(np.uint8) - - -if __name__ == "__main__": - main(sys.argv[1], sys.argv[2]) +"""Convert make_matlab_kinetics.m's output into matlab_kinetics.h5. + +usage: python make_matlab_kinetics_h5.py kinetics_fixture.mat OUT.h5 + +The MATLAB script saves a v7.3 .mat (HDF5 with MATLAB's dimensions reversed +and vectors as 2-D arrays). This writes the flat datasets the test reads, +in numpy orientation: Y (rows, n), M (separations, rows, n), +seps, LS (trials, sources, frames), score, nEvents, +keep (vectors 1-D). A subset of the islocalmax rows is kept (60 with +noise, 60 of whole numbers) to keep the file small. +""" + +import sys + +import h5py +import numpy as np + + +def main(src: str, dst: str) -> None: + """Read the .mat and write the fixture.""" + with h5py.File(src, "r") as f, h5py.File(dst, "w") as g: + y = f["Y"][()].T + m = f["M"][()].transpose(2, 1, 0).astype(np.uint8) + rows = np.r_[0:60, 100:160] + g.attrs["source"] = "make_matlab_kinetics.m (GIAnT-MATLAB main 5a0673b, MATLAB R2024b)" + g["Y"] = y[rows] + g["M"] = m[:, rows] + g["seps"] = f["seps"][()].ravel() + g.create_dataset( + "LS", + data=f["LS"][()].transpose(2, 1, 0), + compression="gzip", + compression_opts=9, + shuffle=True, + ) + g["score"] = f["score"][()].ravel() + g["nEvents"] = f["nEvents"][()].ravel().astype(np.int64) + g["keep"] = f["keep"][()].ravel().astype(np.uint8) + + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2]) diff --git a/tests/raster/data/make_matlab_trial_data.m b/tests/raster/data/make_matlab_trial_data.m index 07f36f4a..daec87c5 100644 --- a/tests/raster/data/make_matlab_trial_data.m +++ b/tests/raster/data/make_matlab_trial_data.m @@ -1,81 +1,81 @@ -% MATLAB references for GIAnT-Python tests/raster/test_raster_trial_data.py -% (R2024b; nansvd.m is GIAnT-MATLAB main 5a0673b's dependencies/nansvd.m) -rng(7); -out = struct(); - -% smoothdata's moving mean: even, odd and fractional windows -x = [1 nan 3 4 nan nan 7 8 9 10 nan 12 2 5 nan 1]; -w = [4 5 4.6 5.4 3.2]; -out.mm_x = x; out.mm_w = w; out.mm_y = nan(numel(w), numel(x)); -for k = 1:numel(w) - out.mm_y(k, :) = smoothdata(x, 2, 'movmean', w(k), 'omitmissing'); -end - -% medfilt2 with NaN, and the labeled pixels of loadTrial -A = 10 * rand(9, 11); A(rand(size(A)) < 0.2) = nan; -out.med_in = A; out.med_out = medfilt2(A, [3 3]); -lab = medfilt2(A, [3 3]); -out.labeled = double(~isnan(A) & lab > 3 * prctile(lab(~isnan(lab)), 25)); - -% motion upsampling: interp1 pchip with extrapolation -ds = ceil(3:133.58:3000); mot = cumsum(randn(size(ds))) * 0.3; -lines = ceil(1:53.4333:3050); -out.pchip_x = ds; out.pchip_y = mot; out.pchip_q = lines; -out.pchip_v = interp1(ds, mot, lines, 'pchip', 'extrap'); - -% discarded frames at the extraction's frames -d = rand(1, 37) < 0.2; n = 91; -out.disc_in = double(d); -out.disc_out = double(interp1(1:numel(d), double(d(:)), linspace(1, numel(d), n)) > 0); -out.blocks = round(linspace(1, 5633 + 1, ceil(5633 / 600) + 1)); - -% nansvd and the denoised ROI trace of loadTrial -t = 1:300; -D = (rand(12, 1) + 0.5) * (5 + sin(t / 9)) + 0.4 * randn(12, 300) + 3 * rand(12, 1) * cos(t / 23); -D(rand(size(D)) < 0.05) = nan; D(3, :) = nan; D(:, 40:44) = nan; D(7, 1:150) = nan; -[UU, SS, VV, bg] = nansvd(D, 3, 10, 0.33); -roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; -[~, selPC] = max(roiLikeness); -out.svd_d = D; out.svd_s = diag(SS)'; out.svd_bg = bg; out.svd_recon = UU * SS * VV'; -out.svd_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); -D1 = D(5, :); % a one-pixel ROI: fewer components than requested -[UU, SS, VV, bg] = nansvd(D1, 3, 10, 0.33); -roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; -[~, selPC] = max(roiLikeness); -out.svd1_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); - -% the end of loadTrial (processAllTrials_Async.m, after the block loop): -% discards, aberrantly negative samples, gap filling, variance multiplier -IMsel = 5 + randn(6, 2, 120); Finvsel = 1 + rand(6, 120); -IMsel(2, :, :) = nan; % a pixel without any sample -IMsel(3, 1, 20:75) = nan; % a gap longer than the window -IMsel(4, 2, [1:5 100:120]) = nan; % gaps at both ends -IMsel(5, 1, 60) = -40; % an aberrantly negative sample -IMsel(6, :, 30:33) = nan; -Finvsel(squeeze(isnan(IMsel(:, 1, :)))) = nan; -discardFrames = false(1, 48); discardFrames([10 11 30]) = true; -params.baselineWindow_samps = 16; -out.fin_y_in = IMsel; out.fin_finv_in = Finvsel; out.fin_discard_in = double(discardFrames); -out.fin_window = params.baselineWindow_samps; -if numel(discardFrames) > 1 - discard = interp1(1:numel(discardFrames), double(discardFrames(:)), linspace(1, numel(discardFrames), size(IMsel,3)))>0; -else - discard = repmat(any(discardFrames(:)), 1, size(IMsel,3)); -end -IMsel(:,:,discard) = nan; -IMsel(IMsel<-2*std(IMsel,0,3, 'omitmissing')) = nan; -nans = isnan(IMsel); -nanFill = IMsel; -nanFill(all(nans,3)) = 0; -passes = 0; -while any(isnan(nanFill), 'all') - nanFill = smoothdata(nanFill,3,"movmean",params.baselineWindow_samps, 'omitmissing'); - passes = passes + 1; -end -IMsel(nans) = nanFill(nans); -Finvsel(squeeze(nans(:,1,:))) = 1000*mean(Finvsel,'all', 'omitmissing'); -out.fin_y = IMsel; out.fin_finv = Finvsel; out.fin_discard = double(discard); out.fin_passes = passes; -fprintf('passes %d\n', passes); - -save('matlab_trial_data.mat', '-struct', 'out', '-v7'); -disp(out.mm_y); +% MATLAB references for GIAnT-Python tests/raster/test_raster_trial_data.py +% (R2024b; nansvd.m is GIAnT-MATLAB main 5a0673b's dependencies/nansvd.m) +rng(7); +out = struct(); + +% smoothdata's moving mean: even, odd and fractional windows +x = [1 nan 3 4 nan nan 7 8 9 10 nan 12 2 5 nan 1]; +w = [4 5 4.6 5.4 3.2]; +out.mm_x = x; out.mm_w = w; out.mm_y = nan(numel(w), numel(x)); +for k = 1:numel(w) + out.mm_y(k, :) = smoothdata(x, 2, 'movmean', w(k), 'omitmissing'); +end + +% medfilt2 with NaN, and the labeled pixels of loadTrial +A = 10 * rand(9, 11); A(rand(size(A)) < 0.2) = nan; +out.med_in = A; out.med_out = medfilt2(A, [3 3]); +lab = medfilt2(A, [3 3]); +out.labeled = double(~isnan(A) & lab > 3 * prctile(lab(~isnan(lab)), 25)); + +% motion upsampling: interp1 pchip with extrapolation +ds = ceil(3:133.58:3000); mot = cumsum(randn(size(ds))) * 0.3; +lines = ceil(1:53.4333:3050); +out.pchip_x = ds; out.pchip_y = mot; out.pchip_q = lines; +out.pchip_v = interp1(ds, mot, lines, 'pchip', 'extrap'); + +% discarded frames at the extraction's frames +d = rand(1, 37) < 0.2; n = 91; +out.disc_in = double(d); +out.disc_out = double(interp1(1:numel(d), double(d(:)), linspace(1, numel(d), n)) > 0); +out.blocks = round(linspace(1, 5633 + 1, ceil(5633 / 600) + 1)); + +% nansvd and the denoised ROI trace of loadTrial +t = 1:300; +D = (rand(12, 1) + 0.5) * (5 + sin(t / 9)) + 0.4 * randn(12, 300) + 3 * rand(12, 1) * cos(t / 23); +D(rand(size(D)) < 0.05) = nan; D(3, :) = nan; D(:, 40:44) = nan; D(7, 1:150) = nan; +[UU, SS, VV, bg] = nansvd(D, 3, 10, 0.33); +roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; +[~, selPC] = max(roiLikeness); +out.svd_d = D; out.svd_s = diag(SS)'; out.svd_bg = bg; out.svd_recon = UU * SS * VV'; +out.svd_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); +D1 = D(5, :); % a one-pixel ROI: fewer components than requested +[UU, SS, VV, bg] = nansvd(D1, 3, 10, 0.33); +roiLikeness = (abs(mean(UU, 1, 'omitnan')) ./ sqrt(mean(UU.^2, 1, 'omitnan'))) .* diag(SS)'; +[~, selPC] = max(roiLikeness); +out.svd1_trace = mean(bg + (UU(:, selPC) * SS(selPC, selPC) * VV(:, selPC)'), 1, 'omitnan'); + +% the end of loadTrial (processAllTrials_Async.m, after the block loop): +% discards, aberrantly negative samples, gap filling, variance multiplier +IMsel = 5 + randn(6, 2, 120); Finvsel = 1 + rand(6, 120); +IMsel(2, :, :) = nan; % a pixel without any sample +IMsel(3, 1, 20:75) = nan; % a gap longer than the window +IMsel(4, 2, [1:5 100:120]) = nan; % gaps at both ends +IMsel(5, 1, 60) = -40; % an aberrantly negative sample +IMsel(6, :, 30:33) = nan; +Finvsel(squeeze(isnan(IMsel(:, 1, :)))) = nan; +discardFrames = false(1, 48); discardFrames([10 11 30]) = true; +params.baselineWindow_samps = 16; +out.fin_y_in = IMsel; out.fin_finv_in = Finvsel; out.fin_discard_in = double(discardFrames); +out.fin_window = params.baselineWindow_samps; +if numel(discardFrames) > 1 + discard = interp1(1:numel(discardFrames), double(discardFrames(:)), linspace(1, numel(discardFrames), size(IMsel,3)))>0; +else + discard = repmat(any(discardFrames(:)), 1, size(IMsel,3)); +end +IMsel(:,:,discard) = nan; +IMsel(IMsel<-2*std(IMsel,0,3, 'omitmissing')) = nan; +nans = isnan(IMsel); +nanFill = IMsel; +nanFill(all(nans,3)) = 0; +passes = 0; +while any(isnan(nanFill), 'all') + nanFill = smoothdata(nanFill,3,"movmean",params.baselineWindow_samps, 'omitmissing'); + passes = passes + 1; +end +IMsel(nans) = nanFill(nans); +Finvsel(squeeze(nans(:,1,:))) = 1000*mean(Finvsel,'all', 'omitmissing'); +out.fin_y = IMsel; out.fin_finv = Finvsel; out.fin_discard = double(discard); out.fin_passes = passes; +fprintf('passes %d\n', passes); + +save('matlab_trial_data.mat', '-struct', 'out', '-v7'); +disp(out.mm_y); diff --git a/tests/raster/test_raster_alignment.py b/tests/raster/test_raster_alignment.py index 866698dd..e2225dd1 100644 --- a/tests/raster/test_raster_alignment.py +++ b/tests/raster/test_raster_alignment.py @@ -1,350 +1,350 @@ -"""Tests of the across-trial alignment of SiLo's plan stage.""" - -from collections.abc import Callable, Sequence - -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import ( - TrialWarp, - align_trials, - dftregistration_clipped, - interp2_linear, - make_consensus_template, - mask_to_consensus, - matlab_round, - template_samples, - warp_trial_image, - xcorr2_nans, -) - -NAN = np.nan - - -def _scene( - shape: tuple[int, int] = (60, 80), n_blobs: int = 25, seed: int = 0 -) -> Callable[..., np.ndarray]: - """Build a smooth image of Gaussian blobs, with a function to shift it. - - Returns - ------- - Callable - render(shift), the scene image moved by shift. - """ - rng = np.random.default_rng(seed) - centres = rng.uniform([8, 8], [shape[0] - 8, shape[1] - 8], (n_blobs, 2)) - amps = rng.uniform(1, 3, n_blobs) - - def render(shift: Sequence[float] | np.ndarray = (0.0, 0.0)) -> np.ndarray: - """Render the scene moved by shift. - - Pixel p shows scene point p - shift. - - Returns - ------- - np.ndarray - The scene image of shape, moved by shift. - """ - rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) - im = np.full(shape, 0.2) - for (r0, c0), a in zip(centres, amps): - im += a * np.exp( - -((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * 2.0**2) - ) - return im - - return render - - -def test_matlab_round_halves_away_from_zero() -> None: - """MATLAB rounds 2.5 to 3 and -2.5 to -3. - - The largest double below a half rounds down. - """ - np.testing.assert_array_equal( - matlab_round([2.5, -2.5, 3.5, 0.5, 0.49999999999999994, -0.2]), - [3, -3, 4, 1, 0, 0], - ) - - -def test_interp2_linear_is_matlabs() -> None: - """Values from MATLAB R2024b's interp2 on the same image. - - A point on a grid row or column ignores the next one (so a NaN there does - not spread), fractional points next to a NaN are NaN, outside is NaN. - """ - v = np.array([[1, 2, 3], [4, NAN, 6], [7, 8, 9], [10, 11, 12]], dtype=float) - rr, cc = np.mgrid[:4, :3].astype(float) - np.testing.assert_array_equal(interp2_linear(v, rr, cc), v) - np.testing.assert_array_equal( - interp2_linear(v, rr + 0.25, cc), - [ - [1.75, NAN, 3.75], - [4.75, NAN, 6.75], - [7.75, 8.75, 9.75], - [NAN, NAN, NAN], - ], - ) - np.testing.assert_array_equal( - interp2_linear(v, rr, cc + 0.5), - [ - [1.5, 2.5, NAN], - [NAN, NAN, NAN], - [7.5, 8.5, NAN], - [10.5, 11.5, NAN], - ], - ) - # the last row and column are inside; just beyond is not - np.testing.assert_array_equal( - interp2_linear(v, [3, 0, 0, 3.0000001], [2, 2, 2.0000001, 0]), - [12, 3, NAN, NAN], - ) - assert np.isnan(interp2_linear(v, NAN, 1.0)) - - -def test_xcorr2_nans_finds_shifts() -> None: - """A frame moved by a known amount against the template. - - The motion is the frame's shift, to a fraction of a pixel, and the - correlation is near 1. NaN borders and a NaN hole do not matter. - """ - render = _scene() - template = render() - template[:3] = NAN - template[20:23, 30:34] = NAN - for shift in [(2.0, -3.0), (0.4, 1.7), (-1.3, 0.25)]: - frame = render(shift) - frame[:, -2:] = NAN - centre = matlab_round(shift) - motion, r = xcorr2_nans(frame, template, centre, 4) - np.testing.assert_allclose(motion, shift, atol=0.08) - assert r > 0.99 - # a search that starts away from the shift still finds it - motion, _ = xcorr2_nans(render((2.0, -3.0)), template, (0, 0), 4) - np.testing.assert_allclose(motion, (2.0, -3.0), atol=0.05) - - -def test_xcorr2_nans_edge_of_search_and_errors() -> None: - """A maximum on the edge of the search is returned whole (no parabola). - - Shapes must agree. - """ - render = _scene() - motion, _ = xcorr2_nans(render((3.0, 0.0)), render(), (0, 0), 2) - np.testing.assert_array_equal(motion, [2.0, 0.0]) - with pytest.raises(ValueError, match="frame is"): - xcorr2_nans(np.zeros((4, 5)), np.zeros((5, 4)), (0, 0), 1) - - -def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: - """Where shifted pixels leave the image the mask is rolled as MATLAB's circshift. - - This is the general path; it must agree with the index lookup on an image - where nothing wraps, and run where it does. - """ - render = _scene((30, 40), 12, seed=3) - template, frame = render(), render((1.0, -1.0)) - motion, _r = xcorr2_nans(frame, template, (1, -1), 2) - np.testing.assert_allclose(motion, (1.0, -1.0), atol=0.05) - # a centre beyond the margin makes the valid pixels wrap around - wrapped, _ = xcorr2_nans(frame, template, (9, 0), 2) - assert np.isfinite(wrapped).all() - - -def test_dftregistration_clipped_whole_shifts() -> None: - """A circularly shifted image is registered by minus its shift. - - A shift outside the clip window is not found. - """ - rng = np.random.default_rng(1) - ref = rng.normal(size=(64, 48)) - moved = np.roll(ref, (5, -7), axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) - assert out[2:] == (-5, 7) - assert out[0] < 1e-6 # identical up to the shift - far = np.roll(ref, (20, 0), axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(far), 10) - assert abs(out[2]) <= 5 and abs(out[3]) <= 5 - - -def test_dftregistration_clipped_odd_sizes_as_matlab() -> None: - """On an odd axis MATLAB returns a shift of half the axis as its negative alias. - - MATLAB's midpoint test (rloc > fix(m/2) on the one-based index) does - this: values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 - image moved circularly. - """ - rng = np.random.default_rng(4) - matlab = { - (5, 7): { - (-2, 0): (-3, 0), # the alias of +2 on 5 rows - (2, 0): (-2, 0), - (0, 3): (0, -3), - (0, -3): (0, -4), # the alias of +3 on 7 columns - (1, -2): (-1, 2), - }, - (6, 8): { - (-3, 0): (-3, 0), - (3, 0): (-3, 0), - (0, 4): (0, -4), - (0, -4): (0, -4), - }, - } - for shape, cases in matlab.items(): - ref = rng.normal(size=shape) - for moved_by, expect in cases.items(): - moved = np.roll(ref, moved_by, axis=(0, 1)) - out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) - assert out[2:] == expect, (shape, moved_by) - - -def test_template_samples() -> None: - """Up to 20 kept trials, evenly spaced as MATLAB's round(linspace(1, n, 20)).""" - keep = np.array([True, False, True, True]) - np.testing.assert_array_equal(template_samples(keep), [0, 2, 3]) - many = template_samples(np.ones(50, bool)) - assert many.size == 20 and many[0] == 0 and many[-1] == 49 - # MATLAB: round(linspace(1, 50, 20)) starts 1 4 6 9 11 - np.testing.assert_array_equal(many[:5] + 1, [1, 4, 6, 9, 11]) - - -def test_consensus_template_of_shifted_copies() -> None: - """Copies of one scene are averaged on the reference. - - One image gives itself on the larger canvas. - """ - render = _scene() - shifts = [(0, 0), (1, 0), (0, -2), (1, 1), (-1, 2)] - stack = np.stack([render(s) for s in shifts]) - stack[:, :2] = NAN - template = make_consensus_template(stack, 5) - assert template.shape == (70, 90) - # the reference is one of the copies: the template shows the scene - # moved by that copy's shift (the parabola fit of a whole shift is off - # by a few thousandths of a pixel) - best = min(np.nanmax(np.abs(template[5:-5, 5:-5] - render(s))) for s in shifts) - assert best < 5e-3 - alone = make_consensus_template(stack[:1], 3) - np.testing.assert_array_equal(alone[3:-3, 3:-3], stack[0]) - assert np.isnan(alone[:3]).all() and np.isnan(alone[:, -3:]).all() - - -def test_consensus_template_without_overlap_is_nan() -> None: - """Images that share no pixels give no template.""" - a = np.full((20, 20), NAN) - b = a.copy() - a[:8] = 1.0 - b[12:] = 1.0 - assert np.isnan(make_consensus_template(np.stack([a, b]), 2)).all() - - -def test_trial_warp_coordinates() -> None: - """Shifts and affine maps; MATLAB's one-based affine round-trips.""" - warp = TrialWarp.from_shifts([[0.5, -1.25], [NAN, NAN]]) - np.testing.assert_array_equal(warp.aligned, [True, False]) - assert warp.n_trials == 2 and warp.is_shift(0) - np.testing.assert_array_equal(warp.shift(0), [0.5, -1.25]) - r_t, c_t = warp.coords(0, np.array([0.0, 3.0]), np.array([2.0, 4.0])) - np.testing.assert_array_equal(r_t, [0.5, 3.5]) - np.testing.assert_array_equal(c_t, [0.75, 2.75]) - # MATLAB: [rT; cT] = A * [r; c; 1] in one-based coordinates - a1 = np.array([[[1.01, 0.02, -0.4], [-0.03, 0.98, 0.7]]]) - affine = TrialWarp.from_matlab(a1) - assert not affine.is_shift(0) - with pytest.raises(ValueError, match="not a shift"): - affine.shift(0) - np.testing.assert_allclose(affine.to_matlab(), a1, atol=1e-15) - r_t, c_t = affine.coords(0, 4.0, 9.0) - expect = a1[0] @ [5.0, 10.0, 1.0] - 1 - np.testing.assert_allclose([r_t, c_t], expect, atol=1e-12) - # a shift is the same in both conventions - np.testing.assert_array_equal( - TrialWarp.from_shifts([[0.5, -1.25]]).to_matlab()[0, :, 2], - [0.5, -1.25], - ) - - -def test_patchwise_warp_is_not_a_shift() -> None: - """A warp with patch centres is not a shift, whatever its affine part. - - It maps through its field (zero displacements: the identity). - """ - nodes = np.array([[0, 0], [5, 1], [2, 9.0]]) - warp = TrialWarp(np.eye(2, 3)[None], nodes=nodes, sigma=3.0) - assert not warp.is_shift(0) and warp.is_patchwise - r, c = warp.coords(0, np.array([1.5, 3.0]), np.array([2.0, 7.0])) - np.testing.assert_allclose(r, [1.5, 3.0], atol=1e-12) - np.testing.assert_allclose(c, [2.0, 7.0], atol=1e-12) - - -def test_warp_trial_image() -> None: - """A whole shift moves the image exactly (NaN where it leaves the trial's image). - - Channels are resampled alike; fractional shifts interpolate. - """ - rng = np.random.default_rng(2) - im = rng.normal(size=(6, 7)) - warp = TrialWarp.from_shifts([[1.0, -2.0], [0.5, 0.0]]) - out = warp_trial_image(im, warp, 0) - np.testing.assert_array_equal(out[:5, 2:], im[1:, :5]) - assert np.isnan(out[5]).all() and np.isnan(out[:, :2]).all() - two = warp_trial_image(np.stack([im, 2 * im], axis=2), warp, 0) - np.testing.assert_array_equal(two[:, :, 0], out) - np.testing.assert_array_equal(two[:, :, 1], 2 * out) - half = warp_trial_image(im, warp, 1) - np.testing.assert_allclose(half[:5], (im[:5] + im[1:]) / 2) - with pytest.raises(ValueError, match="nearest"): - warp_trial_image(im, warp, 0, method="nearest") - - -def test_align_trials_recovers_shifts() -> None: - """Trials that show one scene at known offsets are aligned to each other. - - They agree to within a tenth of a pixel; trials that are not kept, or - without an activity image, are left out. - """ - render = _scene((70, 90), 30, seed=5) - true = np.array([[0.0, 0.0], [1.3, -0.6], [-2.2, 1.9], [0.4, 3.1], [0, 0], [0, 0]]) - m = np.stack([render(s) for s in true]) - m[:, :, :4] = NAN - act = np.ones(m.shape) - act[5] = NAN # no activity image: not aligned - keep = np.array([True, True, True, True, False, True]) - res = align_trials(m, act, keep, max_shift=5) - assert res.template.shape == (80, 100) - np.testing.assert_array_equal(res.samples, [0, 1, 2, 3, 5]) - assert np.isnan(res.shifts[4:]).all() and np.isnan(res.corr[4:]).all() - # shifts are relative to the template's reference trial - rel = res.shifts[:4] - res.shifts[0] - np.testing.assert_allclose(rel, true[:4] - true[0], atol=0.1) - assert (res.corr[:4] > 0.99).all() - with pytest.raises(ValueError, match="no trials"): - align_trials(m, act, np.zeros(6, bool)) - - -def test_mask_to_consensus() -> None: - """A mask drawn on a trial moves by minus the trial's shift. - - The shift is rounded as MATLAB's shiftRoiData (halves away from zero); - pixels leaving the frame are dropped; an unknown or unaligned trial only - crops or pads; an affine map takes the nearest trial pixel - (roisToConsensusFrame). - """ - mask = np.zeros((6, 8), bool) - mask[2, 3] = mask[5, 7] = True - warp = TrialWarp.from_shifts([[1.4, -2.5], [NAN, NAN], [0.0, 0.0], [-0.5, 0.5]]) - out = mask_to_consensus(mask, warp, 0, (6, 8)) - # consensus (r, c) is trial (r + 1.4, c - 2.5): the mask moves by - # round(-1.4) = -1 rows and round(2.5) = 3 columns - assert out.sum() == 1 and out[1, 6] - half = mask_to_consensus(mask, warp, 3, (6, 8)) - assert half.sum() == 1 and half[3, 2] # +1 row, -1 column - np.testing.assert_array_equal(mask_to_consensus(mask, warp, 2, (6, 8)), mask) - for trial in (None, 1): - padded = mask_to_consensus(mask, warp, trial, (7, 7)) - assert padded.shape == (7, 7) and padded.sum() == 1 and padded[2, 3] - # an affine map that is nearly the shift (1, -2) of trial 0 - affine = TrialWarp([[[1.0, 1e-9, 1.0], [0.0, 1.0, -2.0]]]) - assert not affine.is_shift(0) - moved = mask_to_consensus(mask, affine, 0, (6, 8)) - assert moved.sum() == 1 and moved[1, 5] +"""Tests of the across-trial alignment of SiLo's plan stage.""" + +from collections.abc import Callable, Sequence + +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import ( + TrialWarp, + align_trials, + dftregistration_clipped, + interp2_linear, + make_consensus_template, + mask_to_consensus, + matlab_round, + template_samples, + warp_trial_image, + xcorr2_nans, +) + +NAN = np.nan + + +def _scene( + shape: tuple[int, int] = (60, 80), n_blobs: int = 25, seed: int = 0 +) -> Callable[..., np.ndarray]: + """Build a smooth image of Gaussian blobs, with a function to shift it. + + Returns + ------- + Callable + render(shift), the scene image moved by shift. + """ + rng = np.random.default_rng(seed) + centres = rng.uniform([8, 8], [shape[0] - 8, shape[1] - 8], (n_blobs, 2)) + amps = rng.uniform(1, 3, n_blobs) + + def render(shift: Sequence[float] | np.ndarray = (0.0, 0.0)) -> np.ndarray: + """Render the scene moved by shift. + + Pixel p shows scene point p - shift. + + Returns + ------- + np.ndarray + The scene image of shape, moved by shift. + """ + rr, cc = np.mgrid[: shape[0], : shape[1]].astype(float) + im = np.full(shape, 0.2) + for (r0, c0), a in zip(centres, amps): + im += a * np.exp( + -((rr - r0 - shift[0]) ** 2 + (cc - c0 - shift[1]) ** 2) / (2 * 2.0**2) + ) + return im + + return render + + +def test_matlab_round_halves_away_from_zero() -> None: + """MATLAB rounds 2.5 to 3 and -2.5 to -3. + + The largest double below a half rounds down. + """ + np.testing.assert_array_equal( + matlab_round([2.5, -2.5, 3.5, 0.5, 0.49999999999999994, -0.2]), + [3, -3, 4, 1, 0, 0], + ) + + +def test_interp2_linear_is_matlabs() -> None: + """Values from MATLAB R2024b's interp2 on the same image. + + A point on a grid row or column ignores the next one (so a NaN there does + not spread), fractional points next to a NaN are NaN, outside is NaN. + """ + v = np.array([[1, 2, 3], [4, NAN, 6], [7, 8, 9], [10, 11, 12]], dtype=float) + rr, cc = np.mgrid[:4, :3].astype(float) + np.testing.assert_array_equal(interp2_linear(v, rr, cc), v) + np.testing.assert_array_equal( + interp2_linear(v, rr + 0.25, cc), + [ + [1.75, NAN, 3.75], + [4.75, NAN, 6.75], + [7.75, 8.75, 9.75], + [NAN, NAN, NAN], + ], + ) + np.testing.assert_array_equal( + interp2_linear(v, rr, cc + 0.5), + [ + [1.5, 2.5, NAN], + [NAN, NAN, NAN], + [7.5, 8.5, NAN], + [10.5, 11.5, NAN], + ], + ) + # the last row and column are inside; just beyond is not + np.testing.assert_array_equal( + interp2_linear(v, [3, 0, 0, 3.0000001], [2, 2, 2.0000001, 0]), + [12, 3, NAN, NAN], + ) + assert np.isnan(interp2_linear(v, NAN, 1.0)) + + +def test_xcorr2_nans_finds_shifts() -> None: + """A frame moved by a known amount against the template. + + The motion is the frame's shift, to a fraction of a pixel, and the + correlation is near 1. NaN borders and a NaN hole do not matter. + """ + render = _scene() + template = render() + template[:3] = NAN + template[20:23, 30:34] = NAN + for shift in [(2.0, -3.0), (0.4, 1.7), (-1.3, 0.25)]: + frame = render(shift) + frame[:, -2:] = NAN + centre = matlab_round(shift) + motion, r = xcorr2_nans(frame, template, centre, 4) + np.testing.assert_allclose(motion, shift, atol=0.08) + assert r > 0.99 + # a search that starts away from the shift still finds it + motion, _ = xcorr2_nans(render((2.0, -3.0)), template, (0, 0), 4) + np.testing.assert_allclose(motion, (2.0, -3.0), atol=0.05) + + +def test_xcorr2_nans_edge_of_search_and_errors() -> None: + """A maximum on the edge of the search is returned whole (no parabola). + + Shapes must agree. + """ + render = _scene() + motion, _ = xcorr2_nans(render((3.0, 0.0)), render(), (0, 0), 2) + np.testing.assert_array_equal(motion, [2.0, 0.0]) + with pytest.raises(ValueError, match="frame is"): + xcorr2_nans(np.zeros((4, 5)), np.zeros((5, 4)), (0, 0), 1) + + +def test_xcorr2_nans_wrapping_matches_the_rolled_masks() -> None: + """Where shifted pixels leave the image the mask is rolled as MATLAB's circshift. + + This is the general path; it must agree with the index lookup on an image + where nothing wraps, and run where it does. + """ + render = _scene((30, 40), 12, seed=3) + template, frame = render(), render((1.0, -1.0)) + motion, _r = xcorr2_nans(frame, template, (1, -1), 2) + np.testing.assert_allclose(motion, (1.0, -1.0), atol=0.05) + # a centre beyond the margin makes the valid pixels wrap around + wrapped, _ = xcorr2_nans(frame, template, (9, 0), 2) + assert np.isfinite(wrapped).all() + + +def test_dftregistration_clipped_whole_shifts() -> None: + """A circularly shifted image is registered by minus its shift. + + A shift outside the clip window is not found. + """ + rng = np.random.default_rng(1) + ref = rng.normal(size=(64, 48)) + moved = np.roll(ref, (5, -7), axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) + assert out[2:] == (-5, 7) + assert out[0] < 1e-6 # identical up to the shift + far = np.roll(ref, (20, 0), axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(far), 10) + assert abs(out[2]) <= 5 and abs(out[3]) <= 5 + + +def test_dftregistration_clipped_odd_sizes_as_matlab() -> None: + """On an odd axis MATLAB returns a shift of half the axis as its negative alias. + + MATLAB's midpoint test (rloc > fix(m/2) on the one-based index) does + this: values of dftregistration_clipped.m (R2024b) for a 5 x 7 and a 6 x 8 + image moved circularly. + """ + rng = np.random.default_rng(4) + matlab = { + (5, 7): { + (-2, 0): (-3, 0), # the alias of +2 on 5 rows + (2, 0): (-2, 0), + (0, 3): (0, -3), + (0, -3): (0, -4), # the alias of +3 on 7 columns + (1, -2): (-1, 2), + }, + (6, 8): { + (-3, 0): (-3, 0), + (3, 0): (-3, 0), + (0, 4): (0, -4), + (0, -4): (0, -4), + }, + } + for shape, cases in matlab.items(): + ref = rng.normal(size=shape) + for moved_by, expect in cases.items(): + moved = np.roll(ref, moved_by, axis=(0, 1)) + out = dftregistration_clipped(np.fft.fft2(ref), np.fft.fft2(moved), 80) + assert out[2:] == expect, (shape, moved_by) + + +def test_template_samples() -> None: + """Up to 20 kept trials, evenly spaced as MATLAB's round(linspace(1, n, 20)).""" + keep = np.array([True, False, True, True]) + np.testing.assert_array_equal(template_samples(keep), [0, 2, 3]) + many = template_samples(np.ones(50, bool)) + assert many.size == 20 and many[0] == 0 and many[-1] == 49 + # MATLAB: round(linspace(1, 50, 20)) starts 1 4 6 9 11 + np.testing.assert_array_equal(many[:5] + 1, [1, 4, 6, 9, 11]) + + +def test_consensus_template_of_shifted_copies() -> None: + """Copies of one scene are averaged on the reference. + + One image gives itself on the larger canvas. + """ + render = _scene() + shifts = [(0, 0), (1, 0), (0, -2), (1, 1), (-1, 2)] + stack = np.stack([render(s) for s in shifts]) + stack[:, :2] = NAN + template = make_consensus_template(stack, 5) + assert template.shape == (70, 90) + # the reference is one of the copies: the template shows the scene + # moved by that copy's shift (the parabola fit of a whole shift is off + # by a few thousandths of a pixel) + best = min(np.nanmax(np.abs(template[5:-5, 5:-5] - render(s))) for s in shifts) + assert best < 5e-3 + alone = make_consensus_template(stack[:1], 3) + np.testing.assert_array_equal(alone[3:-3, 3:-3], stack[0]) + assert np.isnan(alone[:3]).all() and np.isnan(alone[:, -3:]).all() + + +def test_consensus_template_without_overlap_is_nan() -> None: + """Images that share no pixels give no template.""" + a = np.full((20, 20), NAN) + b = a.copy() + a[:8] = 1.0 + b[12:] = 1.0 + assert np.isnan(make_consensus_template(np.stack([a, b]), 2)).all() + + +def test_trial_warp_coordinates() -> None: + """Shifts and affine maps; MATLAB's one-based affine round-trips.""" + warp = TrialWarp.from_shifts([[0.5, -1.25], [NAN, NAN]]) + np.testing.assert_array_equal(warp.aligned, [True, False]) + assert warp.n_trials == 2 and warp.is_shift(0) + np.testing.assert_array_equal(warp.shift(0), [0.5, -1.25]) + r_t, c_t = warp.coords(0, np.array([0.0, 3.0]), np.array([2.0, 4.0])) + np.testing.assert_array_equal(r_t, [0.5, 3.5]) + np.testing.assert_array_equal(c_t, [0.75, 2.75]) + # MATLAB: [rT; cT] = A * [r; c; 1] in one-based coordinates + a1 = np.array([[[1.01, 0.02, -0.4], [-0.03, 0.98, 0.7]]]) + affine = TrialWarp.from_matlab(a1) + assert not affine.is_shift(0) + with pytest.raises(ValueError, match="not a shift"): + affine.shift(0) + np.testing.assert_allclose(affine.to_matlab(), a1, atol=1e-15) + r_t, c_t = affine.coords(0, 4.0, 9.0) + expect = a1[0] @ [5.0, 10.0, 1.0] - 1 + np.testing.assert_allclose([r_t, c_t], expect, atol=1e-12) + # a shift is the same in both conventions + np.testing.assert_array_equal( + TrialWarp.from_shifts([[0.5, -1.25]]).to_matlab()[0, :, 2], + [0.5, -1.25], + ) + + +def test_patchwise_warp_is_not_a_shift() -> None: + """A warp with patch centres is not a shift, whatever its affine part. + + It maps through its field (zero displacements: the identity). + """ + nodes = np.array([[0, 0], [5, 1], [2, 9.0]]) + warp = TrialWarp(np.eye(2, 3)[None], nodes=nodes, sigma=3.0) + assert not warp.is_shift(0) and warp.is_patchwise + r, c = warp.coords(0, np.array([1.5, 3.0]), np.array([2.0, 7.0])) + np.testing.assert_allclose(r, [1.5, 3.0], atol=1e-12) + np.testing.assert_allclose(c, [2.0, 7.0], atol=1e-12) + + +def test_warp_trial_image() -> None: + """A whole shift moves the image exactly (NaN where it leaves the trial's image). + + Channels are resampled alike; fractional shifts interpolate. + """ + rng = np.random.default_rng(2) + im = rng.normal(size=(6, 7)) + warp = TrialWarp.from_shifts([[1.0, -2.0], [0.5, 0.0]]) + out = warp_trial_image(im, warp, 0) + np.testing.assert_array_equal(out[:5, 2:], im[1:, :5]) + assert np.isnan(out[5]).all() and np.isnan(out[:, :2]).all() + two = warp_trial_image(np.stack([im, 2 * im], axis=2), warp, 0) + np.testing.assert_array_equal(two[:, :, 0], out) + np.testing.assert_array_equal(two[:, :, 1], 2 * out) + half = warp_trial_image(im, warp, 1) + np.testing.assert_allclose(half[:5], (im[:5] + im[1:]) / 2) + with pytest.raises(ValueError, match="nearest"): + warp_trial_image(im, warp, 0, method="nearest") + + +def test_align_trials_recovers_shifts() -> None: + """Trials that show one scene at known offsets are aligned to each other. + + They agree to within a tenth of a pixel; trials that are not kept, or + without an activity image, are left out. + """ + render = _scene((70, 90), 30, seed=5) + true = np.array([[0.0, 0.0], [1.3, -0.6], [-2.2, 1.9], [0.4, 3.1], [0, 0], [0, 0]]) + m = np.stack([render(s) for s in true]) + m[:, :, :4] = NAN + act = np.ones(m.shape) + act[5] = NAN # no activity image: not aligned + keep = np.array([True, True, True, True, False, True]) + res = align_trials(m, act, keep, max_shift=5) + assert res.template.shape == (80, 100) + np.testing.assert_array_equal(res.samples, [0, 1, 2, 3, 5]) + assert np.isnan(res.shifts[4:]).all() and np.isnan(res.corr[4:]).all() + # shifts are relative to the template's reference trial + rel = res.shifts[:4] - res.shifts[0] + np.testing.assert_allclose(rel, true[:4] - true[0], atol=0.1) + assert (res.corr[:4] > 0.99).all() + with pytest.raises(ValueError, match="no trials"): + align_trials(m, act, np.zeros(6, bool)) + + +def test_mask_to_consensus() -> None: + """A mask drawn on a trial moves by minus the trial's shift. + + The shift is rounded as MATLAB's shiftRoiData (halves away from zero); + pixels leaving the frame are dropped; an unknown or unaligned trial only + crops or pads; an affine map takes the nearest trial pixel + (roisToConsensusFrame). + """ + mask = np.zeros((6, 8), bool) + mask[2, 3] = mask[5, 7] = True + warp = TrialWarp.from_shifts([[1.4, -2.5], [NAN, NAN], [0.0, 0.0], [-0.5, 0.5]]) + out = mask_to_consensus(mask, warp, 0, (6, 8)) + # consensus (r, c) is trial (r + 1.4, c - 2.5): the mask moves by + # round(-1.4) = -1 rows and round(2.5) = 3 columns + assert out.sum() == 1 and out[1, 6] + half = mask_to_consensus(mask, warp, 3, (6, 8)) + assert half.sum() == 1 and half[3, 2] # +1 row, -1 column + np.testing.assert_array_equal(mask_to_consensus(mask, warp, 2, (6, 8)), mask) + for trial in (None, 1): + padded = mask_to_consensus(mask, warp, trial, (7, 7)) + assert padded.shape == (7, 7) and padded.sum() == 1 and padded[2, 3] + # an affine map that is nearly the shift (1, -2) of trial 0 + affine = TrialWarp([[[1.0, 1e-9, 1.0], [0.0, 1.0, -2.0]]]) + assert not affine.is_shift(0) + moved = mask_to_consensus(mask, affine, 0, (6, 8)) + assert moved.sum() == 1 and moved[1, 5] diff --git a/tests/raster/test_raster_annotations.py b/tests/raster/test_raster_annotations.py index 9cac2716..7a8ee6d0 100644 --- a/tests/raster/test_raster_annotations.py +++ b/tests/raster/test_raster_annotations.py @@ -1,171 +1,171 @@ -"""Tests of reading SILo's annotations.h5 and moving ROIs to the consensus frame. - -MATLAB functions: loadAnnotationsH5, roisToConsensusFrame, shiftRoiData. -""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import TrialWarp -from giant_python.extraction.raster.annotations import ( - PathAnnotations, - UserRoi, - annotation_trial, - read_annotations, - rois_to_consensus, - session_annotations, - soma_mask, -) - -SHAPE = (12, 16) # MATLAB rows x cols of the annotation image - - -def _text(f: h5py.File, path: str, value: str) -> None: - """Write a string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" - f.create_dataset(path, data=np.array([[ord(c)] for c in value], dtype=np.uint16)) - - -def _matlab(f: h5py.File, path: str, value: np.ndarray) -> None: - """Write a numeric array as MATLAB's h5write stores it (dimensions reversed).""" - f.create_dataset(path, data=np.ascontiguousarray(np.asarray(value).T)) - - -def write_annotations(path: Path, zero_indexed: bool | None = True) -> list[np.ndarray]: - """Write a file with two paths in MATLAB's layout and return the masks. - - Returns - ------- - list[np.ndarray] - The boolean ROI masks written to the first path, in ROI order. - """ - masks = [] - with h5py.File(path, "w") as f: - _matlab(f, "row_major", np.uint8([[0]])) - if zero_indexed is not None: - _matlab(f, "coords_zero_indexed", np.uint8([[int(zero_indexed)]])) - _matlab(f, "schema_version", np.uint32([[2]])) - for d, (label, fn) in enumerate([ - ("Soma 1", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz"), - ("spine", ""), - ]): - root = f"Path{d + 1}" - _text(f, f"{root}/dr", "C:\\data\\moco") - if fn: - _text(f, f"{root}/fn", fn) - _matlab(f, f"{root}/n_rois", np.uint32([[2 if d == 0 else 0]])) - if d: - continue - for k, (lab, r0, c0) in enumerate([(label, 2, 3), ("sp2", 6, 9)]): - mask = np.zeros(SHAPE, np.uint8) - mask[r0 : r0 + 3, c0 : c0 + 2] = 1 - masks.append(mask.astype(bool)) - roi = f"{root}/roi_{k + 1:03d}" - _text(f, f"{roi}/type", "circle") - _text(f, f"{roi}/label", lab) - _matlab(f, f"{roi}/mask", mask) - # zero-based [row col] in the file when zero-indexed - center = ( - np.array([[r0 + 1.0, c0 + 0.5]]) - if zero_indexed - else np.array([[c0 + 1.5, r0 + 2.0]]) - ) - _matlab(f, f"{roi}/center", center) - _matlab(f, f"{roi}/radius", np.array([[1.5]])) - return masks - - -@pytest.mark.parametrize("zero_indexed", [True, False]) -def test_read_annotations(tmp_path: Path, zero_indexed: bool) -> None: - """Strings, masks (MATLAB orientation) and geometry are read back.""" - path = tmp_path / "annotations.h5" - masks = write_annotations(path, zero_indexed) - paths = read_annotations(path) - assert len(paths) == 2 - a = paths[0] - assert a.fn == "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz" - assert a.dr == "C:\\data\\moco" - assert [r.label for r in a.rois] == ["Soma 1", "sp2"] - assert [r.type for r in a.rois] == ["circle", "circle"] - np.testing.assert_array_equal(a.rois[0].mask, masks[0]) - # images.roi [x, y], one-based - np.testing.assert_allclose(a.rois[0].center, [4.5, 4.0]) - assert a.rois[0].radius == 1.5 - assert a.rois[0].is_soma and not a.rois[1].is_soma - assert paths[1].fn == "" and paths[1].rois == [] - assert [a.path for a in paths] == [1, 2] - - -def test_annotation_trial() -> None: - """The annotation's file is matched with or without its extension.""" - fns = ["E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", "E1T2DMD1_X.h5"] - assert annotation_trial("E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz", fns) == 0 - assert annotation_trial("E1T2DMD1_X.tif", fns) == 1 - assert annotation_trial("C:\\moco\\E1T2DMD1_X", fns) == 1 - assert annotation_trial("other", fns) is None - assert annotation_trial("", fns) is None - - -def test_rois_to_consensus_shift(tmp_path: Path) -> None: - """Masks move by minus the trial's rounded shift, geometry exactly. - - A trial that is not known or not aligned leaves them in place. - """ - path = tmp_path / "annotations.h5" - masks = write_annotations(path) - ann = read_annotations(path)[0] - fns = ["t1.tif", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif"] - warp = TrialWarp.from_shifts(np.array([[0.0, 0.0], [1.4, -2.0]])) - shape = (14, 15) - moved = rois_to_consensus(ann, fns, warp, shape) - want = np.zeros(shape, bool) - r, c = np.nonzero(masks[0]) - keep = (r - 1 >= 0) & (c + 2 < shape[1]) - want[r[keep] - 1, c[keep] + 2] = True - np.testing.assert_array_equal(moved[0].mask, want) - np.testing.assert_allclose(moved[0].center, ann.rois[0].center + [2, -1.4]) - assert ann.rois[0].mask.shape == SHAPE # the input is unchanged - unaligned = TrialWarp.from_shifts(np.array([[0, 0], [np.nan, np.nan]])) - with pytest.warns(UserWarning, match="not aligned"): - same = rois_to_consensus(ann, fns, unaligned, shape) - np.testing.assert_array_equal(same[0].mask[:12, :15], masks[0][:, :15]) - with pytest.warns(UserWarning, match="not in the trial table"): - rois_to_consensus(ann, ["a.tif", "b.tif"], warp, shape) - - -def test_soma_mask_and_session(tmp_path: Path) -> None: - """Soma masks are the union of the ROIs labelled SOMA. - - A session without a file has no annotations. - """ - rois = [ - UserRoi("soma", "polygon", np.eye(4, dtype=bool)), - UserRoi("Spine", "circle", np.ones((4, 4), bool)), - UserRoi("SOMA2", "circle", np.zeros((0, 0), bool)), - ] - np.testing.assert_array_equal(soma_mask(rois, (3, 5))[:, :3], np.eye(3)) - assert session_annotations(None, 2) == [None, None] - assert session_annotations(tmp_path / "missing.h5", 1) == [None] - path = tmp_path / "annotations.h5" - write_annotations(path) - got = session_annotations(path, 3) - assert isinstance(got[0], PathAnnotations) and got[2] is None - # paths are placed by their numbers, not by their order in the file - with h5py.File(path, "a") as f: - f.move("Path1", "Path3") - got = session_annotations(path, 3) - assert got[0] is None and got[1].path == 2 and got[2].path == 3 - - -def test_text_is_utf16(tmp_path: Path) -> None: - """MATLAB stores text as UTF-16 code units, surrogate pairs included.""" - label = "soma é😀" - codes = np.frombuffer(label.encode("utf-16-le"), dtype=" None: + """Write a string as MATLAB's saveAnnotationsH5 writes it (uint16 codes).""" + f.create_dataset(path, data=np.array([[ord(c)] for c in value], dtype=np.uint16)) + + +def _matlab(f: h5py.File, path: str, value: np.ndarray) -> None: + """Write a numeric array as MATLAB's h5write stores it (dimensions reversed).""" + f.create_dataset(path, data=np.ascontiguousarray(np.asarray(value).T)) + + +def write_annotations(path: Path, zero_indexed: bool | None = True) -> list[np.ndarray]: + """Write a file with two paths in MATLAB's layout and return the masks. + + Returns + ------- + list[np.ndarray] + The boolean ROI masks written to the first path, in ROI order. + """ + masks = [] + with h5py.File(path, "w") as f: + _matlab(f, "row_major", np.uint8([[0]])) + if zero_indexed is not None: + _matlab(f, "coords_zero_indexed", np.uint8([[int(zero_indexed)]])) + _matlab(f, "schema_version", np.uint32([[2]])) + for d, (label, fn) in enumerate([ + ("Soma 1", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz"), + ("spine", ""), + ]): + root = f"Path{d + 1}" + _text(f, f"{root}/dr", "C:\\data\\moco") + if fn: + _text(f, f"{root}/fn", fn) + _matlab(f, f"{root}/n_rois", np.uint32([[2 if d == 0 else 0]])) + if d: + continue + for k, (lab, r0, c0) in enumerate([(label, 2, 3), ("sp2", 6, 9)]): + mask = np.zeros(SHAPE, np.uint8) + mask[r0 : r0 + 3, c0 : c0 + 2] = 1 + masks.append(mask.astype(bool)) + roi = f"{root}/roi_{k + 1:03d}" + _text(f, f"{roi}/type", "circle") + _text(f, f"{roi}/label", lab) + _matlab(f, f"{roi}/mask", mask) + # zero-based [row col] in the file when zero-indexed + center = ( + np.array([[r0 + 1.0, c0 + 0.5]]) + if zero_indexed + else np.array([[c0 + 1.5, r0 + 2.0]]) + ) + _matlab(f, f"{roi}/center", center) + _matlab(f, f"{roi}/radius", np.array([[1.5]])) + return masks + + +@pytest.mark.parametrize("zero_indexed", [True, False]) +def test_read_annotations(tmp_path: Path, zero_indexed: bool) -> None: + """Strings, masks (MATLAB orientation) and geometry are read back.""" + path = tmp_path / "annotations.h5" + masks = write_annotations(path, zero_indexed) + paths = read_annotations(path) + assert len(paths) == 2 + a = paths[0] + assert a.fn == "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz" + assert a.dr == "C:\\data\\moco" + assert [r.label for r in a.rois] == ["Soma 1", "sp2"] + assert [r.type for r in a.rois] == ["circle", "circle"] + np.testing.assert_array_equal(a.rois[0].mask, masks[0]) + # images.roi [x, y], one-based + np.testing.assert_allclose(a.rois[0].center, [4.5, 4.0]) + assert a.rois[0].radius == 1.5 + assert a.rois[0].is_soma and not a.rois[1].is_soma + assert paths[1].fn == "" and paths[1].rois == [] + assert [a.path for a in paths] == [1, 2] + + +def test_annotation_trial() -> None: + """The annotation's file is matched with or without its extension.""" + fns = ["E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif", "E1T2DMD1_X.h5"] + assert annotation_trial("E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz", fns) == 0 + assert annotation_trial("E1T2DMD1_X.tif", fns) == 1 + assert annotation_trial("C:\\moco\\E1T2DMD1_X", fns) == 1 + assert annotation_trial("other", fns) is None + assert annotation_trial("", fns) is None + + +def test_rois_to_consensus_shift(tmp_path: Path) -> None: + """Masks move by minus the trial's rounded shift, geometry exactly. + + A trial that is not known or not aligned leaves them in place. + """ + path = tmp_path / "annotations.h5" + masks = write_annotations(path) + ann = read_annotations(path)[0] + fns = ["t1.tif", "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.tif"] + warp = TrialWarp.from_shifts(np.array([[0.0, 0.0], [1.4, -2.0]])) + shape = (14, 15) + moved = rois_to_consensus(ann, fns, warp, shape) + want = np.zeros(shape, bool) + r, c = np.nonzero(masks[0]) + keep = (r - 1 >= 0) & (c + 2 < shape[1]) + want[r[keep] - 1, c[keep] + 2] = True + np.testing.assert_array_equal(moved[0].mask, want) + np.testing.assert_allclose(moved[0].center, ann.rois[0].center + [2, -1.4]) + assert ann.rois[0].mask.shape == SHAPE # the input is unchanged + unaligned = TrialWarp.from_shifts(np.array([[0, 0], [np.nan, np.nan]])) + with pytest.warns(UserWarning, match="not aligned"): + same = rois_to_consensus(ann, fns, unaligned, shape) + np.testing.assert_array_equal(same[0].mask[:12, :15], masks[0][:, :15]) + with pytest.warns(UserWarning, match="not in the trial table"): + rois_to_consensus(ann, ["a.tif", "b.tif"], warp, shape) + + +def test_soma_mask_and_session(tmp_path: Path) -> None: + """Soma masks are the union of the ROIs labelled SOMA. + + A session without a file has no annotations. + """ + rois = [ + UserRoi("soma", "polygon", np.eye(4, dtype=bool)), + UserRoi("Spine", "circle", np.ones((4, 4), bool)), + UserRoi("SOMA2", "circle", np.zeros((0, 0), bool)), + ] + np.testing.assert_array_equal(soma_mask(rois, (3, 5))[:, :3], np.eye(3)) + assert session_annotations(None, 2) == [None, None] + assert session_annotations(tmp_path / "missing.h5", 1) == [None] + path = tmp_path / "annotations.h5" + write_annotations(path) + got = session_annotations(path, 3) + assert isinstance(got[0], PathAnnotations) and got[2] is None + # paths are placed by their numbers, not by their order in the file + with h5py.File(path, "a") as f: + f.move("Path1", "Path3") + got = session_annotations(path, 3) + assert got[0] is None and got[1].path == 2 and got[2].path == 3 + + +def test_text_is_utf16(tmp_path: Path) -> None: + """MATLAB stores text as UTF-16 code units, surrogate pairs included.""" + label = "soma é😀" + codes = np.frombuffer(label.encode("utf-16-le"), dtype=" np.ndarray: - """Build a stack that is linear in row and column, the same in every frame. - - Returns - ------- - np.ndarray - The (n_t, n_r, n_c) stack a + br * row + bc * col. - """ - r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") - return np.broadcast_to(a + br * r + bc * c, (n_t, n_r, n_c)).copy() - - -def test_baseline_file_names() -> None: - """The file is named from the trial's stem or its movie's name.""" - assert baseline_file("d", "E1T2DMD1").name == "E1T2DMD1_BASELINE-80Hz.h5" - name = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - assert baseline_file("d", name).name == "E1T2DMD1_BASELINE-80Hz.h5" - - -def test_read_network_baseline_orientation(tmp_path: Path) -> None: - """slap2-f0 writes (frame, MATLAB col, MATLAB row). - - Reading gives (frame, row, col). - """ - stack = np.random.default_rng(0).random((4, 3, 5)).astype(np.float32) - path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" - with h5py.File(path, "w") as f: - f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) - f.attrs["checkpoint"] = "x.pt" - values, attrs = read_network_baseline(path) - assert values.shape == (4, 3, 5) - np.testing.assert_allclose(values, stack, rtol=1e-3) - assert attrs["checkpoint"] == "x.pt" - - -def test_read_network_baseline_rejects_other_shapes(tmp_path: Path) -> None: - """A /baseline that is not three-dimensional is refused.""" - path = tmp_path / "b.h5" - with h5py.File(path, "w") as f: - f["baseline"] = np.zeros((4, 3)) - with pytest.raises(ValueError, match="frame, col, row"): - read_network_baseline(path) - - -def test_bilinear_is_exact_on_a_plane() -> None: - """A plane is sampled exactly at sub-pixel positions.""" - stack = _plane(3, 6, 7) - rc = np.array([[0.0, 0.0], [2.5, 3.25], [4.9, 5.1], [5.0, 6.0]]) - values, weight = sample_bilinear(stack, rc) - want = 100 + 10 * rc[:, 0] + 5 * rc[:, 1] - np.testing.assert_allclose(values, np.repeat(want[:, None], 3, 1)) - np.testing.assert_allclose(weight, 1.0) - - -def test_bilinear_renormalizes_over_neighbours_with_values() -> None: - """Neighbours without a value are left out. - - Too little weight left gives NaN. - """ - stack = np.full((2, 4, 4), 7.0) - stack[:, 1, 2] = np.nan - # (1.2, 1.2): the NaN corner (1, 2) carries 0.8 * 0.2 of the weight - values, weight = sample_bilinear(stack, np.array([[1.2, 1.2]])) - np.testing.assert_allclose(values, 7.0) - np.testing.assert_allclose(weight, 1 - 0.16) - # (1.1, 1.9): it carries 0.9 * 0.9 = 0.81 - values, weight = sample_bilinear(stack, np.array([[1.1, 1.9]])) - assert np.isnan(values).all() - np.testing.assert_allclose(weight, 0.19) - values, _ = sample_bilinear(stack, np.array([[1.1, 1.9]]), 0.1) - np.testing.assert_allclose(values, 7.0) - - -def test_bilinear_outside_the_frame() -> None: - """Neighbours outside the stack have no value. - - A whole-pixel position on the last row needs no neighbour beyond it. - """ - stack = _plane(1, 3, 3) - values, weight = sample_bilinear(stack, np.array([[2.0, 1.0], [2.4, 1.0], [-1.0, -1.0]])) - np.testing.assert_allclose(values[0], 100 + 20 + 5) - np.testing.assert_allclose(weight[0], 1.0) - np.testing.assert_allclose(values[1], 125) - np.testing.assert_allclose(weight[1], 0.6) - assert np.isnan(values[2]).all() - assert weight[2] == 0 - - -def test_bilinear_per_frame_nans() -> None: - """A neighbour missing in one frame only is left out of that frame.""" - stack = _plane(3, 3, 3) - stack[1, 1, 1] = np.nan - values, weight = sample_bilinear(stack, np.array([[1.75, 1.0]])) - np.testing.assert_allclose(values[0, [0, 2]], 100 + 17.5 + 5) - np.testing.assert_allclose(values[0, 1], 100 + 20 + 5) - np.testing.assert_allclose(weight, 0.75) - with pytest.raises(ValueError): - sample_bilinear(stack, np.array([[np.nan, 1.0]])) - with pytest.raises(ValueError): - sample_bilinear(stack, np.array([[1.0, 1.0]]), 0.0) - - -def test_interp_frames_linear_in_lines() -> None: - """Linear in line number, NaN samples left out, ends held.""" - src = np.array([10.0, 30.0, 50.0, 70.0]) - vals = np.array([[1.0, 3.0, 5.0, 7.0], [1.0, np.nan, 5.0, 7.0]]) - dst = np.array([0.0, 10.0, 20.0, 45.0, 70.0, 90.0]) - out = interp_frames(vals, src, dst) - np.testing.assert_allclose(out[0], [1, 1, 2, 4.5, 7, 7]) - np.testing.assert_allclose(out[1], [1, 1, 2, 4.5, 7, 7]) - nan_row = interp_frames(np.full((1, 4), np.nan), src, dst) - assert np.isnan(nan_row).all() - one = interp_frames(np.array([[4.0]]), np.array([5.0]), dst) - np.testing.assert_allclose(one, 4.0) - with pytest.raises(ValueError): - interp_frames(vals, src[::-1], dst) - with pytest.raises(ValueError): - interp_frames(vals[:, :3], src, dst) - - -def _registration( - n_r: int = 12, - n_c: int = 14, - lines_80: int = 100, - lines_200: int = 40, - n_lines: int = 8000, -) -> tuple[ - np.ndarray, - np.ndarray, - np.ndarray, - Callable[[ArrayLike, ArrayLike, ArrayLike], np.ndarray], -]: - """Build a synthetic network baseline: a plane times a slow time course. - - Returns the stack (counts), the registered frames' lines, the - extraction frames' lines and the true value as a function of - (row, col, line). - - Returns - ------- - stack : np.ndarray - The baseline stack (counts). - ds : np.ndarray - The registered frames' lines. - fl : np.ndarray - The extraction frames' lines. - truth : Callable - The true value as a function of (row, col, line). - """ - ds = np.arange(1, n_lines, lines_80, dtype=np.float64) - fl = np.arange(1, n_lines, lines_200, dtype=np.float64) - - def truth(r: ArrayLike, c: ArrayLike, line: ArrayLike) -> np.ndarray: - """Return the baseline in counts. - - Returns - ------- - np.ndarray - The baseline at (r, c, line), in counts. - """ - return (200 + 8 * r + 3 * c) * (1 + 0.1 * np.sin(line / 2000.0)) - - r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") - stack = truth(r[None], c[None], ds[:, None, None]).astype(np.float32) - return stack, ds, fl, truth - - -def test_map_baseline_space_time_units() -> None: - """Space, time and units of the mapping, against the known field.""" - stack, ds, fl, truth = _registration() - rc = np.array([[3.4, 5.7], [0.0, 0.0], [11.0, 13.0], [6.5, 2.25]]) - mapped = map_baseline(stack, rc, ds, fl, photon_scale=25.0) - assert isinstance(mapped, MappedBaseline) - assert mapped.values.shape == (4, fl.size) - assert not mapped.missing.any() - want = truth(rc[:, :1], rc[:, 1:], fl[None, :]) / 25.0 - inner = fl <= ds[-1] - # linear interpolation of a slow sine: error below 1e-4 relative - np.testing.assert_allclose(mapped.values[:, inner], want[:, inner], 2e-4) - # after the last registered frame: its value - last = truth(rc[:, 0], rc[:, 1], ds[-1]) / 25.0 - tail = np.broadcast_to(last[:, None], mapped.values[:, ~inner].shape) - np.testing.assert_allclose(mapped.values[:, ~inner], tail, 1e-6) - - -def test_map_baseline_missing_pixels_and_fallback() -> None: - """Pixels without a network value are flagged. - - With the data given they get its starting baseline. - """ - stack, ds, fl, _ = _registration() - stack[:, :, :4] = np.nan - rc = np.array([[5.0, 1.0], [5.0, 3.6], [5.0, 3.4], [5.0, 8.0]]) - mapped = map_baseline(stack, rc, ds, fl, 25.0) - # (5, 3.6) has 0.6 of its weight on column 4, (5, 3.4) only 0.4 - np.testing.assert_array_equal(mapped.missing, [True, False, True, False]) - assert np.isnan(mapped.values[mapped.missing]).all() - rng = np.random.default_rng(1) - data = 8 + rng.normal(0, 0.1, (4, fl.size)) - params = SolverParams() - filled = map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data) - np.testing.assert_array_equal(filled.missing, mapped.missing) - miss = mapped.missing - np.testing.assert_allclose(filled.values[miss], initial_baseline(data[miss], params)) - np.testing.assert_allclose(filled.values[~miss], mapped.values[~miss]) - with pytest.raises(ValueError, match="fallback_data"): - map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data[:, :5]) - - -def test_map_baseline_dropped_frames_are_interpolated_over() -> None: - """Dropped registered frames do not enter the time interpolation.""" - stack, ds, fl, truth = _registration() - bad = stack.copy() - drop = np.zeros(ds.size, bool) - drop[20:25] = True - bad[drop] = 1e6 - rc = np.array([[4.0, 4.0]]) - mapped = map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop) - want = truth(4.0, 4.0, fl) - np.testing.assert_allclose(mapped.values[0], want, rtol=5e-3) - kept = map_baseline(stack, rc, ds, fl, 1.0) - none = map_baseline(stack, rc, ds, fl, 1.0, drop_frames=np.zeros_like(drop)) - np.testing.assert_array_equal(kept.values, none.values) - with pytest.raises(ValueError, match="drop_frames"): - map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop[:-1]) - with pytest.raises(ValueError, match="every registered frame"): - map_baseline(bad, rc, ds, fl, 1.0, drop_frames=np.ones_like(drop)) - - -def test_map_baseline_checks_inputs() -> None: - """Mismatched frames and a bad photon scale are refused.""" - stack, ds, fl, _ = _registration() - rc = np.zeros((1, 2)) - with pytest.raises(ValueError, match="registration has"): - map_baseline(stack, rc, ds[:-1], fl, 25.0) - for scale in (0.0, -1.0, np.nan): - with pytest.raises(ValueError, match="photon_scale"): - map_baseline(stack, rc, ds, fl, scale) - - -def test_interp_frames_in_blocks() -> None: - """Interpolating in blocks gives the same rows.""" - rng = np.random.default_rng(11) - vals = rng.random((37, 20)) - src = np.arange(20) * 5.0 - dst = np.linspace(-3, 103, 51) - np.testing.assert_array_equal( - interp_frames(vals, src, dst, block=4), interp_frames(vals, src, dst) - ) +"""Tests of the mapping of the F0 network's baseline onto the extraction. + +The baseline is mapped onto the extraction's pixels, frames and units. +""" + +from collections.abc import Callable +from pathlib import Path + +import h5py +import numpy as np +import pytest +from numpy.typing import ArrayLike + +from giant_python.extraction.raster.baseline_map import ( + MappedBaseline, + baseline_file, + interp_frames, + map_baseline, + read_network_baseline, + sample_bilinear, +) +from giant_python.extraction.raster.solver_baseline import initial_baseline +from giant_python.extraction.raster.solver_setup import SolverParams + + +def _plane( + n_t: int, n_r: int, n_c: int, a: float = 100.0, br: float = 10.0, bc: float = 5.0 +) -> np.ndarray: + """Build a stack that is linear in row and column, the same in every frame. + + Returns + ------- + np.ndarray + The (n_t, n_r, n_c) stack a + br * row + bc * col. + """ + r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") + return np.broadcast_to(a + br * r + bc * c, (n_t, n_r, n_c)).copy() + + +def test_baseline_file_names() -> None: + """The file is named from the trial's stem or its movie's name.""" + assert baseline_file("d", "E1T2DMD1").name == "E1T2DMD1_BASELINE-80Hz.h5" + name = "E1T2DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + assert baseline_file("d", name).name == "E1T2DMD1_BASELINE-80Hz.h5" + + +def test_read_network_baseline_orientation(tmp_path: Path) -> None: + """slap2-f0 writes (frame, MATLAB col, MATLAB row). + + Reading gives (frame, row, col). + """ + stack = np.random.default_rng(0).random((4, 3, 5)).astype(np.float32) + path = tmp_path / "E1T1DMD1_BASELINE-80Hz.h5" + with h5py.File(path, "w") as f: + f["baseline"] = stack.transpose(0, 2, 1).astype(np.float16) + f.attrs["checkpoint"] = "x.pt" + values, attrs = read_network_baseline(path) + assert values.shape == (4, 3, 5) + np.testing.assert_allclose(values, stack, rtol=1e-3) + assert attrs["checkpoint"] == "x.pt" + + +def test_read_network_baseline_rejects_other_shapes(tmp_path: Path) -> None: + """A /baseline that is not three-dimensional is refused.""" + path = tmp_path / "b.h5" + with h5py.File(path, "w") as f: + f["baseline"] = np.zeros((4, 3)) + with pytest.raises(ValueError, match="frame, col, row"): + read_network_baseline(path) + + +def test_bilinear_is_exact_on_a_plane() -> None: + """A plane is sampled exactly at sub-pixel positions.""" + stack = _plane(3, 6, 7) + rc = np.array([[0.0, 0.0], [2.5, 3.25], [4.9, 5.1], [5.0, 6.0]]) + values, weight = sample_bilinear(stack, rc) + want = 100 + 10 * rc[:, 0] + 5 * rc[:, 1] + np.testing.assert_allclose(values, np.repeat(want[:, None], 3, 1)) + np.testing.assert_allclose(weight, 1.0) + + +def test_bilinear_renormalizes_over_neighbours_with_values() -> None: + """Neighbours without a value are left out. + + Too little weight left gives NaN. + """ + stack = np.full((2, 4, 4), 7.0) + stack[:, 1, 2] = np.nan + # (1.2, 1.2): the NaN corner (1, 2) carries 0.8 * 0.2 of the weight + values, weight = sample_bilinear(stack, np.array([[1.2, 1.2]])) + np.testing.assert_allclose(values, 7.0) + np.testing.assert_allclose(weight, 1 - 0.16) + # (1.1, 1.9): it carries 0.9 * 0.9 = 0.81 + values, weight = sample_bilinear(stack, np.array([[1.1, 1.9]])) + assert np.isnan(values).all() + np.testing.assert_allclose(weight, 0.19) + values, _ = sample_bilinear(stack, np.array([[1.1, 1.9]]), 0.1) + np.testing.assert_allclose(values, 7.0) + + +def test_bilinear_outside_the_frame() -> None: + """Neighbours outside the stack have no value. + + A whole-pixel position on the last row needs no neighbour beyond it. + """ + stack = _plane(1, 3, 3) + values, weight = sample_bilinear(stack, np.array([[2.0, 1.0], [2.4, 1.0], [-1.0, -1.0]])) + np.testing.assert_allclose(values[0], 100 + 20 + 5) + np.testing.assert_allclose(weight[0], 1.0) + np.testing.assert_allclose(values[1], 125) + np.testing.assert_allclose(weight[1], 0.6) + assert np.isnan(values[2]).all() + assert weight[2] == 0 + + +def test_bilinear_per_frame_nans() -> None: + """A neighbour missing in one frame only is left out of that frame.""" + stack = _plane(3, 3, 3) + stack[1, 1, 1] = np.nan + values, weight = sample_bilinear(stack, np.array([[1.75, 1.0]])) + np.testing.assert_allclose(values[0, [0, 2]], 100 + 17.5 + 5) + np.testing.assert_allclose(values[0, 1], 100 + 20 + 5) + np.testing.assert_allclose(weight, 0.75) + with pytest.raises(ValueError): + sample_bilinear(stack, np.array([[np.nan, 1.0]])) + with pytest.raises(ValueError): + sample_bilinear(stack, np.array([[1.0, 1.0]]), 0.0) + + +def test_interp_frames_linear_in_lines() -> None: + """Linear in line number, NaN samples left out, ends held.""" + src = np.array([10.0, 30.0, 50.0, 70.0]) + vals = np.array([[1.0, 3.0, 5.0, 7.0], [1.0, np.nan, 5.0, 7.0]]) + dst = np.array([0.0, 10.0, 20.0, 45.0, 70.0, 90.0]) + out = interp_frames(vals, src, dst) + np.testing.assert_allclose(out[0], [1, 1, 2, 4.5, 7, 7]) + np.testing.assert_allclose(out[1], [1, 1, 2, 4.5, 7, 7]) + nan_row = interp_frames(np.full((1, 4), np.nan), src, dst) + assert np.isnan(nan_row).all() + one = interp_frames(np.array([[4.0]]), np.array([5.0]), dst) + np.testing.assert_allclose(one, 4.0) + with pytest.raises(ValueError): + interp_frames(vals, src[::-1], dst) + with pytest.raises(ValueError): + interp_frames(vals[:, :3], src, dst) + + +def _registration( + n_r: int = 12, + n_c: int = 14, + lines_80: int = 100, + lines_200: int = 40, + n_lines: int = 8000, +) -> tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + Callable[[ArrayLike, ArrayLike, ArrayLike], np.ndarray], +]: + """Build a synthetic network baseline: a plane times a slow time course. + + Returns the stack (counts), the registered frames' lines, the + extraction frames' lines and the true value as a function of + (row, col, line). + + Returns + ------- + stack : np.ndarray + The baseline stack (counts). + ds : np.ndarray + The registered frames' lines. + fl : np.ndarray + The extraction frames' lines. + truth : Callable + The true value as a function of (row, col, line). + """ + ds = np.arange(1, n_lines, lines_80, dtype=np.float64) + fl = np.arange(1, n_lines, lines_200, dtype=np.float64) + + def truth(r: ArrayLike, c: ArrayLike, line: ArrayLike) -> np.ndarray: + """Return the baseline in counts. + + Returns + ------- + np.ndarray + The baseline at (r, c, line), in counts. + """ + return (200 + 8 * r + 3 * c) * (1 + 0.1 * np.sin(line / 2000.0)) + + r, c = np.meshgrid(np.arange(n_r), np.arange(n_c), indexing="ij") + stack = truth(r[None], c[None], ds[:, None, None]).astype(np.float32) + return stack, ds, fl, truth + + +def test_map_baseline_space_time_units() -> None: + """Space, time and units of the mapping, against the known field.""" + stack, ds, fl, truth = _registration() + rc = np.array([[3.4, 5.7], [0.0, 0.0], [11.0, 13.0], [6.5, 2.25]]) + mapped = map_baseline(stack, rc, ds, fl, photon_scale=25.0) + assert isinstance(mapped, MappedBaseline) + assert mapped.values.shape == (4, fl.size) + assert not mapped.missing.any() + want = truth(rc[:, :1], rc[:, 1:], fl[None, :]) / 25.0 + inner = fl <= ds[-1] + # linear interpolation of a slow sine: error below 1e-4 relative + np.testing.assert_allclose(mapped.values[:, inner], want[:, inner], 2e-4) + # after the last registered frame: its value + last = truth(rc[:, 0], rc[:, 1], ds[-1]) / 25.0 + tail = np.broadcast_to(last[:, None], mapped.values[:, ~inner].shape) + np.testing.assert_allclose(mapped.values[:, ~inner], tail, 1e-6) + + +def test_map_baseline_missing_pixels_and_fallback() -> None: + """Pixels without a network value are flagged. + + With the data given they get its starting baseline. + """ + stack, ds, fl, _ = _registration() + stack[:, :, :4] = np.nan + rc = np.array([[5.0, 1.0], [5.0, 3.6], [5.0, 3.4], [5.0, 8.0]]) + mapped = map_baseline(stack, rc, ds, fl, 25.0) + # (5, 3.6) has 0.6 of its weight on column 4, (5, 3.4) only 0.4 + np.testing.assert_array_equal(mapped.missing, [True, False, True, False]) + assert np.isnan(mapped.values[mapped.missing]).all() + rng = np.random.default_rng(1) + data = 8 + rng.normal(0, 0.1, (4, fl.size)) + params = SolverParams() + filled = map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data) + np.testing.assert_array_equal(filled.missing, mapped.missing) + miss = mapped.missing + np.testing.assert_allclose(filled.values[miss], initial_baseline(data[miss], params)) + np.testing.assert_allclose(filled.values[~miss], mapped.values[~miss]) + with pytest.raises(ValueError, match="fallback_data"): + map_baseline(stack, rc, ds, fl, 25.0, fallback_data=data[:, :5]) + + +def test_map_baseline_dropped_frames_are_interpolated_over() -> None: + """Dropped registered frames do not enter the time interpolation.""" + stack, ds, fl, truth = _registration() + bad = stack.copy() + drop = np.zeros(ds.size, bool) + drop[20:25] = True + bad[drop] = 1e6 + rc = np.array([[4.0, 4.0]]) + mapped = map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop) + want = truth(4.0, 4.0, fl) + np.testing.assert_allclose(mapped.values[0], want, rtol=5e-3) + kept = map_baseline(stack, rc, ds, fl, 1.0) + none = map_baseline(stack, rc, ds, fl, 1.0, drop_frames=np.zeros_like(drop)) + np.testing.assert_array_equal(kept.values, none.values) + with pytest.raises(ValueError, match="drop_frames"): + map_baseline(bad, rc, ds, fl, 1.0, drop_frames=drop[:-1]) + with pytest.raises(ValueError, match="every registered frame"): + map_baseline(bad, rc, ds, fl, 1.0, drop_frames=np.ones_like(drop)) + + +def test_map_baseline_checks_inputs() -> None: + """Mismatched frames and a bad photon scale are refused.""" + stack, ds, fl, _ = _registration() + rc = np.zeros((1, 2)) + with pytest.raises(ValueError, match="registration has"): + map_baseline(stack, rc, ds[:-1], fl, 25.0) + for scale in (0.0, -1.0, np.nan): + with pytest.raises(ValueError, match="photon_scale"): + map_baseline(stack, rc, ds, fl, scale) + + +def test_interp_frames_in_blocks() -> None: + """Interpolating in blocks gives the same rows.""" + rng = np.random.default_rng(11) + vals = rng.random((37, 20)) + src = np.arange(20) * 5.0 + dst = np.linspace(-3, 103, 51) + np.testing.assert_array_equal( + interp_frames(vals, src, dst, block=4), interp_frames(vals, src, dst) + ) diff --git a/tests/raster/test_raster_f0_images.py b/tests/raster/test_raster_f0_images.py index 0e0ae0ea..f11192ed 100644 --- a/tests/raster/test_raster_f0_images.py +++ b/tests/raster/test_raster_f0_images.py @@ -1,330 +1,330 @@ -"""Tests of SILo's per-trial F0 images (f0_im_trim_s). - -Covers the frames they average, the solver's per-subproblem image, results -files, assembly over subproblems and the summaries (GIAnT-MATLAB's spine-size -branch). -""" - -import argparse -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import numpy.typing as npt -import pytest - -from giant_python.cli_silo import params_from_args -from giant_python.extraction.raster.results import ( - TrialOutcome, - TrialRecord, - _same, - read_results, - write_results, -) -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - assemble_results, - solve_subproblem, -) -from giant_python.extraction.raster.solver_setup import Subproblem, f0_image_frames -from giant_python.extraction.raster.summary import PathResult, write_summaries -from giant_python.models.params import SiloParams -from giant_python.spine.summary_io import RunSummary - -from .test_raster_solver import ( - PARAMS, - _placed, - _result, - fixture, # noqa: F401 (a pytest fixture) -) -from .test_raster_summary import N_TRIALS, C, H, W, alignment, make_plan -from .test_raster_summary import outcome as summary_outcome - - -def test_f0_image_frames_trim_the_kept_frames() -> None: - """Kept frames less the trim at each end. - - All kept frames when the trim leaves none; no trim keeps every kept frame. - """ - discard = np.zeros(20, bool) - discard[[5, 6]] = True - fr = f0_image_frames(discard, 0.02, 200.0) # 4 frames each end - want = ~discard - want[:4] = want[16:] = False - np.testing.assert_array_equal(fr, want) - np.testing.assert_array_equal(f0_image_frames(discard, 0.0, 200), ~discard) - # a trial too short for the trim is averaged whole (its kept frames) - np.testing.assert_array_equal(f0_image_frames(discard, 1.0, 200), ~discard) - assert not f0_image_frames(np.ones(5, bool), 0.0, 200).any() - # half a frame rounds up (MATLAB's round, the spine readout's trim) - fr = f0_image_frames(np.zeros(20, bool), 0.0125, 200.0) # 2.5 frames - assert fr[3:17].all() and not fr[:3].any() and not fr[17:].any() - - -def test_solver_averages_its_final_baseline( - fixture: tuple[Subproblem, dict[str, np.ndarray]], # noqa: F811 -) -> None: - """The F0 image is the final baseline averaged over the given frames. - - The final baseline is as kept with keep_baseline; averaged per channel and - pixel. - """ - sub, _ = fixture - n_t = sub.y.shape[2] - frames = np.zeros(n_t, bool) - frames[n_t // 5 : 4 * n_t // 5] = True - frames[::7] = False - r = solve_subproblem( - replace(sub, f0_frames=frames), - PARAMS, - SolverOptions(keep_baseline=True), - ) - assert r.f0_image.shape == (sub.y.shape[0], sub.y.shape[1]) - np.testing.assert_allclose(r.f0_image, r.baseline[:, :, frames].mean(axis=2), rtol=1e-12) - assert solve_subproblem(sub, PARAMS).f0_image is None - with pytest.raises(ValueError, match="f0_frames has"): - solve_subproblem(replace(sub, f0_frames=frames[:-1]), PARAMS) - - -def _with_image(result: SubproblemResult, image: npt.ArrayLike) -> SubproblemResult: - """Return result with an F0 image. - - Returns - ------- - SubproblemResult - A copy of result whose f0_image is image as a float array. - """ - return replace(result, f0_image=np.asarray(image, float)) - - -def test_assembly_averages_shared_pixels() -> None: - """Pixels held by several subproblems get the mean of their images. - - In movie units; pixels held by none are NaN; without an image in every - subproblem there is none. - """ - subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - b = _with_image(_result(2, 2, 6, 2.0), [[10, 20], [30, 40]]) - t = assemble_results(subs, [a, b], 6, 5, photon_scale=25.0) - want = np.full((2, 6), np.nan) - want[:, [0, 1]] = [[1, 2], [4, 5]] - want[:, 2] = [10, 30] - want[:, 4] = [(3 + 20) / 2, (6 + 40) / 2] - np.testing.assert_allclose(t.f0_image, 25.0 * want) - t2 = assemble_results(subs, [a, _result(2, 2, 6, 2.0)], 6, 5, photon_scale=25.0) - assert t2.f0_image is None - with pytest.raises(ValueError, match="f0_image is"): - assemble_results(subs, [a, _with_image(b, [[1, 2, 3]])], 6, 5, photon_scale=25.0) - - -def _record(n_t: int = 6) -> TrialRecord: - """Build a trial record of n_t frames. - - Returns - ------- - TrialRecord - A record of n_t frames with zero fluorescence, no ROIs and no discarded frames. - """ - return TrialRecord( - frame_lines=np.arange(n_t) + 1, - discard=np.zeros(n_t, bool), - global_f=np.zeros((2, n_t)), - roi_f=np.zeros((0, 2, n_t)), - roi_fsvd=np.zeros((0, 2, n_t)), - ) - - -def test_results_files_keep_the_image(tmp_path: Path) -> None: - """The image goes into the results file and back. - - A result without one reads back without one, and the two do not count as - equal. - """ - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - b = _result(3, 1, 6, 1.0) - attrs = {"n_subproblems": 2, "n_pixels": 6, "n_sources": 5} - path = write_results( - tmp_path / "r.h5", - _record(), - {0: (np.array([0, 1, 4]), np.array([2]), a), 1: ([2, 3, 5], [0], b)}, - attrs, - ) - back = read_results(path).results - np.testing.assert_array_equal(back[0][2].f0_image, a.f0_image) - assert back[1][2].f0_image is None - with h5py.File(path) as f: - assert "f0_image" in f["subproblems/0"] - assert "f0_image" not in f["subproblems/1"] - assert _same(back[0], (np.array([0, 1, 4]), np.array([2]), a)) - assert not _same(back[0], (np.array([0, 1, 4]), np.array([2]), b)) - - -def _f0_outcome(t: int, n_px: int, scale: float) -> TrialOutcome: - """Build the summary tests' trial outcome with an F0 image. - - The analysis channel c of pixel p holds scale * (100 c + p + 1). - - Returns - ------- - TrialOutcome - The summary tests' outcome for trial t and n_px pixels, with that F0 image - set on its activity. - """ - out = summary_outcome(t, n_px) - img = scale * (100.0 * np.arange(C)[:, None] + np.arange(n_px)[None, :] + 1) - out.activity.f0_image = img - return out - - -def test_summaries_hold_the_f0_images(tmp_path: Path) -> None: - """The summaries hold the per-trial F0 images and the user ROIs' F0. - - The per-trial F0 images (file channel order, NaN outside the selected - pixels and for trials without one), their mean over trials and the user - ROIs' F0 with coverage, in MATLAB's layout, read back by the spine - readout's reader. - """ - plan = make_plan() - n_px = plan.n_pixels - result = PathResult( - plan=plan, - trials=[None, _f0_outcome(1, n_px, 1.0), _f0_outcome(2, n_px, 2.0)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=["spine01", "soma"], - roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], - ) - params = SiloParams(activity_channel=2).to_matlab(C, 80.0, 1, "a", "b") - exp = tmp_path / "experiment_summary.h5" - per = tmp_path / "per_trial_summary.h5" - write_summaries(exp, per, [result], params, N_TRIALS, C, 2) - rows, cols = plan.selected_pixels() - # activity channel 2 is analysis channel 0 - want = np.full((N_TRIALS, H, W, C), np.nan) - for t, scale in ((1, 1.0), (2, 2.0)): - want[t, rows, cols, 1] = scale * (np.arange(n_px) + 1) - want[t, rows, cols, 0] = scale * (100 + np.arange(n_px) + 1) - with h5py.File(per) as f: - g = f["Path1"] - raw = g["visualizations/per_trial_F0_im"] - assert raw.dtype == np.float32 - assert raw.shape == g["visualizations/per_trial_mean_im"].shape - np.testing.assert_allclose(raw[()].T[:, :, 0].transpose(0, 2, 3, 1), want) - roi = g["user_rois/per_trial_F0"][()].T # rois, channels, trials - cov = g["user_rois/per_trial_F0_coverage"][()].T # rois, trials - with h5py.File(exp) as f: - f0_im = f["Path1/visualizations/F0_im"][()].T[:, 0] # C, H, W - with np.errstate(invalid="ignore"): - mean = np.nanmean(want[1:], axis=0).transpose(2, 0, 1) - np.testing.assert_allclose(f0_im, mean) - eye = np.eye(H, W, dtype=bool) - for r, mask in enumerate((eye, np.ones((H, W), bool))): - for t in range(N_TRIALS): - vals = want[t][mask] # pixels, channels - if t == 0: - assert np.isnan(roi[r, :, t]).all() and cov[r, t] == 0 - continue - np.testing.assert_allclose(roi[r, :, t], np.nanmean(vals, 0)) - assert cov[r, t] == pytest.approx(np.isfinite(vals[:, 1]).mean()) - run = RunSummary(tmp_path) - for c in range(C): - np.testing.assert_allclose(run.per_trial_images(1, "per_trial_F0_im", c), want[..., c]) - - -def test_no_f0_images_without_them(tmp_path: Path) -> None: - """Trials without F0 images give no F0 datasets.""" - plan = make_plan() - n_px = plan.n_pixels - result = PathResult( - plan=plan, - trials=[None, summary_outcome(1, n_px), summary_outcome(2, n_px)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=["spine01", "soma"], - roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], - ) - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0) - exp, per = tmp_path / "e.h5", tmp_path / "p.h5" - write_summaries(exp, per, [result], params, N_TRIALS, C, 1) - with h5py.File(per) as f, h5py.File(exp) as g: - assert "per_trial_F0_im" not in f["Path1/visualizations"] - assert "per_trial_F0" not in f.get("Path1/user_rois", {}) - assert "F0_im" not in g["Path1/visualizations"] - assert "F0imTrim_s" not in g["params"] - - -def test_trial_outcome_carries_the_image() -> None: - """A trial's processed activity keeps the assembled F0 image.""" - from giant_python.extraction.raster.results import trial_outcome - - class File: - """A results file in memory.""" - - def __init__(self, results: dict, attrs: dict) -> None: - """Hold the parts :func:`trial_outcome` reads.""" - self.record = _record() - self.results = results - self.attrs = attrs - - a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) - attrs = { - "n_subproblems": 1, - "n_pixels": 3, - "n_sources": 1, - "photon_scale": 2.0, - "container": "c", - "container_hash": "h", - } - out = trial_outcome( - [File({0: (np.arange(3), np.array([0]), a)}, attrs)], - replace(PARAMS), - ) - assert isinstance(out, TrialOutcome) - np.testing.assert_allclose(out.activity.f0_image, 2.0 * a.f0_image) - - -def test_settings_and_options() -> None: - """The trim is a solve-stage setting recorded only when F0 images are made. - - Results files made without them stay current then; the command line turns - them off or sets the trim, not both. - """ - assert "f0_im_trim_s" not in SiloParams(f0_im_trim_s=None).stage_settings("solve") - assert SiloParams().stage_settings("solve")["f0_im_trim_s"] == 1.0 - assert SiloParams().to_matlab(2, 80.0)["F0imTrim_s"] == 1.0 - with pytest.raises(ValueError, match="f0_im_trim_s"): - SiloParams(f0_im_trim_s=-1.0) - - def args(**kw: object) -> argparse.Namespace: - """Build a namespace with the F0-image options. - - Returns - ------- - argparse.Namespace - The options f0_im_trim_s (None) and no_f0_images (False), overridden by - kw. - """ - return argparse.Namespace(**{"f0_im_trim_s": None, "no_f0_images": False, **kw}) - - assert params_from_args(args()).f0_im_trim_s == 1.0 - assert params_from_args(args(no_f0_images=True)).f0_im_trim_s is None - assert params_from_args(args(f0_im_trim_s=0.5)).f0_im_trim_s == 0.5 - with pytest.raises(ValueError, match="not both"): - params_from_args(args(f0_im_trim_s=0.5, no_f0_images=True)) - - -def test_results_without_images_assemble_without(tmp_path: Path) -> None: - """Results of a run without F0 images give a trial without an image. - - Also for older files. - """ - r = SubproblemResult( - footprints=np.ones((2, 1)), - events=np.zeros((2, 1, 6)), - ls=np.zeros((2, 1, 6)), - f0=np.ones((2, 1, 6)), - snr=np.ones(1), - ) - t = assemble_results([_placed([0, 1], [0], 6)], [r], 2, 1, 25.0) - assert t.f0_image is None +"""Tests of SILo's per-trial F0 images (f0_im_trim_s). + +Covers the frames they average, the solver's per-subproblem image, results +files, assembly over subproblems and the summaries (GIAnT-MATLAB's spine-size +branch). +""" + +import argparse +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import numpy.typing as npt +import pytest + +from giant_python.cli_silo import params_from_args +from giant_python.extraction.raster.results import ( + TrialOutcome, + TrialRecord, + _same, + read_results, + write_results, +) +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + assemble_results, + solve_subproblem, +) +from giant_python.extraction.raster.solver_setup import Subproblem, f0_image_frames +from giant_python.extraction.raster.summary import PathResult, write_summaries +from giant_python.models.params import SiloParams +from giant_python.spine.summary_io import RunSummary + +from .test_raster_solver import ( + PARAMS, + _placed, + _result, + fixture, # noqa: F401 (a pytest fixture) +) +from .test_raster_summary import N_TRIALS, C, H, W, alignment, make_plan +from .test_raster_summary import outcome as summary_outcome + + +def test_f0_image_frames_trim_the_kept_frames() -> None: + """Kept frames less the trim at each end. + + All kept frames when the trim leaves none; no trim keeps every kept frame. + """ + discard = np.zeros(20, bool) + discard[[5, 6]] = True + fr = f0_image_frames(discard, 0.02, 200.0) # 4 frames each end + want = ~discard + want[:4] = want[16:] = False + np.testing.assert_array_equal(fr, want) + np.testing.assert_array_equal(f0_image_frames(discard, 0.0, 200), ~discard) + # a trial too short for the trim is averaged whole (its kept frames) + np.testing.assert_array_equal(f0_image_frames(discard, 1.0, 200), ~discard) + assert not f0_image_frames(np.ones(5, bool), 0.0, 200).any() + # half a frame rounds up (MATLAB's round, the spine readout's trim) + fr = f0_image_frames(np.zeros(20, bool), 0.0125, 200.0) # 2.5 frames + assert fr[3:17].all() and not fr[:3].any() and not fr[17:].any() + + +def test_solver_averages_its_final_baseline( + fixture: tuple[Subproblem, dict[str, np.ndarray]], # noqa: F811 +) -> None: + """The F0 image is the final baseline averaged over the given frames. + + The final baseline is as kept with keep_baseline; averaged per channel and + pixel. + """ + sub, _ = fixture + n_t = sub.y.shape[2] + frames = np.zeros(n_t, bool) + frames[n_t // 5 : 4 * n_t // 5] = True + frames[::7] = False + r = solve_subproblem( + replace(sub, f0_frames=frames), + PARAMS, + SolverOptions(keep_baseline=True), + ) + assert r.f0_image.shape == (sub.y.shape[0], sub.y.shape[1]) + np.testing.assert_allclose(r.f0_image, r.baseline[:, :, frames].mean(axis=2), rtol=1e-12) + assert solve_subproblem(sub, PARAMS).f0_image is None + with pytest.raises(ValueError, match="f0_frames has"): + solve_subproblem(replace(sub, f0_frames=frames[:-1]), PARAMS) + + +def _with_image(result: SubproblemResult, image: npt.ArrayLike) -> SubproblemResult: + """Return result with an F0 image. + + Returns + ------- + SubproblemResult + A copy of result whose f0_image is image as a float array. + """ + return replace(result, f0_image=np.asarray(image, float)) + + +def test_assembly_averages_shared_pixels() -> None: + """Pixels held by several subproblems get the mean of their images. + + In movie units; pixels held by none are NaN; without an image in every + subproblem there is none. + """ + subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + b = _with_image(_result(2, 2, 6, 2.0), [[10, 20], [30, 40]]) + t = assemble_results(subs, [a, b], 6, 5, photon_scale=25.0) + want = np.full((2, 6), np.nan) + want[:, [0, 1]] = [[1, 2], [4, 5]] + want[:, 2] = [10, 30] + want[:, 4] = [(3 + 20) / 2, (6 + 40) / 2] + np.testing.assert_allclose(t.f0_image, 25.0 * want) + t2 = assemble_results(subs, [a, _result(2, 2, 6, 2.0)], 6, 5, photon_scale=25.0) + assert t2.f0_image is None + with pytest.raises(ValueError, match="f0_image is"): + assemble_results(subs, [a, _with_image(b, [[1, 2, 3]])], 6, 5, photon_scale=25.0) + + +def _record(n_t: int = 6) -> TrialRecord: + """Build a trial record of n_t frames. + + Returns + ------- + TrialRecord + A record of n_t frames with zero fluorescence, no ROIs and no discarded frames. + """ + return TrialRecord( + frame_lines=np.arange(n_t) + 1, + discard=np.zeros(n_t, bool), + global_f=np.zeros((2, n_t)), + roi_f=np.zeros((0, 2, n_t)), + roi_fsvd=np.zeros((0, 2, n_t)), + ) + + +def test_results_files_keep_the_image(tmp_path: Path) -> None: + """The image goes into the results file and back. + + A result without one reads back without one, and the two do not count as + equal. + """ + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + b = _result(3, 1, 6, 1.0) + attrs = {"n_subproblems": 2, "n_pixels": 6, "n_sources": 5} + path = write_results( + tmp_path / "r.h5", + _record(), + {0: (np.array([0, 1, 4]), np.array([2]), a), 1: ([2, 3, 5], [0], b)}, + attrs, + ) + back = read_results(path).results + np.testing.assert_array_equal(back[0][2].f0_image, a.f0_image) + assert back[1][2].f0_image is None + with h5py.File(path) as f: + assert "f0_image" in f["subproblems/0"] + assert "f0_image" not in f["subproblems/1"] + assert _same(back[0], (np.array([0, 1, 4]), np.array([2]), a)) + assert not _same(back[0], (np.array([0, 1, 4]), np.array([2]), b)) + + +def _f0_outcome(t: int, n_px: int, scale: float) -> TrialOutcome: + """Build the summary tests' trial outcome with an F0 image. + + The analysis channel c of pixel p holds scale * (100 c + p + 1). + + Returns + ------- + TrialOutcome + The summary tests' outcome for trial t and n_px pixels, with that F0 image + set on its activity. + """ + out = summary_outcome(t, n_px) + img = scale * (100.0 * np.arange(C)[:, None] + np.arange(n_px)[None, :] + 1) + out.activity.f0_image = img + return out + + +def test_summaries_hold_the_f0_images(tmp_path: Path) -> None: + """The summaries hold the per-trial F0 images and the user ROIs' F0. + + The per-trial F0 images (file channel order, NaN outside the selected + pixels and for trials without one), their mean over trials and the user + ROIs' F0 with coverage, in MATLAB's layout, read back by the spine + readout's reader. + """ + plan = make_plan() + n_px = plan.n_pixels + result = PathResult( + plan=plan, + trials=[None, _f0_outcome(1, n_px, 1.0), _f0_outcome(2, n_px, 2.0)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=["spine01", "soma"], + roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], + ) + params = SiloParams(activity_channel=2).to_matlab(C, 80.0, 1, "a", "b") + exp = tmp_path / "experiment_summary.h5" + per = tmp_path / "per_trial_summary.h5" + write_summaries(exp, per, [result], params, N_TRIALS, C, 2) + rows, cols = plan.selected_pixels() + # activity channel 2 is analysis channel 0 + want = np.full((N_TRIALS, H, W, C), np.nan) + for t, scale in ((1, 1.0), (2, 2.0)): + want[t, rows, cols, 1] = scale * (np.arange(n_px) + 1) + want[t, rows, cols, 0] = scale * (100 + np.arange(n_px) + 1) + with h5py.File(per) as f: + g = f["Path1"] + raw = g["visualizations/per_trial_F0_im"] + assert raw.dtype == np.float32 + assert raw.shape == g["visualizations/per_trial_mean_im"].shape + np.testing.assert_allclose(raw[()].T[:, :, 0].transpose(0, 2, 3, 1), want) + roi = g["user_rois/per_trial_F0"][()].T # rois, channels, trials + cov = g["user_rois/per_trial_F0_coverage"][()].T # rois, trials + with h5py.File(exp) as f: + f0_im = f["Path1/visualizations/F0_im"][()].T[:, 0] # C, H, W + with np.errstate(invalid="ignore"): + mean = np.nanmean(want[1:], axis=0).transpose(2, 0, 1) + np.testing.assert_allclose(f0_im, mean) + eye = np.eye(H, W, dtype=bool) + for r, mask in enumerate((eye, np.ones((H, W), bool))): + for t in range(N_TRIALS): + vals = want[t][mask] # pixels, channels + if t == 0: + assert np.isnan(roi[r, :, t]).all() and cov[r, t] == 0 + continue + np.testing.assert_allclose(roi[r, :, t], np.nanmean(vals, 0)) + assert cov[r, t] == pytest.approx(np.isfinite(vals[:, 1]).mean()) + run = RunSummary(tmp_path) + for c in range(C): + np.testing.assert_allclose(run.per_trial_images(1, "per_trial_F0_im", c), want[..., c]) + + +def test_no_f0_images_without_them(tmp_path: Path) -> None: + """Trials without F0 images give no F0 datasets.""" + plan = make_plan() + n_px = plan.n_pixels + result = PathResult( + plan=plan, + trials=[None, summary_outcome(1, n_px), summary_outcome(2, n_px)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=["spine01", "soma"], + roi_masks=[np.eye(H, W, dtype=bool), np.ones((H, W), bool)], + ) + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0) + exp, per = tmp_path / "e.h5", tmp_path / "p.h5" + write_summaries(exp, per, [result], params, N_TRIALS, C, 1) + with h5py.File(per) as f, h5py.File(exp) as g: + assert "per_trial_F0_im" not in f["Path1/visualizations"] + assert "per_trial_F0" not in f.get("Path1/user_rois", {}) + assert "F0_im" not in g["Path1/visualizations"] + assert "F0imTrim_s" not in g["params"] + + +def test_trial_outcome_carries_the_image() -> None: + """A trial's processed activity keeps the assembled F0 image.""" + from giant_python.extraction.raster.results import trial_outcome + + class File: + """A results file in memory.""" + + def __init__(self, results: dict, attrs: dict) -> None: + """Hold the parts :func:`trial_outcome` reads.""" + self.record = _record() + self.results = results + self.attrs = attrs + + a = _with_image(_result(3, 1, 6, 1.0), [[1, 2, 3], [4, 5, 6]]) + attrs = { + "n_subproblems": 1, + "n_pixels": 3, + "n_sources": 1, + "photon_scale": 2.0, + "container": "c", + "container_hash": "h", + } + out = trial_outcome( + [File({0: (np.arange(3), np.array([0]), a)}, attrs)], + replace(PARAMS), + ) + assert isinstance(out, TrialOutcome) + np.testing.assert_allclose(out.activity.f0_image, 2.0 * a.f0_image) + + +def test_settings_and_options() -> None: + """The trim is a solve-stage setting recorded only when F0 images are made. + + Results files made without them stay current then; the command line turns + them off or sets the trim, not both. + """ + assert "f0_im_trim_s" not in SiloParams(f0_im_trim_s=None).stage_settings("solve") + assert SiloParams().stage_settings("solve")["f0_im_trim_s"] == 1.0 + assert SiloParams().to_matlab(2, 80.0)["F0imTrim_s"] == 1.0 + with pytest.raises(ValueError, match="f0_im_trim_s"): + SiloParams(f0_im_trim_s=-1.0) + + def args(**kw: object) -> argparse.Namespace: + """Build a namespace with the F0-image options. + + Returns + ------- + argparse.Namespace + The options f0_im_trim_s (None) and no_f0_images (False), overridden by + kw. + """ + return argparse.Namespace(**{"f0_im_trim_s": None, "no_f0_images": False, **kw}) + + assert params_from_args(args()).f0_im_trim_s == 1.0 + assert params_from_args(args(no_f0_images=True)).f0_im_trim_s is None + assert params_from_args(args(f0_im_trim_s=0.5)).f0_im_trim_s == 0.5 + with pytest.raises(ValueError, match="not both"): + params_from_args(args(f0_im_trim_s=0.5, no_f0_images=True)) + + +def test_results_without_images_assemble_without(tmp_path: Path) -> None: + """Results of a run without F0 images give a trial without an image. + + Also for older files. + """ + r = SubproblemResult( + footprints=np.ones((2, 1)), + events=np.zeros((2, 1, 6)), + ls=np.zeros((2, 1, 6)), + f0=np.ones((2, 1, 6)), + snr=np.ones(1), + ) + t = assemble_results([_placed([0, 1], [0], 6)], [r], 2, 1, 25.0) + assert t.f0_image is None diff --git a/tests/raster/test_raster_peaks.py b/tests/raster/test_raster_peaks.py index 8054893b..b99eab03 100644 --- a/tests/raster/test_raster_peaks.py +++ b/tests/raster/test_raster_peaks.py @@ -1,308 +1,308 @@ -"""Tests of the getActImPeaks port (raster SiLo seeds).""" - -import numpy as np -import pytest -from scipy.optimize import OptimizeResult - -from giant_python.extraction.raster.peaks import ( - _eval_budget, - _IntegratedGaussians, - _WindowedGaussians, - get_act_im_peaks, - ordfilt3x3, -) - - -def test_ordfilt_matches_matlab() -> None: - """MATLAB ordfilt2(A, 9 or 8, ones(3)): zero padding, NaN windows.""" - a = np.array([[np.nan, 1, -2], [2, 3, -1], [-5, np.nan, 4]]) - nan = np.nan - np.testing.assert_array_equal( - ordfilt3x3(a, 9), [[nan, nan, 3], [nan, nan, nan], [nan, nan, nan]] - ) - np.testing.assert_array_equal( - ordfilt3x3(a, 8), [[nan, nan, 1], [nan, nan, nan], [nan, nan, nan]] - ) - np.testing.assert_array_equal(ordfilt3x3(np.array([[-1.0, -2], [-3, -4]]), 9), np.zeros((2, 2))) - - -def test_jacobian_matches_finite_differences() -> None: - """The analytical Jacobian of the integrated Gaussians is right.""" - yy, xx = np.mgrid[1:12, 1:14] - model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) - theta = np.array([3.0, 1.5, 5.2, 7.7, 4.1, 9.3, 1.1, 0.8]) - jac = model.jacobian(theta) - eps = 1e-6 - num = np.column_stack([ - (model.value(theta + eps * e) - model.value(theta - eps * e)) / (2 * eps) - for e in np.eye(theta.size) - ]) - np.testing.assert_allclose(jac, num, rtol=1e-5, atol=1e-8) - # the value-only path (no derivatives) is the Jacobian path's value - a, (vy, _, _), (vx, _, _) = model.parts(theta) - np.testing.assert_array_equal(model.value(theta), (vy * vx) @ a) - - -def test_finds_separated_gaussians() -> None: - """Two blobs on noise are found at their centres (0-based).""" - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:40, :50] - img = 0.05 * rng.standard_normal((40, 50)) - for r, c in ((10.3, 12.6), (28.0, 35.4)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - img[:, :2] = np.nan - pk = get_act_im_peaks(img, 8) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) - - -def test_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: - """A LAPACK SVD failure in the default solver retries with lsmr.""" - from giant_python.extraction.raster import peaks - - calls = [] - real = peaks.least_squares - - def flaky(*args: object, **kwargs: object) -> OptimizeResult: - """least_squares whose default (SVD) solver always fails. - - Returns - ------- - OptimizeResult - The result of the real least_squares when tr_solver is given. - - Raises - ------ - numpy.linalg.LinAlgError - If the default solver (no tr_solver) is used. - """ - calls.append(kwargs.get("tr_solver")) - if kwargs.get("tr_solver") is None: - raise np.linalg.LinAlgError("SVD did not converge") - return real(*args, **kwargs) - - monkeypatch.setattr(peaks, "least_squares", flaky) - yy, xx = np.mgrid[1:16, 1:16] - model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) - data = model.value(np.array([3.0, 7.4, 8.2, 1.2])) - theta = peaks._fit( - np.array([[2.0, 7.0, 8.0, 1.0]]), - yy.ravel() + 0.0, - xx.ravel() + 0.0, - data, - np.array([[0.0, 5.5, 6.5, 0.2]]), - np.array([[np.inf, 8.5, 9.5, 5.0]]), - ) - assert calls == [None, "lsmr"] - np.testing.assert_allclose(theta[0], [3.0, 7.4, 8.2, 1.2], atol=1e-3) - - -def test_exclusion_mask_and_empty() -> None: - """No seeds inside the exclusion mask; none in pure noise.""" - rng = np.random.default_rng(1) - yy, xx = np.mgrid[:30, :30] - img = 0.05 * rng.standard_normal((30, 30)) - img += 4 * np.exp(-((yy - 15) ** 2 + (xx - 15) ** 2) / 2) - mask = np.zeros((30, 30), bool) - mask[12:19, 12:19] = True - assert get_act_im_peaks(img, 8, mask).shape[0] == 0 - assert get_act_im_peaks(rng.standard_normal((30, 30)), 8).shape == (0, 4) - - -def test_no_fitted_centre_inside_the_exclusion_mask() -> None: - """A source whose centre is just inside the mask is dropped. - - It seeds on its unmasked flank, and its fit moves back into the mask: it - is dropped. A source clear of the mask is kept. - """ - rng = np.random.default_rng(2) - yy, xx = np.mgrid[:30, :40] - img = 0.05 * rng.standard_normal((30, 40)) - for r, c in ((15.0, 15.2), (15.0, 30.0)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - mask = np.zeros((30, 40), bool) - mask[:, 15:20] = True # the first source's centre and right flank - pk = get_act_im_peaks(img, 8, mask) - assert pk.shape[0] == 1 - np.testing.assert_allclose(pk[0, 1:3], [15.0, 30.0], atol=0.15) - unmasked = get_act_im_peaks(img, 8) - assert unmasked.shape[0] == 2 - - -def test_eval_budget_matches_matlab_iterations() -> None: - """MATLAB's 5000 evaluations with finite differences allow (5000 - 1) // (n + 1) iterations. - - The budget here allows as many steps (one evaluation each, plus the - start), down to one step at n = 2500. - """ - for n in (4, 40, 400, 2500, 4998): - assert _eval_budget(n) - 1 == (5000 - 1) // (n + 1) - assert _eval_budget(2500) == 2 # one step (was 1: none) - assert _eval_budget(5000) == 1 # MATLAB cannot take a step either - - -def test_rounding_is_matlabs() -> None: - """Halves round away from zero as in MATLAB (numpy rounds them to even). - - So a centre at exactly k + 0.5 lands on MATLAB's pixel. - """ - from giant_python.extraction.raster.peaks import _rounded_index - - theta = np.array([[1.0, 4.5, 2.5, 0.35], [1.0, 3.5, 7.49, 0.35]]) - iy, ix = _rounded_index(theta, (10, 10)) # 1-based in, 0-based out - np.testing.assert_array_equal(iy, [4, 3]) # MATLAB 5 and 4 - np.testing.assert_array_equal(ix, [2, 6]) # MATLAB 3 and 7 - - -def _windowed( - shape: tuple[int, int], starts: np.ndarray, window: int, rows: np.ndarray | None = None -) -> tuple[_WindowedGaussians, np.ndarray, np.ndarray]: - """Build a windowed model on a gap-free image, and the edges it uses. - - Returns - ------- - model : _WindowedGaussians - The windowed model over the pixels in rows. - ys : np.ndarray - Row coordinates (1-based) of those pixels. - xs : np.ndarray - Column coordinates (1-based) of those pixels. - """ - cols, rws = np.nonzero(np.ones(shape, bool).T) - idx = np.full(shape, -1, np.int64) - idx[rws, cols] = np.arange(rws.size) - edges = (rws + 0.5, rws + 1.5, cols + 0.5, cols + 1.5) - rows = np.arange(rws.size) if rows is None else rows - model = _WindowedGaussians(idx, edges, np.asarray(starts), window, rows) - return model, rws[rows] + 1.0, cols[rows] + 1.0 - - -def test_windowed_model_is_the_integrated_model_within_its_window() -> None: - """With windows covering the image, the windowed model is the dense one. - - Positions are offsets from the start pixels; its Jacobian, dense and - sparse, matches finite differences. - """ - starts = np.array([[4, 6], [9, 3]]) # 0-based start pixels - theta = np.array([[3.0, 5.4, 7.2, 0.7], [1.5, 9.8, 4.1, 1.1]]) - model, ys, xs = _windowed((12, 14), starts, 20) - x = np.concatenate([ - theta[:, 0], - theta[:, 1] - starts[:, 0] - 1, - theta[:, 2] - starts[:, 1] - 1, - theta[:, 3], - ]) - dense = _IntegratedGaussians(ys, xs).value(theta.ravel(order="F")) - np.testing.assert_allclose(model.value(x), dense, rtol=1e-12) - eps = 1e-6 - num = np.column_stack([ - (model.value(x + eps * e) - model.value(x - eps * e)) / (2 * eps) for e in np.eye(x.size) - ]) - np.testing.assert_allclose(model.jacobian(x, True), num, atol=1e-7) - np.testing.assert_allclose(model.jacobian(x, False).toarray(), num, atol=1e-7) - # a narrow window leaves the peak out of pixels beyond it - narrow, ys, xs = _windowed((12, 14), starts[:1], 2) - far = (np.abs(ys - 5) > 2) | (np.abs(xs - 7) > 2) - assert np.all(narrow.value(x[[0, 2, 4, 6]])[far] == 0) - - -@pytest.mark.parametrize("dense_max", [400, 0]) -@pytest.mark.parametrize("merge_px", [0.0, 1.5]) -def test_local_fit_finds_separated_gaussians( - merge_px: float, dense_max: int, monkeypatch: pytest.MonkeyPatch -) -> None: - """The local fit finds the blobs the MATLAB fit finds, at their centres. - - With the dense (SVD) solver of small fits and with the sparse (lsmr) one - of large fits. - """ - from giant_python.extraction.raster import peaks - - monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:40, :50] - img = 0.05 * rng.standard_normal((40, 50)) - for r, c in ((10.3, 12.6), (28.0, 35.4)): - img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) - img[:, :2] = np.nan - pk = get_act_im_peaks(img, 8, fit="local", merge_px=merge_px) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) - - -def _split_prone_image() -> np.ndarray: - """Two sources as activity images show them. - - A peak narrower than a pixel on a wider base, on unit noise. - - Returns - ------- - np.ndarray - A 30 x 30 image with two such sources. - """ - rng = np.random.default_rng(0) - yy, xx = np.mgrid[:30, :30] - img = rng.standard_normal((30, 30)) - for r, c in ((10.5, 12.0), (20.2, 8.4)): - d2 = (yy - r) ** 2 + (xx - c) ** 2 - img += 40 * np.exp(-d2 / (2 * 0.45**2)) + 6 * np.exp(-d2 / 5.12) - return img - - -def test_local_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: - """A LAPACK SVD failure in a local fit's dense solver retries with the sparse one. - - And the seeds are found. - """ - from giant_python.extraction.raster import peaks - - calls = [] - real = peaks.least_squares - - def flaky(*args: object, **kwargs: object) -> OptimizeResult: - """least_squares whose dense (SVD) solver always fails. - - Returns - ------- - OptimizeResult - The result of the real least_squares when the dense solver is not requested. - - Raises - ------ - numpy.linalg.LinAlgError - If the dense solver (tr_solver="exact") is used. - """ - calls.append(kwargs.get("tr_solver")) - if kwargs.get("tr_solver") == "exact": - raise np.linalg.LinAlgError("SVD did not converge") - return real(*args, **kwargs) - - monkeypatch.setattr(peaks, "least_squares", flaky) - pk = get_act_im_peaks(_split_prone_image(), 3, fit="local", merge_px=1.5) - assert calls[:2] == ["exact", "lsmr"] - assert pk.shape[0] == 2 - - -@pytest.mark.parametrize("fit", ["matlab", "local"]) -def test_merge_keeps_one_seed_per_split_peak(fit: str) -> None: - """MATLAB's rule fits each source as several peaks less than 1.5 px apart. - - merge_px 1.5 keeps one per source, at the source. - """ - img = _split_prone_image() - assert get_act_im_peaks(img, 3, fit=fit).shape[0] > 2 - pk = get_act_im_peaks(img, 3, fit=fit, merge_px=1.5) - assert pk.shape[0] == 2 - order = np.argsort(pk[:, 1]) - np.testing.assert_allclose(pk[order, 1:3], [[10.5, 12.0], [20.2, 8.4]], atol=0.5) - - -def test_seed_fit_options_are_checked() -> None: - """Unknown fits and negative merge distances raise.""" - img = _split_prone_image() - with pytest.raises(ValueError): - get_act_im_peaks(img, 3, fit="other") - with pytest.raises(ValueError): - get_act_im_peaks(img, 3, merge_px=-1) +"""Tests of the getActImPeaks port (raster SiLo seeds).""" + +import numpy as np +import pytest +from scipy.optimize import OptimizeResult + +from giant_python.extraction.raster.peaks import ( + _eval_budget, + _IntegratedGaussians, + _WindowedGaussians, + get_act_im_peaks, + ordfilt3x3, +) + + +def test_ordfilt_matches_matlab() -> None: + """MATLAB ordfilt2(A, 9 or 8, ones(3)): zero padding, NaN windows.""" + a = np.array([[np.nan, 1, -2], [2, 3, -1], [-5, np.nan, 4]]) + nan = np.nan + np.testing.assert_array_equal( + ordfilt3x3(a, 9), [[nan, nan, 3], [nan, nan, nan], [nan, nan, nan]] + ) + np.testing.assert_array_equal( + ordfilt3x3(a, 8), [[nan, nan, 1], [nan, nan, nan], [nan, nan, nan]] + ) + np.testing.assert_array_equal(ordfilt3x3(np.array([[-1.0, -2], [-3, -4]]), 9), np.zeros((2, 2))) + + +def test_jacobian_matches_finite_differences() -> None: + """The analytical Jacobian of the integrated Gaussians is right.""" + yy, xx = np.mgrid[1:12, 1:14] + model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) + theta = np.array([3.0, 1.5, 5.2, 7.7, 4.1, 9.3, 1.1, 0.8]) + jac = model.jacobian(theta) + eps = 1e-6 + num = np.column_stack([ + (model.value(theta + eps * e) - model.value(theta - eps * e)) / (2 * eps) + for e in np.eye(theta.size) + ]) + np.testing.assert_allclose(jac, num, rtol=1e-5, atol=1e-8) + # the value-only path (no derivatives) is the Jacobian path's value + a, (vy, _, _), (vx, _, _) = model.parts(theta) + np.testing.assert_array_equal(model.value(theta), (vy * vx) @ a) + + +def test_finds_separated_gaussians() -> None: + """Two blobs on noise are found at their centres (0-based).""" + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:40, :50] + img = 0.05 * rng.standard_normal((40, 50)) + for r, c in ((10.3, 12.6), (28.0, 35.4)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + img[:, :2] = np.nan + pk = get_act_im_peaks(img, 8) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) + + +def test_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: + """A LAPACK SVD failure in the default solver retries with lsmr.""" + from giant_python.extraction.raster import peaks + + calls = [] + real = peaks.least_squares + + def flaky(*args: object, **kwargs: object) -> OptimizeResult: + """least_squares whose default (SVD) solver always fails. + + Returns + ------- + OptimizeResult + The result of the real least_squares when tr_solver is given. + + Raises + ------ + numpy.linalg.LinAlgError + If the default solver (no tr_solver) is used. + """ + calls.append(kwargs.get("tr_solver")) + if kwargs.get("tr_solver") is None: + raise np.linalg.LinAlgError("SVD did not converge") + return real(*args, **kwargs) + + monkeypatch.setattr(peaks, "least_squares", flaky) + yy, xx = np.mgrid[1:16, 1:16] + model = _IntegratedGaussians(yy.ravel() + 0.0, xx.ravel() + 0.0) + data = model.value(np.array([3.0, 7.4, 8.2, 1.2])) + theta = peaks._fit( + np.array([[2.0, 7.0, 8.0, 1.0]]), + yy.ravel() + 0.0, + xx.ravel() + 0.0, + data, + np.array([[0.0, 5.5, 6.5, 0.2]]), + np.array([[np.inf, 8.5, 9.5, 5.0]]), + ) + assert calls == [None, "lsmr"] + np.testing.assert_allclose(theta[0], [3.0, 7.4, 8.2, 1.2], atol=1e-3) + + +def test_exclusion_mask_and_empty() -> None: + """No seeds inside the exclusion mask; none in pure noise.""" + rng = np.random.default_rng(1) + yy, xx = np.mgrid[:30, :30] + img = 0.05 * rng.standard_normal((30, 30)) + img += 4 * np.exp(-((yy - 15) ** 2 + (xx - 15) ** 2) / 2) + mask = np.zeros((30, 30), bool) + mask[12:19, 12:19] = True + assert get_act_im_peaks(img, 8, mask).shape[0] == 0 + assert get_act_im_peaks(rng.standard_normal((30, 30)), 8).shape == (0, 4) + + +def test_no_fitted_centre_inside_the_exclusion_mask() -> None: + """A source whose centre is just inside the mask is dropped. + + It seeds on its unmasked flank, and its fit moves back into the mask: it + is dropped. A source clear of the mask is kept. + """ + rng = np.random.default_rng(2) + yy, xx = np.mgrid[:30, :40] + img = 0.05 * rng.standard_normal((30, 40)) + for r, c in ((15.0, 15.2), (15.0, 30.0)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + mask = np.zeros((30, 40), bool) + mask[:, 15:20] = True # the first source's centre and right flank + pk = get_act_im_peaks(img, 8, mask) + assert pk.shape[0] == 1 + np.testing.assert_allclose(pk[0, 1:3], [15.0, 30.0], atol=0.15) + unmasked = get_act_im_peaks(img, 8) + assert unmasked.shape[0] == 2 + + +def test_eval_budget_matches_matlab_iterations() -> None: + """MATLAB's 5000 evaluations with finite differences allow (5000 - 1) // (n + 1) iterations. + + The budget here allows as many steps (one evaluation each, plus the + start), down to one step at n = 2500. + """ + for n in (4, 40, 400, 2500, 4998): + assert _eval_budget(n) - 1 == (5000 - 1) // (n + 1) + assert _eval_budget(2500) == 2 # one step (was 1: none) + assert _eval_budget(5000) == 1 # MATLAB cannot take a step either + + +def test_rounding_is_matlabs() -> None: + """Halves round away from zero as in MATLAB (numpy rounds them to even). + + So a centre at exactly k + 0.5 lands on MATLAB's pixel. + """ + from giant_python.extraction.raster.peaks import _rounded_index + + theta = np.array([[1.0, 4.5, 2.5, 0.35], [1.0, 3.5, 7.49, 0.35]]) + iy, ix = _rounded_index(theta, (10, 10)) # 1-based in, 0-based out + np.testing.assert_array_equal(iy, [4, 3]) # MATLAB 5 and 4 + np.testing.assert_array_equal(ix, [2, 6]) # MATLAB 3 and 7 + + +def _windowed( + shape: tuple[int, int], starts: np.ndarray, window: int, rows: np.ndarray | None = None +) -> tuple[_WindowedGaussians, np.ndarray, np.ndarray]: + """Build a windowed model on a gap-free image, and the edges it uses. + + Returns + ------- + model : _WindowedGaussians + The windowed model over the pixels in rows. + ys : np.ndarray + Row coordinates (1-based) of those pixels. + xs : np.ndarray + Column coordinates (1-based) of those pixels. + """ + cols, rws = np.nonzero(np.ones(shape, bool).T) + idx = np.full(shape, -1, np.int64) + idx[rws, cols] = np.arange(rws.size) + edges = (rws + 0.5, rws + 1.5, cols + 0.5, cols + 1.5) + rows = np.arange(rws.size) if rows is None else rows + model = _WindowedGaussians(idx, edges, np.asarray(starts), window, rows) + return model, rws[rows] + 1.0, cols[rows] + 1.0 + + +def test_windowed_model_is_the_integrated_model_within_its_window() -> None: + """With windows covering the image, the windowed model is the dense one. + + Positions are offsets from the start pixels; its Jacobian, dense and + sparse, matches finite differences. + """ + starts = np.array([[4, 6], [9, 3]]) # 0-based start pixels + theta = np.array([[3.0, 5.4, 7.2, 0.7], [1.5, 9.8, 4.1, 1.1]]) + model, ys, xs = _windowed((12, 14), starts, 20) + x = np.concatenate([ + theta[:, 0], + theta[:, 1] - starts[:, 0] - 1, + theta[:, 2] - starts[:, 1] - 1, + theta[:, 3], + ]) + dense = _IntegratedGaussians(ys, xs).value(theta.ravel(order="F")) + np.testing.assert_allclose(model.value(x), dense, rtol=1e-12) + eps = 1e-6 + num = np.column_stack([ + (model.value(x + eps * e) - model.value(x - eps * e)) / (2 * eps) for e in np.eye(x.size) + ]) + np.testing.assert_allclose(model.jacobian(x, True), num, atol=1e-7) + np.testing.assert_allclose(model.jacobian(x, False).toarray(), num, atol=1e-7) + # a narrow window leaves the peak out of pixels beyond it + narrow, ys, xs = _windowed((12, 14), starts[:1], 2) + far = (np.abs(ys - 5) > 2) | (np.abs(xs - 7) > 2) + assert np.all(narrow.value(x[[0, 2, 4, 6]])[far] == 0) + + +@pytest.mark.parametrize("dense_max", [400, 0]) +@pytest.mark.parametrize("merge_px", [0.0, 1.5]) +def test_local_fit_finds_separated_gaussians( + merge_px: float, dense_max: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """The local fit finds the blobs the MATLAB fit finds, at their centres. + + With the dense (SVD) solver of small fits and with the sparse (lsmr) one + of large fits. + """ + from giant_python.extraction.raster import peaks + + monkeypatch.setattr(peaks, "_LOCAL_DENSE_MAX", dense_max) + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:40, :50] + img = 0.05 * rng.standard_normal((40, 50)) + for r, c in ((10.3, 12.6), (28.0, 35.4)): + img += 4 * np.exp(-((yy - r) ** 2 + (xx - c) ** 2) / (2 * 1.1**2)) + img[:, :2] = np.nan + pk = get_act_im_peaks(img, 8, fit="local", merge_px=merge_px) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.3, 12.6], [28.0, 35.4]], atol=0.15) + + +def _split_prone_image() -> np.ndarray: + """Two sources as activity images show them. + + A peak narrower than a pixel on a wider base, on unit noise. + + Returns + ------- + np.ndarray + A 30 x 30 image with two such sources. + """ + rng = np.random.default_rng(0) + yy, xx = np.mgrid[:30, :30] + img = rng.standard_normal((30, 30)) + for r, c in ((10.5, 12.0), (20.2, 8.4)): + d2 = (yy - r) ** 2 + (xx - c) ** 2 + img += 40 * np.exp(-d2 / (2 * 0.45**2)) + 6 * np.exp(-d2 / 5.12) + return img + + +def test_local_fit_falls_back_when_svd_fails(monkeypatch: pytest.MonkeyPatch) -> None: + """A LAPACK SVD failure in a local fit's dense solver retries with the sparse one. + + And the seeds are found. + """ + from giant_python.extraction.raster import peaks + + calls = [] + real = peaks.least_squares + + def flaky(*args: object, **kwargs: object) -> OptimizeResult: + """least_squares whose dense (SVD) solver always fails. + + Returns + ------- + OptimizeResult + The result of the real least_squares when the dense solver is not requested. + + Raises + ------ + numpy.linalg.LinAlgError + If the dense solver (tr_solver="exact") is used. + """ + calls.append(kwargs.get("tr_solver")) + if kwargs.get("tr_solver") == "exact": + raise np.linalg.LinAlgError("SVD did not converge") + return real(*args, **kwargs) + + monkeypatch.setattr(peaks, "least_squares", flaky) + pk = get_act_im_peaks(_split_prone_image(), 3, fit="local", merge_px=1.5) + assert calls[:2] == ["exact", "lsmr"] + assert pk.shape[0] == 2 + + +@pytest.mark.parametrize("fit", ["matlab", "local"]) +def test_merge_keeps_one_seed_per_split_peak(fit: str) -> None: + """MATLAB's rule fits each source as several peaks less than 1.5 px apart. + + merge_px 1.5 keeps one per source, at the source. + """ + img = _split_prone_image() + assert get_act_im_peaks(img, 3, fit=fit).shape[0] > 2 + pk = get_act_im_peaks(img, 3, fit=fit, merge_px=1.5) + assert pk.shape[0] == 2 + order = np.argsort(pk[:, 1]) + np.testing.assert_allclose(pk[order, 1:3], [[10.5, 12.0], [20.2, 8.4]], atol=0.5) + + +def test_seed_fit_options_are_checked() -> None: + """Unknown fits and negative merge distances raise.""" + img = _split_prone_image() + with pytest.raises(ValueError): + get_act_im_peaks(img, 3, fit="other") + with pytest.raises(ValueError): + get_act_im_peaks(img, 3, merge_px=-1) diff --git a/tests/raster/test_raster_refit.py b/tests/raster/test_raster_refit.py index 02f736c9..0739a805 100644 --- a/tests/raster/test_raster_refit.py +++ b/tests/raster/test_raster_refit.py @@ -1,351 +1,351 @@ -"""Tests of the ground-truth refit test of the subproblem solver.""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.refit_test import ( - RefitTruth, - blur_error, - by_size, - draw_refit_data, - drift_error, - edge_error, - find_events, - refit_test, - scale_error, - score_refit, - shared_component, - summarize, -) -from giant_python.extraction.raster.solver import ( - SolverOptions, - solve_subproblem, -) -from giant_python.extraction.raster.solver_baseline import source_f0 -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -# MATLAB's 3 x 3 support, which the MATLAB subproblem's thresholds below -# were set with (the default is 5 x 5) -PARAMS = SolverParams(valid_kernel=3) - - -def test_find_events() -> None: - """Peaks above 2% of the largest are events. - - They are at least the lag after the previous peak (kept or not), away from - the trial's ends. - """ - x = np.zeros(60) - x[[2, 10, 14, 17, 30, 31, 44, 55]] = [5, 4, 3, 6, 0.05, 2, 1, 9] - # frame 2 is within 5 of the start; 14 and 17 follow a peak within the - # lag of 5; 30 is below 2% of 9, and not a maximum next to 31; 55 is - # within lag + 3 of the end - assert find_events(x, 5).tolist() == [10, 31, 44] - assert find_events(x, 3).tolist() == [10, 14, 17, 31, 44] - assert find_events(np.zeros(30), 5).size == 0 - # a plateau counts once, at its last frame - y = np.zeros(40) - y[[20, 21]] = 3.0 - assert find_events(y, 5).tolist() == [21] - - -def _truth(x: np.ndarray, h: np.ndarray | None = None) -> RefitTruth: - """Build a truth with the given activity, flat baseline and F0. - - Returns - ------- - RefitTruth - The truth with activity x, the weights h (a default if None), a flat baseline of - 2, a flat F0 of 4 and zero data. - """ - n_src, n_t = x.shape - if h is None: - h = np.array([[0.5], [0.3], [0.2]])[:, :n_src] - return RefitTruth( - h=h, - x=x, - b=np.full((h.shape[0], n_t), 2.0), - f0=np.full((n_src, n_t), 4.0), - z=np.zeros((h.shape[0], n_t)), - ) - - -def test_score_refit_of_a_perfect_and_a_scaled_refit() -> None: - """A refit equal to the truth recovers everything. - - A refit at half the size and with one event missing is scored as such. - """ - k = np.exp(-np.arange(12) / 4.8) - x = np.zeros((1, 120)) - for t, a in ((20, 2.0), (60, 8.0), (95, 1.0)): - x[0, t : t + 12] += a * k - truth = _truth(x) - f0, ls = truth.f0, x.copy() - src, ev = score_refit(truth, x, f0, ls, 4.8) - assert src[0]["recovered"] == pytest.approx(1.0) - assert src[0]["slope"] == pytest.approx(1.0) - assert src[0]["f0_ratio"] == src[0]["f0_ratio_active"] == 1.0 - assert src[0]["baseline"] == pytest.approx(2.0) - assert src[0]["peak_h"] == 0.5 - assert [e["found"] for e in ev] == [True] * 3 - assert [e["size"] for e in ev] == pytest.approx([1.0, 4.0, 0.5]) - for e in ev: - assert e["refit_mass"] == pytest.approx(e["true_mass"]) - - half = 0.5 * x - half[0, 90:] = 0 # the last event is missed - src, ev = score_refit(truth, half, 1.1 * f0, 2 * ls, 4.8) - assert src[0]["f0_ratio"] == pytest.approx(1.1) - assert src[0]["ls_recovered"] == pytest.approx(2.0) - assert [e["found"] for e in ev] == [True, True, False] - assert ev[0]["refit_mass"] == pytest.approx(0.5 * ev[0]["true_mass"]) - rows = by_size(ev) - assert [(r["size_from"], r["n"]) for r in rows] == [ - (0.5, 1), - (1.0, 1), - (4.0, 1), - ] - assert rows[0]["share_found"] == 0 and np.isnan(rows[0]["recovered_found"]) - assert rows[1]["recovered_found"] == pytest.approx(0.5) - summary = summarize(src, ev) - assert summary["n_sources"] == 1 and summary["n_events"] == 3 - assert 0.3 < summary["pooled"] < 0.5 - - -def test_score_refit_of_a_silent_source() -> None: - """A source without true activity has no events and NaN recovery.""" - truth = _truth(np.zeros((1, 50))) - src, ev = score_refit(truth, np.zeros((1, 50)), truth.f0, truth.x, 4.8) - assert ev == [] and np.isnan(src[0]["recovered"]) - assert np.isnan(src[0]["f0_ratio_active"]) - assert np.isnan(summarize(src, ev)["pooled"]) - - -def test_refit_test_on_a_real_subproblem() -> None: - """The refit of data redrawn from a real subproblem's fit recovers the events it finds. - - The subproblem is a dim one, 5 s long, most events below one unit; the same - seed gives the same data. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - r = refit_test([sub], PARAMS, SolverOptions(), seed=3, keep_truths=True) - s = r.summary - assert s["n_sources"] == 2 and s["n_events"] >= 20 - assert len(r.sources) == 2 and len(r.events) == s["n_events"] - assert all(row["subproblem"] == 0 for row in r.sources + r.events) - assert 0.3 < s["recovered"] < 1.2 and 0.3 < s["pooled"] < 1.2 - assert 1.0 < s["f0_ratio"] < 1.3 - found = np.mean([e["found"] for e in r.events]) - assert found > 0.25 - many = [row for row in r.by_size if row["n"] >= 10] - assert many and all(0.6 < row["recovered_found"] < 1.2 for row in many) - truth = r.truths[0] - assert truth.z.shape == sub.finv.shape and truth.z.min() >= 0 - # the redrawn data have the truth's mean - mean = truth.b + truth.h @ truth.x - assert truth.z.mean() == pytest.approx(mean.mean(), rel=0.02) - again = refit_test([sub], PARAMS, seed=3, keep_truths=True) - assert np.array_equal(again.truths[0].z, truth.z) - assert refit_test([sub], PARAMS, seed=4).truths == [] - # the truth of a redraw needs its baseline - fit = solve_subproblem(sub, PARAMS) - with pytest.raises(ValueError, match="keep_baseline"): - draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0)) - - -def _crop_truth(n_t: int = 40) -> tuple[Subproblem, RefitTruth]: - """Build a truth on a 4 x 5 crop with a baseline that varies over pixels. - - Returns - ------- - sub : Subproblem - The crop's subproblem, with one source. - truth : RefitTruth - The truth, with a baseline that varies over pixels. - """ - sel = np.ones((4, 5), bool) - sub = Subproblem( - y=np.ones((1, 20, n_t)), - finv=np.ones((20, n_t)), - sel=sel, - sources_rc=np.array([[1, 2]]), - ) - b = np.outer(np.arange(1.0, 21.0), np.ones(n_t)) - truth = RefitTruth( - h=np.full((20, 1), 0.05), - x=np.zeros((1, n_t)), - b=b, - f0=np.full((1, n_t), 4.0), - z=np.zeros((20, n_t)), - ) - return sub, truth - - -def test_baseline_errors() -> None: - """Scale, drift, trial-edge and blur errors of the true baseline.""" - sub, truth = _crop_truth() - rng = np.random.default_rng(0) - b = truth.b - np.testing.assert_allclose(scale_error(-0.05)(truth, sub, rng), 0.95 * b) - d = drift_error(0.1)(truth, sub, rng) - np.testing.assert_allclose(d[:, 0], 0.95 * b[:, 0]) - np.testing.assert_allclose(d[:, -1], 1.05 * b[:, -1]) - np.testing.assert_allclose(d.mean(1), b.mean(1)) - e = edge_error(0.03, 5)(truth, sub, rng) - np.testing.assert_allclose(e[:, :5], 1.03 * b[:, :5]) - np.testing.assert_allclose(e[:, -5:], 1.03 * b[:, -5:]) - np.testing.assert_allclose(e[:, 5:-5], b[:, 5:-5]) - # a flat baseline stays flat when blurred, edges included - flat = RefitTruth(truth.h, truth.x, np.full_like(b, 3.0), truth.f0, b) - np.testing.assert_allclose(blur_error(1.0)(flat, sub, rng), 3.0) - blurred = blur_error(1.0)(truth, sub, rng) - assert blurred.shape == b.shape - assert np.ptp(blurred[:, 0]) < np.ptp(b[:, 0]) - np.testing.assert_allclose(blurred.mean(), b.mean(), rtol=0.05) - - -def test_shared_component() -> None: - """A shared fast change of the given root mean square. - - It is the same for every pixel, reproducible from its generator. - """ - sub, truth = _crop_truth(n_t=4000) - change = shared_component(0.02) - b1 = change(truth.b, sub, np.random.default_rng(5)) - course = b1 / truth.b - 1 - np.testing.assert_allclose(course, course[:1].repeat(20, 0)) - assert np.sqrt(np.mean(course[0] ** 2)) == pytest.approx(0.02) - # smoothed: neighbouring frames are correlated - assert np.corrcoef(course[0, :-1], course[0, 1:])[0, 1] > 0.6 - b2 = change(truth.b, sub, np.random.default_rng(5)) - np.testing.assert_array_equal(b1, b2) - - -def test_refit_test_with_a_given_baseline() -> None: - """The refit can get the true baseline, or one with an error. - - The truth's baseline can carry a shared change that the given one lacks; - the truth fits can be passed in. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - opt = SolverOptions(keep_baseline=True) - fit = solve_subproblem(sub, PARAMS, opt) - fixed = replace(PARAMS, baseline_mode="fixed") - exact = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - given_baseline=scale_error(0.0), - keep_truths=True, - ) - plain = refit_test([sub], PARAMS, opt, seed=2, keep_truths=True) - # the same draws whatever the refit gets - np.testing.assert_array_equal(exact.truths[0].z, plain.truths[0].z) - high = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - given_baseline=scale_error(0.1), - ) - assert high.summary["pooled"] < exact.summary["pooled"] - assert high.summary["f0_ratio"] > exact.summary["f0_ratio"] + 0.01 - shared = refit_test( - [sub], - PARAMS, - opt, - refit_params=fixed, - seed=2, - fits=[fit], - truth_baseline=shared_component(0.05), - keep_truths=True, - ) - tr = shared.truths[0] - np.testing.assert_array_equal(tr.b_fit, fit.baseline[0]) - assert not np.allclose(tr.b, tr.b_fit) - np.testing.assert_allclose(tr.f0, source_f0(tr.h, tr.b)) - with pytest.raises(ValueError, match="fits for"): - refit_test([sub], PARAMS, opt, fits=[fit, fit]) - - -def test_edge_error_scales_overlapping_ends_once() -> None: - """In a trial shorter than both windows, every frame is scaled once.""" - sub, truth = _crop_truth(n_t=10) - b = edge_error(0.1, 6)(truth, sub, np.random.default_rng(0)) - np.testing.assert_allclose(b, 1.1 * truth.b) - - -def test_refit_keeps_the_subproblems_own_baseline() -> None: - """Without a given_baseline the refit keeps each subproblem's own baseline. - - It keeps the external baseline, so network modes can be refitted. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - opt = SolverOptions(keep_baseline=True) - fit = solve_subproblem(sub, PARAMS, opt) - own = replace(sub, baseline=fit.baseline[0], _coords=None) - gain = replace(PARAMS, baseline_mode="gain") - r = refit_test([own], gain, opt, seed=1) - assert r.summary["n_sources"] == 2 - with pytest.raises(ValueError, match="Subproblem.baseline"): - refit_test([sub], gain, opt, seed=1) - - -def test_truth_baseline_gets_a_copy() -> None: - """An in-place change of the true baseline leaves the fit unchanged.""" - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - fit = solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) - before = fit.baseline.copy() - - def in_place(b: np.ndarray, sub: Subproblem, rng: np.random.Generator) -> np.ndarray: - """Scale the given array itself. - - Returns - ------- - np.ndarray - The same array b, scaled by 1.5 in place. - """ - b *= 1.5 - return b - - tr = draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0), truth_baseline=in_place) - np.testing.assert_array_equal(fit.baseline, before) - np.testing.assert_array_equal(tr.b_fit, before[0]) - np.testing.assert_allclose(tr.b, 1.5 * before[0]) +"""Tests of the ground-truth refit test of the subproblem solver.""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.refit_test import ( + RefitTruth, + blur_error, + by_size, + draw_refit_data, + drift_error, + edge_error, + find_events, + refit_test, + scale_error, + score_refit, + shared_component, + summarize, +) +from giant_python.extraction.raster.solver import ( + SolverOptions, + solve_subproblem, +) +from giant_python.extraction.raster.solver_baseline import source_f0 +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +# MATLAB's 3 x 3 support, which the MATLAB subproblem's thresholds below +# were set with (the default is 5 x 5) +PARAMS = SolverParams(valid_kernel=3) + + +def test_find_events() -> None: + """Peaks above 2% of the largest are events. + + They are at least the lag after the previous peak (kept or not), away from + the trial's ends. + """ + x = np.zeros(60) + x[[2, 10, 14, 17, 30, 31, 44, 55]] = [5, 4, 3, 6, 0.05, 2, 1, 9] + # frame 2 is within 5 of the start; 14 and 17 follow a peak within the + # lag of 5; 30 is below 2% of 9, and not a maximum next to 31; 55 is + # within lag + 3 of the end + assert find_events(x, 5).tolist() == [10, 31, 44] + assert find_events(x, 3).tolist() == [10, 14, 17, 31, 44] + assert find_events(np.zeros(30), 5).size == 0 + # a plateau counts once, at its last frame + y = np.zeros(40) + y[[20, 21]] = 3.0 + assert find_events(y, 5).tolist() == [21] + + +def _truth(x: np.ndarray, h: np.ndarray | None = None) -> RefitTruth: + """Build a truth with the given activity, flat baseline and F0. + + Returns + ------- + RefitTruth + The truth with activity x, the weights h (a default if None), a flat baseline of + 2, a flat F0 of 4 and zero data. + """ + n_src, n_t = x.shape + if h is None: + h = np.array([[0.5], [0.3], [0.2]])[:, :n_src] + return RefitTruth( + h=h, + x=x, + b=np.full((h.shape[0], n_t), 2.0), + f0=np.full((n_src, n_t), 4.0), + z=np.zeros((h.shape[0], n_t)), + ) + + +def test_score_refit_of_a_perfect_and_a_scaled_refit() -> None: + """A refit equal to the truth recovers everything. + + A refit at half the size and with one event missing is scored as such. + """ + k = np.exp(-np.arange(12) / 4.8) + x = np.zeros((1, 120)) + for t, a in ((20, 2.0), (60, 8.0), (95, 1.0)): + x[0, t : t + 12] += a * k + truth = _truth(x) + f0, ls = truth.f0, x.copy() + src, ev = score_refit(truth, x, f0, ls, 4.8) + assert src[0]["recovered"] == pytest.approx(1.0) + assert src[0]["slope"] == pytest.approx(1.0) + assert src[0]["f0_ratio"] == src[0]["f0_ratio_active"] == 1.0 + assert src[0]["baseline"] == pytest.approx(2.0) + assert src[0]["peak_h"] == 0.5 + assert [e["found"] for e in ev] == [True] * 3 + assert [e["size"] for e in ev] == pytest.approx([1.0, 4.0, 0.5]) + for e in ev: + assert e["refit_mass"] == pytest.approx(e["true_mass"]) + + half = 0.5 * x + half[0, 90:] = 0 # the last event is missed + src, ev = score_refit(truth, half, 1.1 * f0, 2 * ls, 4.8) + assert src[0]["f0_ratio"] == pytest.approx(1.1) + assert src[0]["ls_recovered"] == pytest.approx(2.0) + assert [e["found"] for e in ev] == [True, True, False] + assert ev[0]["refit_mass"] == pytest.approx(0.5 * ev[0]["true_mass"]) + rows = by_size(ev) + assert [(r["size_from"], r["n"]) for r in rows] == [ + (0.5, 1), + (1.0, 1), + (4.0, 1), + ] + assert rows[0]["share_found"] == 0 and np.isnan(rows[0]["recovered_found"]) + assert rows[1]["recovered_found"] == pytest.approx(0.5) + summary = summarize(src, ev) + assert summary["n_sources"] == 1 and summary["n_events"] == 3 + assert 0.3 < summary["pooled"] < 0.5 + + +def test_score_refit_of_a_silent_source() -> None: + """A source without true activity has no events and NaN recovery.""" + truth = _truth(np.zeros((1, 50))) + src, ev = score_refit(truth, np.zeros((1, 50)), truth.f0, truth.x, 4.8) + assert ev == [] and np.isnan(src[0]["recovered"]) + assert np.isnan(src[0]["f0_ratio_active"]) + assert np.isnan(summarize(src, ev)["pooled"]) + + +def test_refit_test_on_a_real_subproblem() -> None: + """The refit of data redrawn from a real subproblem's fit recovers the events it finds. + + The subproblem is a dim one, 5 s long, most events below one unit; the same + seed gives the same data. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + r = refit_test([sub], PARAMS, SolverOptions(), seed=3, keep_truths=True) + s = r.summary + assert s["n_sources"] == 2 and s["n_events"] >= 20 + assert len(r.sources) == 2 and len(r.events) == s["n_events"] + assert all(row["subproblem"] == 0 for row in r.sources + r.events) + assert 0.3 < s["recovered"] < 1.2 and 0.3 < s["pooled"] < 1.2 + assert 1.0 < s["f0_ratio"] < 1.3 + found = np.mean([e["found"] for e in r.events]) + assert found > 0.25 + many = [row for row in r.by_size if row["n"] >= 10] + assert many and all(0.6 < row["recovered_found"] < 1.2 for row in many) + truth = r.truths[0] + assert truth.z.shape == sub.finv.shape and truth.z.min() >= 0 + # the redrawn data have the truth's mean + mean = truth.b + truth.h @ truth.x + assert truth.z.mean() == pytest.approx(mean.mean(), rel=0.02) + again = refit_test([sub], PARAMS, seed=3, keep_truths=True) + assert np.array_equal(again.truths[0].z, truth.z) + assert refit_test([sub], PARAMS, seed=4).truths == [] + # the truth of a redraw needs its baseline + fit = solve_subproblem(sub, PARAMS) + with pytest.raises(ValueError, match="keep_baseline"): + draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0)) + + +def _crop_truth(n_t: int = 40) -> tuple[Subproblem, RefitTruth]: + """Build a truth on a 4 x 5 crop with a baseline that varies over pixels. + + Returns + ------- + sub : Subproblem + The crop's subproblem, with one source. + truth : RefitTruth + The truth, with a baseline that varies over pixels. + """ + sel = np.ones((4, 5), bool) + sub = Subproblem( + y=np.ones((1, 20, n_t)), + finv=np.ones((20, n_t)), + sel=sel, + sources_rc=np.array([[1, 2]]), + ) + b = np.outer(np.arange(1.0, 21.0), np.ones(n_t)) + truth = RefitTruth( + h=np.full((20, 1), 0.05), + x=np.zeros((1, n_t)), + b=b, + f0=np.full((1, n_t), 4.0), + z=np.zeros((20, n_t)), + ) + return sub, truth + + +def test_baseline_errors() -> None: + """Scale, drift, trial-edge and blur errors of the true baseline.""" + sub, truth = _crop_truth() + rng = np.random.default_rng(0) + b = truth.b + np.testing.assert_allclose(scale_error(-0.05)(truth, sub, rng), 0.95 * b) + d = drift_error(0.1)(truth, sub, rng) + np.testing.assert_allclose(d[:, 0], 0.95 * b[:, 0]) + np.testing.assert_allclose(d[:, -1], 1.05 * b[:, -1]) + np.testing.assert_allclose(d.mean(1), b.mean(1)) + e = edge_error(0.03, 5)(truth, sub, rng) + np.testing.assert_allclose(e[:, :5], 1.03 * b[:, :5]) + np.testing.assert_allclose(e[:, -5:], 1.03 * b[:, -5:]) + np.testing.assert_allclose(e[:, 5:-5], b[:, 5:-5]) + # a flat baseline stays flat when blurred, edges included + flat = RefitTruth(truth.h, truth.x, np.full_like(b, 3.0), truth.f0, b) + np.testing.assert_allclose(blur_error(1.0)(flat, sub, rng), 3.0) + blurred = blur_error(1.0)(truth, sub, rng) + assert blurred.shape == b.shape + assert np.ptp(blurred[:, 0]) < np.ptp(b[:, 0]) + np.testing.assert_allclose(blurred.mean(), b.mean(), rtol=0.05) + + +def test_shared_component() -> None: + """A shared fast change of the given root mean square. + + It is the same for every pixel, reproducible from its generator. + """ + sub, truth = _crop_truth(n_t=4000) + change = shared_component(0.02) + b1 = change(truth.b, sub, np.random.default_rng(5)) + course = b1 / truth.b - 1 + np.testing.assert_allclose(course, course[:1].repeat(20, 0)) + assert np.sqrt(np.mean(course[0] ** 2)) == pytest.approx(0.02) + # smoothed: neighbouring frames are correlated + assert np.corrcoef(course[0, :-1], course[0, 1:])[0, 1] > 0.6 + b2 = change(truth.b, sub, np.random.default_rng(5)) + np.testing.assert_array_equal(b1, b2) + + +def test_refit_test_with_a_given_baseline() -> None: + """The refit can get the true baseline, or one with an error. + + The truth's baseline can carry a shared change that the given one lacks; + the truth fits can be passed in. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + opt = SolverOptions(keep_baseline=True) + fit = solve_subproblem(sub, PARAMS, opt) + fixed = replace(PARAMS, baseline_mode="fixed") + exact = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + given_baseline=scale_error(0.0), + keep_truths=True, + ) + plain = refit_test([sub], PARAMS, opt, seed=2, keep_truths=True) + # the same draws whatever the refit gets + np.testing.assert_array_equal(exact.truths[0].z, plain.truths[0].z) + high = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + given_baseline=scale_error(0.1), + ) + assert high.summary["pooled"] < exact.summary["pooled"] + assert high.summary["f0_ratio"] > exact.summary["f0_ratio"] + 0.01 + shared = refit_test( + [sub], + PARAMS, + opt, + refit_params=fixed, + seed=2, + fits=[fit], + truth_baseline=shared_component(0.05), + keep_truths=True, + ) + tr = shared.truths[0] + np.testing.assert_array_equal(tr.b_fit, fit.baseline[0]) + assert not np.allclose(tr.b, tr.b_fit) + np.testing.assert_allclose(tr.f0, source_f0(tr.h, tr.b)) + with pytest.raises(ValueError, match="fits for"): + refit_test([sub], PARAMS, opt, fits=[fit, fit]) + + +def test_edge_error_scales_overlapping_ends_once() -> None: + """In a trial shorter than both windows, every frame is scaled once.""" + sub, truth = _crop_truth(n_t=10) + b = edge_error(0.1, 6)(truth, sub, np.random.default_rng(0)) + np.testing.assert_allclose(b, 1.1 * truth.b) + + +def test_refit_keeps_the_subproblems_own_baseline() -> None: + """Without a given_baseline the refit keeps each subproblem's own baseline. + + It keeps the external baseline, so network modes can be refitted. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + opt = SolverOptions(keep_baseline=True) + fit = solve_subproblem(sub, PARAMS, opt) + own = replace(sub, baseline=fit.baseline[0], _coords=None) + gain = replace(PARAMS, baseline_mode="gain") + r = refit_test([own], gain, opt, seed=1) + assert r.summary["n_sources"] == 2 + with pytest.raises(ValueError, match="Subproblem.baseline"): + refit_test([sub], gain, opt, seed=1) + + +def test_truth_baseline_gets_a_copy() -> None: + """An in-place change of the true baseline leaves the fit unchanged.""" + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + fit = solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) + before = fit.baseline.copy() + + def in_place(b: np.ndarray, sub: Subproblem, rng: np.random.Generator) -> np.ndarray: + """Scale the given array itself. + + Returns + ------- + np.ndarray + The same array b, scaled by 1.5 in place. + """ + b *= 1.5 + return b + + tr = draw_refit_data(sub, fit, PARAMS, np.random.default_rng(0), truth_baseline=in_place) + np.testing.assert_array_equal(fit.baseline, before) + np.testing.assert_array_equal(tr.b_fit, before[0]) + np.testing.assert_allclose(tr.b, 1.5 * before[0]) diff --git a/tests/raster/test_raster_seed_acceptance.py b/tests/raster/test_raster_seed_acceptance.py index 60a12f52..a5a99c9d 100644 --- a/tests/raster/test_raster_seed_acceptance.py +++ b/tests/raster/test_raster_seed_acceptance.py @@ -1,477 +1,477 @@ -"""Tests of the seed threshold set from the combined image's null. - -That is seed_acceptance='null' (GIAnT-Python#51); also tests of the null -images that carry it from the localize stage to the plan stage. -""" - -from pathlib import Path - -import numpy as np -import pytest -from scipy import ndimage - -from giant_python.extraction.raster.peaks import get_act_im_peaks, ordfilt3x3 -from giant_python.extraction.raster.plan import ( - PlanParams, - TrialImages, - combined_activity_image, - combined_null_image, - plan_path, -) -from giant_python.extraction.raster.seeding import ( - candidate_statistic, - null_background, - null_threshold, - seed_sources, -) -from giant_python.extraction.raster.stage_files import ( - read_localization, - write_localization, -) -from giant_python.models.params import SiloParams - - -def _noise_field( - rng: np.random.Generator, shape: tuple[int, int] = (120, 140), sigma: float = 1.3 -) -> np.ndarray: - """Smoothed Gaussian noise: a stand-in for a null activity image. - - Returns - ------- - np.ndarray - The noise image of the given shape. - """ - return ndimage.gaussian_filter(rng.standard_normal(shape), sigma) - - -def test_candidate_statistic_is_the_seeding_rule() -> None: - """Maxima whose second-largest neighbour exceeds a threshold are the candidates. - - They are exactly get_act_im_peaks' candidates. - """ - rng = np.random.default_rng(0) - im = _noise_field(rng) - im[:3] = np.nan - excl = np.zeros(im.shape, bool) - excl[50:60, 50:60] = True - rc, value = candidate_statistic(im, excl) - th = np.quantile(value, 0.9) - explored = im * ~excl - with np.errstate(invalid="ignore"): - cand = (ordfilt3x3(explored, 8) > th) & (explored == ordfilt3x3(explored, 9)) - mine = np.zeros(im.shape, bool) - mine[tuple(rc[value > th].T)] = True - np.testing.assert_array_equal(mine, cand) - assert not excl[tuple(rc.T)].any() - - -def test_null_threshold_gives_the_expected_false_seeds() -> None: - """A null threshold gives about the requested false candidates per field. - - A threshold set on one null field for 2 false candidates per field is - crossed about twice per field on independent fields of the same noise; a - lax target is read off the null, a strict one extrapolated. - """ - rng = np.random.default_rng(1) - fields = [_noise_field(rng) for _ in range(41)] - (mu, sd), th, info = null_threshold(np.stack(fields[:4]), 2.0) - assert info["extrapolated"] and info["draws"] == 4 - counts = [np.sum((candidate_statistic(f)[1] - mu) / sd > th) for f in fields[4:]] - assert 1.0 < np.mean(counts) < 4.0 - _, th_lax, info_lax = null_threshold(fields[0], 200.0) - assert not info_lax["extrapolated"] - assert np.sum((candidate_statistic(fields[0])[1] - mu) / sd > th_lax) <= 210 - _, th_strict, _ = null_threshold(fields[0], 0.1) - assert th_strict > th_lax - with pytest.raises(ValueError): - null_threshold(fields[0], 0.0) - with pytest.raises(ValueError): - null_threshold(np.zeros((20, 20)), 1.0) - - -def test_background_override() -> None: - """The image's own median and robust SD as the background reproduce MATLAB's threshold. - - A doubled scale with half the threshold does too. - """ - rng = np.random.default_rng(2) - im = _noise_field(rng, (60, 60)) * 0.2 - for r, c in ((15, 15), (30, 44), (45, 20)): - im[r - 2 : r + 3, c - 2 : c + 3] += 3 * np.exp( - -np.add.outer(np.arange(-2, 3) ** 2, np.arange(-2, 3) ** 2) / 2 - ) - v = im[np.isfinite(im)] - mu = np.median(v) - sd = np.median(np.abs(v - mu)) / 0.6741891400433162 - ref = get_act_im_peaks(im, 5.0, fit="local") - same = get_act_im_peaks(im, 5.0, fit="local", background=(mu, sd)) - half = get_act_im_peaks(im, 2.5, fit="local", background=(mu, 2 * sd)) - np.testing.assert_allclose(same, ref) - np.testing.assert_allclose(half, ref) - assert ref.shape[0] == 3 - with pytest.raises(ValueError): - get_act_im_peaks(im, 5.0, background=(0.0, 0.0)) - - -def test_seed_sources_with_the_null() -> None: - """acceptance='null' seeds at the null's threshold and reports it. - - It needs the null image. - """ - rng = np.random.default_rng(3) - im = _noise_field(rng, (80, 80)) - g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) - im[37:44, 37:44] += 3.0 * g # a source well above the noise (SD ~0.2) - null = np.stack([_noise_field(rng, (80, 80)) for _ in range(2)]) - info = {} - seeds = seed_sources( - im, - 99.0, - fit="local", - acceptance="null", - null_im=null, - false_per_field=1.0, - info=info, - ) - bg, th, _ = null_threshold(null, 1.0) - np.testing.assert_allclose(seeds, get_act_im_peaks(im, th, fit="local", background=bg)) - assert info["peak_th"] == pytest.approx(th) and info["draws"] == 2 - assert np.hypot(*(seeds[:, 1:3] - 40).T).min() < 1.0 - with pytest.raises(ValueError): - seed_sources(im, 3.0, acceptance="null") - with pytest.raises(ValueError): - seed_sources(im, 3.0, acceptance="robust") - info = {} - seed_sources(im, 3.0, fit="local", info=info) - assert info == {"peak_th": 3.0, "background": None} - - -def test_combined_null_is_combined_like_the_image() -> None: - """Null images equal to the activity images combine to the combined activity image. - - Same scale, mask and median subtraction. - """ - rng = np.random.default_rng(4) - act = np.stack([np.abs(_noise_field(rng, (30, 40))) * 50 for _ in range(4)]) - act[1, :2] = np.nan - im, _, _ = combined_activity_image(act, 0.33) - null = combined_null_image(act[:, None], act, 0.33) - assert null.shape == (1, 30, 40) - np.testing.assert_allclose(null[0], im, equal_nan=True) - - -def _trials( - rng: np.random.Generator, - n: int = 3, - shape: tuple[int, int] = (48, 52), - null: bool = True, -) -> list[TrialImages]: - """Trials of one structured mean image with noise activity images. - - Returns - ------- - list of TrialImages - n trials sharing a mean image, each with a noise activity image - and, when null is true, a noise null image. - """ - base = ndimage.gaussian_filter(rng.random(shape), 2) * 100 + 10 - out = [] - for _ in range(n): - act = np.abs(_noise_field(rng, shape)) - act[20, 20] += 5 - nul = np.abs(_noise_field(rng, shape))[None] if null else None - out.append(TrialImages(base[..., None] + rng.random(shape + (1,)), act, null_im=nul)) - return out - - -def test_plan_with_null_acceptance() -> None: - """The plan seeds with the trials' null images and reports the threshold. - - Without null images it refuses. - """ - rng = np.random.default_rng(5) - trials = _trials(rng) - det = {} - p = PlanParams( - seed_acceptance="null", - seed_false_per_field=2.0, - inter_trial_alignment="rigid", - ) - plan = plan_path(trials, params=p, details=det) - assert det["null_im"].shape == (1,) + plan.shape - assert det["seed_info"]["draws"] == 1 and det["seed_info"]["background"] - det0 = {} - plan_path(trials, params=PlanParams(inter_trial_alignment="rigid"), details=det0) - assert det0["seed_info"]["background"] is None and "null_im" not in det0 - with pytest.raises(ValueError, match="null images"): - plan_path(_trials(rng, null=False), params=p) - with pytest.raises(ValueError): - PlanParams(seed_acceptance="robust") - with pytest.raises(ValueError): - PlanParams(seed_false_per_field=0) - - -def test_null_images_round_trip(tmp_path: Path) -> None: - """Localization files keep the null images when given.""" - rng = np.random.default_rng(6) - act = rng.random((6, 7)) - null = rng.random((2, 6, 7)).astype(np.float32) - path = tmp_path / "loc.h5" - write_localization( - path, - rng.random((6, 7, 1)), - act, - act, - np.zeros(5, bool), - None, - {}, - None, - null, - ) - rec = read_localization(path) - np.testing.assert_array_equal(rec.null_im, null) - assert rec.attrs["null_im"] == 1 - np.testing.assert_array_equal(rec.trial_images().null_im, null) - write_localization(path, rng.random((6, 7, 1)), act, act, np.zeros(5, bool), None, {}) - assert read_localization(path).null_im is None - - -def test_silo_params_null_acceptance() -> None: - """The localization keeps null images exactly when the seeding needs them (unless set). - - Both need the bootstrap null; defaults leave the stage hashes and MATLAB's - fields alone. - """ - default = SiloParams() - assert default.seed_acceptance == "image" - assert default.localization_keep_null is False - net = SiloParams(baseline_source="network", seed_acceptance="null") - assert net.localization_keep_null is True - assert net.plan_params().seed_acceptance == "null" - assert "localization_keep_null" in net.stage_settings("localize") - assert "seed_acceptance" in net.stage_settings("plan") - assert "localization_keep_null" not in SiloParams(baseline_source="network").stage_settings( - "localize" - ) - m = net.to_matlab(2, 80.0) - assert m["seedAcceptance"] == "null" and m["localizationKeepNull"] - assert "seedAcceptance" not in default.to_matlab(2, 80.0) - keep = SiloParams(baseline_source="network", localization_keep_null=True) - assert keep.seed_acceptance == "image" and keep.localization_keep_null - for bad in ( - {"seed_acceptance": "null"}, # no bootstrap null - { - "baseline_source": "network", - "seed_acceptance": "null", - "localization_keep_null": False, - }, - {"baseline_source": "network", "seed_false_per_field": -1.0}, - {"baseline_source": "network", "seed_acceptance": "robust"}, - ): - with pytest.raises(ValueError): - SiloParams(**bad) - - -def test_silo_params_evidence_test() -> None: - """The evidence test is off by default with MATLAB's baseline. - - It is on with the network's (min_source_event_rate 2 per minute) and - reaches only the collect stage's settings when on. - """ - default = SiloParams() - assert default.min_source_snr == 0 and default.min_source_event_rate == 0 - assert "min_source_snr" not in default.stage_settings("collect") - assert "min_source_event_rate" not in default.stage_settings("collect") - net = SiloParams(baseline_source="network") - assert net.min_source_snr == 0 and net.min_source_event_rate == 2.0 - assert net.stage_settings("collect")["min_source_event_rate"] == 2.0 - assert "min_source_event_rate" not in net.stage_settings("plan") - on = SiloParams(min_source_snr=2.0, min_source_event_rate=1.5) - assert on.stage_settings("collect")["min_source_snr"] == 2.0 - assert on.to_matlab(2, 80.0)["minSourceSNR"] == 2.0 - assert on.to_matlab(2, 80.0)["minSourceEventRate"] == 1.5 - for bad in ({"min_source_snr": -1.0}, {"min_source_event_rate": -1}): - with pytest.raises(ValueError): - SiloParams(**bad) - - -def test_seed_heights() -> None: - """A source's seed height: the second-largest 3 x 3 value around its pixel. - - In robust SDs above the image's median (NaN left out). - """ - from giant_python.extraction.raster.peaks import _MAD_SCALE - from giant_python.extraction.raster.seeding import seed_heights - - rng = np.random.default_rng(3) - im = rng.standard_normal((40, 50)) - mu = np.median(im) - sigma = np.median(np.abs(im - mu)) / _MAD_SCALE - im[10, 10], im[10, 11] = 50.0, 9.0 * sigma + mu # second largest: 9 SDs - im[0, 0], im[0, 1], im[1, 0], im[1, 1] = 40.0, 30.0, np.nan, np.nan - h = seed_heights(im, np.array([10, 0, 25]), np.array([10, 0, 30])) - # the planted values barely move the image's median and MAD - vals = im[np.isfinite(im)] - mu = np.median(vals) - sigma = np.median(np.abs(vals - mu)) / _MAD_SCALE - win = np.sort(im[24:27, 29:32].ravel()) - np.testing.assert_allclose( - h, [(im[10, 11] - mu) / sigma, (30.0 - mu) / sigma, (win[-2] - mu) / sigma] - ) - assert np.isnan(seed_heights(np.full((5, 5), np.nan), [2], [2])).all() - assert np.isnan(seed_heights(np.ones((5, 5)), [2], [2])).all() - - -def test_silo_params_evidence_margin() -> None: - """The evidence test judges sources seeded below peak_th + 2 by default. - - The margin enters the collect hash and the params struct only when the - test is on, so MATLAB's settings keep both. - """ - m = SiloParams() - assert m.evidence_margin == 2.0 and not m.evidence_test - assert "evidence_margin" not in m.stage_settings("collect") - assert "evidenceMargin" not in m.to_matlab(2, 80.0) - net = SiloParams(baseline_source="network") - assert net.evidence_test and net.evidence_judge_below == 5.0 - assert net.stage_settings("collect")["evidence_margin"] == 2.0 - assert net.to_matlab(2, 80.0)["evidenceMargin"] == 2.0 - every = SiloParams(baseline_source="network", evidence_margin=None) - assert every.evidence_judge_below is None - assert every.to_matlab(2, 80.0)["evidenceMargin"] == np.inf - assert every.stage_settings("collect") != net.stage_settings("collect") - with pytest.raises(ValueError): - SiloParams(evidence_margin=-1.0) - # the null seed thresholds do not count in the image's robust SDs - # above peak_th: the evidence test then judges every source - for mode in ("null", "null_sd"): - p = SiloParams(baseline_source="network", seed_acceptance=mode) - assert p.evidence_test and p.evidence_judge_below is None - - -def test_null_sd_acceptance() -> None: - """acceptance='null_sd' counts peak_th in robust SDs of the null. - - The plan and SiloParams accept it with the null images. - """ - rng = np.random.default_rng(7) - im = _noise_field(rng, (80, 80)) - g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) - im[37:44, 37:44] += 3.0 * g - null = 2.0 * _noise_field(rng, (80, 80))[None] - info = {} - seeds = seed_sources(im, 4.0, fit="local", acceptance="null_sd", null_im=null, info=info) - bg = null_background(null) - np.testing.assert_allclose(seeds, get_act_im_peaks(im, 4.0, fit="local", background=bg)) - assert info["background"] == pytest.approx(bg) - with pytest.raises(ValueError): - seed_sources(im, 4.0, acceptance="null_sd") - det = {} - plan_path( - _trials(np.random.default_rng(8)), - params=PlanParams(seed_acceptance="null_sd", inter_trial_alignment="rigid"), - details=det, - ) - assert det["null_im"].shape[0] == 1 and det["seed_info"]["background"] - p = SiloParams(baseline_source="network", seed_acceptance="null_sd") - assert p.localization_keep_null and p.plan_params().seed_acceptance == ("null_sd") - - -def test_amplitude_rule_pixel_keeps_sharp_peaks() -> None: - """The 'pixel' amplitude rule keeps sharp peaks that MATLAB's test drops. - - MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a sharp - peak whose own pixel is well above the threshold; 'pixel' keeps it, and - drops a peak whose own pixel is below. - """ - from giant_python.extraction.raster.peaks import _finish - - theta = np.array([[0.9, 10.0, 10.0, 0.3], [0.1, 20.0, 20.0, 0.3]]) - excl = np.zeros((30, 30), bool) - assert _finish(theta, 0.22, excl, False).shape[0] == 0 - kept = _finish(theta, 0.22, excl, False, "pixel") - np.testing.assert_allclose(kept[:, 1:3], [[9.0, 9.0]]) - with pytest.raises(ValueError): - get_act_im_peaks(np.zeros((10, 10)), 3.0, amplitude_rule="area") - with pytest.raises(ValueError): - PlanParams(seed_amplitude_rule="area") - p = SiloParams(seed_amplitude_rule="pixel") - assert p.plan_params().seed_amplitude_rule == "pixel" - assert "seed_amplitude_rule" in p.stage_settings("plan") - assert "seed_amplitude_rule" not in SiloParams().stage_settings("plan") - - -def test_null_images_from_localization_and_empty_plans() -> None: - """The in-memory adapter carries the localization's null images. - - A plan without valid trials has no seeds in the null modes too. - """ - from types import SimpleNamespace - - rng = np.random.default_rng(9) - null = rng.random((1, 6, 7)) - loc = SimpleNamespace(act_im=rng.random((6, 7)), peaks=None, info={"null": {"null_im": null}}) - trial = SimpleNamespace(mean_im=rng.random((6, 7, 1)), discard=np.zeros(4, bool), half_ims=None) - np.testing.assert_array_equal(TrialImages.from_localization(loc, trial).null_im, null) - loc.info = {} - assert TrialImages.from_localization(loc, trial).null_im is None - blank = [ - TrialImages(t.mean_im, np.full(t.act_im.shape, np.nan), null_im=t.null_im) - for t in _trials(np.random.default_rng(10)) - ] - plan = plan_path( - blank, - params=PlanParams(seed_acceptance="null", inter_trial_alignment="rigid"), - ) - assert plan.valid_trials.size == 0 and plan.seeds.shape == (0, 4) - - -def test_trial_null_seeds_are_independent() -> None: - """With kept null images every trial-path draws its own null movies. - - Distinct seeds, apart by more than a trial's draws; the default - calibration's seed is not used for them. - """ - from giant_python.pipeline.silo import trial_null_seed - - seeds = {trial_null_seed(0, d, t) for d in range(3) for t in range(200)} - assert len(seeds) == 600 - s = sorted(seeds) - assert min(np.diff(s)) >= 1000 and min(s) > 0 - assert trial_null_seed(7, 0, 0) == trial_null_seed(0, 0, 0) + 7 - - -def test_pixel_rule_uses_the_fits_pixel_edges() -> None: - """Beside a gap in the imaged columns the fits' pixel is wider. - - The 'pixel' rule integrates the same wider pixel. - """ - from giant_python.extraction.raster.peaks import _finish, _pixel_bounds - - finite = np.ones((20, 20), bool) - finite[:, 11:14] = False # a gap of 3 columns right of column 10 - (ylo, yhi), (xlo, xhi) = _pixel_bounds(finite) - np.testing.assert_allclose([ylo[5], yhi[5]], [5.5, 6.5]) - assert xhi[10] - xlo[10] == pytest.approx(2.5) # midpoint to column 15 - theta = np.array([[0.3, 10.0, 11.4, 0.6]]) # 1-based centre in col 11 - excl = np.zeros((20, 20), bool) - unit = _finish(theta, 0.22, excl, False, "pixel") - wide = _finish(theta, 0.22, excl, False, "pixel", 0.0, ((ylo, yhi), (xlo, xhi))) - assert unit.shape[0] == 0 and wide.shape[0] == 1 - - -def test_trial_null_seeds_leave_room_for_many_draws() -> None: - """With more draws than the default block, blocks widen. - - So no two trial-paths share a seed. - """ - from giant_python.pipeline.silo import trial_null_seed - - draws = 2500 - used = set() - for d in range(2): - for t in range(4): - s0 = trial_null_seed(0, d, t, draws) - block = set(range(s0, s0 + draws)) - assert not block & used - used |= block +"""Tests of the seed threshold set from the combined image's null. + +That is seed_acceptance='null' (GIAnT-Python#51); also tests of the null +images that carry it from the localize stage to the plan stage. +""" + +from pathlib import Path + +import numpy as np +import pytest +from scipy import ndimage + +from giant_python.extraction.raster.peaks import get_act_im_peaks, ordfilt3x3 +from giant_python.extraction.raster.plan import ( + PlanParams, + TrialImages, + combined_activity_image, + combined_null_image, + plan_path, +) +from giant_python.extraction.raster.seeding import ( + candidate_statistic, + null_background, + null_threshold, + seed_sources, +) +from giant_python.extraction.raster.stage_files import ( + read_localization, + write_localization, +) +from giant_python.models.params import SiloParams + + +def _noise_field( + rng: np.random.Generator, shape: tuple[int, int] = (120, 140), sigma: float = 1.3 +) -> np.ndarray: + """Smoothed Gaussian noise: a stand-in for a null activity image. + + Returns + ------- + np.ndarray + The noise image of the given shape. + """ + return ndimage.gaussian_filter(rng.standard_normal(shape), sigma) + + +def test_candidate_statistic_is_the_seeding_rule() -> None: + """Maxima whose second-largest neighbour exceeds a threshold are the candidates. + + They are exactly get_act_im_peaks' candidates. + """ + rng = np.random.default_rng(0) + im = _noise_field(rng) + im[:3] = np.nan + excl = np.zeros(im.shape, bool) + excl[50:60, 50:60] = True + rc, value = candidate_statistic(im, excl) + th = np.quantile(value, 0.9) + explored = im * ~excl + with np.errstate(invalid="ignore"): + cand = (ordfilt3x3(explored, 8) > th) & (explored == ordfilt3x3(explored, 9)) + mine = np.zeros(im.shape, bool) + mine[tuple(rc[value > th].T)] = True + np.testing.assert_array_equal(mine, cand) + assert not excl[tuple(rc.T)].any() + + +def test_null_threshold_gives_the_expected_false_seeds() -> None: + """A null threshold gives about the requested false candidates per field. + + A threshold set on one null field for 2 false candidates per field is + crossed about twice per field on independent fields of the same noise; a + lax target is read off the null, a strict one extrapolated. + """ + rng = np.random.default_rng(1) + fields = [_noise_field(rng) for _ in range(41)] + (mu, sd), th, info = null_threshold(np.stack(fields[:4]), 2.0) + assert info["extrapolated"] and info["draws"] == 4 + counts = [np.sum((candidate_statistic(f)[1] - mu) / sd > th) for f in fields[4:]] + assert 1.0 < np.mean(counts) < 4.0 + _, th_lax, info_lax = null_threshold(fields[0], 200.0) + assert not info_lax["extrapolated"] + assert np.sum((candidate_statistic(fields[0])[1] - mu) / sd > th_lax) <= 210 + _, th_strict, _ = null_threshold(fields[0], 0.1) + assert th_strict > th_lax + with pytest.raises(ValueError): + null_threshold(fields[0], 0.0) + with pytest.raises(ValueError): + null_threshold(np.zeros((20, 20)), 1.0) + + +def test_background_override() -> None: + """The image's own median and robust SD as the background reproduce MATLAB's threshold. + + A doubled scale with half the threshold does too. + """ + rng = np.random.default_rng(2) + im = _noise_field(rng, (60, 60)) * 0.2 + for r, c in ((15, 15), (30, 44), (45, 20)): + im[r - 2 : r + 3, c - 2 : c + 3] += 3 * np.exp( + -np.add.outer(np.arange(-2, 3) ** 2, np.arange(-2, 3) ** 2) / 2 + ) + v = im[np.isfinite(im)] + mu = np.median(v) + sd = np.median(np.abs(v - mu)) / 0.6741891400433162 + ref = get_act_im_peaks(im, 5.0, fit="local") + same = get_act_im_peaks(im, 5.0, fit="local", background=(mu, sd)) + half = get_act_im_peaks(im, 2.5, fit="local", background=(mu, 2 * sd)) + np.testing.assert_allclose(same, ref) + np.testing.assert_allclose(half, ref) + assert ref.shape[0] == 3 + with pytest.raises(ValueError): + get_act_im_peaks(im, 5.0, background=(0.0, 0.0)) + + +def test_seed_sources_with_the_null() -> None: + """acceptance='null' seeds at the null's threshold and reports it. + + It needs the null image. + """ + rng = np.random.default_rng(3) + im = _noise_field(rng, (80, 80)) + g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) + im[37:44, 37:44] += 3.0 * g # a source well above the noise (SD ~0.2) + null = np.stack([_noise_field(rng, (80, 80)) for _ in range(2)]) + info = {} + seeds = seed_sources( + im, + 99.0, + fit="local", + acceptance="null", + null_im=null, + false_per_field=1.0, + info=info, + ) + bg, th, _ = null_threshold(null, 1.0) + np.testing.assert_allclose(seeds, get_act_im_peaks(im, th, fit="local", background=bg)) + assert info["peak_th"] == pytest.approx(th) and info["draws"] == 2 + assert np.hypot(*(seeds[:, 1:3] - 40).T).min() < 1.0 + with pytest.raises(ValueError): + seed_sources(im, 3.0, acceptance="null") + with pytest.raises(ValueError): + seed_sources(im, 3.0, acceptance="robust") + info = {} + seed_sources(im, 3.0, fit="local", info=info) + assert info == {"peak_th": 3.0, "background": None} + + +def test_combined_null_is_combined_like_the_image() -> None: + """Null images equal to the activity images combine to the combined activity image. + + Same scale, mask and median subtraction. + """ + rng = np.random.default_rng(4) + act = np.stack([np.abs(_noise_field(rng, (30, 40))) * 50 for _ in range(4)]) + act[1, :2] = np.nan + im, _, _ = combined_activity_image(act, 0.33) + null = combined_null_image(act[:, None], act, 0.33) + assert null.shape == (1, 30, 40) + np.testing.assert_allclose(null[0], im, equal_nan=True) + + +def _trials( + rng: np.random.Generator, + n: int = 3, + shape: tuple[int, int] = (48, 52), + null: bool = True, +) -> list[TrialImages]: + """Trials of one structured mean image with noise activity images. + + Returns + ------- + list of TrialImages + n trials sharing a mean image, each with a noise activity image + and, when null is true, a noise null image. + """ + base = ndimage.gaussian_filter(rng.random(shape), 2) * 100 + 10 + out = [] + for _ in range(n): + act = np.abs(_noise_field(rng, shape)) + act[20, 20] += 5 + nul = np.abs(_noise_field(rng, shape))[None] if null else None + out.append(TrialImages(base[..., None] + rng.random(shape + (1,)), act, null_im=nul)) + return out + + +def test_plan_with_null_acceptance() -> None: + """The plan seeds with the trials' null images and reports the threshold. + + Without null images it refuses. + """ + rng = np.random.default_rng(5) + trials = _trials(rng) + det = {} + p = PlanParams( + seed_acceptance="null", + seed_false_per_field=2.0, + inter_trial_alignment="rigid", + ) + plan = plan_path(trials, params=p, details=det) + assert det["null_im"].shape == (1,) + plan.shape + assert det["seed_info"]["draws"] == 1 and det["seed_info"]["background"] + det0 = {} + plan_path(trials, params=PlanParams(inter_trial_alignment="rigid"), details=det0) + assert det0["seed_info"]["background"] is None and "null_im" not in det0 + with pytest.raises(ValueError, match="null images"): + plan_path(_trials(rng, null=False), params=p) + with pytest.raises(ValueError): + PlanParams(seed_acceptance="robust") + with pytest.raises(ValueError): + PlanParams(seed_false_per_field=0) + + +def test_null_images_round_trip(tmp_path: Path) -> None: + """Localization files keep the null images when given.""" + rng = np.random.default_rng(6) + act = rng.random((6, 7)) + null = rng.random((2, 6, 7)).astype(np.float32) + path = tmp_path / "loc.h5" + write_localization( + path, + rng.random((6, 7, 1)), + act, + act, + np.zeros(5, bool), + None, + {}, + None, + null, + ) + rec = read_localization(path) + np.testing.assert_array_equal(rec.null_im, null) + assert rec.attrs["null_im"] == 1 + np.testing.assert_array_equal(rec.trial_images().null_im, null) + write_localization(path, rng.random((6, 7, 1)), act, act, np.zeros(5, bool), None, {}) + assert read_localization(path).null_im is None + + +def test_silo_params_null_acceptance() -> None: + """The localization keeps null images exactly when the seeding needs them (unless set). + + Both need the bootstrap null; defaults leave the stage hashes and MATLAB's + fields alone. + """ + default = SiloParams() + assert default.seed_acceptance == "image" + assert default.localization_keep_null is False + net = SiloParams(baseline_source="network", seed_acceptance="null") + assert net.localization_keep_null is True + assert net.plan_params().seed_acceptance == "null" + assert "localization_keep_null" in net.stage_settings("localize") + assert "seed_acceptance" in net.stage_settings("plan") + assert "localization_keep_null" not in SiloParams(baseline_source="network").stage_settings( + "localize" + ) + m = net.to_matlab(2, 80.0) + assert m["seedAcceptance"] == "null" and m["localizationKeepNull"] + assert "seedAcceptance" not in default.to_matlab(2, 80.0) + keep = SiloParams(baseline_source="network", localization_keep_null=True) + assert keep.seed_acceptance == "image" and keep.localization_keep_null + for bad in ( + {"seed_acceptance": "null"}, # no bootstrap null + { + "baseline_source": "network", + "seed_acceptance": "null", + "localization_keep_null": False, + }, + {"baseline_source": "network", "seed_false_per_field": -1.0}, + {"baseline_source": "network", "seed_acceptance": "robust"}, + ): + with pytest.raises(ValueError): + SiloParams(**bad) + + +def test_silo_params_evidence_test() -> None: + """The evidence test is off by default with MATLAB's baseline. + + It is on with the network's (min_source_event_rate 2 per minute) and + reaches only the collect stage's settings when on. + """ + default = SiloParams() + assert default.min_source_snr == 0 and default.min_source_event_rate == 0 + assert "min_source_snr" not in default.stage_settings("collect") + assert "min_source_event_rate" not in default.stage_settings("collect") + net = SiloParams(baseline_source="network") + assert net.min_source_snr == 0 and net.min_source_event_rate == 2.0 + assert net.stage_settings("collect")["min_source_event_rate"] == 2.0 + assert "min_source_event_rate" not in net.stage_settings("plan") + on = SiloParams(min_source_snr=2.0, min_source_event_rate=1.5) + assert on.stage_settings("collect")["min_source_snr"] == 2.0 + assert on.to_matlab(2, 80.0)["minSourceSNR"] == 2.0 + assert on.to_matlab(2, 80.0)["minSourceEventRate"] == 1.5 + for bad in ({"min_source_snr": -1.0}, {"min_source_event_rate": -1}): + with pytest.raises(ValueError): + SiloParams(**bad) + + +def test_seed_heights() -> None: + """A source's seed height: the second-largest 3 x 3 value around its pixel. + + In robust SDs above the image's median (NaN left out). + """ + from giant_python.extraction.raster.peaks import _MAD_SCALE + from giant_python.extraction.raster.seeding import seed_heights + + rng = np.random.default_rng(3) + im = rng.standard_normal((40, 50)) + mu = np.median(im) + sigma = np.median(np.abs(im - mu)) / _MAD_SCALE + im[10, 10], im[10, 11] = 50.0, 9.0 * sigma + mu # second largest: 9 SDs + im[0, 0], im[0, 1], im[1, 0], im[1, 1] = 40.0, 30.0, np.nan, np.nan + h = seed_heights(im, np.array([10, 0, 25]), np.array([10, 0, 30])) + # the planted values barely move the image's median and MAD + vals = im[np.isfinite(im)] + mu = np.median(vals) + sigma = np.median(np.abs(vals - mu)) / _MAD_SCALE + win = np.sort(im[24:27, 29:32].ravel()) + np.testing.assert_allclose( + h, [(im[10, 11] - mu) / sigma, (30.0 - mu) / sigma, (win[-2] - mu) / sigma] + ) + assert np.isnan(seed_heights(np.full((5, 5), np.nan), [2], [2])).all() + assert np.isnan(seed_heights(np.ones((5, 5)), [2], [2])).all() + + +def test_silo_params_evidence_margin() -> None: + """The evidence test judges sources seeded below peak_th + 2 by default. + + The margin enters the collect hash and the params struct only when the + test is on, so MATLAB's settings keep both. + """ + m = SiloParams() + assert m.evidence_margin == 2.0 and not m.evidence_test + assert "evidence_margin" not in m.stage_settings("collect") + assert "evidenceMargin" not in m.to_matlab(2, 80.0) + net = SiloParams(baseline_source="network") + assert net.evidence_test and net.evidence_judge_below == 5.0 + assert net.stage_settings("collect")["evidence_margin"] == 2.0 + assert net.to_matlab(2, 80.0)["evidenceMargin"] == 2.0 + every = SiloParams(baseline_source="network", evidence_margin=None) + assert every.evidence_judge_below is None + assert every.to_matlab(2, 80.0)["evidenceMargin"] == np.inf + assert every.stage_settings("collect") != net.stage_settings("collect") + with pytest.raises(ValueError): + SiloParams(evidence_margin=-1.0) + # the null seed thresholds do not count in the image's robust SDs + # above peak_th: the evidence test then judges every source + for mode in ("null", "null_sd"): + p = SiloParams(baseline_source="network", seed_acceptance=mode) + assert p.evidence_test and p.evidence_judge_below is None + + +def test_null_sd_acceptance() -> None: + """acceptance='null_sd' counts peak_th in robust SDs of the null. + + The plan and SiloParams accept it with the null images. + """ + rng = np.random.default_rng(7) + im = _noise_field(rng, (80, 80)) + g = np.exp(-np.add.outer(np.arange(-3, 4) ** 2, np.arange(-3, 4) ** 2) / 4) + im[37:44, 37:44] += 3.0 * g + null = 2.0 * _noise_field(rng, (80, 80))[None] + info = {} + seeds = seed_sources(im, 4.0, fit="local", acceptance="null_sd", null_im=null, info=info) + bg = null_background(null) + np.testing.assert_allclose(seeds, get_act_im_peaks(im, 4.0, fit="local", background=bg)) + assert info["background"] == pytest.approx(bg) + with pytest.raises(ValueError): + seed_sources(im, 4.0, acceptance="null_sd") + det = {} + plan_path( + _trials(np.random.default_rng(8)), + params=PlanParams(seed_acceptance="null_sd", inter_trial_alignment="rigid"), + details=det, + ) + assert det["null_im"].shape[0] == 1 and det["seed_info"]["background"] + p = SiloParams(baseline_source="network", seed_acceptance="null_sd") + assert p.localization_keep_null and p.plan_params().seed_acceptance == ("null_sd") + + +def test_amplitude_rule_pixel_keeps_sharp_peaks() -> None: + """The 'pixel' amplitude rule keeps sharp peaks that MATLAB's test drops. + + MATLAB's final test (a 2 x 2 pixel mean of the Gaussian) drops a sharp + peak whose own pixel is well above the threshold; 'pixel' keeps it, and + drops a peak whose own pixel is below. + """ + from giant_python.extraction.raster.peaks import _finish + + theta = np.array([[0.9, 10.0, 10.0, 0.3], [0.1, 20.0, 20.0, 0.3]]) + excl = np.zeros((30, 30), bool) + assert _finish(theta, 0.22, excl, False).shape[0] == 0 + kept = _finish(theta, 0.22, excl, False, "pixel") + np.testing.assert_allclose(kept[:, 1:3], [[9.0, 9.0]]) + with pytest.raises(ValueError): + get_act_im_peaks(np.zeros((10, 10)), 3.0, amplitude_rule="area") + with pytest.raises(ValueError): + PlanParams(seed_amplitude_rule="area") + p = SiloParams(seed_amplitude_rule="pixel") + assert p.plan_params().seed_amplitude_rule == "pixel" + assert "seed_amplitude_rule" in p.stage_settings("plan") + assert "seed_amplitude_rule" not in SiloParams().stage_settings("plan") + + +def test_null_images_from_localization_and_empty_plans() -> None: + """The in-memory adapter carries the localization's null images. + + A plan without valid trials has no seeds in the null modes too. + """ + from types import SimpleNamespace + + rng = np.random.default_rng(9) + null = rng.random((1, 6, 7)) + loc = SimpleNamespace(act_im=rng.random((6, 7)), peaks=None, info={"null": {"null_im": null}}) + trial = SimpleNamespace(mean_im=rng.random((6, 7, 1)), discard=np.zeros(4, bool), half_ims=None) + np.testing.assert_array_equal(TrialImages.from_localization(loc, trial).null_im, null) + loc.info = {} + assert TrialImages.from_localization(loc, trial).null_im is None + blank = [ + TrialImages(t.mean_im, np.full(t.act_im.shape, np.nan), null_im=t.null_im) + for t in _trials(np.random.default_rng(10)) + ] + plan = plan_path( + blank, + params=PlanParams(seed_acceptance="null", inter_trial_alignment="rigid"), + ) + assert plan.valid_trials.size == 0 and plan.seeds.shape == (0, 4) + + +def test_trial_null_seeds_are_independent() -> None: + """With kept null images every trial-path draws its own null movies. + + Distinct seeds, apart by more than a trial's draws; the default + calibration's seed is not used for them. + """ + from giant_python.pipeline.silo import trial_null_seed + + seeds = {trial_null_seed(0, d, t) for d in range(3) for t in range(200)} + assert len(seeds) == 600 + s = sorted(seeds) + assert min(np.diff(s)) >= 1000 and min(s) > 0 + assert trial_null_seed(7, 0, 0) == trial_null_seed(0, 0, 0) + 7 + + +def test_pixel_rule_uses_the_fits_pixel_edges() -> None: + """Beside a gap in the imaged columns the fits' pixel is wider. + + The 'pixel' rule integrates the same wider pixel. + """ + from giant_python.extraction.raster.peaks import _finish, _pixel_bounds + + finite = np.ones((20, 20), bool) + finite[:, 11:14] = False # a gap of 3 columns right of column 10 + (ylo, yhi), (xlo, xhi) = _pixel_bounds(finite) + np.testing.assert_allclose([ylo[5], yhi[5]], [5.5, 6.5]) + assert xhi[10] - xlo[10] == pytest.approx(2.5) # midpoint to column 15 + theta = np.array([[0.3, 10.0, 11.4, 0.6]]) # 1-based centre in col 11 + excl = np.zeros((20, 20), bool) + unit = _finish(theta, 0.22, excl, False, "pixel") + wide = _finish(theta, 0.22, excl, False, "pixel", 0.0, ((ylo, yhi), (xlo, xhi))) + assert unit.shape[0] == 0 and wide.shape[0] == 1 + + +def test_trial_null_seeds_leave_room_for_many_draws() -> None: + """With more draws than the default block, blocks widen. + + So no two trial-paths share a seed. + """ + from giant_python.pipeline.silo import trial_null_seed + + draws = 2500 + used = set() + for d in range(2): + for t in range(4): + s0 = trial_null_seed(0, d, t, draws) + block = set(range(s0, s0 + draws)) + assert not block & used + used |= block diff --git a/tests/raster/test_raster_silo_alignment.py b/tests/raster/test_raster_silo_alignment.py index 477e7cbe..990ef403 100644 --- a/tests/raster/test_raster_silo_alignment.py +++ b/tests/raster/test_raster_silo_alignment.py @@ -1,276 +1,276 @@ -"""The affine and patchwise across-trial alignments in giant silo's stages. - -Half images in the localization files, staged and streamed runs, the plan's -maps in the summaries, ROIs and per-trial peaks. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.alignment import ( - TrialWarp, - mask_to_consensus, - warp_trial_image, -) -from giant_python.extraction.raster.annotations import ( - PathAnnotations, - UserRoi, - rois_to_consensus, -) -from giant_python.extraction.raster.plan import ( - PlanParams, - plan_path, - read_plan, - write_plan, -) -from giant_python.extraction.raster.stage_files import ( - read_localization, - write_localization, -) -from giant_python.extraction.raster.summary import _peaks_to_consensus -from giant_python.pipeline import silo, silo_collect, silo_solve -from giant_python.pipeline.silo_session import SiloSession - -from .test_raster_plan import _synthetic_trials -from .test_raster_silo_stages import ( # noqa: F401 - EX, - N_PATHS, - N_TRIALS, - PARAMS, - _all_results, - _equal, - _summary, - fake, - make_session, -) - -PATCHWISE = replace(PARAMS, inter_trial_alignment="patchwise", align_patch_px=200) - - -@pytest.fixture -def halves(fake: None) -> None: # noqa: F811 - """Provide the fake session's localization (half images when asked).""" - - -def test_patchwise_streamed_and_staged_runs_agree(tmp_path: Path, halves: None) -> None: - """Patchwise alignment: the streaming driver and the stages agree. - - Under patchwise alignment the streaming driver and the stages give the - same results and summaries; the localization files hold the half images, - the plans a patchwise field, the summary its displacements. - """ - table = make_session(tmp_path / "streamed") - silo.run_silo(table, PATCHWISE, EX) - s1 = SiloSession.open(table) - rec = read_localization(s1.localize_file(0, 0)) - assert rec.half_ims is not None and rec.attrs["half_ims"] == 1 - plan = read_plan(s1.plan_file(0)) - assert plan.warp.is_patchwise and plan.warp.patch is not None - with h5py.File(s1.out_dir / "experiment_summary.h5", "r") as f: - disp = f["Path1/frame_info/trial_alignment_displacement"][()] - assert np.isfinite(disp).any() - streamed = _all_results(s1) - s2 = SiloSession.open(make_session(tmp_path / "staged")) - silo.localize(s2, PATCHWISE, EX) - silo.plan(s2, PATCHWISE, EX) - silo.prepare(s2, PATCHWISE, EX) - for job in silo_solve.dispatch(s2, PATCHWISE, 2, EX): - silo_solve.solve_job(job, execution=EX) - silo_collect.collect(s2, PATCHWISE, EX) - staged = _all_results(s2) - assert staged.keys() == streamed.keys() - for key in staged: - for name, value in staged[key].items(): - np.testing.assert_array_equal(value, streamed[key][name]) - _equal( - _summary(s2.out_dir / "experiment_summary.h5"), - _summary(s1.out_dir / "experiment_summary.h5"), - ) - - -def test_localize_redoes_files_without_halves(tmp_path: Path, halves: None) -> None: - """Files localized for a rigid plan lack the half images. - - A patchwise plan refuses them and the patchwise localize stage redoes - them. Rigid and affine runs accept files with and without half images and - redo neither, so existing localizations stay usable. - """ - s = SiloSession.open(make_session(tmp_path)) - rigid = replace(PATCHWISE, inter_trial_alignment="rigid") - affine = replace(PATCHWISE, inter_trial_alignment="affine") - assert len(silo.localize(s, rigid, EX)) == N_PATHS * N_TRIALS - assert read_localization(s.localize_file(0, 0)).half_ims is None - for p in (rigid, affine): - assert silo.localize_jobs(s, p) == [] - assert silo.plan_one(s, p, 0, overwrite=True).exists() - with pytest.raises(ValueError, match="half images"): - silo.plan_one(s, PATCHWISE, 0) - jobs = silo.localize_jobs(s, PATCHWISE) - assert len(jobs) == N_PATHS * N_TRIALS - silo.localize(s, PATCHWISE, EX) - assert silo.localize_jobs(s, PATCHWISE) == [] - for p in (rigid, affine): - assert silo.localize_jobs(s, p) == [] - assert silo.plan_one(s, p, 0, overwrite=True).exists() - assert silo.plan_one(s, PATCHWISE, 0).exists() - # only a patchwise plan reads the half images - assert all(r.half_ims is None for r in silo._plan_inputs(s, 0)) - assert all(r.half_ims is not None for r in silo._plan_inputs(s, 0, True)) - - -def test_later_stages_refuse_another_alignment(tmp_path: Path, halves: None) -> None: - """Prepare and collect use the plan's maps and record the settings. - - Another alignment, or another patch size for patchwise, is refused. - """ - s = SiloSession.open(make_session(tmp_path)) - silo.localize(s, PATCHWISE, EX) - silo.plan(s, PATCHWISE, EX) - rigid = replace(PATCHWISE, inter_trial_alignment="rigid") - other = replace(PATCHWISE, align_patch_px=300) - # a fractional plan setting is not equal to its integer part - pf = s.plan_file(0) - plan = read_plan(pf) - plan.params = replace(plan.params, align_patch_px=200.5) - with pytest.raises(ValueError, match="align_patch_px"): - silo.check_plan_alignment("plan", plan, PATCHWISE) - silo.check_plan_alignment("plan", read_plan(pf), PATCHWISE) - for p in (rigid, other): - with pytest.raises(ValueError, match="align"): - silo.prepare(s, p, EX) - with pytest.raises(ValueError, match="align"): - silo_collect.collect(s, p, EX) - - -@pytest.mark.parametrize("mode", ["affine", "patchwise"]) -def test_plan_with_a_refined_alignment(tmp_path: Path, mode: str) -> None: - """The valid trials get the refined maps (the same valid trials as rigid). - - The aligned images are warped through them; the shifts are the - displacements at the canvas centre; the plan file keeps the maps. - """ - trials = _synthetic_trials() - for t in trials: - t.half_ims = np.stack([t.mean_im, t.mean_im * 1.01]) - rigid = plan_path(trials, params=PlanParams(peak_th=12.0, inter_trial_alignment="rigid")) - details = {} - plan = plan_path( - trials, - params=PlanParams(peak_th=12.0, inter_trial_alignment=mode, align_patch_px=600), - details=details, - ) - np.testing.assert_array_equal(plan.valid_trials, rigid.valid_trials) - assert np.isfinite(details["alignment_info"].corr[plan.valid_trials]).all() - assert plan.warp.is_patchwise == (mode == "patchwise") - h, w = plan.shape - x0 = np.array([(h - 1) / 2, (w - 1) / 2]) - for t in plan.aligned_trials: - r, c = plan.warp.coords(t, x0[:1], x0[1:]) - np.testing.assert_allclose(plan.shifts[t], [r[0] - x0[0], c[0] - x0[1]], atol=1e-12) - np.testing.assert_array_equal( - plan.mean_aligned[t], - warp_trial_image(plan.mean_ims[t], plan.warp, t), - ) - # the refinement moves the maps by well under a pixel here (pure - # shifts), and the sources stay where they were - assert np.abs(plan.shifts - rigid.shifts).max() < 0.2 - np.testing.assert_array_equal(plan.source_rows, rigid.source_rows) - write_plan(tmp_path / "plan.h5", plan) - back = read_plan(tmp_path / "plan.h5") - np.testing.assert_array_equal(back.warp.affine, plan.warp.affine) - np.testing.assert_array_equal(back.warp.disp, plan.warp.disp) - assert back.warp.sigma == plan.warp.sigma or mode == "affine" - if mode == "patchwise": - np.testing.assert_array_equal(back.warp.patch, plan.warp.patch) - assert back.params.align_patch_px == 600 - - -def test_localization_file_keeps_half_images(tmp_path: Path) -> None: - """The half images round-trip as float32; files without them read as None.""" - rng = np.random.default_rng(0) - mean = rng.random((5, 6, 2)) - halves = rng.random((2, 5, 6, 2)) - f = write_localization( - tmp_path / "a.h5", - mean, - mean[..., 0], - mean[..., 0], - [0, 1], - None, - {"settings_hash": "x"}, - halves, - ) - rec = read_localization(f) - np.testing.assert_array_equal(rec.half_ims, halves.astype(np.float32)) - assert rec.trial_images().half_ims is rec.half_ims - assert read_localization(f, half_ims=False).half_ims is None - g = write_localization(tmp_path / "b.h5", mean, mean[..., 0], mean[..., 0], [0, 1], None, {}) - assert read_localization(g).half_ims is None - assert read_localization(g).attrs["half_ims"] == 0 - - -def _bent_warp(n_trials: int = 2, shape: tuple[int, int] = (40, 50)) -> TrialWarp: - """Build an affine map with a bent field on top, per trial. - - Returns - ------- - TrialWarp - The per-trial affine maps, with the displacements of six random nodes. - """ - rng = np.random.default_rng(1) - nodes = rng.uniform([5, 5], [shape[0] - 5, shape[1] - 5], (6, 2)) - affine = np.zeros((n_trials, 2, 3)) - disp = np.zeros((n_trials, 6, 2)) - for t in range(n_trials): - a = np.array([[1.003, 0.002, 0.6 + t], [-0.002, 0.998, -1.1]]) - affine[t] = a - disp[t] = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T - disp[t] += 0.3 * rng.standard_normal((6, 2)) - return TrialWarp(affine, nodes, 8.0, disp) - - -def test_rois_through_a_full_map() -> None: - """ROIs go through a full map. - - Masks take the trial mask's value at each consensus pixel's mapped - position; geometry goes through the inverse map (one-based [x, y]). - """ - warp = _bent_warp() - mask = np.zeros((40, 50), bool) - mask[18:23, 20:26] = True - center = np.array([23.0, 21.0]) # x (col), y (row), one-based - ann = PathAnnotations( - path=1, - dr="", - fn="E1T2DMD1", - rois=[UserRoi("SOMA a", "circle", mask, center=center)], - ) - rois = rois_to_consensus(ann, ["E1T1DMD1.tif", "E1T2DMD1.tif"], warp, (40, 50)) - np.testing.assert_array_equal(rois[0].mask, mask_to_consensus(mask, warp, 1, (40, 50))) - r, c = warp.coords(1, rois[0].center[1:] - 1, rois[0].center[:1] - 1) - np.testing.assert_allclose([c[0] + 1, r[0] + 1], center, atol=1e-6) - - -def test_per_trial_peaks_into_the_consensus_frame() -> None: - """Through the inverse of a non-shift map, minus the shift of a rigid one.""" - - class Plan: - """What _peaks_to_consensus reads of a plan.""" - - def __init__(self, warp: TrialWarp, shifts: np.ndarray) -> None: - """Store a warp and its shifts.""" - self.warp, self.shifts = warp, shifts - - peaks = np.array([[1.0, 10.0, 12.0, 0.5], [2.0, 30.5, 40.25, 0.5]]) - warp = _bent_warp() - out = _peaks_to_consensus(Plan(warp, np.zeros((2, 2))), 1, peaks) - r, c = warp.coords(1, out[:, 0], out[:, 1]) - np.testing.assert_allclose(np.column_stack([r, c]), peaks[:, 1:3], atol=1e-6) - rigid = TrialWarp.from_shifts([[0.5, -1.0], [1.0, 2.0]]) - shifts = np.array([[0.5, -1], [1, 2]]) - out = _peaks_to_consensus(Plan(rigid, shifts), 1, peaks) - np.testing.assert_array_equal(out, peaks[:, 1:3] - [1.0, 2.0]) +"""The affine and patchwise across-trial alignments in giant silo's stages. + +Half images in the localization files, staged and streamed runs, the plan's +maps in the summaries, ROIs and per-trial peaks. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.alignment import ( + TrialWarp, + mask_to_consensus, + warp_trial_image, +) +from giant_python.extraction.raster.annotations import ( + PathAnnotations, + UserRoi, + rois_to_consensus, +) +from giant_python.extraction.raster.plan import ( + PlanParams, + plan_path, + read_plan, + write_plan, +) +from giant_python.extraction.raster.stage_files import ( + read_localization, + write_localization, +) +from giant_python.extraction.raster.summary import _peaks_to_consensus +from giant_python.pipeline import silo, silo_collect, silo_solve +from giant_python.pipeline.silo_session import SiloSession + +from .test_raster_plan import _synthetic_trials +from .test_raster_silo_stages import ( # noqa: F401 + EX, + N_PATHS, + N_TRIALS, + PARAMS, + _all_results, + _equal, + _summary, + fake, + make_session, +) + +PATCHWISE = replace(PARAMS, inter_trial_alignment="patchwise", align_patch_px=200) + + +@pytest.fixture +def halves(fake: None) -> None: # noqa: F811 + """Provide the fake session's localization (half images when asked).""" + + +def test_patchwise_streamed_and_staged_runs_agree(tmp_path: Path, halves: None) -> None: + """Patchwise alignment: the streaming driver and the stages agree. + + Under patchwise alignment the streaming driver and the stages give the + same results and summaries; the localization files hold the half images, + the plans a patchwise field, the summary its displacements. + """ + table = make_session(tmp_path / "streamed") + silo.run_silo(table, PATCHWISE, EX) + s1 = SiloSession.open(table) + rec = read_localization(s1.localize_file(0, 0)) + assert rec.half_ims is not None and rec.attrs["half_ims"] == 1 + plan = read_plan(s1.plan_file(0)) + assert plan.warp.is_patchwise and plan.warp.patch is not None + with h5py.File(s1.out_dir / "experiment_summary.h5", "r") as f: + disp = f["Path1/frame_info/trial_alignment_displacement"][()] + assert np.isfinite(disp).any() + streamed = _all_results(s1) + s2 = SiloSession.open(make_session(tmp_path / "staged")) + silo.localize(s2, PATCHWISE, EX) + silo.plan(s2, PATCHWISE, EX) + silo.prepare(s2, PATCHWISE, EX) + for job in silo_solve.dispatch(s2, PATCHWISE, 2, EX): + silo_solve.solve_job(job, execution=EX) + silo_collect.collect(s2, PATCHWISE, EX) + staged = _all_results(s2) + assert staged.keys() == streamed.keys() + for key in staged: + for name, value in staged[key].items(): + np.testing.assert_array_equal(value, streamed[key][name]) + _equal( + _summary(s2.out_dir / "experiment_summary.h5"), + _summary(s1.out_dir / "experiment_summary.h5"), + ) + + +def test_localize_redoes_files_without_halves(tmp_path: Path, halves: None) -> None: + """Files localized for a rigid plan lack the half images. + + A patchwise plan refuses them and the patchwise localize stage redoes + them. Rigid and affine runs accept files with and without half images and + redo neither, so existing localizations stay usable. + """ + s = SiloSession.open(make_session(tmp_path)) + rigid = replace(PATCHWISE, inter_trial_alignment="rigid") + affine = replace(PATCHWISE, inter_trial_alignment="affine") + assert len(silo.localize(s, rigid, EX)) == N_PATHS * N_TRIALS + assert read_localization(s.localize_file(0, 0)).half_ims is None + for p in (rigid, affine): + assert silo.localize_jobs(s, p) == [] + assert silo.plan_one(s, p, 0, overwrite=True).exists() + with pytest.raises(ValueError, match="half images"): + silo.plan_one(s, PATCHWISE, 0) + jobs = silo.localize_jobs(s, PATCHWISE) + assert len(jobs) == N_PATHS * N_TRIALS + silo.localize(s, PATCHWISE, EX) + assert silo.localize_jobs(s, PATCHWISE) == [] + for p in (rigid, affine): + assert silo.localize_jobs(s, p) == [] + assert silo.plan_one(s, p, 0, overwrite=True).exists() + assert silo.plan_one(s, PATCHWISE, 0).exists() + # only a patchwise plan reads the half images + assert all(r.half_ims is None for r in silo._plan_inputs(s, 0)) + assert all(r.half_ims is not None for r in silo._plan_inputs(s, 0, True)) + + +def test_later_stages_refuse_another_alignment(tmp_path: Path, halves: None) -> None: + """Prepare and collect use the plan's maps and record the settings. + + Another alignment, or another patch size for patchwise, is refused. + """ + s = SiloSession.open(make_session(tmp_path)) + silo.localize(s, PATCHWISE, EX) + silo.plan(s, PATCHWISE, EX) + rigid = replace(PATCHWISE, inter_trial_alignment="rigid") + other = replace(PATCHWISE, align_patch_px=300) + # a fractional plan setting is not equal to its integer part + pf = s.plan_file(0) + plan = read_plan(pf) + plan.params = replace(plan.params, align_patch_px=200.5) + with pytest.raises(ValueError, match="align_patch_px"): + silo.check_plan_alignment("plan", plan, PATCHWISE) + silo.check_plan_alignment("plan", read_plan(pf), PATCHWISE) + for p in (rigid, other): + with pytest.raises(ValueError, match="align"): + silo.prepare(s, p, EX) + with pytest.raises(ValueError, match="align"): + silo_collect.collect(s, p, EX) + + +@pytest.mark.parametrize("mode", ["affine", "patchwise"]) +def test_plan_with_a_refined_alignment(tmp_path: Path, mode: str) -> None: + """The valid trials get the refined maps (the same valid trials as rigid). + + The aligned images are warped through them; the shifts are the + displacements at the canvas centre; the plan file keeps the maps. + """ + trials = _synthetic_trials() + for t in trials: + t.half_ims = np.stack([t.mean_im, t.mean_im * 1.01]) + rigid = plan_path(trials, params=PlanParams(peak_th=12.0, inter_trial_alignment="rigid")) + details = {} + plan = plan_path( + trials, + params=PlanParams(peak_th=12.0, inter_trial_alignment=mode, align_patch_px=600), + details=details, + ) + np.testing.assert_array_equal(plan.valid_trials, rigid.valid_trials) + assert np.isfinite(details["alignment_info"].corr[plan.valid_trials]).all() + assert plan.warp.is_patchwise == (mode == "patchwise") + h, w = plan.shape + x0 = np.array([(h - 1) / 2, (w - 1) / 2]) + for t in plan.aligned_trials: + r, c = plan.warp.coords(t, x0[:1], x0[1:]) + np.testing.assert_allclose(plan.shifts[t], [r[0] - x0[0], c[0] - x0[1]], atol=1e-12) + np.testing.assert_array_equal( + plan.mean_aligned[t], + warp_trial_image(plan.mean_ims[t], plan.warp, t), + ) + # the refinement moves the maps by well under a pixel here (pure + # shifts), and the sources stay where they were + assert np.abs(plan.shifts - rigid.shifts).max() < 0.2 + np.testing.assert_array_equal(plan.source_rows, rigid.source_rows) + write_plan(tmp_path / "plan.h5", plan) + back = read_plan(tmp_path / "plan.h5") + np.testing.assert_array_equal(back.warp.affine, plan.warp.affine) + np.testing.assert_array_equal(back.warp.disp, plan.warp.disp) + assert back.warp.sigma == plan.warp.sigma or mode == "affine" + if mode == "patchwise": + np.testing.assert_array_equal(back.warp.patch, plan.warp.patch) + assert back.params.align_patch_px == 600 + + +def test_localization_file_keeps_half_images(tmp_path: Path) -> None: + """The half images round-trip as float32; files without them read as None.""" + rng = np.random.default_rng(0) + mean = rng.random((5, 6, 2)) + halves = rng.random((2, 5, 6, 2)) + f = write_localization( + tmp_path / "a.h5", + mean, + mean[..., 0], + mean[..., 0], + [0, 1], + None, + {"settings_hash": "x"}, + halves, + ) + rec = read_localization(f) + np.testing.assert_array_equal(rec.half_ims, halves.astype(np.float32)) + assert rec.trial_images().half_ims is rec.half_ims + assert read_localization(f, half_ims=False).half_ims is None + g = write_localization(tmp_path / "b.h5", mean, mean[..., 0], mean[..., 0], [0, 1], None, {}) + assert read_localization(g).half_ims is None + assert read_localization(g).attrs["half_ims"] == 0 + + +def _bent_warp(n_trials: int = 2, shape: tuple[int, int] = (40, 50)) -> TrialWarp: + """Build an affine map with a bent field on top, per trial. + + Returns + ------- + TrialWarp + The per-trial affine maps, with the displacements of six random nodes. + """ + rng = np.random.default_rng(1) + nodes = rng.uniform([5, 5], [shape[0] - 5, shape[1] - 5], (6, 2)) + affine = np.zeros((n_trials, 2, 3)) + disp = np.zeros((n_trials, 6, 2)) + for t in range(n_trials): + a = np.array([[1.003, 0.002, 0.6 + t], [-0.002, 0.998, -1.1]]) + affine[t] = a + disp[t] = (a[:, :2] @ nodes.T + a[:, 2:3] - nodes.T).T + disp[t] += 0.3 * rng.standard_normal((6, 2)) + return TrialWarp(affine, nodes, 8.0, disp) + + +def test_rois_through_a_full_map() -> None: + """ROIs go through a full map. + + Masks take the trial mask's value at each consensus pixel's mapped + position; geometry goes through the inverse map (one-based [x, y]). + """ + warp = _bent_warp() + mask = np.zeros((40, 50), bool) + mask[18:23, 20:26] = True + center = np.array([23.0, 21.0]) # x (col), y (row), one-based + ann = PathAnnotations( + path=1, + dr="", + fn="E1T2DMD1", + rois=[UserRoi("SOMA a", "circle", mask, center=center)], + ) + rois = rois_to_consensus(ann, ["E1T1DMD1.tif", "E1T2DMD1.tif"], warp, (40, 50)) + np.testing.assert_array_equal(rois[0].mask, mask_to_consensus(mask, warp, 1, (40, 50))) + r, c = warp.coords(1, rois[0].center[1:] - 1, rois[0].center[:1] - 1) + np.testing.assert_allclose([c[0] + 1, r[0] + 1], center, atol=1e-6) + + +def test_per_trial_peaks_into_the_consensus_frame() -> None: + """Through the inverse of a non-shift map, minus the shift of a rigid one.""" + + class Plan: + """What _peaks_to_consensus reads of a plan.""" + + def __init__(self, warp: TrialWarp, shifts: np.ndarray) -> None: + """Store a warp and its shifts.""" + self.warp, self.shifts = warp, shifts + + peaks = np.array([[1.0, 10.0, 12.0, 0.5], [2.0, 30.5, 40.25, 0.5]]) + warp = _bent_warp() + out = _peaks_to_consensus(Plan(warp, np.zeros((2, 2))), 1, peaks) + r, c = warp.coords(1, out[:, 0], out[:, 1]) + np.testing.assert_allclose(np.column_stack([r, c]), peaks[:, 1:3], atol=1e-6) + rigid = TrialWarp.from_shifts([[0.5, -1.0], [1.0, 2.0]]) + shifts = np.array([[0.5, -1], [1, 2]]) + out = _peaks_to_consensus(Plan(rigid, shifts), 1, peaks) + np.testing.assert_array_equal(out, peaks[:, 1:3] - [1.0, 2.0]) diff --git a/tests/raster/test_raster_silo_noise_seeds.py b/tests/raster/test_raster_silo_noise_seeds.py index 1ffb2b43..14b787a0 100644 --- a/tests/raster/test_raster_silo_noise_seeds.py +++ b/tests/raster/test_raster_silo_noise_seeds.py @@ -1,36 +1,36 @@ -"""giant silo on the synthetic session with its own seeding (seeds in noise). - -Seeds placed in noise can end with an all-zero footprint, which made the -activity noise's normal matrix singular (numpy's inv raised where MATLAB's -warns); the run must complete. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.pipeline import silo -from giant_python.pipeline.silo_session import SiloSession - -# the fixture is used by name -from .test_raster_silo_stages import ( - EX, - PARAMS, - fake, # noqa: F401 - make_session, -) - - -@pytest.mark.filterwarnings("ignore::RuntimeWarning") -def test_own_seeding_in_noise_completes(tmp_path: Path, fake: None) -> None: # noqa: F811 - """Without a seeds file the session seeds itself. - - The run finishes and writes its summaries. - """ - table = make_session(tmp_path / "own") - report = silo.run_silo(table, PARAMS, EX) - s = SiloSession.open(table) - assert (s.out_dir / "experiment_summary.h5").exists() - assert report["total"] > 0 - assert np.isfinite(report["total"]) +"""giant silo on the synthetic session with its own seeding (seeds in noise). + +Seeds placed in noise can end with an all-zero footprint, which made the +activity noise's normal matrix singular (numpy's inv raised where MATLAB's +warns); the run must complete. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.pipeline import silo +from giant_python.pipeline.silo_session import SiloSession + +# the fixture is used by name +from .test_raster_silo_stages import ( + EX, + PARAMS, + fake, # noqa: F401 + make_session, +) + + +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_own_seeding_in_noise_completes(tmp_path: Path, fake: None) -> None: # noqa: F811 + """Without a seeds file the session seeds itself. + + The run finishes and writes its summaries. + """ + table = make_session(tmp_path / "own") + report = silo.run_silo(table, PARAMS, EX) + s = SiloSession.open(table) + assert (s.out_dir / "experiment_summary.h5").exists() + assert report["total"] > 0 + assert np.isfinite(report["total"]) diff --git a/tests/raster/test_raster_solver.py b/tests/raster/test_raster_solver.py index 87ff52e3..a7b85ef8 100644 --- a/tests/raster/test_raster_solver.py +++ b/tests/raster/test_raster_solver.py @@ -1,572 +1,572 @@ -"""Tests of the subproblem solver end to end. - -Also tests the assembly of a trial's results and the trial's activity traces. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - assemble_results, - conv_same, - estimate_photon_scale, - process_result, - solve_subproblem, - solve_subproblems, -) -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, - conv_operator, - initial_footprints, - sel_coords, -) - -DATA = Path(__file__).parent / "data" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" -HELPERS = DATA / "matlab_solver_helpers.h5" -# MATLAB's 3 x 3 support: the outputs are compared with MATLAB's (the -# default is 5 x 5; test_valid_kernel_lets_a_wide_footprint_be_fit sets it) -PARAMS = SolverParams(valid_kernel=3) -# MATLAB's loss for the footprint fit (the default holds its variance) -MATLAB_LOSS = replace(PARAMS, footprint_variance="model") - -# the real subproblem and MATLAB's outputs for it -SubproblemFixture = tuple[Subproblem, dict[str, np.ndarray]] - - -def _corr(a: np.ndarray, b: np.ndarray) -> float: - """Pearson correlation of two traces. - - Returns - ------- - float - The correlation coefficient of the flattened traces. - """ - return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) - - -@pytest.fixture(scope="module") -def fixture() -> SubproblemFixture: - """Load a real two-source subproblem and MATLAB's outputs for it. - - Returns - ------- - sub : Subproblem - The subproblem. - out : dict[str, np.ndarray] - MATLAB's outputs for it, by name. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - out = {k: v[()] for k, v in f["out"].items()} - return sub, out - - -@pytest.fixture(scope="module") -def solved(fixture: SubproblemFixture) -> SubproblemResult: - """Return the solver's result on the fixture, with its baseline. - - Returns - ------- - SubproblemResult - The result of solve_subproblem with the default test parameters. - """ - sub, _ = fixture - return solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) - - -@pytest.fixture(scope="module") -def solved_matlab_loss(fixture: SubproblemFixture) -> SubproblemResult: - """Return the result with MATLAB's loss for the footprint fit. - - Returns - ------- - SubproblemResult - The result of solve_subproblem with MATLAB_LOSS, with its baseline. - """ - sub, _ = fixture - opt = SolverOptions(keep_baseline=True) - return solve_subproblem(sub, MATLAB_LOSS, opt) - - -def test_agrees_with_matlab( - fixture: SubproblemFixture, solved_matlab_loss: SubproblemResult -) -> None: - """With MATLAB's loss, the converged solver's outputs are close to MATLAB's. - - MATLAB's fits stop early: same footprints and least squares, similar - activity. - """ - sub, out = fixture - r = solved_matlab_loss - assert r.footprints.shape == (sub.n_pixels, 2) - assert r.events.shape == r.ls.shape == r.f0.shape == (2, 2, 1000) - assert r.baseline.shape == (2, sub.n_pixels, 1000) - np.testing.assert_allclose(r.footprints.sum(0), 1.0, atol=1e-12) - assert r.events.min() >= 0 - for j in range(2): - hp, hm = r.footprints[:, j], out["H"][:, j] - cos = hp @ hm / np.sqrt((hp @ hp) * (hm @ hm)) - assert cos > 0.97 - assert _corr(r.ls[0, j], out["LS"][0, j]) > 0.97 - x = conv_same(r.events[0, j], PARAMS.k) - xm = conv_same(out["S"][0, j], PARAMS.k) - assert _corr(x, xm) > 0.9 - assert 0.8 < x.sum() / xm.sum() < 1.25 - ratio = r.f0[:, j].mean(1) / out["F0"][:, j].mean(1) - assert np.all(np.abs(ratio - 1) < 0.1) - assert np.all(np.isfinite(r.snr)) and np.all(r.snr > 0) - assert np.all(np.abs(r.snr / out["SNR"] - 1) < 0.3) - # channel 2's least squares do not depend on the activity fits - for j in range(2): - assert _corr(r.ls[1, j], out["LS"][1, j]) > 0.97 - - -def test_fits_converge_and_are_recorded(solved: SubproblemResult) -> None: - """Every fit ends on its tolerance, and its record is kept.""" - fits = {k: v for k, v in solved.info.items() if isinstance(v, dict)} - assert set(fits) == { - "activity1", - "footprints1", - "activity2", - "debias", - "activity_ch2", - "debias_ch2", - } - for name, fit in fits.items(): - assert fit["converged"], name - assert fit["iterations"] <= 20 and np.isfinite(fit["loss"]) - assert solved.info["baseline1_seconds"] > 0 - - -def test_events_below_the_floor_are_dropped(solved: SubproblemResult) -> None: - """The debias refit keeps the events of 0.1 or more only. - - It does not move the others' places. - """ - ev = solved.events - assert not np.any((ev > 0) & (ev < 1e-3)) - assert 0.01 < (ev[0] > 0).mean() < 0.5 - - -def test_batch_matches_single_solves(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """Subproblems of different sizes solved together get the results they get alone. - - They agree to the fits' tolerance. - """ - sub, _ = fixture - # a smaller subproblem: the first source and the pixels near it - rows, cols = sel_coords(sub.sel) - r0, c0 = sub.sources_rc[0] - keep = np.hypot(rows - r0, cols - c0) <= 4.2 - sel = np.zeros_like(sub.sel) - sel[rows[keep], cols[keep]] = True - small = Subproblem(y=sub.y[:, keep], finv=sub.finv[keep], sel=sel, sources_rc=[[r0, c0]]) - alone = solve_subproblem(small, PARAMS) - both = solve_subproblems([small, sub], PARAMS, SolverOptions(batch_bytes=1e9)) - assert both[0].footprints.shape == (int(keep.sum()), 1) - for got, ref in ((both[0], alone), (both[1], solved)): - np.testing.assert_allclose(got.footprints, ref.footprints, atol=1e-6) - np.testing.assert_allclose(got.snr, ref.snr, rtol=1e-4) - np.testing.assert_allclose(got.f0, ref.f0, rtol=1e-5) - scale = ref.events.max() - np.testing.assert_allclose(got.events, ref.events, atol=1e-3 * scale) - assert got.baseline is None - - -def test_batches_count_the_footprint_filter( - fixture: SubproblemFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """The size of a batch counts each member's data and its filter arrays. - - The filter arrays are dense, pixels x pixels. - """ - from giant_python.extraction.raster import solver - - sub, _ = fixture - sizes = [] - monkeypatch.setattr( - solver, - "_solve_batch", - lambda subs, p, o: sizes.append(len(subs)) or subs, - ) - n_px, n_t = sub.n_pixels, sub.n_frames - member = (n_px * n_t + 4 * n_px**2) * 8 - solve_subproblems([sub] * 5, PARAMS, SolverOptions(batch_bytes=2 * member)) - assert sizes == [2, 2, 1] - sizes.clear() - # the data alone would let three through - solve_subproblems([sub] * 3, PARAMS, SolverOptions(batch_bytes=3 * n_px * n_t * 8)) - assert sizes == [2, 1] - sizes.clear() - solve_subproblems([sub] * 3, PARAMS) # the CPU's default: one at a time - assert sizes == [1, 1, 1] - - -def test_trials_of_different_length_are_grouped( - fixture: SubproblemFixture, solved: SubproblemResult -) -> None: - """Subproblems with other numbers of frames or channels are solved in their own batches. - - They are returned in the order given. - """ - sub, _ = fixture - short = replace(sub, y=sub.y[:1, :, :600].copy(), finv=sub.finv[:, :600].copy()) - out = solve_subproblems([short, sub], PARAMS, SolverOptions(batch_bytes=1)) - assert out[0].events.shape == (1, 2, 600) - assert out[1].events.shape == (2, 2, 1000) - np.testing.assert_allclose(out[1].footprints, solved.footprints, atol=1e-6) - - -def test_more_than_two_channels_are_refused(fixture: SubproblemFixture) -> None: - """The solver fits the activity channel and one more, as MATLAB's. - - A third channel is refused, not dropped. - """ - sub, _ = fixture - three = replace(sub, y=np.concatenate([sub.y, sub.y[:1]])) - with pytest.raises(ValueError, match="3 channels"): - solve_subproblem(three, PARAMS) - - -def test_data_the_fits_cannot_weigh_are_refused(fixture: SubproblemFixture) -> None: - """Samples and variance multipliers the fits cannot weigh are input errors, not NaN results. - - That is, NaN samples and variance multipliers that are not positive and - finite. - """ - sub, _ = fixture - y = sub.y[:1].copy() - y[0, 3, 7] = np.nan - with pytest.raises(ValueError, match="NaN or infinite"): - solve_subproblem(replace(sub, y=y), PARAMS) - for bad in (0.0, -1.0, np.nan, np.inf): - finv = sub.finv.copy() - finv[5, 9] = bad - with pytest.raises(ValueError, match="variance multiplier"): - solve_subproblem(replace(sub, y=sub.y[:1], finv=finv), PARAMS) - empty = replace(sub, y=sub.y[:1], sources_rc=np.zeros((0, 2), int)) - with pytest.raises(ValueError, match="no source"): - solve_subproblem(empty, PARAMS) - assert solve_subproblems([], PARAMS) == [] - - -def test_options_are_checked() -> None: - """Options the fits cannot run with are refused when they are made.""" - with pytest.raises(ValueError, match="dtype"): - SolverOptions(dtype="float16") - with pytest.raises(ValueError, match="max_iter"): - SolverOptions(max_iter=-1) - with pytest.raises(ValueError, match="names no fit"): - SolverOptions(fit_max_iter={"footprint1": 0}) - with pytest.raises(ValueError, match="whole number"): - SolverOptions(fit_max_iter={"footprints1": -1}) - with pytest.raises(ValueError, match="batch_bytes"): - SolverOptions(batch_bytes=-1.0) - caps = {"activity2": 3, "debias": 0, "activity_ch2": 1, "debias_ch2": 2} - opt = SolverOptions(fit_max_iter=caps, max_iter=7) - assert opt.fit_options("activity2")["max_iter"] == 3 - assert opt.fit_options("activity1")["max_iter"] == 7 - - -def test_float32_fits_are_close(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """Fits in float32 give nearly the float64 result.""" - sub, _ = fixture - r = solve_subproblem(sub, PARAMS, SolverOptions(dtype="float32")) - for j in range(2): - assert _corr(r.footprints[:, j], solved.footprints[:, j]) > 0.999 - x = conv_same(r.events[0, j], PARAMS.k) - ref = conv_same(solved.events[0, j], PARAMS.k) - assert _corr(x, ref) > 0.995 - np.testing.assert_allclose(r.f0, solved.f0, rtol=1e-2) - - -def test_iteration_cap_is_reported(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """With one Newton iteration per fit, the fits are marked as not converged. - - They also reach higher losses. - """ - sub, _ = fixture - r = solve_subproblem(sub, PARAMS, SolverOptions(max_iter=1)) - assert not r.info["activity1"]["converged"] - assert r.info["activity1"]["iterations"] == 1 - assert r.info["activity1"]["loss"] > solved.info["activity1"]["loss"] - - -def test_single_fits_can_be_capped(fixture: SubproblemFixture, solved: SubproblemResult) -> None: - """A cap on one fit leaves the others to converge. - - A cap of 0 on the footprint fit keeps the starting footprints' shape. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - opt = SolverOptions(fit_max_iter={"footprints1": 0}) - r = solve_subproblem(one, PARAMS, opt) - assert r.info["footprints1"]["iterations"] == 0 - assert not r.info["footprints1"]["converged"] - assert r.info["activity1"]["converged"] and r.info["activity2"]["converged"] - assert r.info["activity1"]["loss"] == pytest.approx(solved.info["activity1"]["loss"], rel=1e-9) - # the starting Hs through the footprint filter, normalized - start = initial_footprints(sub.sel, sub.sources_rc, PARAMS.sigma_px)[0] - h = conv_operator(sub.sel, PARAMS.hfilter) @ start - np.testing.assert_allclose(r.footprints, h / h.sum(0), atol=1e-12) - assert np.abs(r.footprints - solved.footprints).max() > 1e-3 - - -def test_default_footprint_fit_holds_its_variance( - solved: SubproblemResult, solved_matlab_loss: SubproblemResult -) -> None: - """By default the variance of the footprint fit is held at its value at the fit's start. - - So the fit does not gain from raising the model: the footprints come out - more compact than with MATLAB's loss, and F0, which scales with their - spread, lower. Both fits converge. - """ - assert PARAMS.footprint_variance == "fixed" - fixed, model = solved, solved_matlab_loss - assert fixed.info["footprints1"]["converged"] - assert model.info["footprints1"]["converged"] - np.testing.assert_allclose(fixed.footprints.sum(0), 1.0, atol=1e-12) - compact = (fixed.footprints**2).sum(0) - assert np.all(compact > 1.02 * (model.footprints**2).sum(0)) - assert np.all(fixed.f0[0].mean(1) < model.f0[0].mean(1)) - for j in range(2): - assert _corr(fixed.footprints[:, j], model.footprints[:, j]) > 0.98 - # what precedes the footprint fit does not depend on the choice - assert fixed.info["activity1"]["loss"] == pytest.approx( - model.info["activity1"]["loss"], rel=1e-12 - ) - with pytest.raises(ValueError, match="footprint_variance"): - replace(PARAMS, footprint_variance="other") - - -def test_debias_variance_model_gives_larger_events( - fixture: SubproblemFixture, solved: SubproblemResult -) -> None: - """The model-variance debias refit rewards larger activity. - - This is MATLAB's behaviour before the fixed variance; the rest is unchanged. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - r = solve_subproblem(one, replace(PARAMS, debias_variance="model")) - assert r.events.shape == (1, 2, 1000) - np.testing.assert_allclose(r.footprints, solved.footprints, atol=1e-6) - np.testing.assert_allclose(r.ls[0], solved.ls[0], atol=1e-6) - assert r.events.sum() > 1.1 * solved.events[0].sum() - # both refit the events that the L1 fits found - same = (r.events[0] > 0) == (solved.events[0] > 0) - assert same.mean() > 0.99 - - -def test_one_outer_iteration(fixture: SubproblemFixture) -> None: - """With nmf_iter 1 the footprints stay at their start. - - No baseline or footprint fit runs. - """ - sub, _ = fixture - one = replace(sub, y=sub.y[:1]) - r = solve_subproblem(one, replace(PARAMS, nmf_iter=1)) - assert "footprints1" not in r.info and "activity1" in r.info - assert r.events.shape == (1, 2, 1000) - - -def test_photon_scale_matches_matlab() -> None: - """ExtractTrial's photon scale estimate.""" - with h5py.File(HELPERS, "r") as f: - finv = f["photon/Finv"][()] - y = 3 * f["photon/counts"][()] * np.sqrt(finv) - ref = float(f["photon/scale"][()]) - assert estimate_photon_scale(y, finv) == pytest.approx(ref, rel=1e-12) - - -def _result(n_px: int, n_src: int, n_t: int, value: float, n_ch: int = 2) -> SubproblemResult: - """Build a subproblem result filled with a constant. - - Returns - ------- - SubproblemResult - Footprints equal to value, events value, least squares 2 * value, - F0 3 * value and SNR 10 * value. - """ - return SubproblemResult( - footprints=np.full((n_px, n_src), value), - events=np.full((n_ch, n_src, n_t), value), - ls=np.full((n_ch, n_src, n_t), 2 * value), - f0=np.full((n_ch, n_src, n_t), 3 * value), - snr=np.full(n_src, 10 * value), - ) - - -def _placed(pixels: list[int], sources: list[int], n_t: int) -> Subproblem: - """Build a subproblem that only says where its results go. - - Returns - ------- - Subproblem - A subproblem with zero data whose pixels and sources are those given. - """ - n_px = len(pixels) - return Subproblem( - y=np.zeros((2, n_px, n_t), np.float32), - finv=np.ones((n_px, n_t), np.float32), - sel=np.ones((1, n_px), dtype=bool), - sources_rc=[[0, j] for j in range(len(sources))], - pixels=np.array(pixels), - sources=np.array(sources), - ) - - -def test_assemble_results() -> None: - """Results go to their pixels and sources. - - Events, least squares and F0 return to movie units; what no subproblem - covers is NaN. - """ - subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] - results = [_result(3, 1, 6, 1.0), _result(2, 2, 6, 2.0)] - t = assemble_results(subs, results, 6, 5, photon_scale=25.0) - assert t.footprints.dtype == np.float32 - assert t.footprints.shape == (6, 5) - assert np.all(t.footprints[[0, 1, 4], 2] == 1.0) - assert np.all(t.footprints[[2, 4]][:, [0, 3]] == 2.0) - assert np.isnan(t.footprints[0, 0]) and np.isnan(t.footprints[5]).all() - assert t.events.shape == t.ls.shape == t.f0.shape == (2, 5, 6) - assert np.all(t.events[:, 2] == 25.0) and np.all(t.events[:, 3] == 50.0) - assert np.all(t.ls[:, 0] == 100.0) and np.all(t.f0[:, 2] == 75.0) - assert np.isnan(t.events[:, [1, 4]]).all() - assert np.array_equal(t.snr[[0, 2, 3]], [20.0, 10.0, 20.0]) - assert np.isnan(t.snr[[1, 4]]).all() - with pytest.raises(ValueError, match="pixels and sources"): - assemble_results([replace(subs[0], pixels=None)], results[:1], 6, 5, 25.0) - # indices that would put results in the wrong place are refused - for bad, message in ( - ({"pixels": np.array([0, 1, 6])}, "pixels indices must lie"), - ({"sources": np.array([5])}, "sources indices must lie"), - ({"pixels": np.array([0, 1])}, "3 pixels and 2 indices for"), - ({"pixels": np.array([0, 1, 1])}, "pixels indices repeat"), - ): - with pytest.raises(ValueError, match=message): - assemble_results([replace(subs[0], **bad)], results[:1], 6, 5, 25.0) - with pytest.raises(ValueError, match="negative index"): - replace(subs[0], pixels=np.array([0, -1, 4])) - # one result per subproblem, each of the trial's channels and frames - with pytest.raises(ValueError, match="2 subproblems and 1 results"): - assemble_results(subs, results[:1], 6, 5, 25.0) - with pytest.raises(ValueError, match="at least one"): - assemble_results([], [], 6, 5, 25.0) - one_channel = _result(2, 2, 6, 2.0, n_ch=1) - with pytest.raises(ValueError, match="events are"): - assemble_results(subs, [results[0], one_channel], 6, 5, 25.0) - short = _result(2, 2, 5, 2.0) - with pytest.raises(ValueError, match="events are"): - assemble_results(subs, [results[0], short], 6, 5, 25.0) - wrong_snr = _result(2, 2, 6, 2.0) - wrong_snr.snr = np.ones(3) - with pytest.raises(ValueError, match="one SNR per source"): - assemble_results(subs, [results[0], wrong_snr], 6, 5, 25.0) - - -def test_process_result() -> None: - """The denoised activity is the events convolved with each channel's kernel. - - Discarded frames are NaN in the traces, as MATLAB leaves them (channel 2's - events keep their values). - """ - n_t = 40 - rng = np.random.default_rng(0) - subs = [_placed([0, 1], [0, 1], n_t)] - res = _result(2, 2, n_t, 1.0) - res.events = (rng.random((2, 2, n_t)) < 0.2) * rng.random((2, 2, n_t)) - trial = assemble_results(subs, [res], 2, 2, photon_scale=2.0) - discard = np.zeros(n_t, dtype=bool) - discard[[3, 4, 30]] = True - params = SolverParams(tau_s=0.01, tau2_s=0.02) - act = process_result(trial, params, discard) - keep = ~discard - np.testing.assert_allclose( - act.denoised[0][:, keep], - conv_same(trial.events[0], params.k)[:, keep], - ) - np.testing.assert_allclose( - act.denoised[1][:, keep], - conv_same(trial.events[1], params.k2)[:, keep], - ) - assert np.isnan(act.denoised[:, :, discard]).all() - assert np.isnan(act.ls[:, :, discard]).all() - assert np.isnan(act.events[0][:, discard]).all() - assert np.array_equal(act.events[1], trial.events[1]) - assert np.array_equal(act.events[0][:, keep], trial.events[0][:, keep]) - assert act.f0 is trial.f0 and act.snr is trial.snr - with pytest.raises(ValueError, match="discard has 39 frames"): - process_result(trial, params, discard[:-1]) - # the trial's own arrays are left as they were - assert not np.isnan(trial.events).any() - - -def test_conv_same_is_matlabs() -> None: - """'same' keeps the first argument's length, also below the kernel's.""" - k = np.array([0.0, 0.0, 1.0, 0.5, 0.25]) - x = np.array([[1.0, 0.0, 0.0, 2.0]]) - assert np.array_equal(conv_same(x, k), [[1.0, 0.5, 0.25, 2.0]]) - assert np.array_equal(conv_same(x[:, :2], k), [[1.0, 0.5]]) - - -def _rms_width(h: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> float: - """RMS width per axis of a footprint about its centroid. - - Returns - ------- - float - The root mean square width per axis of the clipped, normalised footprint. - """ - h = np.clip(h, 0, None) / np.clip(h, 0, None).sum() - m = np.array([h @ rows, h @ cols]) - return float(np.sqrt((h @ ((rows - m[0]) ** 2 + (cols - m[1]) ** 2)) / 2)) - - -def test_valid_kernel_lets_a_wide_footprint_be_fit() -> None: - """A sigma-1.8 source on its true baseline, fit with the 3 x 3 and 5 x 5 supports. - - With the 3 x 3 support the fitted footprint stops near its ceiling (1.56 px), - with 5 x 5 it gets close to the truth (1.8 px). - """ - rng = np.random.default_rng(3) - sel = np.ones((13, 13), dtype=bool) - rows, cols = sel_coords(sel) - rows, cols = rows.astype(float), cols.astype(float) - h = np.exp(-((rows - 6) ** 2 + (cols - 6) ** 2) / (2 * 1.8**2)) - h /= h.sum() - n = 8000 - ev = np.where(rng.random(n) < 0.01, rng.exponential(150.0, n), 0.0) - x = np.convolve(ev, PARAMS.k, mode="same") - b = np.full((h.size, n), 2.0) - y = rng.poisson(b + h[:, None] * x[None]).astype(np.float64)[None] - sub = Subproblem( - y=y, - finv=np.ones(y.shape[1:]), - sel=sel, - sources_rc=np.array([[6, 6]]), - baseline=b, - ) - true_w = _rms_width(h, rows, cols) - widths = {} - for vk in (3, 5): - p = replace(PARAMS, baseline_mode="fixed", valid_kernel=vk) - res = solve_subproblem(sub, p) - widths[vk] = _rms_width(res.footprints[:, 0], rows, cols) - assert widths[3] < 1.57 - assert abs(widths[5] - true_w) < 0.1 - assert abs(widths[5] - true_w) < abs(widths[3] - true_w) / 2 +"""Tests of the subproblem solver end to end. + +Also tests the assembly of a trial's results and the trial's activity traces. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + assemble_results, + conv_same, + estimate_photon_scale, + process_result, + solve_subproblem, + solve_subproblems, +) +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, + conv_operator, + initial_footprints, + sel_coords, +) + +DATA = Path(__file__).parent / "data" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" +HELPERS = DATA / "matlab_solver_helpers.h5" +# MATLAB's 3 x 3 support: the outputs are compared with MATLAB's (the +# default is 5 x 5; test_valid_kernel_lets_a_wide_footprint_be_fit sets it) +PARAMS = SolverParams(valid_kernel=3) +# MATLAB's loss for the footprint fit (the default holds its variance) +MATLAB_LOSS = replace(PARAMS, footprint_variance="model") + +# the real subproblem and MATLAB's outputs for it +SubproblemFixture = tuple[Subproblem, dict[str, np.ndarray]] + + +def _corr(a: np.ndarray, b: np.ndarray) -> float: + """Pearson correlation of two traces. + + Returns + ------- + float + The correlation coefficient of the flattened traces. + """ + return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) + + +@pytest.fixture(scope="module") +def fixture() -> SubproblemFixture: + """Load a real two-source subproblem and MATLAB's outputs for it. + + Returns + ------- + sub : Subproblem + The subproblem. + out : dict[str, np.ndarray] + MATLAB's outputs for it, by name. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + out = {k: v[()] for k, v in f["out"].items()} + return sub, out + + +@pytest.fixture(scope="module") +def solved(fixture: SubproblemFixture) -> SubproblemResult: + """Return the solver's result on the fixture, with its baseline. + + Returns + ------- + SubproblemResult + The result of solve_subproblem with the default test parameters. + """ + sub, _ = fixture + return solve_subproblem(sub, PARAMS, SolverOptions(keep_baseline=True)) + + +@pytest.fixture(scope="module") +def solved_matlab_loss(fixture: SubproblemFixture) -> SubproblemResult: + """Return the result with MATLAB's loss for the footprint fit. + + Returns + ------- + SubproblemResult + The result of solve_subproblem with MATLAB_LOSS, with its baseline. + """ + sub, _ = fixture + opt = SolverOptions(keep_baseline=True) + return solve_subproblem(sub, MATLAB_LOSS, opt) + + +def test_agrees_with_matlab( + fixture: SubproblemFixture, solved_matlab_loss: SubproblemResult +) -> None: + """With MATLAB's loss, the converged solver's outputs are close to MATLAB's. + + MATLAB's fits stop early: same footprints and least squares, similar + activity. + """ + sub, out = fixture + r = solved_matlab_loss + assert r.footprints.shape == (sub.n_pixels, 2) + assert r.events.shape == r.ls.shape == r.f0.shape == (2, 2, 1000) + assert r.baseline.shape == (2, sub.n_pixels, 1000) + np.testing.assert_allclose(r.footprints.sum(0), 1.0, atol=1e-12) + assert r.events.min() >= 0 + for j in range(2): + hp, hm = r.footprints[:, j], out["H"][:, j] + cos = hp @ hm / np.sqrt((hp @ hp) * (hm @ hm)) + assert cos > 0.97 + assert _corr(r.ls[0, j], out["LS"][0, j]) > 0.97 + x = conv_same(r.events[0, j], PARAMS.k) + xm = conv_same(out["S"][0, j], PARAMS.k) + assert _corr(x, xm) > 0.9 + assert 0.8 < x.sum() / xm.sum() < 1.25 + ratio = r.f0[:, j].mean(1) / out["F0"][:, j].mean(1) + assert np.all(np.abs(ratio - 1) < 0.1) + assert np.all(np.isfinite(r.snr)) and np.all(r.snr > 0) + assert np.all(np.abs(r.snr / out["SNR"] - 1) < 0.3) + # channel 2's least squares do not depend on the activity fits + for j in range(2): + assert _corr(r.ls[1, j], out["LS"][1, j]) > 0.97 + + +def test_fits_converge_and_are_recorded(solved: SubproblemResult) -> None: + """Every fit ends on its tolerance, and its record is kept.""" + fits = {k: v for k, v in solved.info.items() if isinstance(v, dict)} + assert set(fits) == { + "activity1", + "footprints1", + "activity2", + "debias", + "activity_ch2", + "debias_ch2", + } + for name, fit in fits.items(): + assert fit["converged"], name + assert fit["iterations"] <= 20 and np.isfinite(fit["loss"]) + assert solved.info["baseline1_seconds"] > 0 + + +def test_events_below_the_floor_are_dropped(solved: SubproblemResult) -> None: + """The debias refit keeps the events of 0.1 or more only. + + It does not move the others' places. + """ + ev = solved.events + assert not np.any((ev > 0) & (ev < 1e-3)) + assert 0.01 < (ev[0] > 0).mean() < 0.5 + + +def test_batch_matches_single_solves(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """Subproblems of different sizes solved together get the results they get alone. + + They agree to the fits' tolerance. + """ + sub, _ = fixture + # a smaller subproblem: the first source and the pixels near it + rows, cols = sel_coords(sub.sel) + r0, c0 = sub.sources_rc[0] + keep = np.hypot(rows - r0, cols - c0) <= 4.2 + sel = np.zeros_like(sub.sel) + sel[rows[keep], cols[keep]] = True + small = Subproblem(y=sub.y[:, keep], finv=sub.finv[keep], sel=sel, sources_rc=[[r0, c0]]) + alone = solve_subproblem(small, PARAMS) + both = solve_subproblems([small, sub], PARAMS, SolverOptions(batch_bytes=1e9)) + assert both[0].footprints.shape == (int(keep.sum()), 1) + for got, ref in ((both[0], alone), (both[1], solved)): + np.testing.assert_allclose(got.footprints, ref.footprints, atol=1e-6) + np.testing.assert_allclose(got.snr, ref.snr, rtol=1e-4) + np.testing.assert_allclose(got.f0, ref.f0, rtol=1e-5) + scale = ref.events.max() + np.testing.assert_allclose(got.events, ref.events, atol=1e-3 * scale) + assert got.baseline is None + + +def test_batches_count_the_footprint_filter( + fixture: SubproblemFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """The size of a batch counts each member's data and its filter arrays. + + The filter arrays are dense, pixels x pixels. + """ + from giant_python.extraction.raster import solver + + sub, _ = fixture + sizes = [] + monkeypatch.setattr( + solver, + "_solve_batch", + lambda subs, p, o: sizes.append(len(subs)) or subs, + ) + n_px, n_t = sub.n_pixels, sub.n_frames + member = (n_px * n_t + 4 * n_px**2) * 8 + solve_subproblems([sub] * 5, PARAMS, SolverOptions(batch_bytes=2 * member)) + assert sizes == [2, 2, 1] + sizes.clear() + # the data alone would let three through + solve_subproblems([sub] * 3, PARAMS, SolverOptions(batch_bytes=3 * n_px * n_t * 8)) + assert sizes == [2, 1] + sizes.clear() + solve_subproblems([sub] * 3, PARAMS) # the CPU's default: one at a time + assert sizes == [1, 1, 1] + + +def test_trials_of_different_length_are_grouped( + fixture: SubproblemFixture, solved: SubproblemResult +) -> None: + """Subproblems with other numbers of frames or channels are solved in their own batches. + + They are returned in the order given. + """ + sub, _ = fixture + short = replace(sub, y=sub.y[:1, :, :600].copy(), finv=sub.finv[:, :600].copy()) + out = solve_subproblems([short, sub], PARAMS, SolverOptions(batch_bytes=1)) + assert out[0].events.shape == (1, 2, 600) + assert out[1].events.shape == (2, 2, 1000) + np.testing.assert_allclose(out[1].footprints, solved.footprints, atol=1e-6) + + +def test_more_than_two_channels_are_refused(fixture: SubproblemFixture) -> None: + """The solver fits the activity channel and one more, as MATLAB's. + + A third channel is refused, not dropped. + """ + sub, _ = fixture + three = replace(sub, y=np.concatenate([sub.y, sub.y[:1]])) + with pytest.raises(ValueError, match="3 channels"): + solve_subproblem(three, PARAMS) + + +def test_data_the_fits_cannot_weigh_are_refused(fixture: SubproblemFixture) -> None: + """Samples and variance multipliers the fits cannot weigh are input errors, not NaN results. + + That is, NaN samples and variance multipliers that are not positive and + finite. + """ + sub, _ = fixture + y = sub.y[:1].copy() + y[0, 3, 7] = np.nan + with pytest.raises(ValueError, match="NaN or infinite"): + solve_subproblem(replace(sub, y=y), PARAMS) + for bad in (0.0, -1.0, np.nan, np.inf): + finv = sub.finv.copy() + finv[5, 9] = bad + with pytest.raises(ValueError, match="variance multiplier"): + solve_subproblem(replace(sub, y=sub.y[:1], finv=finv), PARAMS) + empty = replace(sub, y=sub.y[:1], sources_rc=np.zeros((0, 2), int)) + with pytest.raises(ValueError, match="no source"): + solve_subproblem(empty, PARAMS) + assert solve_subproblems([], PARAMS) == [] + + +def test_options_are_checked() -> None: + """Options the fits cannot run with are refused when they are made.""" + with pytest.raises(ValueError, match="dtype"): + SolverOptions(dtype="float16") + with pytest.raises(ValueError, match="max_iter"): + SolverOptions(max_iter=-1) + with pytest.raises(ValueError, match="names no fit"): + SolverOptions(fit_max_iter={"footprint1": 0}) + with pytest.raises(ValueError, match="whole number"): + SolverOptions(fit_max_iter={"footprints1": -1}) + with pytest.raises(ValueError, match="batch_bytes"): + SolverOptions(batch_bytes=-1.0) + caps = {"activity2": 3, "debias": 0, "activity_ch2": 1, "debias_ch2": 2} + opt = SolverOptions(fit_max_iter=caps, max_iter=7) + assert opt.fit_options("activity2")["max_iter"] == 3 + assert opt.fit_options("activity1")["max_iter"] == 7 + + +def test_float32_fits_are_close(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """Fits in float32 give nearly the float64 result.""" + sub, _ = fixture + r = solve_subproblem(sub, PARAMS, SolverOptions(dtype="float32")) + for j in range(2): + assert _corr(r.footprints[:, j], solved.footprints[:, j]) > 0.999 + x = conv_same(r.events[0, j], PARAMS.k) + ref = conv_same(solved.events[0, j], PARAMS.k) + assert _corr(x, ref) > 0.995 + np.testing.assert_allclose(r.f0, solved.f0, rtol=1e-2) + + +def test_iteration_cap_is_reported(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """With one Newton iteration per fit, the fits are marked as not converged. + + They also reach higher losses. + """ + sub, _ = fixture + r = solve_subproblem(sub, PARAMS, SolverOptions(max_iter=1)) + assert not r.info["activity1"]["converged"] + assert r.info["activity1"]["iterations"] == 1 + assert r.info["activity1"]["loss"] > solved.info["activity1"]["loss"] + + +def test_single_fits_can_be_capped(fixture: SubproblemFixture, solved: SubproblemResult) -> None: + """A cap on one fit leaves the others to converge. + + A cap of 0 on the footprint fit keeps the starting footprints' shape. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + opt = SolverOptions(fit_max_iter={"footprints1": 0}) + r = solve_subproblem(one, PARAMS, opt) + assert r.info["footprints1"]["iterations"] == 0 + assert not r.info["footprints1"]["converged"] + assert r.info["activity1"]["converged"] and r.info["activity2"]["converged"] + assert r.info["activity1"]["loss"] == pytest.approx(solved.info["activity1"]["loss"], rel=1e-9) + # the starting Hs through the footprint filter, normalized + start = initial_footprints(sub.sel, sub.sources_rc, PARAMS.sigma_px)[0] + h = conv_operator(sub.sel, PARAMS.hfilter) @ start + np.testing.assert_allclose(r.footprints, h / h.sum(0), atol=1e-12) + assert np.abs(r.footprints - solved.footprints).max() > 1e-3 + + +def test_default_footprint_fit_holds_its_variance( + solved: SubproblemResult, solved_matlab_loss: SubproblemResult +) -> None: + """By default the variance of the footprint fit is held at its value at the fit's start. + + So the fit does not gain from raising the model: the footprints come out + more compact than with MATLAB's loss, and F0, which scales with their + spread, lower. Both fits converge. + """ + assert PARAMS.footprint_variance == "fixed" + fixed, model = solved, solved_matlab_loss + assert fixed.info["footprints1"]["converged"] + assert model.info["footprints1"]["converged"] + np.testing.assert_allclose(fixed.footprints.sum(0), 1.0, atol=1e-12) + compact = (fixed.footprints**2).sum(0) + assert np.all(compact > 1.02 * (model.footprints**2).sum(0)) + assert np.all(fixed.f0[0].mean(1) < model.f0[0].mean(1)) + for j in range(2): + assert _corr(fixed.footprints[:, j], model.footprints[:, j]) > 0.98 + # what precedes the footprint fit does not depend on the choice + assert fixed.info["activity1"]["loss"] == pytest.approx( + model.info["activity1"]["loss"], rel=1e-12 + ) + with pytest.raises(ValueError, match="footprint_variance"): + replace(PARAMS, footprint_variance="other") + + +def test_debias_variance_model_gives_larger_events( + fixture: SubproblemFixture, solved: SubproblemResult +) -> None: + """The model-variance debias refit rewards larger activity. + + This is MATLAB's behaviour before the fixed variance; the rest is unchanged. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + r = solve_subproblem(one, replace(PARAMS, debias_variance="model")) + assert r.events.shape == (1, 2, 1000) + np.testing.assert_allclose(r.footprints, solved.footprints, atol=1e-6) + np.testing.assert_allclose(r.ls[0], solved.ls[0], atol=1e-6) + assert r.events.sum() > 1.1 * solved.events[0].sum() + # both refit the events that the L1 fits found + same = (r.events[0] > 0) == (solved.events[0] > 0) + assert same.mean() > 0.99 + + +def test_one_outer_iteration(fixture: SubproblemFixture) -> None: + """With nmf_iter 1 the footprints stay at their start. + + No baseline or footprint fit runs. + """ + sub, _ = fixture + one = replace(sub, y=sub.y[:1]) + r = solve_subproblem(one, replace(PARAMS, nmf_iter=1)) + assert "footprints1" not in r.info and "activity1" in r.info + assert r.events.shape == (1, 2, 1000) + + +def test_photon_scale_matches_matlab() -> None: + """ExtractTrial's photon scale estimate.""" + with h5py.File(HELPERS, "r") as f: + finv = f["photon/Finv"][()] + y = 3 * f["photon/counts"][()] * np.sqrt(finv) + ref = float(f["photon/scale"][()]) + assert estimate_photon_scale(y, finv) == pytest.approx(ref, rel=1e-12) + + +def _result(n_px: int, n_src: int, n_t: int, value: float, n_ch: int = 2) -> SubproblemResult: + """Build a subproblem result filled with a constant. + + Returns + ------- + SubproblemResult + Footprints equal to value, events value, least squares 2 * value, + F0 3 * value and SNR 10 * value. + """ + return SubproblemResult( + footprints=np.full((n_px, n_src), value), + events=np.full((n_ch, n_src, n_t), value), + ls=np.full((n_ch, n_src, n_t), 2 * value), + f0=np.full((n_ch, n_src, n_t), 3 * value), + snr=np.full(n_src, 10 * value), + ) + + +def _placed(pixels: list[int], sources: list[int], n_t: int) -> Subproblem: + """Build a subproblem that only says where its results go. + + Returns + ------- + Subproblem + A subproblem with zero data whose pixels and sources are those given. + """ + n_px = len(pixels) + return Subproblem( + y=np.zeros((2, n_px, n_t), np.float32), + finv=np.ones((n_px, n_t), np.float32), + sel=np.ones((1, n_px), dtype=bool), + sources_rc=[[0, j] for j in range(len(sources))], + pixels=np.array(pixels), + sources=np.array(sources), + ) + + +def test_assemble_results() -> None: + """Results go to their pixels and sources. + + Events, least squares and F0 return to movie units; what no subproblem + covers is NaN. + """ + subs = [_placed([0, 1, 4], [2], 6), _placed([2, 4], [0, 3], 6)] + results = [_result(3, 1, 6, 1.0), _result(2, 2, 6, 2.0)] + t = assemble_results(subs, results, 6, 5, photon_scale=25.0) + assert t.footprints.dtype == np.float32 + assert t.footprints.shape == (6, 5) + assert np.all(t.footprints[[0, 1, 4], 2] == 1.0) + assert np.all(t.footprints[[2, 4]][:, [0, 3]] == 2.0) + assert np.isnan(t.footprints[0, 0]) and np.isnan(t.footprints[5]).all() + assert t.events.shape == t.ls.shape == t.f0.shape == (2, 5, 6) + assert np.all(t.events[:, 2] == 25.0) and np.all(t.events[:, 3] == 50.0) + assert np.all(t.ls[:, 0] == 100.0) and np.all(t.f0[:, 2] == 75.0) + assert np.isnan(t.events[:, [1, 4]]).all() + assert np.array_equal(t.snr[[0, 2, 3]], [20.0, 10.0, 20.0]) + assert np.isnan(t.snr[[1, 4]]).all() + with pytest.raises(ValueError, match="pixels and sources"): + assemble_results([replace(subs[0], pixels=None)], results[:1], 6, 5, 25.0) + # indices that would put results in the wrong place are refused + for bad, message in ( + ({"pixels": np.array([0, 1, 6])}, "pixels indices must lie"), + ({"sources": np.array([5])}, "sources indices must lie"), + ({"pixels": np.array([0, 1])}, "3 pixels and 2 indices for"), + ({"pixels": np.array([0, 1, 1])}, "pixels indices repeat"), + ): + with pytest.raises(ValueError, match=message): + assemble_results([replace(subs[0], **bad)], results[:1], 6, 5, 25.0) + with pytest.raises(ValueError, match="negative index"): + replace(subs[0], pixels=np.array([0, -1, 4])) + # one result per subproblem, each of the trial's channels and frames + with pytest.raises(ValueError, match="2 subproblems and 1 results"): + assemble_results(subs, results[:1], 6, 5, 25.0) + with pytest.raises(ValueError, match="at least one"): + assemble_results([], [], 6, 5, 25.0) + one_channel = _result(2, 2, 6, 2.0, n_ch=1) + with pytest.raises(ValueError, match="events are"): + assemble_results(subs, [results[0], one_channel], 6, 5, 25.0) + short = _result(2, 2, 5, 2.0) + with pytest.raises(ValueError, match="events are"): + assemble_results(subs, [results[0], short], 6, 5, 25.0) + wrong_snr = _result(2, 2, 6, 2.0) + wrong_snr.snr = np.ones(3) + with pytest.raises(ValueError, match="one SNR per source"): + assemble_results(subs, [results[0], wrong_snr], 6, 5, 25.0) + + +def test_process_result() -> None: + """The denoised activity is the events convolved with each channel's kernel. + + Discarded frames are NaN in the traces, as MATLAB leaves them (channel 2's + events keep their values). + """ + n_t = 40 + rng = np.random.default_rng(0) + subs = [_placed([0, 1], [0, 1], n_t)] + res = _result(2, 2, n_t, 1.0) + res.events = (rng.random((2, 2, n_t)) < 0.2) * rng.random((2, 2, n_t)) + trial = assemble_results(subs, [res], 2, 2, photon_scale=2.0) + discard = np.zeros(n_t, dtype=bool) + discard[[3, 4, 30]] = True + params = SolverParams(tau_s=0.01, tau2_s=0.02) + act = process_result(trial, params, discard) + keep = ~discard + np.testing.assert_allclose( + act.denoised[0][:, keep], + conv_same(trial.events[0], params.k)[:, keep], + ) + np.testing.assert_allclose( + act.denoised[1][:, keep], + conv_same(trial.events[1], params.k2)[:, keep], + ) + assert np.isnan(act.denoised[:, :, discard]).all() + assert np.isnan(act.ls[:, :, discard]).all() + assert np.isnan(act.events[0][:, discard]).all() + assert np.array_equal(act.events[1], trial.events[1]) + assert np.array_equal(act.events[0][:, keep], trial.events[0][:, keep]) + assert act.f0 is trial.f0 and act.snr is trial.snr + with pytest.raises(ValueError, match="discard has 39 frames"): + process_result(trial, params, discard[:-1]) + # the trial's own arrays are left as they were + assert not np.isnan(trial.events).any() + + +def test_conv_same_is_matlabs() -> None: + """'same' keeps the first argument's length, also below the kernel's.""" + k = np.array([0.0, 0.0, 1.0, 0.5, 0.25]) + x = np.array([[1.0, 0.0, 0.0, 2.0]]) + assert np.array_equal(conv_same(x, k), [[1.0, 0.5, 0.25, 2.0]]) + assert np.array_equal(conv_same(x[:, :2], k), [[1.0, 0.5]]) + + +def _rms_width(h: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> float: + """RMS width per axis of a footprint about its centroid. + + Returns + ------- + float + The root mean square width per axis of the clipped, normalised footprint. + """ + h = np.clip(h, 0, None) / np.clip(h, 0, None).sum() + m = np.array([h @ rows, h @ cols]) + return float(np.sqrt((h @ ((rows - m[0]) ** 2 + (cols - m[1]) ** 2)) / 2)) + + +def test_valid_kernel_lets_a_wide_footprint_be_fit() -> None: + """A sigma-1.8 source on its true baseline, fit with the 3 x 3 and 5 x 5 supports. + + With the 3 x 3 support the fitted footprint stops near its ceiling (1.56 px), + with 5 x 5 it gets close to the truth (1.8 px). + """ + rng = np.random.default_rng(3) + sel = np.ones((13, 13), dtype=bool) + rows, cols = sel_coords(sel) + rows, cols = rows.astype(float), cols.astype(float) + h = np.exp(-((rows - 6) ** 2 + (cols - 6) ** 2) / (2 * 1.8**2)) + h /= h.sum() + n = 8000 + ev = np.where(rng.random(n) < 0.01, rng.exponential(150.0, n), 0.0) + x = np.convolve(ev, PARAMS.k, mode="same") + b = np.full((h.size, n), 2.0) + y = rng.poisson(b + h[:, None] * x[None]).astype(np.float64)[None] + sub = Subproblem( + y=y, + finv=np.ones(y.shape[1:]), + sel=sel, + sources_rc=np.array([[6, 6]]), + baseline=b, + ) + true_w = _rms_width(h, rows, cols) + widths = {} + for vk in (3, 5): + p = replace(PARAMS, baseline_mode="fixed", valid_kernel=vk) + res = solve_subproblem(sub, p) + widths[vk] = _rms_width(res.footprints[:, 0], rows, cols) + assert widths[3] < 1.57 + assert abs(widths[5] - true_w) < 0.1 + assert abs(widths[5] - true_w) < abs(widths[3] - true_w) / 2 diff --git a/tests/raster/test_raster_solver_baseline.py b/tests/raster/test_raster_solver_baseline.py index c95c7a7b..abd9c761 100644 --- a/tests/raster/test_raster_solver_baseline.py +++ b/tests/raster/test_raster_solver_baseline.py @@ -1,496 +1,496 @@ -"""Tests of the deterministic parts of the subproblem solver. - -The baseline (splitFreq, fitB and its helpers), the floor and the noise -estimate, against GIAnT-MATLAB's values. -""" - -import warnings -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -from numpy.typing import ArrayLike -from scipy import optimize - -from giant_python.extraction.raster import solver_baseline as sb -from giant_python.extraction.raster.localization import movmean_nan -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - conv_operator, - sel_coords, -) - -DATA = Path(__file__).parent / "data" -HELPERS = DATA / "matlab_solver_helpers.h5" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() # SILo's defaults for SLAP2, as the subproblem's -# parameters of the small fitB and getSurround references -SMALL = SolverParams( - sigma_px=1.33, - sel_radius=2, - tau_full=3, - tau2_s=0.05, - analyze_hz=100, - baseline_window_s=0.6, - denoise_window_s=0.1, -) - - -def _close(a: ArrayLike, b: ArrayLike, tol: float = 1e-12) -> None: - """Equal NaN patterns, and differences below tol of the largest value.""" - a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) - assert a.shape == b.shape - assert np.array_equal(np.isnan(a), np.isnan(b)) - assert np.nanmax(np.abs(a - b)) <= tol * np.nanmax(np.abs(b)) - - -def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: - """MATLAB convn(x, k, 'same') along the rows. - - Returns - ------- - np.ndarray - Each row of `x` convolved with `k`, cropped to the length of the row. - """ - c = len(k) // 2 - return np.stack([np.convolve(r, k)[c : c + x.shape[1]] for r in x]) - - -def _read_tree(g: h5py.Group) -> dict[str, Any]: - """Read an HDF5 group as nested dicts of arrays. - - Returns - ------- - dict[str, Any] - The group's datasets as arrays (or scalars) and its subgroups as nested dicts. - """ - return {k: _read_tree(v) if isinstance(v, h5py.Group) else v[()] for k, v in g.items()} - - -@pytest.fixture(scope="module") -def helpers() -> dict[str, Any]: - """MATLAB's values for the helper functions. - - Returns - ------- - dict[str, Any] - The helper fixture file as nested dicts of arrays. - """ - with h5py.File(HELPERS, "r") as f: - return _read_tree(f) - - -@pytest.fixture(scope="module") -def sub() -> dict[str, Any]: - """Load the subproblem fixture: inputs as float64, MATLAB's intermediates. - - Returns - ------- - dict[str, Any] - The fixture file as nested dicts, plus every (the baseline step interval) and the - float64 y and finv and boolean sel copied from its inputs. - """ - with h5py.File(SUBPROBLEM, "r") as f: - d = _read_tree(f) - d["every"] = int(f.attrs["baseline_every"]) - d["y"] = d["in"]["y"].astype(np.float64) - d["finv"] = d["in"]["finv"].astype(np.float64) - d["sel"] = d["in"]["sel"].astype(bool) - return d - - -@pytest.mark.parametrize("window", [4, 7, 20, 50]) -def test_lowess_and_movmean_match_matlab(helpers: dict[str, Any], window: int) -> None: - """Smoothdata's lowess and movmean, for even, odd and too long windows.""" - s = helpers["smooth"] - _close(sb.smooth_lowess(s["A"], window), s[f"lowess_{window}"]) - _close(movmean_nan(s["A"].T, window).T, s[f"movmean_{window}"]) - - -@pytest.mark.parametrize("window", [7, 20]) -def test_lowess_omits_nan_as_matlab(helpers: dict[str, Any], window: int) -> None: - """NaN samples are left out of the local fits.""" - s = helpers["smooth"] - assert np.isnan(s["An"]).sum() == 10 - _close(sb.smooth_lowess(s["An"], window), s[f"lowess_nan_{window}"]) - - -def test_lowess_degenerate_windows() -> None: - """A window of one sample returns the data. - - A window whose only weighted sample is the centre returns it; all-NaN - windows give NaN. - """ - a = np.array([[1.0, 4.0, 2.0, np.nan, np.nan, np.nan, 7.0]]) - assert np.array_equal(sb.smooth_lowess(a[:, :3], 1), a[:, :3]) - out = sb.smooth_lowess(a, 3) - assert np.array_equal(out[0, :3], a[0, :3]) - assert np.isnan(out[0, 4]) - # the NaN next to a value takes it (zero weight, so the window's mean) - assert out[0, 3] == 2.0 and out[0, 5] == 7.0 - - -@pytest.mark.parametrize( - "name, order, n, pad", - [ - ("zeros_3_20", 3, 20, "zeros"), - ("zeros_2_5", 2, 5, "zeros"), - ("zeros_1_4", 1, 4, "zeros"), - ("sym_5_46", 5, 46, "symmetric"), - ("sym_3_7", 3, 7, "symmetric"), - ("sym_2_6", 2, 6, "symmetric"), - ("med_9", 5, 9, "symmetric"), - ], -) -def test_order_filters_match_matlab( - helpers: dict[str, Any], name: str, order: int, n: int, pad: str -) -> None: - """ordfilt2 and medfilt2 along rows, with both paddings. - - The window of 46 is longer than the 41 samples. - """ - o = helpers["ord"] - assert np.array_equal(sb.ordfilt_rows(o["a"], order, n, pad), o[name]) - - -def test_split_freq_matches_matlab(helpers: dict[str, Any]) -> None: - """splitFreq, also for a trial too short to interpolate.""" - s = helpers["split"] - lp, hp = sb.split_freq(s["A"], 10, 6) - _close(lp, s["LP"]) - assert np.array_equal(hp, s["A"] - lp) - short, _ = sb.split_freq(s["A"][:, :15], 10, 6) - _close(short, s["LP_short"]) - _close(sb.split_freq(s["D"], 10, 6)[0], s["LP_nan"]) - - -def test_initial_baseline_takes_min_where_nan(monkeypatch: pytest.MonkeyPatch) -> None: - """Where splitFreq's low-pass is NaN the baseline is min_baseline. - - As MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below. - """ - lp = np.array([[np.nan, 0.5, -1.0], [2.0, np.nan, 0.001]]) - monkeypatch.setattr(sb, "split_freq", lambda *a: (lp, None)) - b = sb.initial_baseline(np.zeros((2, 3)), PARAMS) - assert np.array_equal(b, [[0.01, 0.5, 0.01], [2.0, 0.01, 0.01]]) - - -def test_compute_floor_matches_matlab(helpers: dict[str, Any]) -> None: - """computeFloor, for integer and fractional windows.""" - f = helpers["floor"] - _close(sb.compute_floor(f["X"], 7, 45.5), f["out"]) - _close(sb.compute_floor(f["X"], 6, 40), f["out_int"]) - - -def test_bspline_basis_matches_matlab(helpers: dict[str, Any]) -> None: - """bsplineBasis: whole knot intervals tile the trial. - - One interval when the spacing exceeds it. The products are those of the - basis. - """ - s = helpers["spline"] - b = sb.bspline_basis(101, 17.3) - _close(b.toarray(), s["B"], 1e-14) - _close(sb.bspline_basis(40, 100).toarray(), s["B1"], 1e-14) - assert b.shape == (101, 9) and s["B1"].shape == (40, 4) - np.testing.assert_allclose(b.sum(1), 1.0, atol=1e-14) - dense = b.toarray() - prod = sb._bspline_products(101, 17.3).toarray().reshape(101, 9, 9) - np.testing.assert_allclose(prod, dense[:, :, None] * dense[:, None, :], atol=1e-15) - - -def test_curvature_penalty() -> None: - """Squared second differences per knot interval: constants and lines cost nothing.""" - pc = sb.curvature_penalty(7) - c = np.arange(7.0) - assert np.allclose(pc @ np.ones(7), 0) and np.allclose(pc @ c, 0) - quad = c**2 - assert quad @ pc @ quad == pytest.approx(5 * 2.0**2 / 4) - - -def test_surround_matches_matlab(helpers: dict[str, Any]) -> None: - """GetSurround on a map with a hole, dense and sparse operators.""" - sel = helpers["foot"]["selPix"].astype(bool) - s = helpers["surround"] - _close(SMALL.bfilter, s["Bfilter"].transpose(2, 0, 1)) - ops = sb.surround_operators(sel, SMALL) - assert all(isinstance(op, np.ndarray) for op in ops) # small: dense - ref = s["out"].transpose(2, 0, 1) - _close(sb.get_surround(s["HP"], ops), ref) - sparse_ops = [conv_operator(sel, f) for f in SMALL.bfilter] - _close(sb.get_surround(s["HP"], sparse_ops), ref) - - -def test_fit_baseline_matches_matlab(helpers: dict[str, Any]) -> None: - """FitB on a small synthetic problem. - - MATLAB's quadprog stops at its tolerance, so the baselines agree to about - 1e-8; Python's programs are solved to machine precision. - """ - sel = helpers["foot"]["selPix"].astype(bool) - f = helpers["fitB"] - y = f["Finv"] * f["counts"] - b0 = np.full(y.shape, 1.4) - b, info = sb.fit_baseline(b0, y, f["X"], f["H"], f["Finv"], sel, SMALL, return_info=True) - _close(b, f["B"], 1e-7) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - assert info["coef"].shape == (y.shape[0], 2 + 3 + 13) - # the sources' coefficients are not negative - assert info["coef"][:, :2].min() >= 0 - - -def _random_qp( - rng: np.random.Generator, m: int, n: int, rank: int | None = None -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Build a stack of random bounded quadratic programs. - - Returns - ------- - g : np.ndarray - Symmetric positive semidefinite matrices, (m, n, n). - c : np.ndarray - Linear terms, (m, n). - lb : np.ndarray - Lower bounds (at most 0), (m, n). - ub : np.ndarray - Upper bounds (at least 0), (m, n). - """ - a = rng.standard_normal((m, rank or n + 3, n)) - g = np.einsum("mki,mkj->mij", a, a) - c = rng.standard_normal((m, n)) * 3 - lb = -rng.random((m, n)) - ub = rng.random((m, n)) - return g, c, lb, ub - - -def test_box_qp_matches_scipy() -> None: - """The batched solver finds the minimum that a bounded least-squares solver finds. - - With many bounds active. - """ - rng = np.random.default_rng(3) - g, c, lb, ub = _random_qp(rng, 40, 6) - x, info = sb.solve_box_qp(g, c, lb, ub) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - assert (x >= lb).all() and (x <= ub).all() - assert ((x == lb) | (x == ub)).mean() > 0.2 - for i in range(40): - # min x'Gx/2 - c'x == min |R x - R^-T c|^2 with G = R'R - r = np.linalg.cholesky(g[i]).T - rhs = np.linalg.solve(r.T, c[i]) - ref = optimize.lsq_linear(r, rhs, bounds=(lb[i], ub[i]), method="bvls", tol=1e-13).x - np.testing.assert_allclose(x[i], ref, atol=1e-8) - - -def test_box_qp_zero_curvature_follows_the_linear_term() -> None: - """A variable without curvature goes to the bound that its linear term favours.""" - g = np.zeros((3, 1, 1)) - c = np.array([[1.0], [-1.0], [0.0]]) - lb, ub = np.full((3, 1), -3.0), np.full((3, 1), 2.0) - x, info = sb.solve_box_qp(g, c, lb, ub) - assert x.ravel().tolist() == [2.0, -3.0, 0.0] - assert info["converged"].all() - # beside variables with curvature, which do not depend on it - g = np.array([[[2.0, 0.0], [0.0, 0.0]]]) - x, _ = sb.solve_box_qp(g, np.array([[1.0, 5.0]]), np.full((1, 2), -4.0), np.full((1, 2), 3.0)) - assert x.ravel().tolist() == [0.5, 3.0] - - -def test_box_qp_fixed_variables() -> None: - """Bounds that coincide fix a variable, in the Newton iterations and in the fallback. - - The others are solved around it. - """ - one = np.ones((1, 1)) - for max_iter in (100, 0): - x, _ = sb.solve_box_qp(one[None], 0 * one, one, one, max_iter=max_iter) - assert x.tolist() == [[1.0]] - rng = np.random.default_rng(9) - g, c, lb, ub = _random_qp(rng, 8, 5) - lb[:, 1] = ub[:, 1] = 0.3 - lb[:, 4] = ub[:, 4] = -0.2 - x, info = sb.solve_box_qp(g, c, lb, ub) - assert info["converged"].all() - assert np.all(x[:, 1] == 0.3) and np.all(x[:, 4] == -0.2) - fallback, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert not info["converged"].any() - np.testing.assert_allclose(fallback, x, atol=1e-7) - # the free variables solve the program with the fixed ones moved into - # its linear term - keep = [0, 2, 3] - shift = g[:, keep][:, :, [1, 4]] @ np.array([0.3, -0.2]) - ref, _ = sb.solve_box_qp(g[:, keep][:, :, keep], c[:, keep] - shift, lb[:, keep], ub[:, keep]) - np.testing.assert_allclose(x[:, keep], ref, atol=1e-9) - - -def test_box_qp_fallback_keeps_the_objective() -> None: - """The fallback solves the program as given. - - A singular G whose linear term acts along the null direction ends on the - bounds, without a warning, as the Newton iterations do. - """ - g = np.array([[[1.0, 1.0], [1.0, 1.0]]]) - lb, ub = np.full((1, 2), -2.0), np.full((1, 2), 2.0) - for c in ([[1e-16, -1e-16]], [[0.5, -0.5]]): - c = np.array(c) - for max_iter in (100, 0): - with warnings.catch_warnings(): - warnings.simplefilter("error") - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=max_iter) - assert x.tolist() == [[2.0, -2.0]], (c, max_iter) - assert info["kkt"].max() < 1e-9 - # no linear term at all: the quadratic alone, pushed to the bounds - ones = np.ones((1, 4, 4)) - zero = np.zeros((1, 4)) - x, info = sb.solve_box_qp(ones, zero, np.full((1, 4), 1.0), np.full((1, 4), 2.0), max_iter=0) - assert x.tolist() == [[1.0] * 4] and np.isfinite(info["kkt"]).all() - # a positive semidefinite program with its minimum inside the bounds - c = np.array([[1.0, 1.0]]) - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert x.sum() == pytest.approx(1.0, abs=1e-9) and info["kkt"].max() < 1e-9 - - -def test_box_qp_zero_rows_and_fallback() -> None: - """A variable with a zero row is left at its bound nearest zero. - - A problem the Newton iterations do not finish goes to the fallback. - """ - rng = np.random.default_rng(4) - g, c, lb, ub = _random_qp(rng, 5, 4) - g[:, 2, :] = g[:, :, 2] = 0 - c[:, 2] = 0 - lb[:, 2], ub[:, 2] = 0.25, 3.0 - x, info = sb.solve_box_qp(g, c, lb, ub) - assert np.all(x[:, 2] == 0.25) and info["converged"].all() - ref, _ = sb.solve_box_qp( - np.delete(np.delete(g, 2, 1), 2, 2), - np.delete(c, 2, 1), - np.delete(lb, 2, 1), - np.delete(ub, 2, 1), - ) - np.testing.assert_allclose(np.delete(x, 2, 1), ref, atol=1e-10) - # no iterations: every problem is solved by the fallback - g, c, lb, ub = _random_qp(rng, 6, 5) - good, _ = sb.solve_box_qp(g, c, lb, ub) - x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) - assert not info["converged"].any() - np.testing.assert_allclose(x, good, atol=1e-7) - - -def test_subproblem_start_matches_matlab(sub: dict[str, Any]) -> None: - """Starting baseline, least squares and events of a real subproblem.""" - y, every = sub["y"][0], sub["every"] - b = sb.initial_baseline(y, PARAMS) - _close(b[:, ::every], sub["init"]["B"]) - ls = np.linalg.lstsq(sub["init"]["H"], y - b, rcond=None)[0] - _close(ls, sub["init"]["dFls"]) - prev = np.concatenate([np.zeros((2, 1)), ls[:, :-1]], axis=1) - k_peak = PARAMS.k[PARAMS.k.size // 2] - _close(np.fmax(0, ls - prev) / k_peak, sub["init"]["S"]) - b2 = sb.initial_baseline(sub["y"][1], PARAMS) - _close(b2[:, ::every], sub["ch2"]["B"]) - - -def test_subproblem_noise_and_floor_match_matlab(sub: dict[str, Any]) -> None: - """Noise, SNR and floor from MATLAB's first activity fit.""" - y, it1 = sub["y"][0], sub["it1"] - b = sb.initial_baseline(y, PARAMS) - x = _conv_same(it1["S_out"], PARAMS.k) - var, noise, snr = sb.activity_noise(y, sub["finv"], b, sub["init"]["H"], x, PARAMS.tau_frames) - _close(var, it1["residVar"]) - _close(noise, it1["Xnoise"]) - _close(snr, it1["Xsnr"]) - floor = sb.compute_floor(x, PARAMS.denoise_window, PARAMS.baseline_window) - _close(floor, it1["Xfloor"]) - _close(np.fmax(0, x - floor - noise[:, None]), it1["X_thr"]) - - -def test_subproblem_baseline_fit_matches_matlab(sub: dict[str, Any]) -> None: - """FitB on a real subproblem, to quadprog's tolerance. - - Its trial is shorter than the lowess window of the high-pass split. - """ - y, it1 = sub["y"][0], sub["it1"] - b0 = sb.initial_baseline(y, PARAMS) - b, info = sb.fit_baseline( - b0, - y, - it1["X_thr"], - sub["init"]["H"], - sub["finv"], - sub["sel"], - PARAMS, - return_info=True, - ) - _close(b[:, :: sub["every"]], it1["B_out"], 1e-5) - assert info["converged"].all() and info["kkt"].max() < 1e-9 - - -def test_subproblem_footprint_update_matches_matlab(sub: dict[str, Any]) -> None: - """H from MATLAB's fitted Hs through the footprint filter, and the normalization.""" - it1 = sub["it1"] - h = conv_operator(sub["sel"], PARAMS.hfilter) @ it1["Hs_out"] - norm = h.sum(0) - _close(norm, it1["normFac"]) - _close(h / norm, it1["H"]) - _close(it1["Hs_out"] / norm, it1["Hs"]) - _close(it1["S_out"] * norm[:, None], it1["S"]) - rows, _ = sel_coords(sub["sel"]) - assert h.shape == (rows.size, 2) - - -def test_subproblem_outputs_match_matlab(sub: dict[str, Any]) -> None: - """SNR, least squares and F0 from MATLAB's final activity.""" - y, out, it1 = sub["y"], sub["out"], sub["it1"] - h = out["H"] - b1 = sb.fit_baseline( - sb.initial_baseline(y[0], PARAMS), - y[0], - it1["X_thr"], - sub["init"]["H"], - sub["finv"], - sub["sel"], - PARAMS, - ) - x = _conv_same(out["S"][0], PARAMS.k) - _, _, snr = sb.activity_noise(y[0], sub["finv"], b1, h, x, PARAMS.tau_frames) - _close(snr, out["SNR"], 1e-5) - _close(np.linalg.lstsq(h, y[0] - b1, rcond=None)[0], out["LS"][0], 1e-5) - _close(sb.source_f0(h, b1), out["F0"][0], 1e-5) - b2 = sb.initial_baseline(y[1], PARAMS) - _close(np.linalg.lstsq(h, y[1] - b2, rcond=None)[0], out["LS"][1]) - _close(sb.source_f0(h, b2), out["F0"][1]) - - -def test_interp1_extrapolates() -> None: - """Linear interpolation of rows with linear extrapolation.""" - x = np.array([1.0, 2.0, 4.0]) - y = np.array([[0.0, 1.0, 5.0]]) - out = sb.interp1_extrap(x, y, np.array([0.0, 1.5, 3.0, 5.0])) - np.testing.assert_allclose(out, [[-1.0, 0.5, 3.0, 7.0]]) - - -def test_activity_noise_with_a_zero_footprint_is_matlabs() -> None: - """A source whose footprint is all zero makes the normal matrix singular. - - Noise Inf and SNR 0 for every source, with a warning, as MATLAB's inv - gives; other inputs give the plain inverse's result. - """ - rng = np.random.default_rng(5) - n_px, n_t = 40, 300 - h = np.abs(rng.standard_normal((n_px, 3))) - x = np.abs(rng.standard_normal((3, n_t))) - b = np.full((n_px, n_t), 5.0) - y = b + h @ x + 0.3 * rng.standard_normal((n_px, n_t)) - finv = np.ones((n_px, n_t)) # freshness per pixel and frame - var, noise, snr = sb.activity_noise(y, finv, b, h, x, 4.0) - cov = np.linalg.inv(h.T @ (h / var[:, None])) - np.testing.assert_array_equal(noise, np.sqrt(np.diag(cov) / 4.0)) - assert np.all(np.isfinite(noise)) and np.all(snr > 0) - h0 = h.copy() - h0[:, 1] = 0.0 - with pytest.warns(RuntimeWarning, match="singular"): - _, noise0, snr0 = sb.activity_noise(y, finv, b, h0, x, 4.0) - assert np.all(np.isinf(noise0)) and np.all(snr0 == 0) +"""Tests of the deterministic parts of the subproblem solver. + +The baseline (splitFreq, fitB and its helpers), the floor and the noise +estimate, against GIAnT-MATLAB's values. +""" + +import warnings +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +from numpy.typing import ArrayLike +from scipy import optimize + +from giant_python.extraction.raster import solver_baseline as sb +from giant_python.extraction.raster.localization import movmean_nan +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + conv_operator, + sel_coords, +) + +DATA = Path(__file__).parent / "data" +HELPERS = DATA / "matlab_solver_helpers.h5" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() # SILo's defaults for SLAP2, as the subproblem's +# parameters of the small fitB and getSurround references +SMALL = SolverParams( + sigma_px=1.33, + sel_radius=2, + tau_full=3, + tau2_s=0.05, + analyze_hz=100, + baseline_window_s=0.6, + denoise_window_s=0.1, +) + + +def _close(a: ArrayLike, b: ArrayLike, tol: float = 1e-12) -> None: + """Equal NaN patterns, and differences below tol of the largest value.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + assert a.shape == b.shape + assert np.array_equal(np.isnan(a), np.isnan(b)) + assert np.nanmax(np.abs(a - b)) <= tol * np.nanmax(np.abs(b)) + + +def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: + """MATLAB convn(x, k, 'same') along the rows. + + Returns + ------- + np.ndarray + Each row of `x` convolved with `k`, cropped to the length of the row. + """ + c = len(k) // 2 + return np.stack([np.convolve(r, k)[c : c + x.shape[1]] for r in x]) + + +def _read_tree(g: h5py.Group) -> dict[str, Any]: + """Read an HDF5 group as nested dicts of arrays. + + Returns + ------- + dict[str, Any] + The group's datasets as arrays (or scalars) and its subgroups as nested dicts. + """ + return {k: _read_tree(v) if isinstance(v, h5py.Group) else v[()] for k, v in g.items()} + + +@pytest.fixture(scope="module") +def helpers() -> dict[str, Any]: + """MATLAB's values for the helper functions. + + Returns + ------- + dict[str, Any] + The helper fixture file as nested dicts of arrays. + """ + with h5py.File(HELPERS, "r") as f: + return _read_tree(f) + + +@pytest.fixture(scope="module") +def sub() -> dict[str, Any]: + """Load the subproblem fixture: inputs as float64, MATLAB's intermediates. + + Returns + ------- + dict[str, Any] + The fixture file as nested dicts, plus every (the baseline step interval) and the + float64 y and finv and boolean sel copied from its inputs. + """ + with h5py.File(SUBPROBLEM, "r") as f: + d = _read_tree(f) + d["every"] = int(f.attrs["baseline_every"]) + d["y"] = d["in"]["y"].astype(np.float64) + d["finv"] = d["in"]["finv"].astype(np.float64) + d["sel"] = d["in"]["sel"].astype(bool) + return d + + +@pytest.mark.parametrize("window", [4, 7, 20, 50]) +def test_lowess_and_movmean_match_matlab(helpers: dict[str, Any], window: int) -> None: + """Smoothdata's lowess and movmean, for even, odd and too long windows.""" + s = helpers["smooth"] + _close(sb.smooth_lowess(s["A"], window), s[f"lowess_{window}"]) + _close(movmean_nan(s["A"].T, window).T, s[f"movmean_{window}"]) + + +@pytest.mark.parametrize("window", [7, 20]) +def test_lowess_omits_nan_as_matlab(helpers: dict[str, Any], window: int) -> None: + """NaN samples are left out of the local fits.""" + s = helpers["smooth"] + assert np.isnan(s["An"]).sum() == 10 + _close(sb.smooth_lowess(s["An"], window), s[f"lowess_nan_{window}"]) + + +def test_lowess_degenerate_windows() -> None: + """A window of one sample returns the data. + + A window whose only weighted sample is the centre returns it; all-NaN + windows give NaN. + """ + a = np.array([[1.0, 4.0, 2.0, np.nan, np.nan, np.nan, 7.0]]) + assert np.array_equal(sb.smooth_lowess(a[:, :3], 1), a[:, :3]) + out = sb.smooth_lowess(a, 3) + assert np.array_equal(out[0, :3], a[0, :3]) + assert np.isnan(out[0, 4]) + # the NaN next to a value takes it (zero weight, so the window's mean) + assert out[0, 3] == 2.0 and out[0, 5] == 7.0 + + +@pytest.mark.parametrize( + "name, order, n, pad", + [ + ("zeros_3_20", 3, 20, "zeros"), + ("zeros_2_5", 2, 5, "zeros"), + ("zeros_1_4", 1, 4, "zeros"), + ("sym_5_46", 5, 46, "symmetric"), + ("sym_3_7", 3, 7, "symmetric"), + ("sym_2_6", 2, 6, "symmetric"), + ("med_9", 5, 9, "symmetric"), + ], +) +def test_order_filters_match_matlab( + helpers: dict[str, Any], name: str, order: int, n: int, pad: str +) -> None: + """ordfilt2 and medfilt2 along rows, with both paddings. + + The window of 46 is longer than the 41 samples. + """ + o = helpers["ord"] + assert np.array_equal(sb.ordfilt_rows(o["a"], order, n, pad), o[name]) + + +def test_split_freq_matches_matlab(helpers: dict[str, Any]) -> None: + """splitFreq, also for a trial too short to interpolate.""" + s = helpers["split"] + lp, hp = sb.split_freq(s["A"], 10, 6) + _close(lp, s["LP"]) + assert np.array_equal(hp, s["A"] - lp) + short, _ = sb.split_freq(s["A"][:, :15], 10, 6) + _close(short, s["LP_short"]) + _close(sb.split_freq(s["D"], 10, 6)[0], s["LP_nan"]) + + +def test_initial_baseline_takes_min_where_nan(monkeypatch: pytest.MonkeyPatch) -> None: + """Where splitFreq's low-pass is NaN the baseline is min_baseline. + + As MATLAB's max(minBaseline, NaN) gives; elsewhere it is bounded below. + """ + lp = np.array([[np.nan, 0.5, -1.0], [2.0, np.nan, 0.001]]) + monkeypatch.setattr(sb, "split_freq", lambda *a: (lp, None)) + b = sb.initial_baseline(np.zeros((2, 3)), PARAMS) + assert np.array_equal(b, [[0.01, 0.5, 0.01], [2.0, 0.01, 0.01]]) + + +def test_compute_floor_matches_matlab(helpers: dict[str, Any]) -> None: + """computeFloor, for integer and fractional windows.""" + f = helpers["floor"] + _close(sb.compute_floor(f["X"], 7, 45.5), f["out"]) + _close(sb.compute_floor(f["X"], 6, 40), f["out_int"]) + + +def test_bspline_basis_matches_matlab(helpers: dict[str, Any]) -> None: + """bsplineBasis: whole knot intervals tile the trial. + + One interval when the spacing exceeds it. The products are those of the + basis. + """ + s = helpers["spline"] + b = sb.bspline_basis(101, 17.3) + _close(b.toarray(), s["B"], 1e-14) + _close(sb.bspline_basis(40, 100).toarray(), s["B1"], 1e-14) + assert b.shape == (101, 9) and s["B1"].shape == (40, 4) + np.testing.assert_allclose(b.sum(1), 1.0, atol=1e-14) + dense = b.toarray() + prod = sb._bspline_products(101, 17.3).toarray().reshape(101, 9, 9) + np.testing.assert_allclose(prod, dense[:, :, None] * dense[:, None, :], atol=1e-15) + + +def test_curvature_penalty() -> None: + """Squared second differences per knot interval: constants and lines cost nothing.""" + pc = sb.curvature_penalty(7) + c = np.arange(7.0) + assert np.allclose(pc @ np.ones(7), 0) and np.allclose(pc @ c, 0) + quad = c**2 + assert quad @ pc @ quad == pytest.approx(5 * 2.0**2 / 4) + + +def test_surround_matches_matlab(helpers: dict[str, Any]) -> None: + """GetSurround on a map with a hole, dense and sparse operators.""" + sel = helpers["foot"]["selPix"].astype(bool) + s = helpers["surround"] + _close(SMALL.bfilter, s["Bfilter"].transpose(2, 0, 1)) + ops = sb.surround_operators(sel, SMALL) + assert all(isinstance(op, np.ndarray) for op in ops) # small: dense + ref = s["out"].transpose(2, 0, 1) + _close(sb.get_surround(s["HP"], ops), ref) + sparse_ops = [conv_operator(sel, f) for f in SMALL.bfilter] + _close(sb.get_surround(s["HP"], sparse_ops), ref) + + +def test_fit_baseline_matches_matlab(helpers: dict[str, Any]) -> None: + """FitB on a small synthetic problem. + + MATLAB's quadprog stops at its tolerance, so the baselines agree to about + 1e-8; Python's programs are solved to machine precision. + """ + sel = helpers["foot"]["selPix"].astype(bool) + f = helpers["fitB"] + y = f["Finv"] * f["counts"] + b0 = np.full(y.shape, 1.4) + b, info = sb.fit_baseline(b0, y, f["X"], f["H"], f["Finv"], sel, SMALL, return_info=True) + _close(b, f["B"], 1e-7) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + assert info["coef"].shape == (y.shape[0], 2 + 3 + 13) + # the sources' coefficients are not negative + assert info["coef"][:, :2].min() >= 0 + + +def _random_qp( + rng: np.random.Generator, m: int, n: int, rank: int | None = None +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Build a stack of random bounded quadratic programs. + + Returns + ------- + g : np.ndarray + Symmetric positive semidefinite matrices, (m, n, n). + c : np.ndarray + Linear terms, (m, n). + lb : np.ndarray + Lower bounds (at most 0), (m, n). + ub : np.ndarray + Upper bounds (at least 0), (m, n). + """ + a = rng.standard_normal((m, rank or n + 3, n)) + g = np.einsum("mki,mkj->mij", a, a) + c = rng.standard_normal((m, n)) * 3 + lb = -rng.random((m, n)) + ub = rng.random((m, n)) + return g, c, lb, ub + + +def test_box_qp_matches_scipy() -> None: + """The batched solver finds the minimum that a bounded least-squares solver finds. + + With many bounds active. + """ + rng = np.random.default_rng(3) + g, c, lb, ub = _random_qp(rng, 40, 6) + x, info = sb.solve_box_qp(g, c, lb, ub) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + assert (x >= lb).all() and (x <= ub).all() + assert ((x == lb) | (x == ub)).mean() > 0.2 + for i in range(40): + # min x'Gx/2 - c'x == min |R x - R^-T c|^2 with G = R'R + r = np.linalg.cholesky(g[i]).T + rhs = np.linalg.solve(r.T, c[i]) + ref = optimize.lsq_linear(r, rhs, bounds=(lb[i], ub[i]), method="bvls", tol=1e-13).x + np.testing.assert_allclose(x[i], ref, atol=1e-8) + + +def test_box_qp_zero_curvature_follows_the_linear_term() -> None: + """A variable without curvature goes to the bound that its linear term favours.""" + g = np.zeros((3, 1, 1)) + c = np.array([[1.0], [-1.0], [0.0]]) + lb, ub = np.full((3, 1), -3.0), np.full((3, 1), 2.0) + x, info = sb.solve_box_qp(g, c, lb, ub) + assert x.ravel().tolist() == [2.0, -3.0, 0.0] + assert info["converged"].all() + # beside variables with curvature, which do not depend on it + g = np.array([[[2.0, 0.0], [0.0, 0.0]]]) + x, _ = sb.solve_box_qp(g, np.array([[1.0, 5.0]]), np.full((1, 2), -4.0), np.full((1, 2), 3.0)) + assert x.ravel().tolist() == [0.5, 3.0] + + +def test_box_qp_fixed_variables() -> None: + """Bounds that coincide fix a variable, in the Newton iterations and in the fallback. + + The others are solved around it. + """ + one = np.ones((1, 1)) + for max_iter in (100, 0): + x, _ = sb.solve_box_qp(one[None], 0 * one, one, one, max_iter=max_iter) + assert x.tolist() == [[1.0]] + rng = np.random.default_rng(9) + g, c, lb, ub = _random_qp(rng, 8, 5) + lb[:, 1] = ub[:, 1] = 0.3 + lb[:, 4] = ub[:, 4] = -0.2 + x, info = sb.solve_box_qp(g, c, lb, ub) + assert info["converged"].all() + assert np.all(x[:, 1] == 0.3) and np.all(x[:, 4] == -0.2) + fallback, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert not info["converged"].any() + np.testing.assert_allclose(fallback, x, atol=1e-7) + # the free variables solve the program with the fixed ones moved into + # its linear term + keep = [0, 2, 3] + shift = g[:, keep][:, :, [1, 4]] @ np.array([0.3, -0.2]) + ref, _ = sb.solve_box_qp(g[:, keep][:, :, keep], c[:, keep] - shift, lb[:, keep], ub[:, keep]) + np.testing.assert_allclose(x[:, keep], ref, atol=1e-9) + + +def test_box_qp_fallback_keeps_the_objective() -> None: + """The fallback solves the program as given. + + A singular G whose linear term acts along the null direction ends on the + bounds, without a warning, as the Newton iterations do. + """ + g = np.array([[[1.0, 1.0], [1.0, 1.0]]]) + lb, ub = np.full((1, 2), -2.0), np.full((1, 2), 2.0) + for c in ([[1e-16, -1e-16]], [[0.5, -0.5]]): + c = np.array(c) + for max_iter in (100, 0): + with warnings.catch_warnings(): + warnings.simplefilter("error") + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=max_iter) + assert x.tolist() == [[2.0, -2.0]], (c, max_iter) + assert info["kkt"].max() < 1e-9 + # no linear term at all: the quadratic alone, pushed to the bounds + ones = np.ones((1, 4, 4)) + zero = np.zeros((1, 4)) + x, info = sb.solve_box_qp(ones, zero, np.full((1, 4), 1.0), np.full((1, 4), 2.0), max_iter=0) + assert x.tolist() == [[1.0] * 4] and np.isfinite(info["kkt"]).all() + # a positive semidefinite program with its minimum inside the bounds + c = np.array([[1.0, 1.0]]) + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert x.sum() == pytest.approx(1.0, abs=1e-9) and info["kkt"].max() < 1e-9 + + +def test_box_qp_zero_rows_and_fallback() -> None: + """A variable with a zero row is left at its bound nearest zero. + + A problem the Newton iterations do not finish goes to the fallback. + """ + rng = np.random.default_rng(4) + g, c, lb, ub = _random_qp(rng, 5, 4) + g[:, 2, :] = g[:, :, 2] = 0 + c[:, 2] = 0 + lb[:, 2], ub[:, 2] = 0.25, 3.0 + x, info = sb.solve_box_qp(g, c, lb, ub) + assert np.all(x[:, 2] == 0.25) and info["converged"].all() + ref, _ = sb.solve_box_qp( + np.delete(np.delete(g, 2, 1), 2, 2), + np.delete(c, 2, 1), + np.delete(lb, 2, 1), + np.delete(ub, 2, 1), + ) + np.testing.assert_allclose(np.delete(x, 2, 1), ref, atol=1e-10) + # no iterations: every problem is solved by the fallback + g, c, lb, ub = _random_qp(rng, 6, 5) + good, _ = sb.solve_box_qp(g, c, lb, ub) + x, info = sb.solve_box_qp(g, c, lb, ub, max_iter=0) + assert not info["converged"].any() + np.testing.assert_allclose(x, good, atol=1e-7) + + +def test_subproblem_start_matches_matlab(sub: dict[str, Any]) -> None: + """Starting baseline, least squares and events of a real subproblem.""" + y, every = sub["y"][0], sub["every"] + b = sb.initial_baseline(y, PARAMS) + _close(b[:, ::every], sub["init"]["B"]) + ls = np.linalg.lstsq(sub["init"]["H"], y - b, rcond=None)[0] + _close(ls, sub["init"]["dFls"]) + prev = np.concatenate([np.zeros((2, 1)), ls[:, :-1]], axis=1) + k_peak = PARAMS.k[PARAMS.k.size // 2] + _close(np.fmax(0, ls - prev) / k_peak, sub["init"]["S"]) + b2 = sb.initial_baseline(sub["y"][1], PARAMS) + _close(b2[:, ::every], sub["ch2"]["B"]) + + +def test_subproblem_noise_and_floor_match_matlab(sub: dict[str, Any]) -> None: + """Noise, SNR and floor from MATLAB's first activity fit.""" + y, it1 = sub["y"][0], sub["it1"] + b = sb.initial_baseline(y, PARAMS) + x = _conv_same(it1["S_out"], PARAMS.k) + var, noise, snr = sb.activity_noise(y, sub["finv"], b, sub["init"]["H"], x, PARAMS.tau_frames) + _close(var, it1["residVar"]) + _close(noise, it1["Xnoise"]) + _close(snr, it1["Xsnr"]) + floor = sb.compute_floor(x, PARAMS.denoise_window, PARAMS.baseline_window) + _close(floor, it1["Xfloor"]) + _close(np.fmax(0, x - floor - noise[:, None]), it1["X_thr"]) + + +def test_subproblem_baseline_fit_matches_matlab(sub: dict[str, Any]) -> None: + """FitB on a real subproblem, to quadprog's tolerance. + + Its trial is shorter than the lowess window of the high-pass split. + """ + y, it1 = sub["y"][0], sub["it1"] + b0 = sb.initial_baseline(y, PARAMS) + b, info = sb.fit_baseline( + b0, + y, + it1["X_thr"], + sub["init"]["H"], + sub["finv"], + sub["sel"], + PARAMS, + return_info=True, + ) + _close(b[:, :: sub["every"]], it1["B_out"], 1e-5) + assert info["converged"].all() and info["kkt"].max() < 1e-9 + + +def test_subproblem_footprint_update_matches_matlab(sub: dict[str, Any]) -> None: + """H from MATLAB's fitted Hs through the footprint filter, and the normalization.""" + it1 = sub["it1"] + h = conv_operator(sub["sel"], PARAMS.hfilter) @ it1["Hs_out"] + norm = h.sum(0) + _close(norm, it1["normFac"]) + _close(h / norm, it1["H"]) + _close(it1["Hs_out"] / norm, it1["Hs"]) + _close(it1["S_out"] * norm[:, None], it1["S"]) + rows, _ = sel_coords(sub["sel"]) + assert h.shape == (rows.size, 2) + + +def test_subproblem_outputs_match_matlab(sub: dict[str, Any]) -> None: + """SNR, least squares and F0 from MATLAB's final activity.""" + y, out, it1 = sub["y"], sub["out"], sub["it1"] + h = out["H"] + b1 = sb.fit_baseline( + sb.initial_baseline(y[0], PARAMS), + y[0], + it1["X_thr"], + sub["init"]["H"], + sub["finv"], + sub["sel"], + PARAMS, + ) + x = _conv_same(out["S"][0], PARAMS.k) + _, _, snr = sb.activity_noise(y[0], sub["finv"], b1, h, x, PARAMS.tau_frames) + _close(snr, out["SNR"], 1e-5) + _close(np.linalg.lstsq(h, y[0] - b1, rcond=None)[0], out["LS"][0], 1e-5) + _close(sb.source_f0(h, b1), out["F0"][0], 1e-5) + b2 = sb.initial_baseline(y[1], PARAMS) + _close(np.linalg.lstsq(h, y[1] - b2, rcond=None)[0], out["LS"][1]) + _close(sb.source_f0(h, b2), out["F0"][1]) + + +def test_interp1_extrapolates() -> None: + """Linear interpolation of rows with linear extrapolation.""" + x = np.array([1.0, 2.0, 4.0]) + y = np.array([[0.0, 1.0, 5.0]]) + out = sb.interp1_extrap(x, y, np.array([0.0, 1.5, 3.0, 5.0])) + np.testing.assert_allclose(out, [[-1.0, 0.5, 3.0, 7.0]]) + + +def test_activity_noise_with_a_zero_footprint_is_matlabs() -> None: + """A source whose footprint is all zero makes the normal matrix singular. + + Noise Inf and SNR 0 for every source, with a warning, as MATLAB's inv + gives; other inputs give the plain inverse's result. + """ + rng = np.random.default_rng(5) + n_px, n_t = 40, 300 + h = np.abs(rng.standard_normal((n_px, 3))) + x = np.abs(rng.standard_normal((3, n_t))) + b = np.full((n_px, n_t), 5.0) + y = b + h @ x + 0.3 * rng.standard_normal((n_px, n_t)) + finv = np.ones((n_px, n_t)) # freshness per pixel and frame + var, noise, snr = sb.activity_noise(y, finv, b, h, x, 4.0) + cov = np.linalg.inv(h.T @ (h / var[:, None])) + np.testing.assert_array_equal(noise, np.sqrt(np.diag(cov) / 4.0)) + assert np.all(np.isfinite(noise)) and np.all(snr > 0) + h0 = h.copy() + h0[:, 1] = 0.0 + with pytest.warns(RuntimeWarning, match="singular"): + _, noise0, snr0 = sb.activity_noise(y, finv, b, h0, x, 4.0) + assert np.all(np.isinf(noise0)) and np.all(snr0 == 0) diff --git a/tests/raster/test_raster_solver_baseline_modes.py b/tests/raster/test_raster_solver_baseline_modes.py index 883f6bec..ca8788d0 100644 --- a/tests/raster/test_raster_solver_baseline_modes.py +++ b/tests/raster/test_raster_solver_baseline_modes.py @@ -1,512 +1,512 @@ -"""Tests of the solver's baseline modes. - -These are the variants R0, N0-N3 of the SILo port's baseline test: an external -baseline held, scaled per pixel, scaled by a shared time course, or corrected -by fitB. -""" - -from dataclasses import replace -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.solver import ( - SolverOptions, - SubproblemResult, - conv_same, - solve_subproblem, -) -from giant_python.extraction.raster.solver_baseline import ( - fit_baseline, - fit_gain, - fit_network_gain, - gain_programs, - outside_halves, - shared_time_course, -) -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() -KEEP = SolverOptions(keep_baseline=True) - - -def _corr(a: np.ndarray, b: np.ndarray) -> float: - """Pearson correlation of two traces. - - Returns - ------- - float - The correlation coefficient of the flattened a and b. - """ - return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) - - -@pytest.fixture(scope="module") -def real() -> tuple[Subproblem, SubproblemResult]: - """Load a real two-source subproblem (activity channel only) and solve it. - - Returns it with the default solver's result on it, with its baseline. - - Returns - ------- - sub : Subproblem - The real subproblem. - result : SubproblemResult - The default solver's result on it, with its baseline kept. - """ - with h5py.File(SUBPROBLEM, "r") as f: - sub = Subproblem( - y=f["in/y"][()][:1].astype(np.float64), - finv=f["in/finv"][()].astype(np.float64), - sel=f["in/sel"][()].astype(bool), - sources_rc=f["in/sources_rc"][()], - ) - return sub, solve_subproblem(sub, PARAMS, KEEP) - - -def _synthetic( - seed: int = 0, - n_t: int = 1600, - shared: np.ndarray | None = None, - scale: float = 1.0, -) -> tuple[Subproblem, np.ndarray, np.ndarray]: - """Draw a one-source subproblem from a known baseline and events. - - The baseline is a bright stripe times a slow drift (and shared, a - time course common to all pixels, if given); the data are F - times Poisson counts of mean T / F, with the variance multiplier - F 0.2. Returns the subproblem (with the true - baseline times scale as its external baseline, without the shared - course), the true baseline and the true events. - - Returns - ------- - sub : Subproblem - The subproblem, with the true baseline times scale as its external baseline. - b_true : np.ndarray - The true baseline (including shared if given). - s : np.ndarray - The true events. - """ - rng = np.random.default_rng(seed) - sel = np.ones((13, 13), bool) - rows, cols = np.nonzero(sel.T)[::-1] - t = np.arange(n_t) - slow = 1 + 0.1 * np.sin(2 * np.pi * t / n_t) - space = 2 + 3 * np.exp(-((cols - 6.0) ** 2) / 8) - b = space[:, None] * slow[None, :] - if shared is not None: - b_true = b * shared[None, :] - else: - b_true = b - h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h /= h.sum() - s = np.zeros(n_t) - s[rng.choice(np.arange(20, n_t - 40), 25, replace=False)] = 20 / 0.19 - x = conv_same(s[None], PARAMS.k)[0] - finv = np.full(b.shape, 0.2) - z = finv * rng.poisson((b_true + np.outer(h, x)) / finv) - sub = Subproblem( - y=z[None], - finv=finv, - sel=sel, - sources_rc=np.array([[6, 6]]), - baseline=b * scale, - ) - return sub, b_true, s - - -def test_params_and_subproblem_check_the_baseline() -> None: - """Unknown modes, a misfitting or non-finite baseline are refused.""" - with pytest.raises(ValueError, match="baseline_mode"): - SolverParams(baseline_mode="network") - for bad in (0.0, 1.0): - with pytest.raises(ValueError, match="outside_footprint"): - SolverParams(outside_footprint=bad) - sub, _, _ = _synthetic() - with pytest.raises(ValueError, match="pixels and frames"): - replace(sub, baseline=sub.baseline[:, :-1], _coords=None) - bad = sub.baseline.copy() - bad[0, 0] = np.nan - with pytest.raises(ValueError, match="NaN"): - replace(sub, baseline=bad, _coords=None) - - -def test_modes_other_than_fit_need_a_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """Without Subproblem.baseline only the default mode runs.""" - sub, _ = real - for mode in ("fixed", "gain", "gain_shared", "fit_from"): - with pytest.raises(ValueError, match="Subproblem.baseline"): - solve_subproblem(sub, replace(PARAMS, baseline_mode=mode)) - - -def test_fit_mode_ignores_an_external_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """R0 gives the same results with and without an external baseline.""" - sub, r0 = real - with_b = replace(sub, baseline=2 * r0.baseline[0], _coords=None) - again = solve_subproblem(with_b, PARAMS, KEEP) - for name in ("footprints", "events", "ls", "f0", "baseline"): - np.testing.assert_array_equal(getattr(again, name), getattr(r0, name)) - - -def test_fixed_mode_holds_the_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: - """N0 keeps the given baseline (bounded below). - - Given R0's final baseline, it finds R0's sources. - """ - sub, r0 = real - b = r0.baseline[0] - given = replace(sub, baseline=b, _coords=None) - n0 = solve_subproblem(given, replace(PARAMS, baseline_mode="fixed"), KEEP) - np.testing.assert_array_equal(n0.baseline[0], np.fmax(PARAMS.min_baseline, b)) - for j in range(2): - cos = n0.footprints[:, j] @ r0.footprints[:, j] - cos /= np.linalg.norm(n0.footprints[:, j]) - cos /= np.linalg.norm(r0.footprints[:, j]) - assert cos > 0.99 - x0 = conv_same(r0.events[0, j], PARAMS.k) - xn = conv_same(n0.events[0, j], PARAMS.k) - assert _corr(x0, xn) > 0.9 - assert 0.9 < xn.sum() / x0.sum() < 1.1 - assert "baseline_step" not in n0.info - - -def _mean_error(b: np.ndarray, truth: np.ndarray) -> float: - """Mean absolute error of the pixels' time means, over the truth's mean. - - Returns - ------- - float - The relative error. - """ - return float(np.abs(b.mean(1) - truth.mean(1)).mean() / truth.mean()) - - -def test_fit_from_mode_corrects_little_from_the_right_baseline() -> None: - """N3 given the true baseline stays near it, as R0 comes near it.""" - sub, b_true, _ = _synthetic(seed=7) - n3 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fit_from"), KEEP) - r0 = solve_subproblem(sub, PARAMS, KEEP) - assert _mean_error(n3.baseline[0], b_true) < 0.01 - assert _mean_error(r0.baseline[0], b_true) < 0.01 - - -def test_gain_mode_undoes_a_scale_error() -> None: - """N1 given the true baseline times 1.1 finds gains near 1 / 1.1. - - N0 keeps the error. - """ - sub, b_true, _ = _synthetic(seed=7, scale=1.1) - n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) - gain = n1.info["baseline_step"]["gain"] - assert gain.shape == (sub.n_pixels,) - assert abs(np.median(gain) - 1 / 1.1) < 0.01 - np.testing.assert_allclose( - n1.baseline[0], - np.fmax(PARAMS.min_baseline, gain[:, None] * sub.baseline), - ) - assert _mean_error(n1.baseline[0], b_true) < 0.01 - n0 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fixed"), KEEP) - assert abs(_mean_error(n0.baseline[0], b_true) - 0.1) < 1e-9 - - -def test_gain_programs_without_sources_are_weighted_ratios() -> None: - """With no activity the gain is the weighted ratio of data and predictor.""" - rng = np.random.default_rng(3) - y = rng.random((4, 50)) + 1 - q = rng.random((4, 50)) + 0.5 - finv = rng.random((4, 50)) + 0.5 - x = np.zeros((1, 50)) - h = np.full((4, 1), 0.25) - b, coef = fit_gain(q, y, x, h, finv, q, 0.01) - w = 1 / finv - want = (w * y * q).sum(1) / (w * q * q).sum(1) - np.testing.assert_allclose(coef[:, -1], want, rtol=1e-9) - np.testing.assert_allclose(b, want[:, None] * q, rtol=1e-9) - prog = gain_programs(q, y, x, h, finv, q) - assert prog["g"].shape == (4, 2, 2) and prog["n_sources"] == 1 - assert (prog["lb"] == 0).all() - - -def test_shared_time_course_shrinks_noise_to_its_mean() -> None: - """Without a shared change the factor is flat; with one it follows.""" - rng = np.random.default_rng(4) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - src = np.zeros((n_px, n_t)) - finv = np.ones((n_px, n_t)) - y = rng.poisson(q).astype(np.float64) - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] < 1e-4 - assert np.ptp(c) < 0.01 - assert abs(rec["mean"] - 1) < 0.01 - # Poisson of mean 3 against the loss's variance 3 + 1 - assert abs(rec["alpha"] - 0.75) < 0.03 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] > 0 - assert _corr(c, true) > 0.85 - raw_err = np.abs(rec["raw"] - true).mean() - assert np.abs(c - true).mean() < raw_err - - -def test_gain_shared_mode_finds_a_shared_change() -> None: - """N2 recovers a fast change shared by all pixels that the external baseline lacks. - - N1 does not. - """ - n_t = 1600 - shared = 1 + 0.08 * np.sign(np.sin(np.arange(n_t) / 3.0)) - sub, b_true, _ = _synthetic(seed=5, n_t=n_t, shared=shared) - n2 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain_shared"), KEEP) - step = n2.info["baseline_step"] - assert step["n_outside"] > 50 - assert _corr(step["shared"], shared) > 0.8 - n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) - err2 = np.abs(n2.baseline[0] - b_true).mean() - err1 = np.abs(n1.baseline[0] - b_true).mean() - assert err2 < 0.7 * err1 - - -def test_gain_shared_without_outside_pixels_is_gain() -> None: - """With too few pixels outside the footprints the factor is 1.""" - sub, _, _ = _synthetic(seed=6) - params = replace(PARAMS, baseline_mode="gain_shared") - rows, cols = np.nonzero(sub.sel) - b = sub.baseline - rng = np.random.default_rng(0) - h = rng.random((sub.n_pixels, 1)) + 1 # flat footprint: nothing outside - h /= h.sum() - x = np.zeros((1, sub.n_frames)) - bb, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) - assert info["n_outside"] == 0 - np.testing.assert_array_equal(info["shared"], 1.0) - b1, _info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) - np.testing.assert_array_equal(bb, b1) - assert rows.size == cols.size == sub.n_pixels - - -def test_fit_baseline_offset() -> None: - """A zero offset changes nothing. - - With the true baseline as offset the fitted correction is small. - """ - sub, b_true, s = _synthetic(seed=7) - y = sub.y[0] - x = conv_same(s[None], PARAMS.k) - rows, cols = np.nonzero(sub.sel.T)[::-1] - h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h = (h / h.sum())[:, None] - b0 = sub.baseline - plain = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS) - zero = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=np.zeros_like(y)) - np.testing.assert_allclose(zero, plain, rtol=1e-12, atol=1e-12) - corr = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=b0) - err_from = np.abs(corr - b_true).mean() / b_true.mean() - assert err_from < 0.03 - - -def test_shared_variance_ignores_filled_frames() -> None: - """Filled-in frames (variance multiplier 1000 x) do not hide a shared change. - - They are left out of the shared variance and shrunk alone. - """ - rng = np.random.default_rng(8) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - src = np.zeros((n_px, n_t)) - finv = np.ones((n_px, n_t)) - filled = np.zeros(n_t, bool) - filled[100:160] = True - finv[:, filled] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[:, filled] = 3.0 # filled with a smooth value - c, rec = shared_time_course(y, q, src, finv) - assert rec["s2"] > 0 - assert _corr(c[~filled], true[~filled]) > 0.85 - # the filled frames stay near the mean - assert np.abs(c[filled] - rec["mean"]).max() < 0.01 - - -def test_outside_pixels_ignore_a_source_without_footprint() -> None: - """A source whose footprint is all zero leaves the outside pixels to the other sources.""" - sub, _, _ = _synthetic(seed=9) - params = replace(PARAMS, baseline_mode="gain_shared") - rows, cols = np.nonzero(sub.sel.T)[::-1] - h1 = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) - h = np.column_stack([h1 / h1.sum(), np.zeros(sub.n_pixels)]) - x = np.zeros((2, sub.n_frames)) - b = sub.baseline - _, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) - assert info["n_outside"] > 100 - - -def test_filled_frames_do_not_fake_a_shared_change() -> None: - """With a constant baseline, many filled-in frames leave the residual scale unbiased. - - So no shared change is found. - """ - rng = np.random.default_rng(10) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - filled = rng.random(n_t) < 0.3 - finv[:, filled] = 1000.0 - y = rng.poisson(q).astype(np.float64) - y[:, filled] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert abs(rec["alpha"] - 0.75) < 0.03 - assert np.ptp(c) < 0.01 - - -def test_filled_samples_do_not_count_in_alpha() -> None: - """Pixels filled in at some frames do not bias the residual scale.""" - rng = np.random.default_rng(13) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - holes = rng.random((n_px, n_t)) < 0.3 - finv[holes] = 1000.0 - y = rng.poisson(q).astype(np.float64) - y[holes] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert abs(rec["alpha"] - 0.75) < 0.03 - assert np.ptp(c) < 0.01 - - -def test_shared_change_found_when_most_frames_are_filled() -> None: - """With 70% of the frames filled in, the shared change is still found. - - It is found on the other frames. - """ - rng = np.random.default_rng(12) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - filled = rng.random(n_t) < 0.7 - finv[:, filled] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[:, filled] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv) - assert rec["s2"] > 0 - assert _corr(c[~filled], true[~filled]) > 0.85 - - -def _paired_noise(rng: np.random.Generator, q: np.ndarray, true: np.ndarray) -> np.ndarray: - """Poisson data whose noise neighbouring pixel pairs share (as on resampled frames). - - Each pair's pixels are the mean of two draws. - - Returns - ------- - np.ndarray - Data of shape (n_px, n_t) with each pixel pair sharing its values. - """ - n_px, n_t = q.shape - draws = rng.poisson(q * true[None]).astype(np.float64) - pair = draws.reshape(n_px // 2, 2, n_t).mean(1) - return np.repeat(pair, 2, axis=0) - - -def test_halves_ignore_noise_shared_by_neighbours() -> None: - """Noise shared by neighbouring pixels is no shared change when the halves are apart. - - The independent-noise estimate mistakes it for one. - """ - rng = np.random.default_rng(14) - n_px, n_t = 200, 2000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - src = np.zeros_like(q) - y = _paired_noise(rng, q, np.ones(n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - c1, r1 = shared_time_course(y, q, src, finv) - c2, r2 = shared_time_course(y, q, src, finv, (half_a, half_b)) - assert r1["s2"] > 0 and np.ptp(c1) > 0.05 - assert r2["s2"] < 0.1 * r2["var_raw"] - assert np.std(c2) < 0.3 * np.std(c1) - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = _paired_noise(rng, q, true) - c3, r3 = shared_time_course(y, q, src, finv, (half_a, half_b)) - assert r3["s2"] > 0 - assert _corr(c3, true) > 0.85 - small = np.zeros(n_px, bool) - small[:3] = True - _, r4 = shared_time_course(y, q, src, finv, (small, half_b)) - assert r4["s2"] == 0 - - -def test_outside_halves_are_apart() -> None: - """The halves split the outside pixels along their longer extent, with a gap.""" - sel = np.ones((5, 12), bool) - outside = np.ones(60, bool) - a, b = outside_halves(sel, outside) - _rows, cols = np.nonzero(sel.T)[::-1] - assert cols[a].max() < cols[b].min() - 2 - assert a.sum() > 15 and b.sum() > 15 - - -def test_halves_skip_frames_where_one_half_is_filled() -> None: - """Frames where one half is filled in do not enter the halves' covariance. - - This holds for frames where the whole is not filled in. - """ - rng = np.random.default_rng(15) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - holes = rng.random(n_t) < 0.4 - finv[np.ix_(half_a, holes)] = 1000.0 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - y = rng.poisson(q * true[None]).astype(np.float64) - y[np.ix_(half_a, holes)] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) - assert rec["s2"] == pytest.approx(np.var(true), rel=0.25) - assert _corr(c, true) > 0.85 - - -def test_halves_do_not_shrink_noiseless_factors() -> None: - """Identical noiseless factors in both halves are kept as they are, also with few frames.""" - q = np.ones((20, 2)) - y = q * np.array([0.8, 1.2])[None] - halves = (np.arange(20) < 8, np.arange(20) >= 12) - for finv in (np.ones_like(q), np.ones_like(q) * np.array([1.0, 4.0])): - c, _rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) - np.testing.assert_allclose(c, [0.8, 1.2]) - - -def test_halves_use_the_same_frames_for_both_variances() -> None: - """The halves use the same frames for the shared and the factors' variance. - - When one half is filled in during the quiet part of a shared change, the - shared variance does not exceed the factors' variance on the same - frames, and the change is followed. - """ - rng = np.random.default_rng(16) - n_px, n_t = 200, 3000 - q = np.full((n_px, n_t), 3.0) - finv = np.ones((n_px, n_t)) - half_a = np.arange(n_px) < 90 - half_b = np.arange(n_px) >= 110 - true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) - quiet = true < 1 - finv[np.ix_(half_a, quiet)] = 1000.0 - y = rng.poisson(q * true[None]).astype(np.float64) - y[np.ix_(half_a, quiet)] = 3.0 - c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) - assert 0 < rec["s2"] <= rec["var_used"] - # on these frames the change is half a sine, a smaller variance - assert rec["s2"] == pytest.approx(np.var(true[~quiet]), rel=0.4) - assert _corr(c[~quiet], true[~quiet]) > 0.6 +"""Tests of the solver's baseline modes. + +These are the variants R0, N0-N3 of the SILo port's baseline test: an external +baseline held, scaled per pixel, scaled by a shared time course, or corrected +by fitB. +""" + +from dataclasses import replace +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.solver import ( + SolverOptions, + SubproblemResult, + conv_same, + solve_subproblem, +) +from giant_python.extraction.raster.solver_baseline import ( + fit_baseline, + fit_gain, + fit_network_gain, + gain_programs, + outside_halves, + shared_time_course, +) +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() +KEEP = SolverOptions(keep_baseline=True) + + +def _corr(a: np.ndarray, b: np.ndarray) -> float: + """Pearson correlation of two traces. + + Returns + ------- + float + The correlation coefficient of the flattened a and b. + """ + return float(np.corrcoef(np.ravel(a), np.ravel(b))[0, 1]) + + +@pytest.fixture(scope="module") +def real() -> tuple[Subproblem, SubproblemResult]: + """Load a real two-source subproblem (activity channel only) and solve it. + + Returns it with the default solver's result on it, with its baseline. + + Returns + ------- + sub : Subproblem + The real subproblem. + result : SubproblemResult + The default solver's result on it, with its baseline kept. + """ + with h5py.File(SUBPROBLEM, "r") as f: + sub = Subproblem( + y=f["in/y"][()][:1].astype(np.float64), + finv=f["in/finv"][()].astype(np.float64), + sel=f["in/sel"][()].astype(bool), + sources_rc=f["in/sources_rc"][()], + ) + return sub, solve_subproblem(sub, PARAMS, KEEP) + + +def _synthetic( + seed: int = 0, + n_t: int = 1600, + shared: np.ndarray | None = None, + scale: float = 1.0, +) -> tuple[Subproblem, np.ndarray, np.ndarray]: + """Draw a one-source subproblem from a known baseline and events. + + The baseline is a bright stripe times a slow drift (and shared, a + time course common to all pixels, if given); the data are F + times Poisson counts of mean T / F, with the variance multiplier + F 0.2. Returns the subproblem (with the true + baseline times scale as its external baseline, without the shared + course), the true baseline and the true events. + + Returns + ------- + sub : Subproblem + The subproblem, with the true baseline times scale as its external baseline. + b_true : np.ndarray + The true baseline (including shared if given). + s : np.ndarray + The true events. + """ + rng = np.random.default_rng(seed) + sel = np.ones((13, 13), bool) + rows, cols = np.nonzero(sel.T)[::-1] + t = np.arange(n_t) + slow = 1 + 0.1 * np.sin(2 * np.pi * t / n_t) + space = 2 + 3 * np.exp(-((cols - 6.0) ** 2) / 8) + b = space[:, None] * slow[None, :] + if shared is not None: + b_true = b * shared[None, :] + else: + b_true = b + h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h /= h.sum() + s = np.zeros(n_t) + s[rng.choice(np.arange(20, n_t - 40), 25, replace=False)] = 20 / 0.19 + x = conv_same(s[None], PARAMS.k)[0] + finv = np.full(b.shape, 0.2) + z = finv * rng.poisson((b_true + np.outer(h, x)) / finv) + sub = Subproblem( + y=z[None], + finv=finv, + sel=sel, + sources_rc=np.array([[6, 6]]), + baseline=b * scale, + ) + return sub, b_true, s + + +def test_params_and_subproblem_check_the_baseline() -> None: + """Unknown modes, a misfitting or non-finite baseline are refused.""" + with pytest.raises(ValueError, match="baseline_mode"): + SolverParams(baseline_mode="network") + for bad in (0.0, 1.0): + with pytest.raises(ValueError, match="outside_footprint"): + SolverParams(outside_footprint=bad) + sub, _, _ = _synthetic() + with pytest.raises(ValueError, match="pixels and frames"): + replace(sub, baseline=sub.baseline[:, :-1], _coords=None) + bad = sub.baseline.copy() + bad[0, 0] = np.nan + with pytest.raises(ValueError, match="NaN"): + replace(sub, baseline=bad, _coords=None) + + +def test_modes_other_than_fit_need_a_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """Without Subproblem.baseline only the default mode runs.""" + sub, _ = real + for mode in ("fixed", "gain", "gain_shared", "fit_from"): + with pytest.raises(ValueError, match="Subproblem.baseline"): + solve_subproblem(sub, replace(PARAMS, baseline_mode=mode)) + + +def test_fit_mode_ignores_an_external_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """R0 gives the same results with and without an external baseline.""" + sub, r0 = real + with_b = replace(sub, baseline=2 * r0.baseline[0], _coords=None) + again = solve_subproblem(with_b, PARAMS, KEEP) + for name in ("footprints", "events", "ls", "f0", "baseline"): + np.testing.assert_array_equal(getattr(again, name), getattr(r0, name)) + + +def test_fixed_mode_holds_the_baseline(real: tuple[Subproblem, SubproblemResult]) -> None: + """N0 keeps the given baseline (bounded below). + + Given R0's final baseline, it finds R0's sources. + """ + sub, r0 = real + b = r0.baseline[0] + given = replace(sub, baseline=b, _coords=None) + n0 = solve_subproblem(given, replace(PARAMS, baseline_mode="fixed"), KEEP) + np.testing.assert_array_equal(n0.baseline[0], np.fmax(PARAMS.min_baseline, b)) + for j in range(2): + cos = n0.footprints[:, j] @ r0.footprints[:, j] + cos /= np.linalg.norm(n0.footprints[:, j]) + cos /= np.linalg.norm(r0.footprints[:, j]) + assert cos > 0.99 + x0 = conv_same(r0.events[0, j], PARAMS.k) + xn = conv_same(n0.events[0, j], PARAMS.k) + assert _corr(x0, xn) > 0.9 + assert 0.9 < xn.sum() / x0.sum() < 1.1 + assert "baseline_step" not in n0.info + + +def _mean_error(b: np.ndarray, truth: np.ndarray) -> float: + """Mean absolute error of the pixels' time means, over the truth's mean. + + Returns + ------- + float + The relative error. + """ + return float(np.abs(b.mean(1) - truth.mean(1)).mean() / truth.mean()) + + +def test_fit_from_mode_corrects_little_from_the_right_baseline() -> None: + """N3 given the true baseline stays near it, as R0 comes near it.""" + sub, b_true, _ = _synthetic(seed=7) + n3 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fit_from"), KEEP) + r0 = solve_subproblem(sub, PARAMS, KEEP) + assert _mean_error(n3.baseline[0], b_true) < 0.01 + assert _mean_error(r0.baseline[0], b_true) < 0.01 + + +def test_gain_mode_undoes_a_scale_error() -> None: + """N1 given the true baseline times 1.1 finds gains near 1 / 1.1. + + N0 keeps the error. + """ + sub, b_true, _ = _synthetic(seed=7, scale=1.1) + n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) + gain = n1.info["baseline_step"]["gain"] + assert gain.shape == (sub.n_pixels,) + assert abs(np.median(gain) - 1 / 1.1) < 0.01 + np.testing.assert_allclose( + n1.baseline[0], + np.fmax(PARAMS.min_baseline, gain[:, None] * sub.baseline), + ) + assert _mean_error(n1.baseline[0], b_true) < 0.01 + n0 = solve_subproblem(sub, replace(PARAMS, baseline_mode="fixed"), KEEP) + assert abs(_mean_error(n0.baseline[0], b_true) - 0.1) < 1e-9 + + +def test_gain_programs_without_sources_are_weighted_ratios() -> None: + """With no activity the gain is the weighted ratio of data and predictor.""" + rng = np.random.default_rng(3) + y = rng.random((4, 50)) + 1 + q = rng.random((4, 50)) + 0.5 + finv = rng.random((4, 50)) + 0.5 + x = np.zeros((1, 50)) + h = np.full((4, 1), 0.25) + b, coef = fit_gain(q, y, x, h, finv, q, 0.01) + w = 1 / finv + want = (w * y * q).sum(1) / (w * q * q).sum(1) + np.testing.assert_allclose(coef[:, -1], want, rtol=1e-9) + np.testing.assert_allclose(b, want[:, None] * q, rtol=1e-9) + prog = gain_programs(q, y, x, h, finv, q) + assert prog["g"].shape == (4, 2, 2) and prog["n_sources"] == 1 + assert (prog["lb"] == 0).all() + + +def test_shared_time_course_shrinks_noise_to_its_mean() -> None: + """Without a shared change the factor is flat; with one it follows.""" + rng = np.random.default_rng(4) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + src = np.zeros((n_px, n_t)) + finv = np.ones((n_px, n_t)) + y = rng.poisson(q).astype(np.float64) + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] < 1e-4 + assert np.ptp(c) < 0.01 + assert abs(rec["mean"] - 1) < 0.01 + # Poisson of mean 3 against the loss's variance 3 + 1 + assert abs(rec["alpha"] - 0.75) < 0.03 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] > 0 + assert _corr(c, true) > 0.85 + raw_err = np.abs(rec["raw"] - true).mean() + assert np.abs(c - true).mean() < raw_err + + +def test_gain_shared_mode_finds_a_shared_change() -> None: + """N2 recovers a fast change shared by all pixels that the external baseline lacks. + + N1 does not. + """ + n_t = 1600 + shared = 1 + 0.08 * np.sign(np.sin(np.arange(n_t) / 3.0)) + sub, b_true, _ = _synthetic(seed=5, n_t=n_t, shared=shared) + n2 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain_shared"), KEEP) + step = n2.info["baseline_step"] + assert step["n_outside"] > 50 + assert _corr(step["shared"], shared) > 0.8 + n1 = solve_subproblem(sub, replace(PARAMS, baseline_mode="gain"), KEEP) + err2 = np.abs(n2.baseline[0] - b_true).mean() + err1 = np.abs(n1.baseline[0] - b_true).mean() + assert err2 < 0.7 * err1 + + +def test_gain_shared_without_outside_pixels_is_gain() -> None: + """With too few pixels outside the footprints the factor is 1.""" + sub, _, _ = _synthetic(seed=6) + params = replace(PARAMS, baseline_mode="gain_shared") + rows, cols = np.nonzero(sub.sel) + b = sub.baseline + rng = np.random.default_rng(0) + h = rng.random((sub.n_pixels, 1)) + 1 # flat footprint: nothing outside + h /= h.sum() + x = np.zeros((1, sub.n_frames)) + bb, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) + assert info["n_outside"] == 0 + np.testing.assert_array_equal(info["shared"], 1.0) + b1, _info1 = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=False) + np.testing.assert_array_equal(bb, b1) + assert rows.size == cols.size == sub.n_pixels + + +def test_fit_baseline_offset() -> None: + """A zero offset changes nothing. + + With the true baseline as offset the fitted correction is small. + """ + sub, b_true, s = _synthetic(seed=7) + y = sub.y[0] + x = conv_same(s[None], PARAMS.k) + rows, cols = np.nonzero(sub.sel.T)[::-1] + h = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h = (h / h.sum())[:, None] + b0 = sub.baseline + plain = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS) + zero = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=np.zeros_like(y)) + np.testing.assert_allclose(zero, plain, rtol=1e-12, atol=1e-12) + corr = fit_baseline(b0, y, x, h, sub.finv, sub.sel, PARAMS, offset=b0) + err_from = np.abs(corr - b_true).mean() / b_true.mean() + assert err_from < 0.03 + + +def test_shared_variance_ignores_filled_frames() -> None: + """Filled-in frames (variance multiplier 1000 x) do not hide a shared change. + + They are left out of the shared variance and shrunk alone. + """ + rng = np.random.default_rng(8) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + src = np.zeros((n_px, n_t)) + finv = np.ones((n_px, n_t)) + filled = np.zeros(n_t, bool) + filled[100:160] = True + finv[:, filled] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[:, filled] = 3.0 # filled with a smooth value + c, rec = shared_time_course(y, q, src, finv) + assert rec["s2"] > 0 + assert _corr(c[~filled], true[~filled]) > 0.85 + # the filled frames stay near the mean + assert np.abs(c[filled] - rec["mean"]).max() < 0.01 + + +def test_outside_pixels_ignore_a_source_without_footprint() -> None: + """A source whose footprint is all zero leaves the outside pixels to the other sources.""" + sub, _, _ = _synthetic(seed=9) + params = replace(PARAMS, baseline_mode="gain_shared") + rows, cols = np.nonzero(sub.sel.T)[::-1] + h1 = np.exp(-((rows - 6.0) ** 2 + (cols - 6.0) ** 2) / (2 * 1.33**2)) + h = np.column_stack([h1 / h1.sum(), np.zeros(sub.n_pixels)]) + x = np.zeros((2, sub.n_frames)) + b = sub.baseline + _, info = fit_network_gain(b, b, sub.y[0], x, h, sub.finv, params, shared=True) + assert info["n_outside"] > 100 + + +def test_filled_frames_do_not_fake_a_shared_change() -> None: + """With a constant baseline, many filled-in frames leave the residual scale unbiased. + + So no shared change is found. + """ + rng = np.random.default_rng(10) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + filled = rng.random(n_t) < 0.3 + finv[:, filled] = 1000.0 + y = rng.poisson(q).astype(np.float64) + y[:, filled] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert abs(rec["alpha"] - 0.75) < 0.03 + assert np.ptp(c) < 0.01 + + +def test_filled_samples_do_not_count_in_alpha() -> None: + """Pixels filled in at some frames do not bias the residual scale.""" + rng = np.random.default_rng(13) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + holes = rng.random((n_px, n_t)) < 0.3 + finv[holes] = 1000.0 + y = rng.poisson(q).astype(np.float64) + y[holes] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert abs(rec["alpha"] - 0.75) < 0.03 + assert np.ptp(c) < 0.01 + + +def test_shared_change_found_when_most_frames_are_filled() -> None: + """With 70% of the frames filled in, the shared change is still found. + + It is found on the other frames. + """ + rng = np.random.default_rng(12) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + filled = rng.random(n_t) < 0.7 + finv[:, filled] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[:, filled] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv) + assert rec["s2"] > 0 + assert _corr(c[~filled], true[~filled]) > 0.85 + + +def _paired_noise(rng: np.random.Generator, q: np.ndarray, true: np.ndarray) -> np.ndarray: + """Poisson data whose noise neighbouring pixel pairs share (as on resampled frames). + + Each pair's pixels are the mean of two draws. + + Returns + ------- + np.ndarray + Data of shape (n_px, n_t) with each pixel pair sharing its values. + """ + n_px, n_t = q.shape + draws = rng.poisson(q * true[None]).astype(np.float64) + pair = draws.reshape(n_px // 2, 2, n_t).mean(1) + return np.repeat(pair, 2, axis=0) + + +def test_halves_ignore_noise_shared_by_neighbours() -> None: + """Noise shared by neighbouring pixels is no shared change when the halves are apart. + + The independent-noise estimate mistakes it for one. + """ + rng = np.random.default_rng(14) + n_px, n_t = 200, 2000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + src = np.zeros_like(q) + y = _paired_noise(rng, q, np.ones(n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + c1, r1 = shared_time_course(y, q, src, finv) + c2, r2 = shared_time_course(y, q, src, finv, (half_a, half_b)) + assert r1["s2"] > 0 and np.ptp(c1) > 0.05 + assert r2["s2"] < 0.1 * r2["var_raw"] + assert np.std(c2) < 0.3 * np.std(c1) + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = _paired_noise(rng, q, true) + c3, r3 = shared_time_course(y, q, src, finv, (half_a, half_b)) + assert r3["s2"] > 0 + assert _corr(c3, true) > 0.85 + small = np.zeros(n_px, bool) + small[:3] = True + _, r4 = shared_time_course(y, q, src, finv, (small, half_b)) + assert r4["s2"] == 0 + + +def test_outside_halves_are_apart() -> None: + """The halves split the outside pixels along their longer extent, with a gap.""" + sel = np.ones((5, 12), bool) + outside = np.ones(60, bool) + a, b = outside_halves(sel, outside) + _rows, cols = np.nonzero(sel.T)[::-1] + assert cols[a].max() < cols[b].min() - 2 + assert a.sum() > 15 and b.sum() > 15 + + +def test_halves_skip_frames_where_one_half_is_filled() -> None: + """Frames where one half is filled in do not enter the halves' covariance. + + This holds for frames where the whole is not filled in. + """ + rng = np.random.default_rng(15) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + holes = rng.random(n_t) < 0.4 + finv[np.ix_(half_a, holes)] = 1000.0 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + y = rng.poisson(q * true[None]).astype(np.float64) + y[np.ix_(half_a, holes)] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) + assert rec["s2"] == pytest.approx(np.var(true), rel=0.25) + assert _corr(c, true) > 0.85 + + +def test_halves_do_not_shrink_noiseless_factors() -> None: + """Identical noiseless factors in both halves are kept as they are, also with few frames.""" + q = np.ones((20, 2)) + y = q * np.array([0.8, 1.2])[None] + halves = (np.arange(20) < 8, np.arange(20) >= 12) + for finv in (np.ones_like(q), np.ones_like(q) * np.array([1.0, 4.0])): + c, _rec = shared_time_course(y, q, np.zeros_like(q), finv, halves) + np.testing.assert_allclose(c, [0.8, 1.2]) + + +def test_halves_use_the_same_frames_for_both_variances() -> None: + """The halves use the same frames for the shared and the factors' variance. + + When one half is filled in during the quiet part of a shared change, the + shared variance does not exceed the factors' variance on the same + frames, and the change is followed. + """ + rng = np.random.default_rng(16) + n_px, n_t = 200, 3000 + q = np.full((n_px, n_t), 3.0) + finv = np.ones((n_px, n_t)) + half_a = np.arange(n_px) < 90 + half_b = np.arange(n_px) >= 110 + true = 1 + 0.15 * np.sin(np.arange(n_t) / 7.0) + quiet = true < 1 + finv[np.ix_(half_a, quiet)] = 1000.0 + y = rng.poisson(q * true[None]).astype(np.float64) + y[np.ix_(half_a, quiet)] = 3.0 + c, rec = shared_time_course(y, q, np.zeros_like(q), finv, (half_a, half_b)) + assert 0 < rec["s2"] <= rec["var_used"] + # on these frames the change is half a sine, a smaller variance + assert rec["s2"] == pytest.approx(np.var(true[~quiet]), rel=0.4) + assert _corr(c[~quiet], true[~quiet]) > 0.6 diff --git a/tests/raster/test_raster_solver_fits.py b/tests/raster/test_raster_solver_fits.py index b43cb0f8..da4eea6e 100644 --- a/tests/raster/test_raster_solver_fits.py +++ b/tests/raster/test_raster_solver_fits.py @@ -1,466 +1,466 @@ -"""Tests of the iterative fits of the subproblem solver. - -The loss and its derivatives, the kernel, the bounded Newton solver, and the -fits against GIAnT-MATLAB's from the same inputs. -""" - -import itertools -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -import torch -from numpy.typing import ArrayLike -from scipy import optimize - -from giant_python.extraction.raster import solver_baseline as sb -from giant_python.extraction.raster import solver_fits as sf -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - conv_operator, - temporal_kernel, -) - -SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" -PARAMS = SolverParams() -DT = torch.float64 - - -def _t(a: ArrayLike) -> torch.Tensor: - """Make a float64 tensor with a leading batch dimension of one. - - Returns - ------- - torch.Tensor - a as a float64 tensor of shape ``(1, *a.shape)``. - """ - return torch.as_tensor(np.ascontiguousarray(a), dtype=DT)[None] - - -def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: - """MATLAB convn(x, k, 'same') along the last axis. - - Returns - ------- - np.ndarray - The convolution of each row of x with k, with the shape of x. - """ - c = len(k) // 2 - flat = x.reshape(-1, x.shape[-1]) - out = np.stack([np.convolve(r, k)[c : c + x.shape[-1]] for r in flat]) - return out.reshape(x.shape) - - -def _small_problem( - seed: int = 0, - n_px: int = 14, - n_src: int = 2, - n_t: int = 60, - batch: int = 1, - tau: float = 3.0, -) -> list[torch.Tensor]: - """Random data from overlapping footprints and sparse events. - - Returns - ------- - list[torch.Tensor] - The data z, footprints h, baseline b, weights 1 / finv, events s and - temporal kernel k, in that order. - """ - rng = np.random.default_rng(seed) - k = temporal_kernel(tau) - h = rng.random((batch, n_px, n_src)) ** 3 - h /= h.sum(1, keepdims=True) - s = (rng.random((batch, n_src, n_t)) < 0.1) * rng.uniform(20, 80, (batch, n_src, n_t)) - b = 1.0 + rng.random((batch, n_px, 1)) + 0.2 * rng.random((1, 1, n_t)) - finv = 0.5 + rng.random((batch, n_px, n_t)) - mean = b + h @ _conv_same(s, k) - z = finv * rng.poisson(mean / finv) - tens = [torch.as_tensor(a, dtype=DT) for a in (z, h, b, 1 / finv, s)] - return tens + [torch.as_tensor(k, dtype=DT)] - - -@pytest.mark.parametrize("fixed", [False, True]) -def test_loss_derivatives(fixed: bool) -> None: - """First and second derivative of the loss in the model, by autograd.""" - rng = np.random.default_rng(0) - z = torch.as_tensor(rng.random((2, 3, 5)) * 4) - w = torch.as_tensor(0.5 + rng.random((2, 3, 5))) - s0 = torch.as_tensor(1 + rng.random((2, 3, 5))) if fixed else None - t = torch.as_tensor(rng.random((2, 3, 5)) * 3, dtype=DT).requires_grad_() - f, g, c = sf.variance_loss(z, t, w, s0) - var = s0 if fixed else t + 1 - expected = (w * (z - t) ** 2 / var).sum((-2, -1)) - assert torch.allclose(f, expected, rtol=1e-13) - (g_auto,) = torch.autograd.grad(expected.sum(), t, create_graph=True) - assert torch.allclose(g, g_auto, rtol=1e-12) - (c_auto,) = torch.autograd.grad(g_auto.sum(), t) - assert torch.allclose(c, c_auto, rtol=1e-12) - assert sf.variance_loss(z, t, w, s0, 0)[1:] == (None, None) - assert sf.variance_loss(z, t, w, s0, 1)[2] is None - - -@pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) -@pytest.mark.parametrize("n_t", [5, 40, 400]) -def test_time_kernel_matches_convolution(tau: float, n_t: int) -> None: - """The exponential kernels by shifted additions equal a 'same' convolution. - - This holds for trials shorter and longer than the kernel. - """ - rng = np.random.default_rng(1) - k = temporal_kernel(tau) - kern = sf.TimeKernel(torch.as_tensor(k)) - assert kern.decay == pytest.approx(np.exp(-1 / tau), rel=1e-9) - x = rng.standard_normal((2, 3, n_t)) - y = kern.conv(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-13) - ya = kern.conv_adj(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-13) - - -def test_time_kernel_general() -> None: - """Kernels that are not causal exponentials go through conv1d.""" - rng = np.random.default_rng(2) - x = rng.standard_normal((1, 2, 30)) - for k in ( - np.concatenate([np.zeros(4), [0.5, 0.3, 0.1, 0.07, 0.03]]), - np.array([0.2, 0.5, 0.3]), - np.array([0.0, 0.0, 0.0, 1.0, 0.5, 0.0, 0.25]), - ): - kern = sf.TimeKernel(torch.as_tensor(k)) - assert kern.decay is None - y = kern.conv(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-14) - ya = kern.conv_adj(torch.as_tensor(x)).numpy() - np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-14) - with pytest.raises(ValueError, match="odd"): - sf.TimeKernel(torch.ones(4)) - - -def _check_derivatives(problem: sf.ActivityProblem | sf.FootprintProblem, x: torch.Tensor) -> None: - """Gradient, Hessian products and diagonal against autograd.""" - x = x.clone().requires_grad_() - f = problem.value(x) - (g_auto,) = torch.autograd.grad(f.sum(), x, create_graph=True) - f2, g = problem.value_grad(x.detach()) - assert torch.allclose(f2, f.detach(), rtol=1e-13) - assert torch.allclose(g, g_auto.detach(), rtol=1e-9, atol=1e-10) - rng = np.random.default_rng(5) - v = torch.as_tensor(rng.standard_normal(x.shape)) - (hv_auto,) = torch.autograd.grad((g_auto * v).sum(), x, retain_graph=True) - hv = problem.hess_mult(v) - assert torch.allclose(hv, hv_auto, rtol=1e-9, atol=1e-9) - diag = torch.zeros_like(x) - flat = diag.view(-1) - for i in range(flat.numel()): - e = torch.zeros(flat.numel(), dtype=DT) - e[i] = 1 - flat[i] = problem.hess_mult(e.view(x.shape)).view(-1)[i] - assert torch.allclose(problem.hess_diag(), diag, rtol=1e-9, atol=1e-12) - - -@pytest.mark.parametrize("fixed", [False, True]) -def test_activity_problem_derivatives(fixed: bool) -> None: - """The activity fit's gradient and curvature, with either variance.""" - z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) - s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None - problem = sf.ActivityProblem(z, h, b, k, w, 0.9, s0) - _check_derivatives(problem, s * 0.5 + 1) - - -def test_footprint_problem_derivatives() -> None: - """The footprint fit's gradient and curvature.""" - z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) - rng = np.random.default_rng(6) - g = torch.as_tensor(rng.random((1, 6, 6)) * (rng.random((1, 6, 6)) < 0.6)) - x = sf.TimeKernel(k).conv(s) - support = torch.ones((1, 6, 2), dtype=torch.bool) - problem = sf.FootprintProblem(z, x, b, g, w, support) - _check_derivatives(problem, h.clone()) - - -def test_preconditioner_inverts_one_source() -> None: - """For one source the preconditioner is the inverse of the Hessian on the free events. - - Up to the kernel's truncation. - """ - z, h, b, w, s, k = _small_problem(n_px=8, n_src=1, n_t=200) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - problem.value_grad(s) - rng = np.random.default_rng(7) - free = torch.as_tensor(rng.random(s.shape) < 0.4) - free[..., 50:80] = True # a run of consecutive free events - fm = free.to(DT) - v = torch.as_tensor(rng.standard_normal(s.shape)) * fm - hv = fm * problem.hess_mult(v) - back = problem.preconditioner(free, problem.hess_diag())(hv) - assert float((back - v).norm() / v.norm()) < 0.02 - # the Hessian's diagonal alone is far from it - jacobi = fm / problem.hess_diag() * hv - assert float((jacobi - v).norm() / v.norm()) > 0.3 - - -def test_preconditioner_falls_back_to_diagonal() -> None: - """Kernels that are not exponential get the Hessian's diagonal.""" - z, h, b, w, s, _ = _small_problem(n_px=6, n_t=20) - k = torch.as_tensor([0.0, 0.0, 0.6, 0.1, 0.3], dtype=DT) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - problem.value_grad(s) - free = torch.ones_like(s, dtype=torch.bool) - r = torch.ones_like(s) - diag = problem.hess_diag() - assert torch.equal(problem.preconditioner(free, diag)(r), r / diag) - - -def test_activity_fit_reaches_scipy_optimum() -> None: - """The fit ends at the optimum that L-BFGS-B approaches. - - Many events are on their bound. - """ - z, h, b, w, s_true, k = _small_problem(seed=3, n_px=20, n_t=120) - start = torch.full_like(s_true, 5.0) - s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, history=True) - assert bool(info.converged[0]) and int(info.iterations[0]) < 30 - assert float(info.optimality[0]) < 1e-5 - assert float((s == 0).double().mean()) > 0.4 and float(s.min()) == 0 - losses = [float(f[0]) for f in info.history] - assert all(b2 <= a2 for a2, b2 in itertools.pairwise(losses)) - - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - - def fun(x: np.ndarray) -> tuple[float, np.ndarray]: - """Loss and gradient for scipy. - - Returns - ------- - loss : float - The activity loss at x. - grad : np.ndarray - The flattened gradient of the loss at x. - """ - f, g = problem.value_grad(torch.as_tensor(x).view(s.shape)) - return float(f[0]), g.numpy().ravel() - - ref = optimize.minimize( - fun, - start.numpy().ravel(), - jac=True, - method="L-BFGS-B", - bounds=[(0, None)] * s.numel(), - options={"maxiter": 20000, "maxfun": 50000, "ftol": 1e-15, "gtol": 1e-9}, - ) - assert float(info.loss[0]) <= ref.fun + 1e-9 * abs(ref.fun) - np.testing.assert_allclose(s.numpy().ravel(), ref.x, atol=2e-2) - # the sparse events are recovered - found = _conv_same(s.numpy(), k.numpy()) - truth = _conv_same(s_true.numpy(), k.numpy()) - assert np.corrcoef(found.ravel(), truth.ravel())[0, 1] > 0.7 - - -def test_fit_does_not_depend_on_its_start() -> None: - """A convex fit has one optimum: two starts end at the same events.""" - z, h, b, w, s_true, k = _small_problem(seed=4, n_px=16, n_t=80) - a, _ = sf.fit_activity(z, h, b, k, w, 0.9, torch.zeros_like(s_true)) - c, _ = sf.fit_activity(z, h, b, k, w, 0.9, s_true * 3 + 10) - assert torch.allclose(a, c, atol=1e-4) - - -def test_batched_fit_equals_separate_fits() -> None: - """Members of a batch get the fits they get alone. - - They are padded with weightless pixels and a source held at zero. - """ - z, h, b, w, s_true, k = _small_problem(seed=5, n_px=12, n_t=70, batch=2) - # member 1: 9 pixels and one source; the rest is padding - w[1, 9:] = 0 - z[1, 9:] = 0 - b[1, 9:] = 1 - h[1, :, 1] = 0 - h[1, 9:] = 0 - free = torch.ones_like(s_true, dtype=torch.bool) - free[1, 1] = False - start = torch.full_like(s_true, 2.0) - s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, free=free) - assert bool(info.converged.all()) - assert torch.all(s[1, 1] == 0) - one, i0 = sf.fit_activity(z[:1], h[:1], b[:1], k, w[:1], 0.9, start[:1], free=free[:1]) - two, i1 = sf.fit_activity(z[1:, :9], h[1:, :9, :1], b[1:, :9], k, w[1:, :9], 0.9, start[1:, :1]) - assert torch.allclose(s[0], one[0], atol=1e-5) - assert torch.allclose(s[1, :1], two[0], atol=1e-5) - assert float(info.loss[0]) == pytest.approx(float(i0.loss[0]), rel=1e-10) - assert float(info.loss[1]) == pytest.approx(float(i1.loss[0]), rel=1e-10) - - -def test_iteration_cap_and_free_entries() -> None: - """A capped fit reports that it did not converge and still lowers the loss. - - Entries that are not free stay at zero. - """ - z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) - start = torch.full_like(s_true, 5.0) - problem = sf.ActivityProblem(z, h, b, k, w, 0.9) - _s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) - assert not bool(info.converged[0]) and int(info.iterations[0]) == 1 - assert float(info.loss[0]) < float(problem.value(start)[0]) - _full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) - assert float(done.loss[0]) < float(info.loss[0]) - free = s_true > 0 - s2, info2 = sf.fit_activity(z, h, b, k, w, 0.0, start, free=free) - assert bool(info2.converged[0]) - assert torch.all(s2[~free] == 0) and float(s2[free].min()) >= 0 - - -def test_fixed_variance_fit_is_weighted_least_squares() -> None: - """With the variance held, the fit of the free events is weighted least squares. - - It is the bounded weighted least-squares solution. - """ - z, h, b, w, s_true, k = _small_problem(seed=7, n_px=10, n_src=1, n_t=40) - kern = sf.TimeKernel(k) - s0 = h @ kern.conv(s_true) + b + 1 - free = torch.zeros_like(s_true, dtype=torch.bool) - free[..., ::4] = True - s, info = sf.fit_activity(z, h, b, k, w, 0.0, s_true, s0=s0, free=free, ftol=1e-15) - assert bool(info.converged[0]) - idx = np.nonzero(free.numpy().ravel())[0] - cols = [] - for i in idx: - e = torch.zeros_like(s_true) - e.view(-1)[i] = 1 - cols.append((h @ kern.conv(e)).numpy().ravel()) - sw = np.sqrt((w / s0).numpy().ravel()) - design = np.stack(cols, 1) * sw[:, None] - target = (z - b).numpy().ravel() * sw - ref = optimize.lsq_linear(design, target, bounds=(0, np.inf)).x - np.testing.assert_allclose(s.numpy().ravel()[idx], ref, atol=1e-5) - - -def test_footprint_fit_stays_on_its_support() -> None: - """Footprints are fitted within their support, not below zero. - - They reach a lower loss than the start. - """ - z, _h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) - x = sf.TimeKernel(k).conv(s) - g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 - valid = torch.zeros((1, 12, 2), dtype=torch.bool) - valid[0, :6, 0] = True - valid[0, 5:, 1] = True - start = valid.to(DT) / 6 - hs, info = sf.fit_footprints(z, x, b, g, w, start, valid) - assert bool(info.converged[0]) - assert torch.all(hs[~valid] == 0) and float(hs.min()) >= 0 - problem = sf.FootprintProblem(z, x, b, g, w, valid) - assert float(info.loss[0]) < float(problem.value(start)[0]) - assert torch.allclose(problem.footprints(hs), g @ hs) - - -@pytest.fixture(scope="module") -def matlab() -> dict[str, Any]: - """MATLAB's fits of a real two-source subproblem, and its inputs. - - Returns - ------- - dict[str, Any] - MATLAB's stored groups (in, init, it1, it2, debias, ch2, out) - plus the tensors z, z2, w, b0, b1, b2, g, k and k2. - """ - with h5py.File(SUBPROBLEM, "r") as f: - d = { - g: {k: v[()] for k, v in f[g].items()} - for g in ("in", "init", "it1", "it2", "debias", "ch2", "out") - } - y = d["in"]["y"].astype(np.float64) - finv = d["in"]["finv"].astype(np.float64) - sel = d["in"]["sel"].astype(bool) - b0 = sb.initial_baseline(y[0], PARAMS) - b1 = sb.fit_baseline(b0, y[0], d["it1"]["X_thr"], d["init"]["H"], finv, sel, PARAMS) - d.update( - z=_t(y[0]), - z2=_t(y[1]), - w=_t(1 / finv), - b0=_t(b0), - b1=_t(b1), - b2=_t(sb.initial_baseline(y[1], PARAMS)), - g=_t(conv_operator(sel, PARAMS.hfilter).toarray()), - k=torch.as_tensor(PARAMS.k), - k2=torch.as_tensor(PARAMS.k2), - ) - return d - - -def test_loss_is_matlabs(matlab: dict[str, Any]) -> None: - """MATLAB's reported losses are this loss at MATLAB's solutions.""" - m = matlab - lam = PARAMS.lam - p1 = sf.ActivityProblem(m["z"], _t(m["init"]["H"]), m["b0"], m["k"], m["w"], lam) - assert float(p1.value(_t(m["it1"]["S_out"]))[0]) == pytest.approx(m["it1"]["loss_S"], rel=1e-10) - valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] - ph = sf.FootprintProblem(m["z"], _t(m["it1"]["X_thr"]), m["b1"], m["g"], m["w"], valid) - # the baseline differs from MATLAB's by quadprog's tolerance - assert float(ph.value(_t(m["it1"]["Hs_out"]))[0]) == pytest.approx(m["it1"]["loss_H"], rel=1e-6) - p2 = sf.ActivityProblem(m["z"], _t(m["it1"]["H"]), m["b1"], m["k"], m["w"], lam) - assert float(p2.value(_t(m["it2"]["S_out"]))[0]) == pytest.approx(m["it2"]["loss_S"], rel=1e-6) - pc = sf.ActivityProblem(m["z2"], _t(m["out"]["H"]), m["b2"], m["k2"], m["w"], lam) - assert float(pc.value(_t(m["ch2"]["S_l1"]))[0]) == pytest.approx(m["ch2"]["loss"], rel=1e-10) - - -def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: - """Each fit, started from MATLAB's inputs, ends at a loss no higher than MATLAB's. - - MATLAB's fits stop at iteration caps or tolerances. - """ - m = matlab - lam = PARAMS.lam - s, info = sf.fit_activity( - m["z"], - _t(m["init"]["H"]), - m["b0"], - m["k"], - m["w"], - lam, - _t(m["init"]["S"]), - ) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it1"]["loss_S"] - - valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] - x_thr = _t(m["it1"]["X_thr"]) - _hs, info = sf.fit_footprints( - m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid - ) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it1"]["loss_H"] * (1 - 1e-5) - - h1 = _t(m["it1"]["H"]) - s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], lam, _t(m["it1"]["S"])) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["it2"]["loss_S"] * (1 + 1e-6) - - # debias: MATLAB's refit of its own events, variance held at the start - free = torch.as_tensor(m["debias"]["free"].astype(bool))[None] - start = _t(m["debias"]["S_in"]) - s0 = h1 @ sf.TimeKernel(m["k"]).conv(start) + m["b1"] + 1 - problem = sf.ActivityProblem(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, s0) - f_matlab = float(problem.value(_t(m["debias"]["S_out"]))[0]) - s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, start, s0=s0, free=free) - assert bool(info.converged[0]) - assert float(info.loss[0]) <= f_matlab * (1 + 1e-9) - # MATLAB's refit stops near this optimum: the activity agrees - kern = sf.TimeKernel(m["k"]) - x, x_matlab = kern.conv(s), kern.conv(_t(m["debias"]["S_out"])) - assert float((x - x_matlab).norm() / x_matlab.norm()) < 0.02 - - _s2, info = sf.fit_activity( - m["z2"], - _t(m["out"]["H"]), - m["b2"], - m["k2"], - m["w"], - lam, - _t(m["ch2"]["LS"]), - ) - assert bool(info.converged[0]) - assert float(info.loss[0]) < m["ch2"]["loss"] +"""Tests of the iterative fits of the subproblem solver. + +The loss and its derivatives, the kernel, the bounded Newton solver, and the +fits against GIAnT-MATLAB's from the same inputs. +""" + +import itertools +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +import torch +from numpy.typing import ArrayLike +from scipy import optimize + +from giant_python.extraction.raster import solver_baseline as sb +from giant_python.extraction.raster import solver_fits as sf +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + conv_operator, + temporal_kernel, +) + +SUBPROBLEM = Path(__file__).parent / "data" / "matlab_solver_subproblem.h5" +PARAMS = SolverParams() +DT = torch.float64 + + +def _t(a: ArrayLike) -> torch.Tensor: + """Make a float64 tensor with a leading batch dimension of one. + + Returns + ------- + torch.Tensor + a as a float64 tensor of shape ``(1, *a.shape)``. + """ + return torch.as_tensor(np.ascontiguousarray(a), dtype=DT)[None] + + +def _conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray: + """MATLAB convn(x, k, 'same') along the last axis. + + Returns + ------- + np.ndarray + The convolution of each row of x with k, with the shape of x. + """ + c = len(k) // 2 + flat = x.reshape(-1, x.shape[-1]) + out = np.stack([np.convolve(r, k)[c : c + x.shape[-1]] for r in flat]) + return out.reshape(x.shape) + + +def _small_problem( + seed: int = 0, + n_px: int = 14, + n_src: int = 2, + n_t: int = 60, + batch: int = 1, + tau: float = 3.0, +) -> list[torch.Tensor]: + """Random data from overlapping footprints and sparse events. + + Returns + ------- + list[torch.Tensor] + The data z, footprints h, baseline b, weights 1 / finv, events s and + temporal kernel k, in that order. + """ + rng = np.random.default_rng(seed) + k = temporal_kernel(tau) + h = rng.random((batch, n_px, n_src)) ** 3 + h /= h.sum(1, keepdims=True) + s = (rng.random((batch, n_src, n_t)) < 0.1) * rng.uniform(20, 80, (batch, n_src, n_t)) + b = 1.0 + rng.random((batch, n_px, 1)) + 0.2 * rng.random((1, 1, n_t)) + finv = 0.5 + rng.random((batch, n_px, n_t)) + mean = b + h @ _conv_same(s, k) + z = finv * rng.poisson(mean / finv) + tens = [torch.as_tensor(a, dtype=DT) for a in (z, h, b, 1 / finv, s)] + return tens + [torch.as_tensor(k, dtype=DT)] + + +@pytest.mark.parametrize("fixed", [False, True]) +def test_loss_derivatives(fixed: bool) -> None: + """First and second derivative of the loss in the model, by autograd.""" + rng = np.random.default_rng(0) + z = torch.as_tensor(rng.random((2, 3, 5)) * 4) + w = torch.as_tensor(0.5 + rng.random((2, 3, 5))) + s0 = torch.as_tensor(1 + rng.random((2, 3, 5))) if fixed else None + t = torch.as_tensor(rng.random((2, 3, 5)) * 3, dtype=DT).requires_grad_() + f, g, c = sf.variance_loss(z, t, w, s0) + var = s0 if fixed else t + 1 + expected = (w * (z - t) ** 2 / var).sum((-2, -1)) + assert torch.allclose(f, expected, rtol=1e-13) + (g_auto,) = torch.autograd.grad(expected.sum(), t, create_graph=True) + assert torch.allclose(g, g_auto, rtol=1e-12) + (c_auto,) = torch.autograd.grad(g_auto.sum(), t) + assert torch.allclose(c, c_auto, rtol=1e-12) + assert sf.variance_loss(z, t, w, s0, 0)[1:] == (None, None) + assert sf.variance_loss(z, t, w, s0, 1)[2] is None + + +@pytest.mark.parametrize("tau", [0.7, 4.8, 30.0]) +@pytest.mark.parametrize("n_t", [5, 40, 400]) +def test_time_kernel_matches_convolution(tau: float, n_t: int) -> None: + """The exponential kernels by shifted additions equal a 'same' convolution. + + This holds for trials shorter and longer than the kernel. + """ + rng = np.random.default_rng(1) + k = temporal_kernel(tau) + kern = sf.TimeKernel(torch.as_tensor(k)) + assert kern.decay == pytest.approx(np.exp(-1 / tau), rel=1e-9) + x = rng.standard_normal((2, 3, n_t)) + y = kern.conv(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-13) + ya = kern.conv_adj(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-13) + + +def test_time_kernel_general() -> None: + """Kernels that are not causal exponentials go through conv1d.""" + rng = np.random.default_rng(2) + x = rng.standard_normal((1, 2, 30)) + for k in ( + np.concatenate([np.zeros(4), [0.5, 0.3, 0.1, 0.07, 0.03]]), + np.array([0.2, 0.5, 0.3]), + np.array([0.0, 0.0, 0.0, 1.0, 0.5, 0.0, 0.25]), + ): + kern = sf.TimeKernel(torch.as_tensor(k)) + assert kern.decay is None + y = kern.conv(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(y, _conv_same(x, k), atol=1e-14) + ya = kern.conv_adj(torch.as_tensor(x)).numpy() + np.testing.assert_allclose(ya, _conv_same(x, k[::-1]), atol=1e-14) + with pytest.raises(ValueError, match="odd"): + sf.TimeKernel(torch.ones(4)) + + +def _check_derivatives(problem: sf.ActivityProblem | sf.FootprintProblem, x: torch.Tensor) -> None: + """Gradient, Hessian products and diagonal against autograd.""" + x = x.clone().requires_grad_() + f = problem.value(x) + (g_auto,) = torch.autograd.grad(f.sum(), x, create_graph=True) + f2, g = problem.value_grad(x.detach()) + assert torch.allclose(f2, f.detach(), rtol=1e-13) + assert torch.allclose(g, g_auto.detach(), rtol=1e-9, atol=1e-10) + rng = np.random.default_rng(5) + v = torch.as_tensor(rng.standard_normal(x.shape)) + (hv_auto,) = torch.autograd.grad((g_auto * v).sum(), x, retain_graph=True) + hv = problem.hess_mult(v) + assert torch.allclose(hv, hv_auto, rtol=1e-9, atol=1e-9) + diag = torch.zeros_like(x) + flat = diag.view(-1) + for i in range(flat.numel()): + e = torch.zeros(flat.numel(), dtype=DT) + e[i] = 1 + flat[i] = problem.hess_mult(e.view(x.shape)).view(-1)[i] + assert torch.allclose(problem.hess_diag(), diag, rtol=1e-9, atol=1e-12) + + +@pytest.mark.parametrize("fixed", [False, True]) +def test_activity_problem_derivatives(fixed: bool) -> None: + """The activity fit's gradient and curvature, with either variance.""" + z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) + s0 = (h @ sf.TimeKernel(k).conv(s) + b + 1) if fixed else None + problem = sf.ActivityProblem(z, h, b, k, w, 0.9, s0) + _check_derivatives(problem, s * 0.5 + 1) + + +def test_footprint_problem_derivatives() -> None: + """The footprint fit's gradient and curvature.""" + z, h, b, w, s, k = _small_problem(n_px=6, n_t=14) + rng = np.random.default_rng(6) + g = torch.as_tensor(rng.random((1, 6, 6)) * (rng.random((1, 6, 6)) < 0.6)) + x = sf.TimeKernel(k).conv(s) + support = torch.ones((1, 6, 2), dtype=torch.bool) + problem = sf.FootprintProblem(z, x, b, g, w, support) + _check_derivatives(problem, h.clone()) + + +def test_preconditioner_inverts_one_source() -> None: + """For one source the preconditioner is the inverse of the Hessian on the free events. + + Up to the kernel's truncation. + """ + z, h, b, w, s, k = _small_problem(n_px=8, n_src=1, n_t=200) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + problem.value_grad(s) + rng = np.random.default_rng(7) + free = torch.as_tensor(rng.random(s.shape) < 0.4) + free[..., 50:80] = True # a run of consecutive free events + fm = free.to(DT) + v = torch.as_tensor(rng.standard_normal(s.shape)) * fm + hv = fm * problem.hess_mult(v) + back = problem.preconditioner(free, problem.hess_diag())(hv) + assert float((back - v).norm() / v.norm()) < 0.02 + # the Hessian's diagonal alone is far from it + jacobi = fm / problem.hess_diag() * hv + assert float((jacobi - v).norm() / v.norm()) > 0.3 + + +def test_preconditioner_falls_back_to_diagonal() -> None: + """Kernels that are not exponential get the Hessian's diagonal.""" + z, h, b, w, s, _ = _small_problem(n_px=6, n_t=20) + k = torch.as_tensor([0.0, 0.0, 0.6, 0.1, 0.3], dtype=DT) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + problem.value_grad(s) + free = torch.ones_like(s, dtype=torch.bool) + r = torch.ones_like(s) + diag = problem.hess_diag() + assert torch.equal(problem.preconditioner(free, diag)(r), r / diag) + + +def test_activity_fit_reaches_scipy_optimum() -> None: + """The fit ends at the optimum that L-BFGS-B approaches. + + Many events are on their bound. + """ + z, h, b, w, s_true, k = _small_problem(seed=3, n_px=20, n_t=120) + start = torch.full_like(s_true, 5.0) + s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, history=True) + assert bool(info.converged[0]) and int(info.iterations[0]) < 30 + assert float(info.optimality[0]) < 1e-5 + assert float((s == 0).double().mean()) > 0.4 and float(s.min()) == 0 + losses = [float(f[0]) for f in info.history] + assert all(b2 <= a2 for a2, b2 in itertools.pairwise(losses)) + + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + + def fun(x: np.ndarray) -> tuple[float, np.ndarray]: + """Loss and gradient for scipy. + + Returns + ------- + loss : float + The activity loss at x. + grad : np.ndarray + The flattened gradient of the loss at x. + """ + f, g = problem.value_grad(torch.as_tensor(x).view(s.shape)) + return float(f[0]), g.numpy().ravel() + + ref = optimize.minimize( + fun, + start.numpy().ravel(), + jac=True, + method="L-BFGS-B", + bounds=[(0, None)] * s.numel(), + options={"maxiter": 20000, "maxfun": 50000, "ftol": 1e-15, "gtol": 1e-9}, + ) + assert float(info.loss[0]) <= ref.fun + 1e-9 * abs(ref.fun) + np.testing.assert_allclose(s.numpy().ravel(), ref.x, atol=2e-2) + # the sparse events are recovered + found = _conv_same(s.numpy(), k.numpy()) + truth = _conv_same(s_true.numpy(), k.numpy()) + assert np.corrcoef(found.ravel(), truth.ravel())[0, 1] > 0.7 + + +def test_fit_does_not_depend_on_its_start() -> None: + """A convex fit has one optimum: two starts end at the same events.""" + z, h, b, w, s_true, k = _small_problem(seed=4, n_px=16, n_t=80) + a, _ = sf.fit_activity(z, h, b, k, w, 0.9, torch.zeros_like(s_true)) + c, _ = sf.fit_activity(z, h, b, k, w, 0.9, s_true * 3 + 10) + assert torch.allclose(a, c, atol=1e-4) + + +def test_batched_fit_equals_separate_fits() -> None: + """Members of a batch get the fits they get alone. + + They are padded with weightless pixels and a source held at zero. + """ + z, h, b, w, s_true, k = _small_problem(seed=5, n_px=12, n_t=70, batch=2) + # member 1: 9 pixels and one source; the rest is padding + w[1, 9:] = 0 + z[1, 9:] = 0 + b[1, 9:] = 1 + h[1, :, 1] = 0 + h[1, 9:] = 0 + free = torch.ones_like(s_true, dtype=torch.bool) + free[1, 1] = False + start = torch.full_like(s_true, 2.0) + s, info = sf.fit_activity(z, h, b, k, w, 0.9, start, free=free) + assert bool(info.converged.all()) + assert torch.all(s[1, 1] == 0) + one, i0 = sf.fit_activity(z[:1], h[:1], b[:1], k, w[:1], 0.9, start[:1], free=free[:1]) + two, i1 = sf.fit_activity(z[1:, :9], h[1:, :9, :1], b[1:, :9], k, w[1:, :9], 0.9, start[1:, :1]) + assert torch.allclose(s[0], one[0], atol=1e-5) + assert torch.allclose(s[1, :1], two[0], atol=1e-5) + assert float(info.loss[0]) == pytest.approx(float(i0.loss[0]), rel=1e-10) + assert float(info.loss[1]) == pytest.approx(float(i1.loss[0]), rel=1e-10) + + +def test_iteration_cap_and_free_entries() -> None: + """A capped fit reports that it did not converge and still lowers the loss. + + Entries that are not free stay at zero. + """ + z, h, b, w, s_true, k = _small_problem(seed=6, n_px=16, n_t=80) + start = torch.full_like(s_true, 5.0) + problem = sf.ActivityProblem(z, h, b, k, w, 0.9) + _s1, info = sf.fit_activity(z, h, b, k, w, 0.9, start, max_iter=1) + assert not bool(info.converged[0]) and int(info.iterations[0]) == 1 + assert float(info.loss[0]) < float(problem.value(start)[0]) + _full, done = sf.fit_activity(z, h, b, k, w, 0.9, start) + assert float(done.loss[0]) < float(info.loss[0]) + free = s_true > 0 + s2, info2 = sf.fit_activity(z, h, b, k, w, 0.0, start, free=free) + assert bool(info2.converged[0]) + assert torch.all(s2[~free] == 0) and float(s2[free].min()) >= 0 + + +def test_fixed_variance_fit_is_weighted_least_squares() -> None: + """With the variance held, the fit of the free events is weighted least squares. + + It is the bounded weighted least-squares solution. + """ + z, h, b, w, s_true, k = _small_problem(seed=7, n_px=10, n_src=1, n_t=40) + kern = sf.TimeKernel(k) + s0 = h @ kern.conv(s_true) + b + 1 + free = torch.zeros_like(s_true, dtype=torch.bool) + free[..., ::4] = True + s, info = sf.fit_activity(z, h, b, k, w, 0.0, s_true, s0=s0, free=free, ftol=1e-15) + assert bool(info.converged[0]) + idx = np.nonzero(free.numpy().ravel())[0] + cols = [] + for i in idx: + e = torch.zeros_like(s_true) + e.view(-1)[i] = 1 + cols.append((h @ kern.conv(e)).numpy().ravel()) + sw = np.sqrt((w / s0).numpy().ravel()) + design = np.stack(cols, 1) * sw[:, None] + target = (z - b).numpy().ravel() * sw + ref = optimize.lsq_linear(design, target, bounds=(0, np.inf)).x + np.testing.assert_allclose(s.numpy().ravel()[idx], ref, atol=1e-5) + + +def test_footprint_fit_stays_on_its_support() -> None: + """Footprints are fitted within their support, not below zero. + + They reach a lower loss than the start. + """ + z, _h, b, w, s, k = _small_problem(seed=8, n_px=12, n_t=90) + x = sf.TimeKernel(k).conv(s) + g = torch.eye(12, dtype=DT)[None] * 0.6 + 0.4 / 12 + valid = torch.zeros((1, 12, 2), dtype=torch.bool) + valid[0, :6, 0] = True + valid[0, 5:, 1] = True + start = valid.to(DT) / 6 + hs, info = sf.fit_footprints(z, x, b, g, w, start, valid) + assert bool(info.converged[0]) + assert torch.all(hs[~valid] == 0) and float(hs.min()) >= 0 + problem = sf.FootprintProblem(z, x, b, g, w, valid) + assert float(info.loss[0]) < float(problem.value(start)[0]) + assert torch.allclose(problem.footprints(hs), g @ hs) + + +@pytest.fixture(scope="module") +def matlab() -> dict[str, Any]: + """MATLAB's fits of a real two-source subproblem, and its inputs. + + Returns + ------- + dict[str, Any] + MATLAB's stored groups (in, init, it1, it2, debias, ch2, out) + plus the tensors z, z2, w, b0, b1, b2, g, k and k2. + """ + with h5py.File(SUBPROBLEM, "r") as f: + d = { + g: {k: v[()] for k, v in f[g].items()} + for g in ("in", "init", "it1", "it2", "debias", "ch2", "out") + } + y = d["in"]["y"].astype(np.float64) + finv = d["in"]["finv"].astype(np.float64) + sel = d["in"]["sel"].astype(bool) + b0 = sb.initial_baseline(y[0], PARAMS) + b1 = sb.fit_baseline(b0, y[0], d["it1"]["X_thr"], d["init"]["H"], finv, sel, PARAMS) + d.update( + z=_t(y[0]), + z2=_t(y[1]), + w=_t(1 / finv), + b0=_t(b0), + b1=_t(b1), + b2=_t(sb.initial_baseline(y[1], PARAMS)), + g=_t(conv_operator(sel, PARAMS.hfilter).toarray()), + k=torch.as_tensor(PARAMS.k), + k2=torch.as_tensor(PARAMS.k2), + ) + return d + + +def test_loss_is_matlabs(matlab: dict[str, Any]) -> None: + """MATLAB's reported losses are this loss at MATLAB's solutions.""" + m = matlab + lam = PARAMS.lam + p1 = sf.ActivityProblem(m["z"], _t(m["init"]["H"]), m["b0"], m["k"], m["w"], lam) + assert float(p1.value(_t(m["it1"]["S_out"]))[0]) == pytest.approx(m["it1"]["loss_S"], rel=1e-10) + valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] + ph = sf.FootprintProblem(m["z"], _t(m["it1"]["X_thr"]), m["b1"], m["g"], m["w"], valid) + # the baseline differs from MATLAB's by quadprog's tolerance + assert float(ph.value(_t(m["it1"]["Hs_out"]))[0]) == pytest.approx(m["it1"]["loss_H"], rel=1e-6) + p2 = sf.ActivityProblem(m["z"], _t(m["it1"]["H"]), m["b1"], m["k"], m["w"], lam) + assert float(p2.value(_t(m["it2"]["S_out"]))[0]) == pytest.approx(m["it2"]["loss_S"], rel=1e-6) + pc = sf.ActivityProblem(m["z2"], _t(m["out"]["H"]), m["b2"], m["k2"], m["w"], lam) + assert float(pc.value(_t(m["ch2"]["S_l1"]))[0]) == pytest.approx(m["ch2"]["loss"], rel=1e-10) + + +def test_fits_reach_matlabs_loss_or_lower(matlab: dict[str, Any]) -> None: + """Each fit, started from MATLAB's inputs, ends at a loss no higher than MATLAB's. + + MATLAB's fits stop at iteration caps or tolerances. + """ + m = matlab + lam = PARAMS.lam + s, info = sf.fit_activity( + m["z"], + _t(m["init"]["H"]), + m["b0"], + m["k"], + m["w"], + lam, + _t(m["init"]["S"]), + ) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it1"]["loss_S"] + + valid = torch.as_tensor(m["init"]["Hvalid"].astype(bool))[None] + x_thr = _t(m["it1"]["X_thr"]) + _hs, info = sf.fit_footprints( + m["z"], x_thr, m["b1"], m["g"], m["w"], _t(m["init"]["Hs"]), valid + ) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it1"]["loss_H"] * (1 - 1e-5) + + h1 = _t(m["it1"]["H"]) + s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], lam, _t(m["it1"]["S"])) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["it2"]["loss_S"] * (1 + 1e-6) + + # debias: MATLAB's refit of its own events, variance held at the start + free = torch.as_tensor(m["debias"]["free"].astype(bool))[None] + start = _t(m["debias"]["S_in"]) + s0 = h1 @ sf.TimeKernel(m["k"]).conv(start) + m["b1"] + 1 + problem = sf.ActivityProblem(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, s0) + f_matlab = float(problem.value(_t(m["debias"]["S_out"]))[0]) + s, info = sf.fit_activity(m["z"], h1, m["b1"], m["k"], m["w"], 0.0, start, s0=s0, free=free) + assert bool(info.converged[0]) + assert float(info.loss[0]) <= f_matlab * (1 + 1e-9) + # MATLAB's refit stops near this optimum: the activity agrees + kern = sf.TimeKernel(m["k"]) + x, x_matlab = kern.conv(s), kern.conv(_t(m["debias"]["S_out"])) + assert float((x - x_matlab).norm() / x_matlab.norm()) < 0.02 + + _s2, info = sf.fit_activity( + m["z2"], + _t(m["out"]["H"]), + m["b2"], + m["k2"], + m["w"], + lam, + _t(m["ch2"]["LS"]), + ) + assert bool(info.converged[0]) + assert float(info.loss[0]) < m["ch2"]["loss"] diff --git a/tests/raster/test_raster_solver_setup.py b/tests/raster/test_raster_solver_setup.py index 82305ef7..96d48c04 100644 --- a/tests/raster/test_raster_solver_setup.py +++ b/tests/raster/test_raster_solver_setup.py @@ -1,395 +1,395 @@ -"""Tests of the subproblem solver's parameters, filters and inputs.""" - -import warnings -from pathlib import Path - -import h5py -import numpy as np -import numpy.typing as npt -import pytest -from scipy import signal - -from giant_python.extraction.raster.solver_setup import ( - SolverParams, - Subproblem, - conv_operator, - initial_footprints, - load_matlab_subproblem, - params_from_matlab, - sel_coords, - temporal_kernel, -) - -DATA = Path(__file__).parent / "data" -HELPERS = DATA / "matlab_solver_helpers.h5" -SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" - -# the two parameter sets of the MATLAB references (make_helper_refs.m) -PARAMS_A = SolverParams( - sigma_px=1.6, - sel_radius=4, - tau_full=3.7, - tau2_s=0.05, - analyze_hz=150, - baseline_window_s=2, - denoise_window_s=0.1, -) -PARAMS_B = SolverParams() - - -def _close(a: npt.ArrayLike, b: npt.ArrayLike, tol: float = 1e-13) -> None: - """Largest difference relative to the largest reference value.""" - a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) - assert a.shape == b.shape - assert np.abs(a - b).max() <= tol * np.abs(b).max() - - -@pytest.mark.parametrize("name, params", [("a", PARAMS_A), ("b", PARAMS_B)]) -def test_filters_match_matlab(name: str, params: SolverParams) -> None: - """Footprint filter, surround filters and kernels of setParamsExtractTrial.""" - with h5py.File(HELPERS, "r") as f: - g = f["params"][name] - _close(params.hfilter, g["Hfilter"][()]) - # MATLAB stores the three filters along the third dimension - _close(params.bfilter, g["Bfilter"][()].transpose(2, 0, 1)) - _close(params.k, g["k"][()].ravel()) - _close(params.k2, g["k2"][()].ravel()) - if "baselineWindow_samps" in g: - assert params.baseline_window == g["baselineWindow_samps"][()] - assert params.denoise_window == g["denoiseWindow_samps"][()] - - -def test_kernel_and_windows() -> None: - """The kernel is causal, sums to 1 and peaks at its centre. - - The windows follow MATLAB's rounding. - """ - k = temporal_kernel(4.8) - n = int(np.ceil(6 * 4.8)) - assert k.size == 2 * n + 1 - assert np.all(k[:n] == 0) and np.argmax(k) == n - assert k.sum() == pytest.approx(1.0, abs=1e-15) - assert k[n + 1] / k[n] == pytest.approx(np.exp(-1 / 4.8)) - p = SolverParams(analyze_hz=434.7826087, tau_s=0.024) - assert p.tau_frames == pytest.approx(10.4348, abs=1e-4) - assert p.denoise_window == 87 # ceil(86.96) - assert p.baseline_window == pytest.approx(1739.13, abs=1e-2) # not rounded - assert p.lp_factor == 20 - assert SolverParams(tau_full=7.0).tau_frames == 7.0 - - -def test_params_reject_bad_values() -> None: - """Values the solver cannot run with are refused.""" - with pytest.raises(ValueError, match="debias_variance"): - SolverParams(debias_variance="other") - with pytest.raises(ValueError, match="nmf_iter"): - SolverParams(nmf_iter=0) - with pytest.raises(ValueError, match="sigma_px"): - SolverParams(sigma_px=0) - # divisors: a zero would give a NaN kernel or an endless spline - with pytest.raises(ValueError, match="tau_full"): - SolverParams(tau_full=0) - with pytest.raises(ValueError, match="baseline_knot_factor"): - SolverParams(baseline_knot_factor=0) - with pytest.raises(ValueError, match="tau_s"): - SolverParams(tau_s=float("nan")) - with pytest.raises(ValueError, match="photon_scale"): - SolverParams(photon_scale=float("inf")) - with pytest.raises(ValueError, match="lam"): - SolverParams(lam=-0.1) - assert SolverParams(photon_scale=None, lam=0, phi=0).tau_full is None - # the baseline needs at least two denoise windows per baseline window - with pytest.raises(ValueError, match="baseline_window_s"): - SolverParams(baseline_window_s=0.1, denoise_window_s=0.1) - with pytest.raises(ValueError, match="baseline_window_s"): - SolverParams(baseline_window_s=0.2, denoise_window_s=0.196) - assert SolverParams(baseline_window_s=0.3, denoise_window_s=0.2).lp_factor == 2 - - -def test_initial_footprints_match_matlab() -> None: - """Starting footprints, also for sources at the map's edge and next to an unselected pixel.""" - with h5py.File(HELPERS, "r") as f: - g = f["foot"] - sel = g["selPix"][()].astype(bool) - rc = np.stack([g["R"][()].ravel(), g["C"][()].ravel()], 1) - 1 - hs, h, valid = initial_footprints(sel, rc, float(g["sigma"][()])) - assert np.array_equal(hs, g["Hs"][()]) - _close(h, g["H"][()]) - assert np.array_equal(valid, g["Hvalid"][()].astype(bool)) - - -def test_sel_coords_are_column_major() -> None: - """Pixels are listed as MATLAB's find(sel) lists them.""" - sel = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool) - rows, cols = sel_coords(sel) - assert rows.tolist() == [0, 1, 1, 0] - assert cols.tolist() == [0, 0, 1, 2] - - -def test_conv_operator_is_same_convolution() -> None: - """The operator equals a 'same' convolution of the map, zero outside the selected pixels. - - It is read at the selected pixels. - """ - rng = np.random.default_rng(0) - sel = rng.random((9, 11)) < 0.7 - rows, cols = sel_coords(sel) - values = rng.standard_normal(rows.size) - for shape in ((5, 5), (3, 7), (4, 5)): - filt = rng.standard_normal(shape) - filt[0, 0] = 0 # a zero tap is left out of the sparse matrix - image = np.zeros(sel.shape) - image[rows, cols] = values - # MATLAB's convn 'same': the centre is floor(size / 2) - full = signal.convolve2d(image, filt, mode="full") - r0, c0 = shape[0] // 2, shape[1] // 2 - same = full[r0 : r0 + sel.shape[0], c0 : c0 + sel.shape[1]] - got = conv_operator(sel, filt) @ values - np.testing.assert_allclose(got, same[rows, cols], atol=1e-13) - - -def test_subproblem_checks_its_arrays() -> None: - """A subproblem whose arrays do not fit together is refused.""" - sel = np.ones((3, 3), dtype=bool) - y = np.zeros((1, 9, 20), np.float32) - finv = np.ones((9, 20), np.float32) - sub = Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1]]) - assert (sub.n_pixels, sub.n_frames, sub.n_sources) == (9, 20, 1) - assert sub.coords[0].tolist() == [0, 1, 2] * 3 - with pytest.raises(ValueError, match="pixels"): - Subproblem(y=y[:, :8], finv=finv, sel=sel, sources_rc=[[1, 1]]) - with pytest.raises(ValueError, match="outside"): - Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 3]]) - with pytest.raises(ValueError, match="channels"): - Subproblem(y=y[0], finv=finv, sel=sel, sources_rc=[[1, 1]]) - with pytest.raises(ValueError, match="share a position"): - Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1], [1, 1]]) - - -def _write_matlab_params(g: h5py.Group, params: SolverParams, **extra: np.ndarray) -> None: - """Write a MATLAB params struct as a v7.3 file holds it.""" - fields = { - "analyzeHz": params.analyze_hz, - "tau_s": params.tau_s, - "tau_full": params.tau_frames, - "tau2_s": params.tau2_s, - "sigma_px": params.sigma_px, - "selRadius": params.sel_radius, - "baselineWindow_Glu_s": params.baseline_window_s, - "denoiseWindow_s": params.denoise_window_s, - "minBaseline": params.min_baseline, - "nmfIter": params.nmf_iter, - "phi": params.phi, - } - fields["lambda"] = params.lam - for name, v in fields.items(): - g.create_dataset(name, data=np.array([[float(v)]])) - g.create_dataset("k", data=params.k[None, :]) - g.create_dataset("Hfilter", data=params.hfilter.T) - # MATLAB's (rows, cols, 3) array, dimensions reversed in the file - g.create_dataset("Bfilter", data=params.bfilter.transpose(0, 2, 1)) - for name, v in extra.items(): - g.create_dataset(name, data=v) - - -def _write_matlab_subproblem( - folder: Path, - y: np.ndarray, - finv: np.ndarray, - sel: np.ndarray, - rc: np.ndarray, - params: SolverParams, - row0: int, - col0: int, -) -> Path: - """sub_001.mat and trial.mat as extractTrial saves them (v7.3). - - Returns - ------- - Path - The sub_001.mat file written in folder. - """ - full = np.zeros((sel.shape[0] + row0 + 2, sel.shape[1] + col0 + 1), bool) - full[0, 0] = full[1, 0] = True # two pixels of another subproblem - full[row0 : row0 + sel.shape[0], col0 : col0 + sel.shape[1]] = sel - with h5py.File(folder / "trial.mat", "w") as f: - f.create_dataset("selPix", data=full.T.astype(np.uint8)) - with h5py.File(folder / "sub_001.mat", "w") as f: - # MATLAB's pixels x frames x channels, dimensions reversed - f.create_dataset("Y_p", data=y.transpose(0, 2, 1)) - f.create_dataset("F_inv_p", data=finv.T) - f.create_dataset("selPix_p", data=sel.T.astype(np.uint8)) - g = f.create_group("sources_p") - g.create_dataset("R", data=rc[None, :, 0] + 1.0) - g.create_dataset("C", data=rc[None, :, 1] + 1.0) - f.create_dataset("rowSupport", data=np.array([[row0 + 1.0, 0]]).T) - f.create_dataset("colSupport", data=np.array([[col0 + 1.0, 0]]).T) - f.create_dataset("srcIdx", data=np.array([[4.0, 9.0]])) - debias = np.array([[ord(c)] for c in "Model"], dtype=np.uint16) - empty = f.create_group("params").create_dataset("photonScale", data=np.zeros(2, np.uint64)) - empty.attrs["MATLAB_empty"] = 1 - _write_matlab_params(f["params"], params, debiasVariance=debias) - return folder / "sub_001.mat" - - -def test_load_matlab_subproblem(tmp_path: Path) -> None: - """A saved subproblem is read in the port's convention. - - Channels x pixels x frames, zero-based sources, pixel indices in the - trial's list, and its parameters. - """ - rng = np.random.default_rng(1) - sel = np.ones((4, 5), dtype=bool) - sel[0, 0] = sel[3, 4] = False - n_px = int(sel.sum()) - y = rng.random((2, n_px, 30)) - finv = 0.5 + rng.random((n_px, 30)) - rc = np.array([[1, 1], [2, 3]]) - params = SolverParams(sigma_px=1.6, sel_radius=4, tau_s=0.03, lam=0.7) - path = _write_matlab_subproblem(tmp_path, y, finv, sel, rc, params, 3, 2) - with warnings.catch_warnings(): - warnings.simplefilter("error") - sub, p = load_matlab_subproblem(path) - assert sub.y.dtype == np.float64 - assert np.array_equal(sub.y, y) and np.array_equal(sub.finv, finv) - assert np.array_equal(sub.sel, sel) - assert np.array_equal(sub.sources_rc, rc) - assert (sub.row0, sub.col0) == (3, 2) - assert sub.sources.tolist() == [3, 8] - # the trial's map has two selected pixels before this crop's - assert np.array_equal(sub.pixels, 2 + np.arange(n_px)) - assert p.photon_scale is None and p.debias_variance == "model" - # not a MATLAB parameter: the default, unless the struct names it - assert p.footprint_variance == "fixed" - with h5py.File(path, "r+") as f: - f["params"].create_dataset( - "footprintVariance", - data=np.array([[ord(c)] for c in "Model"], dtype=np.uint16), - ) - assert load_matlab_subproblem(path)[1].footprint_variance == "model" - assert (p.sigma_px, p.sel_radius, p.lam) == (1.6, 4, 0.7) - assert p.tau_frames == pytest.approx(0.03 * 200) - assert load_matlab_subproblem(path, np.float32)[0].y.dtype == np.float32 - - -def test_trial_file_of_another_trial_is_refused(tmp_path: Path) -> None: - """A trial.mat that does not select every pixel of the subproblem is refused. - - It cannot give the subproblem's pixel indices. - """ - sel = np.ones((3, 3), dtype=bool) - path = _write_matlab_subproblem( - tmp_path, - np.zeros((1, 9, 5)), - np.ones((9, 5)), - sel, - np.array([[1, 1]]), - SolverParams(), - 2, - 1, - ) - with h5py.File(tmp_path / "trial.mat", "r+") as f: - full = f["selPix"][()] - full[2, 3] = 0 # one of the crop's pixels, in MATLAB's file order - f["selPix"][...] = full - with pytest.raises(ValueError, match="not from the same trial"): - load_matlab_subproblem(path) - with h5py.File(tmp_path / "trial.mat", "w") as f: - f.create_dataset("selPix", data=np.ones((2, 2), np.uint8)) - with pytest.raises(ValueError, match="not from the same trial"): - load_matlab_subproblem(path) - - -def test_single_channel_subproblem_without_trial_file(tmp_path: Path) -> None: - """One channel is saved as a 2-D array. - - Without trial.mat the pixel indices are unknown. - """ - sel = np.ones((2, 3), dtype=bool) - y = np.arange(6 * 7, dtype=np.float64).reshape(1, 6, 7) - path = _write_matlab_subproblem( - tmp_path, - y, - np.ones((6, 7)), - sel, - np.array([[0, 1]]), - SolverParams(), - 0, - 0, - ) - (tmp_path / "trial.mat").unlink() - with h5py.File(path, "r+") as f: - del f["Y_p"] - f.create_dataset("Y_p", data=y[0].T) - sub, _ = load_matlab_subproblem(path) - assert sub.y.shape == (1, 6, 7) and np.array_equal(sub.y, y) - assert sub.pixels is None - - -def test_params_warn_when_saved_filters_differ(tmp_path: Path) -> None: - """A saved kernel that the scalar parameters do not give is reported.""" - with h5py.File(tmp_path / "p.mat", "w") as f: - g = f.create_group("params") - _write_matlab_params(g, SolverParams()) - g["k"][...] = g["k"][()] * 1.01 - with pytest.warns(UserWarning, match="params.k differs"): - p = params_from_matlab(g) - # a struct without validKernel is MATLAB's 3 x 3 (not the default 5) - assert p == SolverParams(tau_full=4.8, photon_scale=None, valid_kernel=3) - - -def test_subproblem_fixture_starts_as_matlab() -> None: - """The fixture's starting footprints are MATLAB's.""" - with h5py.File(SUBPROBLEM, "r") as f: - sel = f["in/sel"][()].astype(bool) - hs, h, valid = initial_footprints(sel, f["in/sources_rc"][()], PARAMS_B.sigma_px) - assert np.array_equal(hs, f["init/Hs"][()]) - _close(h, f["init/H"][()]) - assert np.array_equal(valid, f["init/Hvalid"][()].astype(bool)) - - -def test_valid_kernel_widens_the_support_only() -> None: - """A larger validKernel widens where Hs may go, nothing else. - - A source at the crop's edge gets the part of the square inside it. - """ - sel = np.ones((15, 15), dtype=bool) - rc = np.array([[7, 7], [0, 1]]) - hs3, h3, v3 = initial_footprints(sel, rc, 1.33) - hs5, h5, v5 = initial_footprints(sel, rc, 1.33, valid_kernel=5) - assert np.array_equal(hs3, hs5) - assert np.array_equal(h3, h5) - assert v3.sum(0).tolist() == [9, 6] - assert v5.sum(0).tolist() == [25, 12] - assert (v3 <= v5).all() - rows, cols = sel_coords(sel) - inside = (np.abs(rows - 7) <= 2) & (np.abs(cols - 7) <= 2) - assert np.array_equal(v5[:, 0], inside) - - -@pytest.mark.parametrize("bad", [0, 2, 4, -3, 3.0, True]) -def test_valid_kernel_must_be_odd_and_positive(bad: float) -> None: - """An even, non-positive or non-integer side is rejected.""" - with pytest.raises(ValueError, match="valid_kernel"): - SolverParams(valid_kernel=bad) - - -def test_valid_kernel_from_matlab() -> None: - """params_from_matlab reads validKernel's side; 3 without one.""" - with h5py.File("vk.h5", "w", driver="core", backing_store=False) as f: - assert params_from_matlab(f.create_group("none")).valid_kernel == 3 - f.create_group("five")["validKernel"] = np.ones((5, 5), np.uint8) - assert params_from_matlab(f["five"]).valid_kernel == 5 - f.create_group("odd")["validKernel"] = np.ones((3, 2), np.uint8) - with pytest.raises(ValueError, match="validKernel"): - params_from_matlab(f["odd"]) - # entries other than 1 are rejected, not read as a full support - for name, value in (("twos", 2.0), ("minus", -1.0), ("nan", np.nan)): - f.create_group(name)["validKernel"] = np.full((5, 5), value) - with pytest.raises(ValueError, match="square of ones"): - params_from_matlab(f[name]) - f.create_group("plus")["validKernel"] = np.array( - [[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8 - ) - with pytest.raises(ValueError, match="5 ones"): - params_from_matlab(f["plus"]) +"""Tests of the subproblem solver's parameters, filters and inputs.""" + +import warnings +from pathlib import Path + +import h5py +import numpy as np +import numpy.typing as npt +import pytest +from scipy import signal + +from giant_python.extraction.raster.solver_setup import ( + SolverParams, + Subproblem, + conv_operator, + initial_footprints, + load_matlab_subproblem, + params_from_matlab, + sel_coords, + temporal_kernel, +) + +DATA = Path(__file__).parent / "data" +HELPERS = DATA / "matlab_solver_helpers.h5" +SUBPROBLEM = DATA / "matlab_solver_subproblem.h5" + +# the two parameter sets of the MATLAB references (make_helper_refs.m) +PARAMS_A = SolverParams( + sigma_px=1.6, + sel_radius=4, + tau_full=3.7, + tau2_s=0.05, + analyze_hz=150, + baseline_window_s=2, + denoise_window_s=0.1, +) +PARAMS_B = SolverParams() + + +def _close(a: npt.ArrayLike, b: npt.ArrayLike, tol: float = 1e-13) -> None: + """Largest difference relative to the largest reference value.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + assert a.shape == b.shape + assert np.abs(a - b).max() <= tol * np.abs(b).max() + + +@pytest.mark.parametrize("name, params", [("a", PARAMS_A), ("b", PARAMS_B)]) +def test_filters_match_matlab(name: str, params: SolverParams) -> None: + """Footprint filter, surround filters and kernels of setParamsExtractTrial.""" + with h5py.File(HELPERS, "r") as f: + g = f["params"][name] + _close(params.hfilter, g["Hfilter"][()]) + # MATLAB stores the three filters along the third dimension + _close(params.bfilter, g["Bfilter"][()].transpose(2, 0, 1)) + _close(params.k, g["k"][()].ravel()) + _close(params.k2, g["k2"][()].ravel()) + if "baselineWindow_samps" in g: + assert params.baseline_window == g["baselineWindow_samps"][()] + assert params.denoise_window == g["denoiseWindow_samps"][()] + + +def test_kernel_and_windows() -> None: + """The kernel is causal, sums to 1 and peaks at its centre. + + The windows follow MATLAB's rounding. + """ + k = temporal_kernel(4.8) + n = int(np.ceil(6 * 4.8)) + assert k.size == 2 * n + 1 + assert np.all(k[:n] == 0) and np.argmax(k) == n + assert k.sum() == pytest.approx(1.0, abs=1e-15) + assert k[n + 1] / k[n] == pytest.approx(np.exp(-1 / 4.8)) + p = SolverParams(analyze_hz=434.7826087, tau_s=0.024) + assert p.tau_frames == pytest.approx(10.4348, abs=1e-4) + assert p.denoise_window == 87 # ceil(86.96) + assert p.baseline_window == pytest.approx(1739.13, abs=1e-2) # not rounded + assert p.lp_factor == 20 + assert SolverParams(tau_full=7.0).tau_frames == 7.0 + + +def test_params_reject_bad_values() -> None: + """Values the solver cannot run with are refused.""" + with pytest.raises(ValueError, match="debias_variance"): + SolverParams(debias_variance="other") + with pytest.raises(ValueError, match="nmf_iter"): + SolverParams(nmf_iter=0) + with pytest.raises(ValueError, match="sigma_px"): + SolverParams(sigma_px=0) + # divisors: a zero would give a NaN kernel or an endless spline + with pytest.raises(ValueError, match="tau_full"): + SolverParams(tau_full=0) + with pytest.raises(ValueError, match="baseline_knot_factor"): + SolverParams(baseline_knot_factor=0) + with pytest.raises(ValueError, match="tau_s"): + SolverParams(tau_s=float("nan")) + with pytest.raises(ValueError, match="photon_scale"): + SolverParams(photon_scale=float("inf")) + with pytest.raises(ValueError, match="lam"): + SolverParams(lam=-0.1) + assert SolverParams(photon_scale=None, lam=0, phi=0).tau_full is None + # the baseline needs at least two denoise windows per baseline window + with pytest.raises(ValueError, match="baseline_window_s"): + SolverParams(baseline_window_s=0.1, denoise_window_s=0.1) + with pytest.raises(ValueError, match="baseline_window_s"): + SolverParams(baseline_window_s=0.2, denoise_window_s=0.196) + assert SolverParams(baseline_window_s=0.3, denoise_window_s=0.2).lp_factor == 2 + + +def test_initial_footprints_match_matlab() -> None: + """Starting footprints, also for sources at the map's edge and next to an unselected pixel.""" + with h5py.File(HELPERS, "r") as f: + g = f["foot"] + sel = g["selPix"][()].astype(bool) + rc = np.stack([g["R"][()].ravel(), g["C"][()].ravel()], 1) - 1 + hs, h, valid = initial_footprints(sel, rc, float(g["sigma"][()])) + assert np.array_equal(hs, g["Hs"][()]) + _close(h, g["H"][()]) + assert np.array_equal(valid, g["Hvalid"][()].astype(bool)) + + +def test_sel_coords_are_column_major() -> None: + """Pixels are listed as MATLAB's find(sel) lists them.""" + sel = np.array([[1, 0, 1], [1, 1, 0]], dtype=bool) + rows, cols = sel_coords(sel) + assert rows.tolist() == [0, 1, 1, 0] + assert cols.tolist() == [0, 0, 1, 2] + + +def test_conv_operator_is_same_convolution() -> None: + """The operator equals a 'same' convolution of the map, zero outside the selected pixels. + + It is read at the selected pixels. + """ + rng = np.random.default_rng(0) + sel = rng.random((9, 11)) < 0.7 + rows, cols = sel_coords(sel) + values = rng.standard_normal(rows.size) + for shape in ((5, 5), (3, 7), (4, 5)): + filt = rng.standard_normal(shape) + filt[0, 0] = 0 # a zero tap is left out of the sparse matrix + image = np.zeros(sel.shape) + image[rows, cols] = values + # MATLAB's convn 'same': the centre is floor(size / 2) + full = signal.convolve2d(image, filt, mode="full") + r0, c0 = shape[0] // 2, shape[1] // 2 + same = full[r0 : r0 + sel.shape[0], c0 : c0 + sel.shape[1]] + got = conv_operator(sel, filt) @ values + np.testing.assert_allclose(got, same[rows, cols], atol=1e-13) + + +def test_subproblem_checks_its_arrays() -> None: + """A subproblem whose arrays do not fit together is refused.""" + sel = np.ones((3, 3), dtype=bool) + y = np.zeros((1, 9, 20), np.float32) + finv = np.ones((9, 20), np.float32) + sub = Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1]]) + assert (sub.n_pixels, sub.n_frames, sub.n_sources) == (9, 20, 1) + assert sub.coords[0].tolist() == [0, 1, 2] * 3 + with pytest.raises(ValueError, match="pixels"): + Subproblem(y=y[:, :8], finv=finv, sel=sel, sources_rc=[[1, 1]]) + with pytest.raises(ValueError, match="outside"): + Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 3]]) + with pytest.raises(ValueError, match="channels"): + Subproblem(y=y[0], finv=finv, sel=sel, sources_rc=[[1, 1]]) + with pytest.raises(ValueError, match="share a position"): + Subproblem(y=y, finv=finv, sel=sel, sources_rc=[[1, 1], [1, 1]]) + + +def _write_matlab_params(g: h5py.Group, params: SolverParams, **extra: np.ndarray) -> None: + """Write a MATLAB params struct as a v7.3 file holds it.""" + fields = { + "analyzeHz": params.analyze_hz, + "tau_s": params.tau_s, + "tau_full": params.tau_frames, + "tau2_s": params.tau2_s, + "sigma_px": params.sigma_px, + "selRadius": params.sel_radius, + "baselineWindow_Glu_s": params.baseline_window_s, + "denoiseWindow_s": params.denoise_window_s, + "minBaseline": params.min_baseline, + "nmfIter": params.nmf_iter, + "phi": params.phi, + } + fields["lambda"] = params.lam + for name, v in fields.items(): + g.create_dataset(name, data=np.array([[float(v)]])) + g.create_dataset("k", data=params.k[None, :]) + g.create_dataset("Hfilter", data=params.hfilter.T) + # MATLAB's (rows, cols, 3) array, dimensions reversed in the file + g.create_dataset("Bfilter", data=params.bfilter.transpose(0, 2, 1)) + for name, v in extra.items(): + g.create_dataset(name, data=v) + + +def _write_matlab_subproblem( + folder: Path, + y: np.ndarray, + finv: np.ndarray, + sel: np.ndarray, + rc: np.ndarray, + params: SolverParams, + row0: int, + col0: int, +) -> Path: + """sub_001.mat and trial.mat as extractTrial saves them (v7.3). + + Returns + ------- + Path + The sub_001.mat file written in folder. + """ + full = np.zeros((sel.shape[0] + row0 + 2, sel.shape[1] + col0 + 1), bool) + full[0, 0] = full[1, 0] = True # two pixels of another subproblem + full[row0 : row0 + sel.shape[0], col0 : col0 + sel.shape[1]] = sel + with h5py.File(folder / "trial.mat", "w") as f: + f.create_dataset("selPix", data=full.T.astype(np.uint8)) + with h5py.File(folder / "sub_001.mat", "w") as f: + # MATLAB's pixels x frames x channels, dimensions reversed + f.create_dataset("Y_p", data=y.transpose(0, 2, 1)) + f.create_dataset("F_inv_p", data=finv.T) + f.create_dataset("selPix_p", data=sel.T.astype(np.uint8)) + g = f.create_group("sources_p") + g.create_dataset("R", data=rc[None, :, 0] + 1.0) + g.create_dataset("C", data=rc[None, :, 1] + 1.0) + f.create_dataset("rowSupport", data=np.array([[row0 + 1.0, 0]]).T) + f.create_dataset("colSupport", data=np.array([[col0 + 1.0, 0]]).T) + f.create_dataset("srcIdx", data=np.array([[4.0, 9.0]])) + debias = np.array([[ord(c)] for c in "Model"], dtype=np.uint16) + empty = f.create_group("params").create_dataset("photonScale", data=np.zeros(2, np.uint64)) + empty.attrs["MATLAB_empty"] = 1 + _write_matlab_params(f["params"], params, debiasVariance=debias) + return folder / "sub_001.mat" + + +def test_load_matlab_subproblem(tmp_path: Path) -> None: + """A saved subproblem is read in the port's convention. + + Channels x pixels x frames, zero-based sources, pixel indices in the + trial's list, and its parameters. + """ + rng = np.random.default_rng(1) + sel = np.ones((4, 5), dtype=bool) + sel[0, 0] = sel[3, 4] = False + n_px = int(sel.sum()) + y = rng.random((2, n_px, 30)) + finv = 0.5 + rng.random((n_px, 30)) + rc = np.array([[1, 1], [2, 3]]) + params = SolverParams(sigma_px=1.6, sel_radius=4, tau_s=0.03, lam=0.7) + path = _write_matlab_subproblem(tmp_path, y, finv, sel, rc, params, 3, 2) + with warnings.catch_warnings(): + warnings.simplefilter("error") + sub, p = load_matlab_subproblem(path) + assert sub.y.dtype == np.float64 + assert np.array_equal(sub.y, y) and np.array_equal(sub.finv, finv) + assert np.array_equal(sub.sel, sel) + assert np.array_equal(sub.sources_rc, rc) + assert (sub.row0, sub.col0) == (3, 2) + assert sub.sources.tolist() == [3, 8] + # the trial's map has two selected pixels before this crop's + assert np.array_equal(sub.pixels, 2 + np.arange(n_px)) + assert p.photon_scale is None and p.debias_variance == "model" + # not a MATLAB parameter: the default, unless the struct names it + assert p.footprint_variance == "fixed" + with h5py.File(path, "r+") as f: + f["params"].create_dataset( + "footprintVariance", + data=np.array([[ord(c)] for c in "Model"], dtype=np.uint16), + ) + assert load_matlab_subproblem(path)[1].footprint_variance == "model" + assert (p.sigma_px, p.sel_radius, p.lam) == (1.6, 4, 0.7) + assert p.tau_frames == pytest.approx(0.03 * 200) + assert load_matlab_subproblem(path, np.float32)[0].y.dtype == np.float32 + + +def test_trial_file_of_another_trial_is_refused(tmp_path: Path) -> None: + """A trial.mat that does not select every pixel of the subproblem is refused. + + It cannot give the subproblem's pixel indices. + """ + sel = np.ones((3, 3), dtype=bool) + path = _write_matlab_subproblem( + tmp_path, + np.zeros((1, 9, 5)), + np.ones((9, 5)), + sel, + np.array([[1, 1]]), + SolverParams(), + 2, + 1, + ) + with h5py.File(tmp_path / "trial.mat", "r+") as f: + full = f["selPix"][()] + full[2, 3] = 0 # one of the crop's pixels, in MATLAB's file order + f["selPix"][...] = full + with pytest.raises(ValueError, match="not from the same trial"): + load_matlab_subproblem(path) + with h5py.File(tmp_path / "trial.mat", "w") as f: + f.create_dataset("selPix", data=np.ones((2, 2), np.uint8)) + with pytest.raises(ValueError, match="not from the same trial"): + load_matlab_subproblem(path) + + +def test_single_channel_subproblem_without_trial_file(tmp_path: Path) -> None: + """One channel is saved as a 2-D array. + + Without trial.mat the pixel indices are unknown. + """ + sel = np.ones((2, 3), dtype=bool) + y = np.arange(6 * 7, dtype=np.float64).reshape(1, 6, 7) + path = _write_matlab_subproblem( + tmp_path, + y, + np.ones((6, 7)), + sel, + np.array([[0, 1]]), + SolverParams(), + 0, + 0, + ) + (tmp_path / "trial.mat").unlink() + with h5py.File(path, "r+") as f: + del f["Y_p"] + f.create_dataset("Y_p", data=y[0].T) + sub, _ = load_matlab_subproblem(path) + assert sub.y.shape == (1, 6, 7) and np.array_equal(sub.y, y) + assert sub.pixels is None + + +def test_params_warn_when_saved_filters_differ(tmp_path: Path) -> None: + """A saved kernel that the scalar parameters do not give is reported.""" + with h5py.File(tmp_path / "p.mat", "w") as f: + g = f.create_group("params") + _write_matlab_params(g, SolverParams()) + g["k"][...] = g["k"][()] * 1.01 + with pytest.warns(UserWarning, match="params.k differs"): + p = params_from_matlab(g) + # a struct without validKernel is MATLAB's 3 x 3 (not the default 5) + assert p == SolverParams(tau_full=4.8, photon_scale=None, valid_kernel=3) + + +def test_subproblem_fixture_starts_as_matlab() -> None: + """The fixture's starting footprints are MATLAB's.""" + with h5py.File(SUBPROBLEM, "r") as f: + sel = f["in/sel"][()].astype(bool) + hs, h, valid = initial_footprints(sel, f["in/sources_rc"][()], PARAMS_B.sigma_px) + assert np.array_equal(hs, f["init/Hs"][()]) + _close(h, f["init/H"][()]) + assert np.array_equal(valid, f["init/Hvalid"][()].astype(bool)) + + +def test_valid_kernel_widens_the_support_only() -> None: + """A larger validKernel widens where Hs may go, nothing else. + + A source at the crop's edge gets the part of the square inside it. + """ + sel = np.ones((15, 15), dtype=bool) + rc = np.array([[7, 7], [0, 1]]) + hs3, h3, v3 = initial_footprints(sel, rc, 1.33) + hs5, h5, v5 = initial_footprints(sel, rc, 1.33, valid_kernel=5) + assert np.array_equal(hs3, hs5) + assert np.array_equal(h3, h5) + assert v3.sum(0).tolist() == [9, 6] + assert v5.sum(0).tolist() == [25, 12] + assert (v3 <= v5).all() + rows, cols = sel_coords(sel) + inside = (np.abs(rows - 7) <= 2) & (np.abs(cols - 7) <= 2) + assert np.array_equal(v5[:, 0], inside) + + +@pytest.mark.parametrize("bad", [0, 2, 4, -3, 3.0, True]) +def test_valid_kernel_must_be_odd_and_positive(bad: float) -> None: + """An even, non-positive or non-integer side is rejected.""" + with pytest.raises(ValueError, match="valid_kernel"): + SolverParams(valid_kernel=bad) + + +def test_valid_kernel_from_matlab() -> None: + """params_from_matlab reads validKernel's side; 3 without one.""" + with h5py.File("vk.h5", "w", driver="core", backing_store=False) as f: + assert params_from_matlab(f.create_group("none")).valid_kernel == 3 + f.create_group("five")["validKernel"] = np.ones((5, 5), np.uint8) + assert params_from_matlab(f["five"]).valid_kernel == 5 + f.create_group("odd")["validKernel"] = np.ones((3, 2), np.uint8) + with pytest.raises(ValueError, match="validKernel"): + params_from_matlab(f["odd"]) + # entries other than 1 are rejected, not read as a full support + for name, value in (("twos", 2.0), ("minus", -1.0), ("nan", np.nan)): + f.create_group(name)["validKernel"] = np.full((5, 5), value) + with pytest.raises(ValueError, match="square of ones"): + params_from_matlab(f[name]) + f.create_group("plus")["validKernel"] = np.array( + [[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8 + ) + with pytest.raises(ValueError, match="5 ones"): + params_from_matlab(f["plus"]) diff --git a/tests/raster/test_raster_stage_files.py b/tests/raster/test_raster_stage_files.py index 16948369..73e7b2b4 100644 --- a/tests/raster/test_raster_stage_files.py +++ b/tests/raster/test_raster_stage_files.py @@ -1,112 +1,112 @@ -"""Tests of the files SILo's stages hand to each other. - -These are per-trial localization files and seeds files. -""" - -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.stage_files import ( - add_peaks, - localization_attrs, - read_localization, - read_seeds, - write_localization, - write_seeds, -) - - -def test_localization_round_trip(tmp_path: Path) -> None: - """Images, discards and peaks come back; peaks can be added later.""" - rng = np.random.default_rng(0) - mean_im = rng.random((6, 7, 2)).astype(np.float32) - act_im = rng.random((6, 7)) - act_im[0, 0] = np.nan - discard = rng.random(40) < 0.2 - path = tmp_path / "loc.h5" - write_localization(path, mean_im, act_im, act_im * 2, discard, None, {"trial": 3}) - rec = read_localization(path) - np.testing.assert_array_equal(rec.mean_im, mean_im) - assert rec.mean_im.dtype == np.float32 - np.testing.assert_array_equal(rec.act_im, act_im) - np.testing.assert_array_equal(rec.summary, act_im * 2) - np.testing.assert_array_equal(rec.discard, discard) - assert rec.peaks is None and rec.attrs["peaks_fitted"] == 0 - assert rec.attrs["trial"] == 3 - peaks = np.array([[1.0, 2.0, 3.0, 0.5]]) - side = add_peaks(path, peaks) - assert side.name == "loc.peaks.h5" # the localization file is not written - rec = read_localization(path) - np.testing.assert_array_equal(rec.peaks, peaks) - assert localization_attrs(path)["peaks_fitted"] == 1 - assert read_localization(path, peaks=False).peaks is None - images = rec.trial_images() - np.testing.assert_array_equal(images.act_im, act_im) - np.testing.assert_array_equal(images.peaks, peaks) - assert not list(tmp_path.glob("*.partial")) - # a new localization replaces the earlier one's peaks - write_localization(path, mean_im, act_im, act_im, discard, None, {"trial": 3}) - assert not side.exists() and read_localization(path).peaks is None - - -def test_localization_format_checks(tmp_path: Path) -> None: - """Other files are refused; a missing file has no attributes.""" - with h5py.File(tmp_path / "other.h5", "w") as f: - f.attrs["format"] = "other" - with pytest.raises(ValueError): - read_localization(tmp_path / "other.h5") - assert localization_attrs(tmp_path / "other.h5") is None - assert localization_attrs(tmp_path / "missing.h5") is None - path = tmp_path / "loc.h5" - write_localization( - path, - np.zeros((2, 2, 1)), - np.zeros((2, 2)), - np.zeros((2, 2)), - np.zeros(3, bool), - None, - {}, - ) - with h5py.File(path, "a") as f: - f.attrs["format_version"] = 99 - with pytest.raises(ValueError, match="99"): - read_localization(path) - - -def test_seeds(tmp_path: Path) -> None: - """Seeds per path, one-based (MATLAB's thetaf) or zero-based.""" - seeds = np.array([[2.0, 10.0, 20.0, 0.5], [1.0, 3.0, 4.0, 0.4]]) - write_seeds(tmp_path / "s1.h5", {2: seeds}, index_base=1) - got = read_seeds(tmp_path / "s1.h5", 3) - assert got[0] is None and got[2] is None - np.testing.assert_array_equal(got[1][:, 1:3], seeds[:, 1:3] - 1) - np.testing.assert_array_equal(got[1][:, [0, 3]], seeds[:, [0, 3]]) - write_seeds(tmp_path / "s0.h5", {1: seeds}) - np.testing.assert_array_equal(read_seeds(tmp_path / "s0.h5", 1)[0], seeds) - with pytest.raises(ValueError): - write_seeds(tmp_path / "bad.h5", {1: seeds}, index_base=2) - - -def test_recording_ids(tmp_path: Path) -> None: - """A recording's files: CYCLE segments and .meta; a missing one raises.""" - from giant_python.pipeline.silo_session import recording_ids - - for name in ( - "rec_DMD1-CYCLE-000000.dat", - "rec_DMD1-CYCLE-000100.dat", - "rec_DMD2-CYCLE-000000.dat", - "rec_DMD1.meta", - "other.meta", - ): - (tmp_path / name).write_bytes(b"x") - ids = recording_ids(tmp_path / "rec_DMD1-CYCLE-000100.dat") - assert [i["name"] for i in ids] == [ - "rec_DMD1-CYCLE-000000.dat", - "rec_DMD1-CYCLE-000100.dat", - "rec_DMD1.meta", - ] - with pytest.raises(FileNotFoundError): - recording_ids(tmp_path / "rec_DMD3-CYCLE-000000.dat") +"""Tests of the files SILo's stages hand to each other. + +These are per-trial localization files and seeds files. +""" + +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.stage_files import ( + add_peaks, + localization_attrs, + read_localization, + read_seeds, + write_localization, + write_seeds, +) + + +def test_localization_round_trip(tmp_path: Path) -> None: + """Images, discards and peaks come back; peaks can be added later.""" + rng = np.random.default_rng(0) + mean_im = rng.random((6, 7, 2)).astype(np.float32) + act_im = rng.random((6, 7)) + act_im[0, 0] = np.nan + discard = rng.random(40) < 0.2 + path = tmp_path / "loc.h5" + write_localization(path, mean_im, act_im, act_im * 2, discard, None, {"trial": 3}) + rec = read_localization(path) + np.testing.assert_array_equal(rec.mean_im, mean_im) + assert rec.mean_im.dtype == np.float32 + np.testing.assert_array_equal(rec.act_im, act_im) + np.testing.assert_array_equal(rec.summary, act_im * 2) + np.testing.assert_array_equal(rec.discard, discard) + assert rec.peaks is None and rec.attrs["peaks_fitted"] == 0 + assert rec.attrs["trial"] == 3 + peaks = np.array([[1.0, 2.0, 3.0, 0.5]]) + side = add_peaks(path, peaks) + assert side.name == "loc.peaks.h5" # the localization file is not written + rec = read_localization(path) + np.testing.assert_array_equal(rec.peaks, peaks) + assert localization_attrs(path)["peaks_fitted"] == 1 + assert read_localization(path, peaks=False).peaks is None + images = rec.trial_images() + np.testing.assert_array_equal(images.act_im, act_im) + np.testing.assert_array_equal(images.peaks, peaks) + assert not list(tmp_path.glob("*.partial")) + # a new localization replaces the earlier one's peaks + write_localization(path, mean_im, act_im, act_im, discard, None, {"trial": 3}) + assert not side.exists() and read_localization(path).peaks is None + + +def test_localization_format_checks(tmp_path: Path) -> None: + """Other files are refused; a missing file has no attributes.""" + with h5py.File(tmp_path / "other.h5", "w") as f: + f.attrs["format"] = "other" + with pytest.raises(ValueError): + read_localization(tmp_path / "other.h5") + assert localization_attrs(tmp_path / "other.h5") is None + assert localization_attrs(tmp_path / "missing.h5") is None + path = tmp_path / "loc.h5" + write_localization( + path, + np.zeros((2, 2, 1)), + np.zeros((2, 2)), + np.zeros((2, 2)), + np.zeros(3, bool), + None, + {}, + ) + with h5py.File(path, "a") as f: + f.attrs["format_version"] = 99 + with pytest.raises(ValueError, match="99"): + read_localization(path) + + +def test_seeds(tmp_path: Path) -> None: + """Seeds per path, one-based (MATLAB's thetaf) or zero-based.""" + seeds = np.array([[2.0, 10.0, 20.0, 0.5], [1.0, 3.0, 4.0, 0.4]]) + write_seeds(tmp_path / "s1.h5", {2: seeds}, index_base=1) + got = read_seeds(tmp_path / "s1.h5", 3) + assert got[0] is None and got[2] is None + np.testing.assert_array_equal(got[1][:, 1:3], seeds[:, 1:3] - 1) + np.testing.assert_array_equal(got[1][:, [0, 3]], seeds[:, [0, 3]]) + write_seeds(tmp_path / "s0.h5", {1: seeds}) + np.testing.assert_array_equal(read_seeds(tmp_path / "s0.h5", 1)[0], seeds) + with pytest.raises(ValueError): + write_seeds(tmp_path / "bad.h5", {1: seeds}, index_base=2) + + +def test_recording_ids(tmp_path: Path) -> None: + """A recording's files: CYCLE segments and .meta; a missing one raises.""" + from giant_python.pipeline.silo_session import recording_ids + + for name in ( + "rec_DMD1-CYCLE-000000.dat", + "rec_DMD1-CYCLE-000100.dat", + "rec_DMD2-CYCLE-000000.dat", + "rec_DMD1.meta", + "other.meta", + ): + (tmp_path / name).write_bytes(b"x") + ids = recording_ids(tmp_path / "rec_DMD1-CYCLE-000100.dat") + assert [i["name"] for i in ids] == [ + "rec_DMD1-CYCLE-000000.dat", + "rec_DMD1-CYCLE-000100.dat", + "rec_DMD1.meta", + ] + with pytest.raises(FileNotFoundError): + recording_ids(tmp_path / "rec_DMD3-CYCLE-000000.dat") diff --git a/tests/raster/test_raster_summary_model.py b/tests/raster/test_raster_summary_model.py index 142d1ea0..66b38f62 100644 --- a/tests/raster/test_raster_summary_model.py +++ b/tests/raster/test_raster_summary_model.py @@ -1,479 +1,479 @@ -"""ExperimentSummary.from_h5 / to_h5 on raster SILo's and BandSILo's summaries. - -Raster SILo's experiment summary is column-major (GIAnT-MATLAB's layout); -BandSILo's schema is also covered. -""" - -import dataclasses -import json -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster import spots as sp -from giant_python.extraction.raster.kinetics import KineticsTest -from giant_python.extraction.raster.summary import ( - PathResult, - _Writer, - write_summaries, -) -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.models.experiment_summary import ( - ExperimentSummary, - FrameInfo, - PathSummary, - Source, - Visualizations, -) -from giant_python.models.params import SiloParams -from giant_python.pipeline.silo_spots import _write as write_spots - -from .test_raster_summary import ( # noqa: F401 (fixture) - FRAMES, - N_TRIALS, - C, - H, - W, - alignment, - make_plan, - outcome, - written, -) - -TOTAL = sum(FRAMES.values()) - - -def _children(a: object, b: object, where: str) -> list[tuple[object, object, str]]: - """Pairs of the members of two containers (dataclass, dict, list). - - Returns - ------- - list[tuple[object, object, str]] - One (member of a, member of b, location) triple per member. - """ - if dataclasses.is_dataclass(a): - assert type(a) is type(b), where - return [ - (getattr(a, f.name), getattr(b, f.name), f"{where}.{f.name}") - for f in dataclasses.fields(a) - if not f.name.startswith("_") - ] - if isinstance(a, dict): - assert set(a) == set(b), where - return [(a[k], b[k], f"{where}[{k}]") for k in a] - assert len(a) == len(b), where - return [(x, y, f"{where}[{i}]") for i, (x, y) in enumerate(zip(a, b))] - - -def _equal(a: object, b: object, where: str = "summary") -> None: - """Two models hold the same values (NaN equal to NaN).""" - if dataclasses.is_dataclass(a) or isinstance(a, (dict, list, tuple)): - for x, y, w in _children(a, b, where): - _equal(x, y, w) - elif a is None or b is None: - assert a is None and b is None, where - elif isinstance(a, str): - assert a == b, where - else: - x, y = np.asarray(a), np.asarray(b) - assert x.shape == y.shape, where - if x.dtype.kind in "fc" or y.dtype.kind in "fc": - np.testing.assert_array_equal(x, y, err_msg=where) - else: - assert np.array_equal(x, y), where - - -def test_from_h5_reads_a_raster_summary(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 - """A raster summary loads with the dimension order of the README. - - It loads with its values, its kinetics and rejected sources, and no - offlineZshifts. - """ - exp, _, _result = written - s = ExperimentSummary.from_h5(exp) - raw = load_struct_h5(exp)["Path1"] - assert [p.path_index for p in s.paths] == [0] # Path2 was None - p = s.paths[0] - assert len(p.sources) == 3 - src = p.sources[1] - assert src.profile.shape == (1, H, W) - assert src.df_ls.shape == src.events.shape == (C, TOTAL) - np.testing.assert_array_equal(src.f0, raw["sources"]["temporal"]["F0"][1]) - np.testing.assert_array_equal([x.snr for x in p.sources], [1.5, np.nan, 6.0]) - np.testing.assert_array_equal([x.kinetic_score for x in p.sources], [0.9, np.nan, 0.5]) - assert [x.kinetic_n_events for x in p.sources] == [10, 2, 6] - assert all(x.spot_id is None for x in p.sources) - assert p.frame_info.offlineZshifts is None - assert p.frame_info.offlineXshifts.shape == (TOTAL, 1) - np.testing.assert_array_equal(p.frame_info.trial_alignment_affine[2], [[1, 0, 1], [0, 1, -2]]) - assert p.frame_info.trial_alignment_displacement is None - np.testing.assert_array_equal(p.rejected["seed_coords"], [[0, 4, 5]]) - assert p.rejected["kinetic_score"].shape == (1, 1) - assert [r.label for r in p.user_rois] == ["spine01", "soma"] - assert p.annotation_enabled - assert p.user_rois[0].mask.shape == (1, H, W) - assert p.user_rois[1].f.shape == (C, TOTAL) - assert p.visualizations.mean_im.shape == (C, 1, H, W) - assert p.visualizations.act_im.shape == (1, H, W) - np.testing.assert_array_equal( - p.visualizations.act_im_peaks, [[0, 3, 3], [0, 9, 12], [0, 10, 15]] - ) - assert p.visualizations.f0_im is None - assert p.global_f.shape == (C, TOTAL) - np.testing.assert_array_equal(p.z_depths, [[-18.75]]) - assert p.spots is None - assert s.params["activityChannel"] == 2 - assert s.attrs == {} - - -def test_paths_without_sources_rois_or_depth(tmp_path: Path) -> None: - """A path whose sources were all removed, without annotations and an unknown depth. - - It sits beside one with sources (in Path2). - """ - plan = make_plan() - n_px = plan.n_pixels - - def result(keep: list[bool]) -> PathResult: - """One path of the plan, with the kinetics' keep. - - Returns - ------- - PathResult - The path's result, with a kinetics test whose keep is keep. - """ - r = PathResult( - plan=plan, - trials=[None, outcome(1, n_px), outcome(2, n_px)], - alignment=[None, alignment(1), alignment(2)], - roi_labels=[], - roi_masks=[], - ) - r.kinetics = KineticsTest( - keep=np.asarray(keep), - score=np.array([0.9, 0.1, 0.4, 0.5]), - n_events=np.array([10, 7, 2, 6]), - ) - return r - - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") - exp = tmp_path / "experiment_summary.h5" - write_summaries( - exp, - tmp_path / "per.h5", - [result([False] * 4), result([True, True, False, True])], - params, - N_TRIALS, - C, - 1, - ) - s = ExperimentSummary.from_h5(exp) - none, some = s.paths - assert (none.path_index, some.path_index) == (0, 1) - assert none.sources == [] and none.user_rois == [] - assert not none.annotation_enabled - assert none.visualizations.act_im_peaks is None - assert none.z_depths is None - assert none.rejected["seed_coords"].shape == (4, 3) - assert none.global_f.shape == (C, TOTAL) - assert len(some.sources) == 3 - assert [x.kinetic_n_events for x in some.sources] == [10, 7, 6] - # a model without sources is written in the band schema and read back - out = tmp_path / "band.h5" - s.to_h5(out) - back = ExperimentSummary.from_h5(out) - assert back.paths[0].sources == [] - assert back.paths[0].z_depths is None - _equal(back.paths[1], some) - - -def _annotated(exp: Path) -> None: - """Add raster extras to the written summary, as raster SILo writes them. - - The extras are a spot annotation, a baseline image, a displacement field - and root attributes. - """ - lab = np.array([0, 1, 0]) # sources 1 and 3 form a spot - out = [ - sp.SpotResult( - np.array([0, 2]), - "merge", - event_corr=0.6, - n_events=20, - K=1, - power=0.4, - cloud_major=0.3, - cloud_minor=0.2, - bic_gain=-3.0, - center=np.array([6.0, 7.5]), - ), - sp.SpotResult(np.array([1]), "single", center=np.array([9.0, 12.0])), - ] - write_spots(exp, "Path1", lab, out, sp.SpotSettings()) - rng = np.random.default_rng(4) - with h5py.File(exp, "a") as f: - ew = _Writer(f) - ew.put("Path1/visualizations/F0_im", rng.random((C, 1, H, W))) - ew.put( - "Path1/frame_info/trial_alignment_displacement", - rng.random((N_TRIALS, 2, H, W)).astype(np.float32), - ) - f.attrs["baseline_source"] = "network" - f.attrs["network_baseline"] = json.dumps({"path1_trial0002": {}}) - - -def test_spot_annotation_and_raster_extras(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 - """The spot annotation with its attributes, and the summary's raster extras. - - These are each source's spot, the baseline image, the displacement field - and the root attributes. - """ - exp, _, _ = written - _annotated(exp) - s = ExperimentSummary.from_h5(exp) - p = s.paths[0] - assert [x.spot_id for x in p.sources] == [1, 2, 1] - spots = p.spots - assert spots["labels"] == list(sp.LABELS) - assert spots["settings"]["link_px"] == 2.5 - assert spots["label"].shape == (2, 1) - names = [spots["labels"][i] for i in spots["label"].ravel()] - assert names == ["merge", "single"] - np.testing.assert_array_equal(spots["n_sources"].ravel(), [2, 1]) - np.testing.assert_array_equal(spots["event_corr"].ravel()[:1], [0.6]) - assert p.visualizations.f0_im.shape == (C, 1, H, W) - assert p.frame_info.trial_alignment_displacement.shape == ( - N_TRIALS, - 2, - H, - W, - ) - assert s.attrs["baseline_source"] == "network" - assert json.loads(s.attrs["network_baseline"]) == {"path1_trial0002": {}} - - -def test_raster_round_trip( - written: tuple[Path, Path, PathResult], # noqa: F811 - tmp_path: Path, -) -> None: - """A raster model written with to_h5 reads back as the same model. - - to_h5 writes BandSILo's row-major schema plus the raster fields, and - refuses to add paths to the column-major file. - """ - exp, _, _ = written - _annotated(exp) - s = ExperimentSummary.from_h5(exp) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 - assert "offlineZshifts" not in f["Path1/frame_info"] - assert f["Path1/sources/spots"].attrs["labels"] - _equal(ExperimentSummary.from_h5(out), s) - with pytest.raises(ValueError, match="column-major"): - s.to_h5(exp) - - -def _band_summary() -> ExperimentSummary: - """Build a BandSILo-like model: every band field, no raster field. - - Returns - ------- - ExperimentSummary - A summary of one path with two sources and random values. - """ - rng = np.random.default_rng(9) - n, frames, ch = 2, 12, 2 - sources = [ - Source( - profile=rng.random((1, H, W)).astype(np.float32), - coords=np.array([0, 3 + j, 4 + j], np.int32), - df_ls=rng.random((ch, frames)), - df_denoised=rng.random((ch, frames)), - events=rng.random((ch, frames)), - f0=rng.random((ch, frames)), - snr=np.float64(2.0 + j), - ) - for j in range(n) - ] - col = np.arange(frames, dtype=float).reshape(-1, 1) - frame_info = FrameInfo( - trial_num_frames=np.array([[5], [7]]), - discard_frames=np.zeros((frames, 1), bool), - frame_line_idxs=np.arange(1, frames + 1).reshape(-1, 1), - offlineXshifts=col, - offlineYshifts=-col, - offlineZshifts=0 * col, - onlineXshifts=col, - onlineYshifts=col, - onlineZshifts=col, - ) - path = PathSummary( - path_index=0, - sources=sources, - visualizations=Visualizations( - mean_im=rng.random((ch, 1, H, W)), - act_im=rng.random((1, H, W)), - act_im_peaks=np.array([[0, 3, 4], [0, 4, 5], [0, 9, 9]]), - ), - frame_info=frame_info, - global_f=rng.random((ch, frames)), - z_depths=np.array([12.5]), - ) - return ExperimentSummary(paths=[path], params={"analyzeHz": 100.0}) - - -BAND_DATASETS = { - "row_major", - "params/analyzeHz", - "Path1/Z_depths", - "Path1/sources/spatial/profiles", - "Path1/sources/spatial/coords", - "Path1/sources/temporal/dF_ls", - "Path1/sources/temporal/dF_denoised", - "Path1/sources/temporal/events", - "Path1/sources/temporal/F0", - "Path1/sources/temporal/SNR", - "Path1/frame_info/trial_num_frames", - "Path1/frame_info/discard_frames", - "Path1/frame_info/frame_line_idxs", - "Path1/frame_info/offlineXshifts", - "Path1/frame_info/offlineYshifts", - "Path1/frame_info/offlineZshifts", - "Path1/frame_info/onlineXshifts", - "Path1/frame_info/onlineYshifts", - "Path1/frame_info/onlineZshifts", - "Path1/global/F", - "Path1/visualizations/act_im", - "Path1/visualizations/mean_im", - "Path1/visualizations/act_im_peaks", - "Path1/user_rois/mask", - "Path1/user_rois/F", - "Path1/user_rois/Fsvd", - "Path1/user_rois/labels", -} - - -def test_band_schema_unchanged(tmp_path: Path) -> None: - """A BandSILo model writes exactly the band datasets and reads back unchanged. - - It writes no raster field and no root attribute. - """ - s = _band_summary() - out = tmp_path / "band.h5" - s.to_h5(out) - names = set() - with h5py.File(out, "r") as f: - f.visititems(lambda name, obj: names.add(name) if isinstance(obj, h5py.Dataset) else None) - assert dict(f.attrs) == {} - assert dict(f["Path1/user_rois"].attrs) == {"annotation_enabled": False} - assert names == BAND_DATASETS - back = ExperimentSummary.from_h5(out) - p = back.paths[0] - assert p.rejected == {} and p.spots is None and back.attrs == {} - assert p.visualizations.f0_im is None - assert all(x.kinetic_score is None for x in p.sources) - _equal(p.sources, s.paths[0].sources) - _equal(p.frame_info, s.paths[0].frame_info) - np.testing.assert_array_equal(p.z_depths, [[12.5]]) - - -def test_partial_raster_scalars_are_refused(tmp_path: Path) -> None: - """A raster field set for some sources only cannot be written.""" - s = _band_summary() - s.paths[0].sources[0].kinetic_score = 0.5 - with pytest.raises(ValueError, match="kinetic_score"): - s.to_h5(tmp_path / "x.h5") - - -def test_raster_round_trip_without_snr( - written: tuple[Path, Path, PathResult], # noqa: F811 - tmp_path: Path, -) -> None: - """A raster file without SNR (no trial gave one) stays without it.""" - exp, _, _ = written - with h5py.File(exp, "a") as f: - del f["Path1/sources/temporal/SNR"] - s = ExperimentSummary.from_h5(exp) - assert all(x.snr is None for x in s.paths[0].sources) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert "SNR" not in f["Path1/sources/temporal"] - _equal(ExperimentSummary.from_h5(out), s) - # a model built in memory with no SNR still gets NaN, as before - band = _band_summary() - for x in band.paths[0].sources: - x.snr = None - band.to_h5(tmp_path / "band.h5") - with h5py.File(tmp_path / "band.h5", "r") as f: - assert np.isnan(f["Path1/sources/temporal/SNR"][()]).all() - - -def test_raster_path_without_frames(tmp_path: Path) -> None: - """A raster path without frames (no trial loaded) is written back and reads the same. - - It has no global trace, no sources and ROI masks without traces. - """ - plan = make_plan() - result = PathResult( - plan=plan, - trials=[None, None, None], - alignment=[None, None, None], - roi_labels=["soma"], - roi_masks=[np.ones((H, W), bool)], - ) - params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") - exp = tmp_path / "experiment_summary.h5" - write_summaries(exp, tmp_path / "per.h5", [result], params, N_TRIALS, C, 1) - s = ExperimentSummary.from_h5(exp) - p = s.paths[0] - assert p.global_f is None and p.sources == [] - assert [r.label for r in p.user_rois] == ["soma"] - assert p.user_rois[0].f is None and p.user_rois[0].fsvd is None - assert p.user_rois[0].mask.shape == (1, H, W) - np.testing.assert_array_equal(p.frame_info.trial_num_frames.ravel(), 0) - out = tmp_path / "rewritten.h5" - s.to_h5(out) - with h5py.File(out, "r") as f: - assert f["Path1/sources/temporal/dF_ls"].shape == (0, C, 0) - assert "F" not in f["Path1/user_rois"] - assert f["Path1/user_rois/mask"].shape == (1, 1, H, W) - assert "global" not in f["Path1"] - _equal(ExperimentSummary.from_h5(out), s) - - -def test_files_without_the_flag_are_refused(tmp_path: Path) -> None: - """A nonempty file without /row_major reads as column-major: refused. - - A new (empty) file is made row-major. - """ - old = tmp_path / "old.h5" - with h5py.File(old, "w") as f: - f["Path1/Z_depths"] = np.zeros((1, 1)) - with pytest.raises(ValueError, match="no /row_major"): - _band_summary().to_h5(old) - new = tmp_path / "new.h5" - h5py.File(new, "w").close() - _band_summary().to_h5(new) - with h5py.File(new, "r") as f: - assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 - - -def test_partial_roi_traces_are_refused(tmp_path: Path) -> None: - """ROIs of which only some have a trace cannot be written.""" - from giant_python.models.experiment_summary import UserRoi - - s = _band_summary() - p = s.paths[0] - p.annotation_enabled = True - mask = np.ones((1, H, W), bool) - p.user_rois = [ - UserRoi(label="a", mask=mask, f=p.global_f.copy()), - UserRoi(label="b", mask=mask), - ] - with pytest.raises(ValueError, match="UserRoi.f"): - s.to_h5(tmp_path / "x.h5") +"""ExperimentSummary.from_h5 / to_h5 on raster SILo's and BandSILo's summaries. + +Raster SILo's experiment summary is column-major (GIAnT-MATLAB's layout); +BandSILo's schema is also covered. +""" + +import dataclasses +import json +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster import spots as sp +from giant_python.extraction.raster.kinetics import KineticsTest +from giant_python.extraction.raster.summary import ( + PathResult, + _Writer, + write_summaries, +) +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.models.experiment_summary import ( + ExperimentSummary, + FrameInfo, + PathSummary, + Source, + Visualizations, +) +from giant_python.models.params import SiloParams +from giant_python.pipeline.silo_spots import _write as write_spots + +from .test_raster_summary import ( # noqa: F401 (fixture) + FRAMES, + N_TRIALS, + C, + H, + W, + alignment, + make_plan, + outcome, + written, +) + +TOTAL = sum(FRAMES.values()) + + +def _children(a: object, b: object, where: str) -> list[tuple[object, object, str]]: + """Pairs of the members of two containers (dataclass, dict, list). + + Returns + ------- + list[tuple[object, object, str]] + One (member of a, member of b, location) triple per member. + """ + if dataclasses.is_dataclass(a): + assert type(a) is type(b), where + return [ + (getattr(a, f.name), getattr(b, f.name), f"{where}.{f.name}") + for f in dataclasses.fields(a) + if not f.name.startswith("_") + ] + if isinstance(a, dict): + assert set(a) == set(b), where + return [(a[k], b[k], f"{where}[{k}]") for k in a] + assert len(a) == len(b), where + return [(x, y, f"{where}[{i}]") for i, (x, y) in enumerate(zip(a, b))] + + +def _equal(a: object, b: object, where: str = "summary") -> None: + """Two models hold the same values (NaN equal to NaN).""" + if dataclasses.is_dataclass(a) or isinstance(a, (dict, list, tuple)): + for x, y, w in _children(a, b, where): + _equal(x, y, w) + elif a is None or b is None: + assert a is None and b is None, where + elif isinstance(a, str): + assert a == b, where + else: + x, y = np.asarray(a), np.asarray(b) + assert x.shape == y.shape, where + if x.dtype.kind in "fc" or y.dtype.kind in "fc": + np.testing.assert_array_equal(x, y, err_msg=where) + else: + assert np.array_equal(x, y), where + + +def test_from_h5_reads_a_raster_summary(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 + """A raster summary loads with the dimension order of the README. + + It loads with its values, its kinetics and rejected sources, and no + offlineZshifts. + """ + exp, _, _result = written + s = ExperimentSummary.from_h5(exp) + raw = load_struct_h5(exp)["Path1"] + assert [p.path_index for p in s.paths] == [0] # Path2 was None + p = s.paths[0] + assert len(p.sources) == 3 + src = p.sources[1] + assert src.profile.shape == (1, H, W) + assert src.df_ls.shape == src.events.shape == (C, TOTAL) + np.testing.assert_array_equal(src.f0, raw["sources"]["temporal"]["F0"][1]) + np.testing.assert_array_equal([x.snr for x in p.sources], [1.5, np.nan, 6.0]) + np.testing.assert_array_equal([x.kinetic_score for x in p.sources], [0.9, np.nan, 0.5]) + assert [x.kinetic_n_events for x in p.sources] == [10, 2, 6] + assert all(x.spot_id is None for x in p.sources) + assert p.frame_info.offlineZshifts is None + assert p.frame_info.offlineXshifts.shape == (TOTAL, 1) + np.testing.assert_array_equal(p.frame_info.trial_alignment_affine[2], [[1, 0, 1], [0, 1, -2]]) + assert p.frame_info.trial_alignment_displacement is None + np.testing.assert_array_equal(p.rejected["seed_coords"], [[0, 4, 5]]) + assert p.rejected["kinetic_score"].shape == (1, 1) + assert [r.label for r in p.user_rois] == ["spine01", "soma"] + assert p.annotation_enabled + assert p.user_rois[0].mask.shape == (1, H, W) + assert p.user_rois[1].f.shape == (C, TOTAL) + assert p.visualizations.mean_im.shape == (C, 1, H, W) + assert p.visualizations.act_im.shape == (1, H, W) + np.testing.assert_array_equal( + p.visualizations.act_im_peaks, [[0, 3, 3], [0, 9, 12], [0, 10, 15]] + ) + assert p.visualizations.f0_im is None + assert p.global_f.shape == (C, TOTAL) + np.testing.assert_array_equal(p.z_depths, [[-18.75]]) + assert p.spots is None + assert s.params["activityChannel"] == 2 + assert s.attrs == {} + + +def test_paths_without_sources_rois_or_depth(tmp_path: Path) -> None: + """A path whose sources were all removed, without annotations and an unknown depth. + + It sits beside one with sources (in Path2). + """ + plan = make_plan() + n_px = plan.n_pixels + + def result(keep: list[bool]) -> PathResult: + """One path of the plan, with the kinetics' keep. + + Returns + ------- + PathResult + The path's result, with a kinetics test whose keep is keep. + """ + r = PathResult( + plan=plan, + trials=[None, outcome(1, n_px), outcome(2, n_px)], + alignment=[None, alignment(1), alignment(2)], + roi_labels=[], + roi_masks=[], + ) + r.kinetics = KineticsTest( + keep=np.asarray(keep), + score=np.array([0.9, 0.1, 0.4, 0.5]), + n_events=np.array([10, 7, 2, 6]), + ) + return r + + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") + exp = tmp_path / "experiment_summary.h5" + write_summaries( + exp, + tmp_path / "per.h5", + [result([False] * 4), result([True, True, False, True])], + params, + N_TRIALS, + C, + 1, + ) + s = ExperimentSummary.from_h5(exp) + none, some = s.paths + assert (none.path_index, some.path_index) == (0, 1) + assert none.sources == [] and none.user_rois == [] + assert not none.annotation_enabled + assert none.visualizations.act_im_peaks is None + assert none.z_depths is None + assert none.rejected["seed_coords"].shape == (4, 3) + assert none.global_f.shape == (C, TOTAL) + assert len(some.sources) == 3 + assert [x.kinetic_n_events for x in some.sources] == [10, 7, 6] + # a model without sources is written in the band schema and read back + out = tmp_path / "band.h5" + s.to_h5(out) + back = ExperimentSummary.from_h5(out) + assert back.paths[0].sources == [] + assert back.paths[0].z_depths is None + _equal(back.paths[1], some) + + +def _annotated(exp: Path) -> None: + """Add raster extras to the written summary, as raster SILo writes them. + + The extras are a spot annotation, a baseline image, a displacement field + and root attributes. + """ + lab = np.array([0, 1, 0]) # sources 1 and 3 form a spot + out = [ + sp.SpotResult( + np.array([0, 2]), + "merge", + event_corr=0.6, + n_events=20, + K=1, + power=0.4, + cloud_major=0.3, + cloud_minor=0.2, + bic_gain=-3.0, + center=np.array([6.0, 7.5]), + ), + sp.SpotResult(np.array([1]), "single", center=np.array([9.0, 12.0])), + ] + write_spots(exp, "Path1", lab, out, sp.SpotSettings()) + rng = np.random.default_rng(4) + with h5py.File(exp, "a") as f: + ew = _Writer(f) + ew.put("Path1/visualizations/F0_im", rng.random((C, 1, H, W))) + ew.put( + "Path1/frame_info/trial_alignment_displacement", + rng.random((N_TRIALS, 2, H, W)).astype(np.float32), + ) + f.attrs["baseline_source"] = "network" + f.attrs["network_baseline"] = json.dumps({"path1_trial0002": {}}) + + +def test_spot_annotation_and_raster_extras(written: tuple[Path, Path, PathResult]) -> None: # noqa: F811 + """The spot annotation with its attributes, and the summary's raster extras. + + These are each source's spot, the baseline image, the displacement field + and the root attributes. + """ + exp, _, _ = written + _annotated(exp) + s = ExperimentSummary.from_h5(exp) + p = s.paths[0] + assert [x.spot_id for x in p.sources] == [1, 2, 1] + spots = p.spots + assert spots["labels"] == list(sp.LABELS) + assert spots["settings"]["link_px"] == 2.5 + assert spots["label"].shape == (2, 1) + names = [spots["labels"][i] for i in spots["label"].ravel()] + assert names == ["merge", "single"] + np.testing.assert_array_equal(spots["n_sources"].ravel(), [2, 1]) + np.testing.assert_array_equal(spots["event_corr"].ravel()[:1], [0.6]) + assert p.visualizations.f0_im.shape == (C, 1, H, W) + assert p.frame_info.trial_alignment_displacement.shape == ( + N_TRIALS, + 2, + H, + W, + ) + assert s.attrs["baseline_source"] == "network" + assert json.loads(s.attrs["network_baseline"]) == {"path1_trial0002": {}} + + +def test_raster_round_trip( + written: tuple[Path, Path, PathResult], # noqa: F811 + tmp_path: Path, +) -> None: + """A raster model written with to_h5 reads back as the same model. + + to_h5 writes BandSILo's row-major schema plus the raster fields, and + refuses to add paths to the column-major file. + """ + exp, _, _ = written + _annotated(exp) + s = ExperimentSummary.from_h5(exp) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 + assert "offlineZshifts" not in f["Path1/frame_info"] + assert f["Path1/sources/spots"].attrs["labels"] + _equal(ExperimentSummary.from_h5(out), s) + with pytest.raises(ValueError, match="column-major"): + s.to_h5(exp) + + +def _band_summary() -> ExperimentSummary: + """Build a BandSILo-like model: every band field, no raster field. + + Returns + ------- + ExperimentSummary + A summary of one path with two sources and random values. + """ + rng = np.random.default_rng(9) + n, frames, ch = 2, 12, 2 + sources = [ + Source( + profile=rng.random((1, H, W)).astype(np.float32), + coords=np.array([0, 3 + j, 4 + j], np.int32), + df_ls=rng.random((ch, frames)), + df_denoised=rng.random((ch, frames)), + events=rng.random((ch, frames)), + f0=rng.random((ch, frames)), + snr=np.float64(2.0 + j), + ) + for j in range(n) + ] + col = np.arange(frames, dtype=float).reshape(-1, 1) + frame_info = FrameInfo( + trial_num_frames=np.array([[5], [7]]), + discard_frames=np.zeros((frames, 1), bool), + frame_line_idxs=np.arange(1, frames + 1).reshape(-1, 1), + offlineXshifts=col, + offlineYshifts=-col, + offlineZshifts=0 * col, + onlineXshifts=col, + onlineYshifts=col, + onlineZshifts=col, + ) + path = PathSummary( + path_index=0, + sources=sources, + visualizations=Visualizations( + mean_im=rng.random((ch, 1, H, W)), + act_im=rng.random((1, H, W)), + act_im_peaks=np.array([[0, 3, 4], [0, 4, 5], [0, 9, 9]]), + ), + frame_info=frame_info, + global_f=rng.random((ch, frames)), + z_depths=np.array([12.5]), + ) + return ExperimentSummary(paths=[path], params={"analyzeHz": 100.0}) + + +BAND_DATASETS = { + "row_major", + "params/analyzeHz", + "Path1/Z_depths", + "Path1/sources/spatial/profiles", + "Path1/sources/spatial/coords", + "Path1/sources/temporal/dF_ls", + "Path1/sources/temporal/dF_denoised", + "Path1/sources/temporal/events", + "Path1/sources/temporal/F0", + "Path1/sources/temporal/SNR", + "Path1/frame_info/trial_num_frames", + "Path1/frame_info/discard_frames", + "Path1/frame_info/frame_line_idxs", + "Path1/frame_info/offlineXshifts", + "Path1/frame_info/offlineYshifts", + "Path1/frame_info/offlineZshifts", + "Path1/frame_info/onlineXshifts", + "Path1/frame_info/onlineYshifts", + "Path1/frame_info/onlineZshifts", + "Path1/global/F", + "Path1/visualizations/act_im", + "Path1/visualizations/mean_im", + "Path1/visualizations/act_im_peaks", + "Path1/user_rois/mask", + "Path1/user_rois/F", + "Path1/user_rois/Fsvd", + "Path1/user_rois/labels", +} + + +def test_band_schema_unchanged(tmp_path: Path) -> None: + """A BandSILo model writes exactly the band datasets and reads back unchanged. + + It writes no raster field and no root attribute. + """ + s = _band_summary() + out = tmp_path / "band.h5" + s.to_h5(out) + names = set() + with h5py.File(out, "r") as f: + f.visititems(lambda name, obj: names.add(name) if isinstance(obj, h5py.Dataset) else None) + assert dict(f.attrs) == {} + assert dict(f["Path1/user_rois"].attrs) == {"annotation_enabled": False} + assert names == BAND_DATASETS + back = ExperimentSummary.from_h5(out) + p = back.paths[0] + assert p.rejected == {} and p.spots is None and back.attrs == {} + assert p.visualizations.f0_im is None + assert all(x.kinetic_score is None for x in p.sources) + _equal(p.sources, s.paths[0].sources) + _equal(p.frame_info, s.paths[0].frame_info) + np.testing.assert_array_equal(p.z_depths, [[12.5]]) + + +def test_partial_raster_scalars_are_refused(tmp_path: Path) -> None: + """A raster field set for some sources only cannot be written.""" + s = _band_summary() + s.paths[0].sources[0].kinetic_score = 0.5 + with pytest.raises(ValueError, match="kinetic_score"): + s.to_h5(tmp_path / "x.h5") + + +def test_raster_round_trip_without_snr( + written: tuple[Path, Path, PathResult], # noqa: F811 + tmp_path: Path, +) -> None: + """A raster file without SNR (no trial gave one) stays without it.""" + exp, _, _ = written + with h5py.File(exp, "a") as f: + del f["Path1/sources/temporal/SNR"] + s = ExperimentSummary.from_h5(exp) + assert all(x.snr is None for x in s.paths[0].sources) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert "SNR" not in f["Path1/sources/temporal"] + _equal(ExperimentSummary.from_h5(out), s) + # a model built in memory with no SNR still gets NaN, as before + band = _band_summary() + for x in band.paths[0].sources: + x.snr = None + band.to_h5(tmp_path / "band.h5") + with h5py.File(tmp_path / "band.h5", "r") as f: + assert np.isnan(f["Path1/sources/temporal/SNR"][()]).all() + + +def test_raster_path_without_frames(tmp_path: Path) -> None: + """A raster path without frames (no trial loaded) is written back and reads the same. + + It has no global trace, no sources and ROI masks without traces. + """ + plan = make_plan() + result = PathResult( + plan=plan, + trials=[None, None, None], + alignment=[None, None, None], + roi_labels=["soma"], + roi_masks=[np.ones((H, W), bool)], + ) + params = SiloParams(f0_im_trim_s=None).to_matlab(C, 80.0, 4, "a", "b") + exp = tmp_path / "experiment_summary.h5" + write_summaries(exp, tmp_path / "per.h5", [result], params, N_TRIALS, C, 1) + s = ExperimentSummary.from_h5(exp) + p = s.paths[0] + assert p.global_f is None and p.sources == [] + assert [r.label for r in p.user_rois] == ["soma"] + assert p.user_rois[0].f is None and p.user_rois[0].fsvd is None + assert p.user_rois[0].mask.shape == (1, H, W) + np.testing.assert_array_equal(p.frame_info.trial_num_frames.ravel(), 0) + out = tmp_path / "rewritten.h5" + s.to_h5(out) + with h5py.File(out, "r") as f: + assert f["Path1/sources/temporal/dF_ls"].shape == (0, C, 0) + assert "F" not in f["Path1/user_rois"] + assert f["Path1/user_rois/mask"].shape == (1, 1, H, W) + assert "global" not in f["Path1"] + _equal(ExperimentSummary.from_h5(out), s) + + +def test_files_without_the_flag_are_refused(tmp_path: Path) -> None: + """A nonempty file without /row_major reads as column-major: refused. + + A new (empty) file is made row-major. + """ + old = tmp_path / "old.h5" + with h5py.File(old, "w") as f: + f["Path1/Z_depths"] = np.zeros((1, 1)) + with pytest.raises(ValueError, match="no /row_major"): + _band_summary().to_h5(old) + new = tmp_path / "new.h5" + h5py.File(new, "w").close() + _band_summary().to_h5(new) + with h5py.File(new, "r") as f: + assert int(np.asarray(f["row_major"][()]).ravel()[0]) == 1 + + +def test_partial_roi_traces_are_refused(tmp_path: Path) -> None: + """ROIs of which only some have a trace cannot be written.""" + from giant_python.models.experiment_summary import UserRoi + + s = _band_summary() + p = s.paths[0] + p.annotation_enabled = True + mask = np.ones((1, H, W), bool) + p.user_rois = [ + UserRoi(label="a", mask=mask, f=p.global_f.copy()), + UserRoi(label="b", mask=mask), + ] + with pytest.raises(ValueError, match="UserRoi.f"): + s.to_h5(tmp_path / "x.h5") diff --git a/tests/registration/__init__.py b/tests/registration/__init__.py index ff03927e..8733c905 100644 --- a/tests/registration/__init__.py +++ b/tests/registration/__init__.py @@ -1 +1 @@ -"""Tests of SLAP2 raster registration.""" +"""Tests of SLAP2 raster registration.""" diff --git a/tests/registration/synthetic.py b/tests/registration/synthetic.py index c6b5bfc7..d84a4d9f 100644 --- a/tests/registration/synthetic.py +++ b/tests/registration/synthetic.py @@ -1,230 +1,230 @@ -"""A small synthetic SLAP2 raster recording with known motion. - -The file mimics the raw layout that giant_python.io.slap2_raster reads: -a header, then cycles of P lines, each line a header (with online-motion -fields) followed by its samples, channel by channel. The parse-plan side is -given directly as a :class:`RasterLayout`. -""" - -from pathlib import Path - -import numpy as np -from numpy.typing import ArrayLike -from scipy.ndimage import gaussian_filter, map_coordinates - -from giant_python.io.slap2_raster import RasterLayout, lit_mirrors - -HEADER_WORDS = 68 -LINE_HEADER_BYTES = 40 - - -def make_layout( - path: Path, - n_cycles: int, - seed: int = 0, - p: int = 7, - curtain: ArrayLike | None = None, - shear: ArrayLike | None = None, -) -> RasterLayout: - """Layout of a synthetic recording (the data file is not written). - - Pixels of the raster block (rows 8-27, columns 10-39 of a 36 x 50 DMD) - are each assigned to 1-3 of the lines 2..p (line 1 has no samples), in - random order within a line. curtain ([c1, c2]) and shear (per - DMD row, default zeros) set the layout's DMD curtain. - - Returns - ------- - RasterLayout - The layout of the synthetic recording. - """ - rng = np.random.default_rng(seed) - n_rows, n_cols, n_ch = 36, 50, 2 - rr, cc = np.meshgrid(np.arange(8, 28), np.arange(10, 40), indexing="ij") - pix = (rr * n_cols + cc).ravel() + 1 - lines = {line: [] for line in range(1, p + 1)} - for px in pix: - for line in rng.choice(np.arange(2, p + 1), rng.integers(1, 4), False): - lines[int(line)].append(px) - slot_line, slot_pos, slot_pixel, n_per = [], [], [], [] - for line in range(1, p + 1): - ids = np.array(lines[line], dtype=np.int64) - rng.shuffle(ids) - slot_line += [line] * ids.size - slot_pos += list(range(ids.size)) - slot_pixel += list(ids) - n_per.append(ids.size) - n_per = np.array(n_per) - header_words = LINE_HEADER_BYTES // 2 - line_words = header_words + n_ch * n_per - line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) - return RasterLayout( - files=(str(path),), - file_cycles=np.array([n_cycles]), - file_offset_words=np.array([HEADER_WORDS]), - words_per_cycle=int(line_words.sum()), - lines_per_cycle=p, - n_rows=n_rows, - n_cols=n_cols, - num_channels=n_ch, - line_period_s=1 / 1600.0, - line_header_bytes=LINE_HEADER_BYTES, - line_header_words=line_header, - row_base=line_header + header_words, - n_per_channel=n_per, - line_fast_z=np.ones(p, dtype=np.int64), - fast_zs=np.array([-20.0]), - slot_line=np.array(slot_line), - slot_pos=np.array(slot_pos), - slot_pixel=np.array(slot_pixel), - dmd_curtain=None if curtain is None else np.asarray(curtain, float), - line_shear=( - None if curtain is None else np.zeros(n_rows) if shear is None else np.asarray(shear) - ), - ) - - -def scene(layout: RasterLayout, seed: int = 1) -> np.ndarray: - """Smooth random brightness pattern over the DMD (photons/sample). - - Returns - ------- - np.ndarray - The brightness of each DMD pixel, of shape (n_rows, n_cols), from 2 to 62. - """ - rng = np.random.default_rng(seed) - img = gaussian_filter(rng.random((layout.n_rows, layout.n_cols)), 1.5) - img = (img - img.min()) / (img.max() - img.min()) - return 2.0 + 60.0 * img**2 - - -def motion(n_lines: int, seed: int = 2) -> np.ndarray: - """Known tissue motion (lines, 2) [rows, cols], within +-2 px. - - Returns - ------- - np.ndarray - The motion of each line, of shape (n_lines, 2): rows, then columns. - """ - t = np.arange(n_lines) / n_lines - rng = np.random.default_rng(seed) - ph = rng.random(2) * 2 * np.pi - return np.stack( - [ - 1.6 * np.sin(2 * np.pi * 1.3 * t + ph[0]), - 1.2 * np.sin(2 * np.pi * 0.7 * t + ph[1]), - ], - 1, - ) - - -def online_offsets(n_lines: int, seed: int = 4) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Piecewise-constant online offsets and the y they put on the DMD. - - The correction switches every 37-80 lines; at a switch x, y or both - change. The header records both on the switch line; x reaches the DMD - then, y 2 lines earlier (6 when x changes too), as measured on SLAP2. - - Returns - ------- - x, y_header, y_dmd : ndarray of int - Per line (index line - 1). - """ - rng = np.random.default_rng(seed) - x = np.zeros(n_lines, dtype=np.int64) - y = np.zeros(n_lines, dtype=np.int64) - switches = [] - s, cur = 0, (2, 0) - while s < n_lines: - nxt = s + int(rng.integers(37, 81)) - kind = int(rng.integers(3)) # 0: x changes, 1: y changes, 2: both - new = cur - if s: - new = ( - int(rng.integers(1, 4)) if kind != 1 else cur[0], - int(rng.integers(-1, 2)) if kind != 0 else cur[1], - ) - switches.append((s, new[0] != cur[0], new[1] != cur[1])) - x[s:nxt], y[s:nxt] = new - cur, s = new, nxt - y_dmd = y.copy() - for s, x_changed, y_changed in switches: - if y_changed: - lead = 6 if x_changed else 2 - y_dmd[s - lead : s] = y[s] - return x, y, y_dmd - - -def write_recording( - layout: RasterLayout, - seed: int = 3, - invalid: float = 0.0, - online: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None, -) -> np.ndarray: - """Write Poisson samples of the moving scene; return the true motion. - - The sample of pixel (r, c) on line l is the scene at - (r - m_r(l), c - m_c(l)); channel 2 sees 0.5 x the scene. Line - headers record online offsets x = cycle % 3, y = -(cycle % 2) and - z = 0.25 * cycle. A fraction invalid of samples is -32768. - - With online = (x, y_header, y_dmd) (see :func:`online_offsets`) the - headers record those offsets and the DMD pattern moves with them, as in - GIAnT-MATLAB's transplant recordings: the sample is the scene at - (r + y_dmd(l) - m_r(l), c + x(l) - m_c(l)). With a DMD curtain in - the layout, samples whose mirror (r + y_dmd(l), c + x(l)) is - behind it get no light (expected count 0). - - Returns - ------- - np.ndarray - The true motion of each line, of shape (lines, 2) [rows, cols]. - """ - rng = np.random.default_rng(seed) - p = layout.lines_per_cycle - n_c = layout.num_cycles - n_lines = n_c * p - m = motion(n_lines) - if online is None: - cyc = np.arange(n_lines) // p - x_h, y_h, y_d = cyc % 3, -(cyc % 2), np.zeros(n_lines, np.int64) - shift_x = np.zeros(n_lines, np.int64) - else: - x_h, y_h, y_d = online - shift_x = x_h - img = scene(layout) - words = np.zeros((n_c, layout.words_per_cycle), dtype=np.int16) - pr = (layout.slot_pixel - 1) // layout.n_cols - pc = (layout.slot_pixel - 1) % layout.n_cols - for c in range(n_c): - for line in range(1, p + 1): - hdr = layout.line_header_words[line - 1] - raw = np.zeros(LINE_HEADER_BYTES, dtype=np.uint8) - ln = c * p + line - 1 - raw[20:22] = np.array([x_h[ln]], np.int16).view(np.uint8) - raw[22:24] = np.array([y_h[ln]], np.int16).view(np.uint8) - raw[32:36] = np.array([0.25 * c], np.float32).view(np.uint8) - words[c, hdr : hdr + LINE_HEADER_BYTES // 2] = raw.view(np.int16) - sel = np.flatnonzero(layout.slot_line == line) - if sel.size == 0: - continue - lam = map_coordinates( - img, - [ - pr[sel] + y_d[ln] - m[ln, 0], - pc[sel] + shift_x[ln] - m[ln, 1], - ], - order=1, - mode="nearest", - ) - if layout.dmd_curtain is not None: - lam = lam * lit_mirrors(layout, pr[sel] + y_d[ln], pc[sel] + x_h[ln]) - for ch, gain in enumerate((1.0, 0.5)): - x = rng.poisson(gain * lam).astype(np.int16) - x[rng.random(x.size) < invalid] = -32768 - base = layout.row_base[line - 1] + ch * layout.n_per_channel[line - 1] - words[c, base + layout.slot_pos[sel]] = x - with open(layout.files[0], "wb") as f: - f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) - f.write(words.tobytes()) - return m +"""A small synthetic SLAP2 raster recording with known motion. + +The file mimics the raw layout that giant_python.io.slap2_raster reads: +a header, then cycles of P lines, each line a header (with online-motion +fields) followed by its samples, channel by channel. The parse-plan side is +given directly as a :class:`RasterLayout`. +""" + +from pathlib import Path + +import numpy as np +from numpy.typing import ArrayLike +from scipy.ndimage import gaussian_filter, map_coordinates + +from giant_python.io.slap2_raster import RasterLayout, lit_mirrors + +HEADER_WORDS = 68 +LINE_HEADER_BYTES = 40 + + +def make_layout( + path: Path, + n_cycles: int, + seed: int = 0, + p: int = 7, + curtain: ArrayLike | None = None, + shear: ArrayLike | None = None, +) -> RasterLayout: + """Layout of a synthetic recording (the data file is not written). + + Pixels of the raster block (rows 8-27, columns 10-39 of a 36 x 50 DMD) + are each assigned to 1-3 of the lines 2..p (line 1 has no samples), in + random order within a line. curtain ([c1, c2]) and shear (per + DMD row, default zeros) set the layout's DMD curtain. + + Returns + ------- + RasterLayout + The layout of the synthetic recording. + """ + rng = np.random.default_rng(seed) + n_rows, n_cols, n_ch = 36, 50, 2 + rr, cc = np.meshgrid(np.arange(8, 28), np.arange(10, 40), indexing="ij") + pix = (rr * n_cols + cc).ravel() + 1 + lines = {line: [] for line in range(1, p + 1)} + for px in pix: + for line in rng.choice(np.arange(2, p + 1), rng.integers(1, 4), False): + lines[int(line)].append(px) + slot_line, slot_pos, slot_pixel, n_per = [], [], [], [] + for line in range(1, p + 1): + ids = np.array(lines[line], dtype=np.int64) + rng.shuffle(ids) + slot_line += [line] * ids.size + slot_pos += list(range(ids.size)) + slot_pixel += list(ids) + n_per.append(ids.size) + n_per = np.array(n_per) + header_words = LINE_HEADER_BYTES // 2 + line_words = header_words + n_ch * n_per + line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) + return RasterLayout( + files=(str(path),), + file_cycles=np.array([n_cycles]), + file_offset_words=np.array([HEADER_WORDS]), + words_per_cycle=int(line_words.sum()), + lines_per_cycle=p, + n_rows=n_rows, + n_cols=n_cols, + num_channels=n_ch, + line_period_s=1 / 1600.0, + line_header_bytes=LINE_HEADER_BYTES, + line_header_words=line_header, + row_base=line_header + header_words, + n_per_channel=n_per, + line_fast_z=np.ones(p, dtype=np.int64), + fast_zs=np.array([-20.0]), + slot_line=np.array(slot_line), + slot_pos=np.array(slot_pos), + slot_pixel=np.array(slot_pixel), + dmd_curtain=None if curtain is None else np.asarray(curtain, float), + line_shear=( + None if curtain is None else np.zeros(n_rows) if shear is None else np.asarray(shear) + ), + ) + + +def scene(layout: RasterLayout, seed: int = 1) -> np.ndarray: + """Smooth random brightness pattern over the DMD (photons/sample). + + Returns + ------- + np.ndarray + The brightness of each DMD pixel, of shape (n_rows, n_cols), from 2 to 62. + """ + rng = np.random.default_rng(seed) + img = gaussian_filter(rng.random((layout.n_rows, layout.n_cols)), 1.5) + img = (img - img.min()) / (img.max() - img.min()) + return 2.0 + 60.0 * img**2 + + +def motion(n_lines: int, seed: int = 2) -> np.ndarray: + """Known tissue motion (lines, 2) [rows, cols], within +-2 px. + + Returns + ------- + np.ndarray + The motion of each line, of shape (n_lines, 2): rows, then columns. + """ + t = np.arange(n_lines) / n_lines + rng = np.random.default_rng(seed) + ph = rng.random(2) * 2 * np.pi + return np.stack( + [ + 1.6 * np.sin(2 * np.pi * 1.3 * t + ph[0]), + 1.2 * np.sin(2 * np.pi * 0.7 * t + ph[1]), + ], + 1, + ) + + +def online_offsets(n_lines: int, seed: int = 4) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Piecewise-constant online offsets and the y they put on the DMD. + + The correction switches every 37-80 lines; at a switch x, y or both + change. The header records both on the switch line; x reaches the DMD + then, y 2 lines earlier (6 when x changes too), as measured on SLAP2. + + Returns + ------- + x, y_header, y_dmd : ndarray of int + Per line (index line - 1). + """ + rng = np.random.default_rng(seed) + x = np.zeros(n_lines, dtype=np.int64) + y = np.zeros(n_lines, dtype=np.int64) + switches = [] + s, cur = 0, (2, 0) + while s < n_lines: + nxt = s + int(rng.integers(37, 81)) + kind = int(rng.integers(3)) # 0: x changes, 1: y changes, 2: both + new = cur + if s: + new = ( + int(rng.integers(1, 4)) if kind != 1 else cur[0], + int(rng.integers(-1, 2)) if kind != 0 else cur[1], + ) + switches.append((s, new[0] != cur[0], new[1] != cur[1])) + x[s:nxt], y[s:nxt] = new + cur, s = new, nxt + y_dmd = y.copy() + for s, x_changed, y_changed in switches: + if y_changed: + lead = 6 if x_changed else 2 + y_dmd[s - lead : s] = y[s] + return x, y, y_dmd + + +def write_recording( + layout: RasterLayout, + seed: int = 3, + invalid: float = 0.0, + online: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None, +) -> np.ndarray: + """Write Poisson samples of the moving scene; return the true motion. + + The sample of pixel (r, c) on line l is the scene at + (r - m_r(l), c - m_c(l)); channel 2 sees 0.5 x the scene. Line + headers record online offsets x = cycle % 3, y = -(cycle % 2) and + z = 0.25 * cycle. A fraction invalid of samples is -32768. + + With online = (x, y_header, y_dmd) (see :func:`online_offsets`) the + headers record those offsets and the DMD pattern moves with them, as in + GIAnT-MATLAB's transplant recordings: the sample is the scene at + (r + y_dmd(l) - m_r(l), c + x(l) - m_c(l)). With a DMD curtain in + the layout, samples whose mirror (r + y_dmd(l), c + x(l)) is + behind it get no light (expected count 0). + + Returns + ------- + np.ndarray + The true motion of each line, of shape (lines, 2) [rows, cols]. + """ + rng = np.random.default_rng(seed) + p = layout.lines_per_cycle + n_c = layout.num_cycles + n_lines = n_c * p + m = motion(n_lines) + if online is None: + cyc = np.arange(n_lines) // p + x_h, y_h, y_d = cyc % 3, -(cyc % 2), np.zeros(n_lines, np.int64) + shift_x = np.zeros(n_lines, np.int64) + else: + x_h, y_h, y_d = online + shift_x = x_h + img = scene(layout) + words = np.zeros((n_c, layout.words_per_cycle), dtype=np.int16) + pr = (layout.slot_pixel - 1) // layout.n_cols + pc = (layout.slot_pixel - 1) % layout.n_cols + for c in range(n_c): + for line in range(1, p + 1): + hdr = layout.line_header_words[line - 1] + raw = np.zeros(LINE_HEADER_BYTES, dtype=np.uint8) + ln = c * p + line - 1 + raw[20:22] = np.array([x_h[ln]], np.int16).view(np.uint8) + raw[22:24] = np.array([y_h[ln]], np.int16).view(np.uint8) + raw[32:36] = np.array([0.25 * c], np.float32).view(np.uint8) + words[c, hdr : hdr + LINE_HEADER_BYTES // 2] = raw.view(np.int16) + sel = np.flatnonzero(layout.slot_line == line) + if sel.size == 0: + continue + lam = map_coordinates( + img, + [ + pr[sel] + y_d[ln] - m[ln, 0], + pc[sel] + shift_x[ln] - m[ln, 1], + ], + order=1, + mode="nearest", + ) + if layout.dmd_curtain is not None: + lam = lam * lit_mirrors(layout, pr[sel] + y_d[ln], pc[sel] + x_h[ln]) + for ch, gain in enumerate((1.0, 0.5)): + x = rng.poisson(gain * lam).astype(np.int16) + x[rng.random(x.size) < invalid] = -32768 + base = layout.row_base[line - 1] + ch * layout.n_per_channel[line - 1] + words[c, base + layout.slot_pos[sel]] = x + with open(layout.files[0], "wb") as f: + f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) + f.write(words.tobytes()) + return m diff --git a/tests/registration/test_compensation.py b/tests/registration/test_compensation.py index 7389f024..d2a9a184 100644 --- a/tests/registration/test_compensation.py +++ b/tests/registration/test_compensation.py @@ -1,229 +1,229 @@ -"""Online-motion compensation (compensateOnline) on synthetic data.""" - -from collections.abc import Sequence -from pathlib import Path - -import numpy as np -import pytest -import torch - -from giant_python.io.slap2_raster import RasterLayout -from giant_python.registration import multiroi -from giant_python.registration.compensation import ( - LineOffsets, - dmd_y, - frame_offsets, - line_offsets, -) -from giant_python.registration.sources import make_source - -from .synthetic import make_layout, online_offsets, write_recording - -# the layout, its online offsets (x, y_header, y_dmd) and the true motion -OnlineRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] - - -def test_dmd_y_leads_header_switches() -> None: - """Y switches 2 lines early, 6 with x, never before the last switch.""" - x = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) - y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 7, 7]) - sw = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 - got = dmd_y(x, y, sw) - # y switch at line index 8 (x unchanged): lines 6-7 take it; the - # switch at 14 (x unchanged): lines 12-13; none before index 10 (x) - want = y.copy() - want[6:8] = 5 - want[12:14] = 7 - np.testing.assert_array_equal(got, want) - x2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 3, 3]) - y2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 4, 4]) - sw2 = np.array([9]) - np.testing.assert_array_equal(dmd_y(x2, y2, sw2), [0, 0, 4, 4, 4, 4, 4, 4, 4, 4]) - - -@pytest.fixture(scope="module") -def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: - """Synthetic recording whose online offsets move the DMD pattern. - - Returns - ------- - OnlineRecording - The raster layout, its online offsets (x, y_header, y_dmd) and the true - motion. - """ - path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400, seed=5) - online = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=online) - return layout, online, truth - - -def test_line_offsets_reproduce_dmd_timing(online_recording: OnlineRecording) -> None: - """Headers decode, y_eff equals the generator's DMD y.""" - layout, (x, y, y_dmd), _ = online_recording - off = line_offsets(layout, (1, layout.total_lines)) - np.testing.assert_array_equal(off.x, x) - np.testing.assert_array_equal(off.y, y) - np.testing.assert_array_equal(off.y_eff, y_dmd) - part = line_offsets(layout, (2000, 3000)) - lo, hi = part.lines_read - assert lo <= 2000 - 7 and hi >= 3000 + 7 - # exact on the requested lines - np.testing.assert_array_equal(part.y_eff[1999:3000], y_dmd[1999:3000]) - assert part.x[0] == x[lo - 1] and part.x[-1] == x[hi - 1] - - -def frames_reference( - layout: RasterLayout, - former_samples: np.ndarray, - offsets: LineOffsets, - times: np.ndarray, - dt: int, - box: Sequence[int], -) -> tuple[np.ndarray, np.ndarray]: - """Compensated weighted means by the definition (slow loops). - - Returns - ------- - num : np.ndarray - (channels, frames, h, w) sums of the weighted, compensated samples - landing on each pixel of box. - den : np.ndarray - Same shape as num: the sums of the weights, so num / den is the - compensated weighted mean. - """ - p, total = layout.lines_per_cycle, layout.total_lines - r0, r1, c0, c1 = box - h, w = r1 - r0 + 1, c1 - c0 + 1 - refs = frame_offsets(offsets, times, dt, p) - dt_read = max(3 * dt, p) - num = np.zeros((layout.num_channels, len(times), h, w)) - den = np.zeros_like(num) - pr = (layout.slot_pixel - 1) // layout.n_cols - pc = (layout.slot_pixel - 1) % layout.n_cols - for f, t in enumerate(times): - for ln in range(max(1, t - dt_read), min(total, t + dt_read) + 1): - wt = np.exp(-abs(t - ln) / dt) - sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) - r = pr[sel] + offsets.y_eff[ln - 1] - refs[f, 1] - r0 - c = pc[sel] + offsets.x[ln - 1] - refs[f, 0] - c0 - ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) - for ch in range(layout.num_channels): - xv = former_samples[ch, sel, (ln - 1) // p].astype(float) - np.add.at(num[ch, f], (r[ok], c[ok]), wt * xv[ok]) - np.add.at(den[ch, f], (r[ok], c[ok]), wt) - return num, den - - -def test_compensated_frames_match_definition(online_recording: OnlineRecording) -> None: - """Each sample moves by its line's offset minus the frame's.""" - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.registration.frames import FrameFormer - - layout, _, _ = online_recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - former = FrameFormer(layout, samples, 0) - times = np.array([400, 1210, 3333, 5000]) - src = make_source(layout, former, 300, 6000, times, times, 20, True) - vals, fresh = src.frames(times) - box = ( - former.rows.min(), - former.rows.max(), - former.cols.min(), - former.cols.max(), - ) - num, den = frames_reference(layout, samples, src.compensation, times, 20, box) - with np.errstate(invalid="ignore"): - want = (num / den).astype(np.float32) - got = src.window.image(vals, float("nan")).numpy() - np.testing.assert_array_equal(np.isnan(got), np.isnan(want)) - np.testing.assert_allclose(got, want, rtol=1e-6) - np.testing.assert_allclose(src.window.image(fresh, 0.0).numpy(), den[0], rtol=1e-6) - - -def total_motion_error( - res: multiroi.TrialRegistration, - adata: dict, - truth: np.ndarray, - header: tuple[np.ndarray, np.ndarray], -) -> float: - """RMS error of the total motion against the kernel-averaged truth. - - Compensated: motion plus each frame's reference offset (relative to - refOffset). Uncompensated: motion plus the header offsets at the - frame's line (header = (x, y)), as GIAnT-MATLAB's transplant - evaluation adds them. - - Returns - ------- - float - Root-mean-square error of the motion estimate after removing its median - offset from the truth. - """ - dt = 20 - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - true = np.stack([np.convolve(truth[:, i], kernel, "same") for i in (0, 1)])[ - :, res.ds_frames - 1 - ] - est = np.stack([res.motion_r, res.motion_c]) - oc = adata["slap2"]["onlineCompensation"] - if oc["enabled"].item(): - ref = oc["refOffset"].ravel() - est = est + np.stack([ - oc["frameRefY"].ravel() - ref[1], - oc["frameRefX"].ravel() - ref[0], - ]) - else: - x, y = header - est = est + np.stack([y[res.ds_frames - 1], x[res.ds_frames - 1]]) - err = est - true - err -= np.median(err, axis=1, keepdims=True) - return float(np.sqrt(np.mean(err**2))) - - -def test_compensated_registration_recovers_motion( - online_recording: OnlineRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Total motion follows the truth with compensation, not without.""" - from giant_python.io.hdf5 import load_struct_h5 - - layout, (x, y, _), truth = online_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - errors = {} - for comp in (True, False): - params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) - res = multiroi.register_trial( - layout.files[0], - 1, - 9000, - tmp_path / f"{comp}.tif", - tmp_path / f"{comp}.h5", - params, - ) - adata = load_struct_h5(tmp_path / f"{comp}.h5") - errors[comp] = total_motion_error(res, adata, truth, (x, y)) - oc = adata["slap2"]["onlineCompensation"] - assert oc["enabled"].item() == int(comp) - oc = load_struct_h5(tmp_path / "True.h5")["slap2"]["onlineCompensation"] - assert np.ptp(oc["frameRefX"]) >= 1 and np.ptp(oc["frameRefY"]) >= 1 - assert errors[True] < 0.1 - assert errors[True] < errors[False] / 3 - - -def test_compensation_on_cuda_matches_cpu(online_recording: OnlineRecording) -> None: - """Compensated frames agree on CUDA and CPU (skipped without a GPU).""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - from giant_python.io.slap2_raster import read_raster_samples - from giant_python.registration.frames import FrameFormer - - layout, _, _ = online_recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - times = np.array([500, 2500, 4100]) - out = [] - for dev in ("cpu", "cuda"): - former = FrameFormer(layout, samples, 0, device=dev) - src = make_source(layout, former, 300, 6000, times, times, 20, True) - out.append(src.frames(times)[0].cpu().numpy()) - np.testing.assert_allclose(out[0], out[1], rtol=1e-6, equal_nan=True) +"""Online-motion compensation (compensateOnline) on synthetic data.""" + +from collections.abc import Sequence +from pathlib import Path + +import numpy as np +import pytest +import torch + +from giant_python.io.slap2_raster import RasterLayout +from giant_python.registration import multiroi +from giant_python.registration.compensation import ( + LineOffsets, + dmd_y, + frame_offsets, + line_offsets, +) +from giant_python.registration.sources import make_source + +from .synthetic import make_layout, online_offsets, write_recording + +# the layout, its online offsets (x, y_header, y_dmd) and the true motion +OnlineRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] + + +def test_dmd_y_leads_header_switches() -> None: + """Y switches 2 lines early, 6 with x, never before the last switch.""" + x = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) + y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 7, 7]) + sw = np.flatnonzero((np.diff(x) != 0) | (np.diff(y) != 0)) + 2 + got = dmd_y(x, y, sw) + # y switch at line index 8 (x unchanged): lines 6-7 take it; the + # switch at 14 (x unchanged): lines 12-13; none before index 10 (x) + want = y.copy() + want[6:8] = 5 + want[12:14] = 7 + np.testing.assert_array_equal(got, want) + x2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 3, 3]) + y2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 4, 4]) + sw2 = np.array([9]) + np.testing.assert_array_equal(dmd_y(x2, y2, sw2), [0, 0, 4, 4, 4, 4, 4, 4, 4, 4]) + + +@pytest.fixture(scope="module") +def online_recording(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: + """Synthetic recording whose online offsets move the DMD pattern. + + Returns + ------- + OnlineRecording + The raster layout, its online offsets (x, y_header, y_dmd) and the true + motion. + """ + path = tmp_path_factory.mktemp("rec") / "online_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400, seed=5) + online = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=online) + return layout, online, truth + + +def test_line_offsets_reproduce_dmd_timing(online_recording: OnlineRecording) -> None: + """Headers decode, y_eff equals the generator's DMD y.""" + layout, (x, y, y_dmd), _ = online_recording + off = line_offsets(layout, (1, layout.total_lines)) + np.testing.assert_array_equal(off.x, x) + np.testing.assert_array_equal(off.y, y) + np.testing.assert_array_equal(off.y_eff, y_dmd) + part = line_offsets(layout, (2000, 3000)) + lo, hi = part.lines_read + assert lo <= 2000 - 7 and hi >= 3000 + 7 + # exact on the requested lines + np.testing.assert_array_equal(part.y_eff[1999:3000], y_dmd[1999:3000]) + assert part.x[0] == x[lo - 1] and part.x[-1] == x[hi - 1] + + +def frames_reference( + layout: RasterLayout, + former_samples: np.ndarray, + offsets: LineOffsets, + times: np.ndarray, + dt: int, + box: Sequence[int], +) -> tuple[np.ndarray, np.ndarray]: + """Compensated weighted means by the definition (slow loops). + + Returns + ------- + num : np.ndarray + (channels, frames, h, w) sums of the weighted, compensated samples + landing on each pixel of box. + den : np.ndarray + Same shape as num: the sums of the weights, so num / den is the + compensated weighted mean. + """ + p, total = layout.lines_per_cycle, layout.total_lines + r0, r1, c0, c1 = box + h, w = r1 - r0 + 1, c1 - c0 + 1 + refs = frame_offsets(offsets, times, dt, p) + dt_read = max(3 * dt, p) + num = np.zeros((layout.num_channels, len(times), h, w)) + den = np.zeros_like(num) + pr = (layout.slot_pixel - 1) // layout.n_cols + pc = (layout.slot_pixel - 1) % layout.n_cols + for f, t in enumerate(times): + for ln in range(max(1, t - dt_read), min(total, t + dt_read) + 1): + wt = np.exp(-abs(t - ln) / dt) + sel = np.flatnonzero(layout.slot_line == (ln - 1) % p + 1) + r = pr[sel] + offsets.y_eff[ln - 1] - refs[f, 1] - r0 + c = pc[sel] + offsets.x[ln - 1] - refs[f, 0] - c0 + ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) + for ch in range(layout.num_channels): + xv = former_samples[ch, sel, (ln - 1) // p].astype(float) + np.add.at(num[ch, f], (r[ok], c[ok]), wt * xv[ok]) + np.add.at(den[ch, f], (r[ok], c[ok]), wt) + return num, den + + +def test_compensated_frames_match_definition(online_recording: OnlineRecording) -> None: + """Each sample moves by its line's offset minus the frame's.""" + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.registration.frames import FrameFormer + + layout, _, _ = online_recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + former = FrameFormer(layout, samples, 0) + times = np.array([400, 1210, 3333, 5000]) + src = make_source(layout, former, 300, 6000, times, times, 20, True) + vals, fresh = src.frames(times) + box = ( + former.rows.min(), + former.rows.max(), + former.cols.min(), + former.cols.max(), + ) + num, den = frames_reference(layout, samples, src.compensation, times, 20, box) + with np.errstate(invalid="ignore"): + want = (num / den).astype(np.float32) + got = src.window.image(vals, float("nan")).numpy() + np.testing.assert_array_equal(np.isnan(got), np.isnan(want)) + np.testing.assert_allclose(got, want, rtol=1e-6) + np.testing.assert_allclose(src.window.image(fresh, 0.0).numpy(), den[0], rtol=1e-6) + + +def total_motion_error( + res: multiroi.TrialRegistration, + adata: dict, + truth: np.ndarray, + header: tuple[np.ndarray, np.ndarray], +) -> float: + """RMS error of the total motion against the kernel-averaged truth. + + Compensated: motion plus each frame's reference offset (relative to + refOffset). Uncompensated: motion plus the header offsets at the + frame's line (header = (x, y)), as GIAnT-MATLAB's transplant + evaluation adds them. + + Returns + ------- + float + Root-mean-square error of the motion estimate after removing its median + offset from the truth. + """ + dt = 20 + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + true = np.stack([np.convolve(truth[:, i], kernel, "same") for i in (0, 1)])[ + :, res.ds_frames - 1 + ] + est = np.stack([res.motion_r, res.motion_c]) + oc = adata["slap2"]["onlineCompensation"] + if oc["enabled"].item(): + ref = oc["refOffset"].ravel() + est = est + np.stack([ + oc["frameRefY"].ravel() - ref[1], + oc["frameRefX"].ravel() - ref[0], + ]) + else: + x, y = header + est = est + np.stack([y[res.ds_frames - 1], x[res.ds_frames - 1]]) + err = est - true + err -= np.median(err, axis=1, keepdims=True) + return float(np.sqrt(np.mean(err**2))) + + +def test_compensated_registration_recovers_motion( + online_recording: OnlineRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Total motion follows the truth with compensation, not without.""" + from giant_python.io.hdf5 import load_struct_h5 + + layout, (x, y, _), truth = online_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + errors = {} + for comp in (True, False): + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=comp) + res = multiroi.register_trial( + layout.files[0], + 1, + 9000, + tmp_path / f"{comp}.tif", + tmp_path / f"{comp}.h5", + params, + ) + adata = load_struct_h5(tmp_path / f"{comp}.h5") + errors[comp] = total_motion_error(res, adata, truth, (x, y)) + oc = adata["slap2"]["onlineCompensation"] + assert oc["enabled"].item() == int(comp) + oc = load_struct_h5(tmp_path / "True.h5")["slap2"]["onlineCompensation"] + assert np.ptp(oc["frameRefX"]) >= 1 and np.ptp(oc["frameRefY"]) >= 1 + assert errors[True] < 0.1 + assert errors[True] < errors[False] / 3 + + +def test_compensation_on_cuda_matches_cpu(online_recording: OnlineRecording) -> None: + """Compensated frames agree on CUDA and CPU (skipped without a GPU).""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + from giant_python.io.slap2_raster import read_raster_samples + from giant_python.registration.frames import FrameFormer + + layout, _, _ = online_recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + times = np.array([500, 2500, 4100]) + out = [] + for dev in ("cpu", "cuda"): + former = FrameFormer(layout, samples, 0, device=dev) + src = make_source(layout, former, 300, 6000, times, times, 20, True) + out.append(src.frames(times)[0].cpu().numpy()) + np.testing.assert_allclose(out[0], out[1], rtol=1e-6, equal_nan=True) diff --git a/tests/registration/test_curtain.py b/tests/registration/test_curtain.py index 3fce524d..d54d0d62 100644 --- a/tests/registration/test_curtain.py +++ b/tests/registration/test_curtain.py @@ -1,381 +1,381 @@ -"""Samples taken behind the DMD curtain (GIAnT-Python#66). - -The synthetic recording's online offsets move the pattern by x in 1..3 -columns; the curtain's last lit column is 41 at the raster's top row and 39 -at its bottom row (the line shear), so the raster's right columns (up to 39) -move behind it at the larger offsets, and column 39 of rows 25-27 at all of -them. -""" - -import dataclasses -import types -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.extraction.raster.trial_data import RasterPixelFrames -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2_raster import ( - INVALID_SAMPLE, - RasterLayout, - _dmd_curtain, - lit_mirrors, - read_raster_samples, - unlit_samples, -) -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer - -from .synthetic import make_layout, online_offsets, write_recording - -# the layout, its online offsets (x, y_header, y_dmd) and the tissue's motion -# as the pattern sees it -CurtainRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] - -N_ROWS = 36 -CURTAIN = (0.05, 40.5 / 49 + 1 / 50) # last lit column 40 at zero shear -SHEAR = np.linspace(1.5, -1.5, N_ROWS) -STRIP = (np.array([25, 26, 27]), 39) # zero-based rows and column always unlit - - -@pytest.fixture(scope="module") -def curtain_recording(tmp_path_factory: pytest.TempPathFactory) -> CurtainRecording: - """Layout and online offsets of a recording with a DMD curtain. - - Returns - ------- - CurtainRecording - The layout, the online offsets and the tissue's motion as the pattern sees it. - """ - path = tmp_path_factory.mktemp("rec") / "curtain_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=900, seed=5, curtain=CURTAIN, shear=SHEAR) - online = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=online) - # the tissue's motion as the pattern sees it: the pattern follows the - # online offsets - seen = np.stack([truth[:, 0] - online[2], truth[:, 1] - online[0]], 1) - return layout, online, seen - - -def plain(layout: RasterLayout) -> RasterLayout: - """Return the same layout without a curtain. - - Returns - ------- - RasterLayout - A copy of layout with no DMD curtain and no line shear. - """ - return dataclasses.replace(layout, dmd_curtain=None, line_shear=None) - - -def unlit_by_definition( - layout: RasterLayout, online: tuple[np.ndarray, np.ndarray, np.ndarray], dmd_y: bool = True -) -> np.ndarray: - """(slots, cycles): True where the slot's mirror is behind the curtain. - - The line's offsets (header x, DMD y; the header's y with dmd_y=False) - put the slot's mirror there. - - Returns - ------- - np.ndarray - The (slots, cycles) bool array, True where the slot's mirror is behind the curtain. - """ - x, y = online[0], online[2] if dmd_y else online[1] - p = layout.lines_per_cycle - lines = np.arange(layout.num_cycles)[None, :] * p + layout.slot_line[:, None] - rows = (layout.slot_pixel - 1) // layout.n_cols - cols = (layout.slot_pixel - 1) % layout.n_cols - return ~lit_mirrors(layout, rows[:, None] + y[lines - 1], cols[:, None] + x[lines - 1]) - - -def test_curtain_from_metadata() -> None: - """The acquisition path's curtain and its DMD's line shear.""" - shear = np.arange(4.0) - meta = types.SimpleNamespace( - acquisitionPathName="Path2", - machineConfiguration=[ - { - "instanceName": "Path1", - "configuration": {"dmdCurtain": [0.0, 1.0], "hDmd": "DMD1"}, - }, - { - "instanceName": "Path2", - "configuration": { - "dmdCurtain": np.array([[0.1], [0.9]]), - # slap2_utils gives some strings as character codes - "hDmd": np.array([68, 77, 68, 50], dtype=np.uint16), - }, - }, - {"instanceName": "DMD2", "configuration": {"lineShear": shear}}, - ], - ) - curtain, got = _dmd_curtain(meta, 4) - np.testing.assert_array_equal(curtain, [0.1, 0.9]) - np.testing.assert_array_equal(got, shear) - # a shear without one value per DMD row is taken as none - np.testing.assert_array_equal(_dmd_curtain(meta, 5)[1], np.zeros(5)) - meta.acquisitionPathName = "Path3" - assert _dmd_curtain(meta, 4) == (None, None) - assert _dmd_curtain(types.SimpleNamespace(), 4) == (None, None) - - -def test_lit_mirrors_is_the_softwares_mask(curtain_recording: CurtainRecording) -> None: - """The acquisition software's curtain mask (makeDmdCurtainMask). - - Written out mirror by mirror. - """ - layout = curtain_recording[0] - n = layout.n_cols - want = np.zeros((layout.n_rows, n), dtype=bool) - for r in range(layout.n_rows): - for m in range(n): - frac = m / (n - 1) - SHEAR[r] / n - want[r, m] = CURTAIN[0] + 1 / n <= frac <= CURTAIN[1] - 1 / n - got = lit_mirrors(layout, np.arange(layout.n_rows)[:, None], np.arange(n)[None, :]) - np.testing.assert_array_equal(got, want) - last = n - 1 - np.argmax(got[:, ::-1], 1) - assert last[8] == 41 and last[27] == 39 - - -def test_unlit_samples_follow_the_offsets(curtain_recording: CurtainRecording) -> None: - """Exactly the samples behind the curtain are found. - - They hold no light, and only they are marked invalid. - """ - layout, online, _ = curtain_recording - n_c = layout.num_cycles - want = unlit_by_definition(layout, online) - assert 0 < want.mean() < 0.1 - s, c = unlit_samples(layout, (0, n_c)) - got = np.zeros_like(want) - got[s, c] = True - np.testing.assert_array_equal(got, want) - # the shear follows the y on the DMD, which switches 2-6 lines before - # the header records it - assert np.any(unlit_by_definition(layout, online, dmd_y=False) != want) - raw = read_raster_samples(layout, (0, n_c)) - assert np.all(raw[:, want] == 0) - masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) - assert np.all(masked[:, want] == INVALID_SAMPLE) - np.testing.assert_array_equal(masked[:, ~want], raw[:, ~want]) - # a part of the recording and some of the slots - cols = (layout.slot_pixel - 1) % layout.n_cols - sl = np.flatnonzero(cols >= 36) - part = read_raster_samples(layout, (100, 400), slots=sl, chunk_cycles=64, mask_unlit=True) - np.testing.assert_array_equal(part, masked[:, sl, 100:400]) - # without a curtain in the metadata, the raw values - np.testing.assert_array_equal( - read_raster_samples(plain(layout), (0, n_c), mask_unlit=True), raw - ) - assert unlit_samples(plain(layout), (0, n_c))[0].size == 0 - - -def kernel_hits( - layout: RasterLayout, unlit: np.ndarray, times: np.ndarray, reach: int, pixels: np.ndarray -) -> np.ndarray: - """(frames, pixels): True where a frame's kernel holds an unlit sample. - - The kernel reaches reach lines to each side; True where it holds an - unlit sample of the pixel. - - Returns - ------- - np.ndarray - The (frames, pixels) bool array, True where a frame's kernel holds an unlit sample. - """ - p = layout.lines_per_cycle - s, c = np.nonzero(unlit) - lines = c * p + layout.slot_line[s] - j = np.searchsorted(pixels, layout.slot_pixel[s]) - hit = np.zeros((times.size, pixels.size), dtype=bool) - for f, t in enumerate(times): - near = np.abs(lines - t) <= reach - hit[f, j[near]] = True - return hit - - -def test_frames_give_unlit_samples_no_weight(curtain_recording: CurtainRecording) -> None: - """Pixels whose samples in a frame are all behind the curtain are NaN. - - Pixels with some are the mean of the lit ones, and every other value is - unchanged bit for bit. - """ - layout, online, _ = curtain_recording - n_c = layout.num_cycles - raw = read_raster_samples(layout, (0, n_c)) - masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) - times, dt = np.arange(30, layout.total_lines - 30, 97), 20 - former = FrameFormer(layout, masked, 0) - v_mask = former.frames(times, dt)[0].numpy() - v_raw = FrameFormer(layout, raw, 0).frames(times, dt)[0].numpy() - reach = max(3 * dt, layout.lines_per_cycle) # inclusive boundary - hit = kernel_hits( - layout, - unlit_by_definition(layout, online), - times, - reach, - former.pixels, - ) - assert hit.any() - np.testing.assert_array_equal(v_mask[:, ~hit], v_raw[:, ~hit]) - assert not np.isnan(v_raw).any() - assert not np.isnan(v_mask[:, ~hit]).any() - gone = np.isnan(v_mask[0]) - assert gone.any() and not gone[~hit].any() - # the strip is missing in every frame - strip = np.isin(former.pixels, STRIP[0] * layout.n_cols + STRIP[1] + 1) - assert strip.sum() == STRIP[0].size and gone[:, strip].all() - # where some samples are lit, the dark ones no longer pull values down - some = hit & ~gone - assert np.all(v_mask[:, some] >= v_raw[:, some]) - assert np.mean(v_mask[:, some] > v_raw[:, some]) > 0.5 - - -def test_extraction_frames_give_unlit_samples_no_weight( - curtain_recording: CurtainRecording, -) -> None: - """SILo's raw frames (rawFramesAt) leave out the same samples.""" - layout, online, _ = curtain_recording - ids = np.unique(layout.slot_pixel) - times, dt = np.arange(40, layout.total_lines - 40, 89), 8 - got = RasterPixelFrames(layout, ids, times, dt, [0, 1]).frames(times) - ref = RasterPixelFrames(plain(layout), ids, times, dt, [0, 1]).frames(times) - values = got[0][:, :-1].numpy() # (channels, pixels, frames) - before = ref[0][:, :-1].numpy() - # exclusive boundary: a kernel reaches max(3 dt, P) - 1 lines - reach = max(3 * dt, layout.lines_per_cycle) - 1 - hit = kernel_hits(layout, unlit_by_definition(layout, online), times, reach, ids).T - # equal to rounding: PixelFormer sums the weights of a band with an - # invalid sample in another order than those of a band without one - np.testing.assert_allclose(values[:, ~hit], before[:, ~hit], rtol=1e-14, atol=0) - assert not np.isnan(values[:, ~hit]).any() - strip = np.isin(ids, STRIP[0] * layout.n_cols + STRIP[1] + 1) - assert np.isnan(values[:, strip]).all() - assert not np.isnan(before).any() - - -def test_registration_window_ignores_the_curtain(curtain_recording: CurtainRecording) -> None: - """The registration window is the bounding box of the first frame's pixels. - - Those are the pixels the first frame samples, lit or not: a column behind - the curtain in that frame stays in the window. - """ - from giant_python.registration.sources import _window_pixels - - layout, online, _ = curtain_recording - x = online[0] - dt = 2 - reach = max(3 * dt, layout.lines_per_cycle) - # a frame whose kernel has x = 3 throughout: column 39 is unlit in - # every row - t = next( - t - for t in range(reach + 1, layout.total_lines - reach) - if np.all(x[t - reach - 1 : t + reach] == 3) - ) - n_c = layout.num_cycles - masked = FrameFormer(layout, read_raster_samples(layout, (0, n_c), mask_unlit=True), 0) - raw = FrameFormer(plain(layout), read_raster_samples(layout, (0, n_c)), 0) - values = masked.frames([t], dt)[0].sum(0)[0].numpy() - assert np.isnan(values[masked.cols == 39]).all() - init = np.array([t, t + 500]) - np.testing.assert_array_equal(_window_pixels(masked, init, dt), _window_pixels(raw, init, dt)) - assert _window_pixels(masked, init, dt)[masked.cols == 39].any() - - -def test_registration_leaves_out_the_strip( - curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Registration forms its frames without the unlit samples. - - The strip is missing from the registered movie, and the motion follows the - true motion (with the dark samples, which move with the offsets, it is off - by 0.2-0.5 px rms in this recording). - """ - layout, _, seen = curtain_recording - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - out = {} - for name, lay in (("curtain", layout), ("plain", plain(layout))): - monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) - res = multiroi.register_trial( - layout.files[0], - 1, - layout.total_lines - 200, - tmp_path / f"{name}.tif", - tmp_path / f"{name}.h5", - params, - ) - out[name] = (res, load_struct_h5(tmp_path / f"{name}.h5")) - res, a = out["curtain"] - dt = 1600 / 80 # the kernel that forms the frames - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - for i, est in enumerate((res.motion_r, res.motion_c)): - true = np.convolve(seen[:, i], kernel, "same")[res.ds_frames - 1] - err = est - true - assert np.sqrt(np.mean((err - np.median(err)) ** 2)) < 0.1 - # the registered movies ((frames, columns, rows) in the file): the strip - # is missing in nearly every frame; registration moves the frames by up - # to 2 px, so its neighbours are missing in part of them - trim_r = a["slap2"]["trimRows"].ravel().astype(int) - trim_c = a["slap2"]["trimCols"].ravel().astype(int) - pad = int(params.maxshift) - r = STRIP[0] + 1 - trim_r[0] + pad - c = STRIP[1] + 1 - trim_c[0] + pad - gone = {} - for name in out: - with h5py.File(tmp_path / f"{name}.tif", "r") as f: - gone[name] = np.isnan(f["data"][:, c, r]).mean(0) - assert np.all(gone["curtain"] > 0.9) - assert gone["curtain"].mean() > gone["plain"].mean() + 0.05 - - -def test_reg_stats_follow_the_alignment_file( - curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """``giant reg-stats`` forms the frames as the registration did. - - Without the samples behind the curtain where the alignment file records - slap2/unlitMasked, with them in files registered before. - """ - from giant_python.pipeline.reg_stats import trial_stats - from giant_python.registration.stats.io import read_stats, stats_path - - layout = curtain_recording[0] - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - movie = tmp_path / "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - adata = tmp_path / "E1T1DMD1_ALIGNMENTDATA.h5" - last = layout.total_lines - 200 - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - multiroi.register_trial(layout.files[0], 1, last, movie, adata, params) - from giant_python.registration.outputs import unlit_masked - - assert unlit_masked(adata) - masks = [] - opened = multiroi.open_trial - - def spy(*args: object, **kwargs: object) -> object: - """Record whether each open_trial call masks the unlit samples. - - Returns - ------- - object - What open_trial returns for the same arguments. - """ - masks.append(args[5] if len(args) > 5 else kwargs["mask_unlit"]) - return opened(*args, **kwargs) - - monkeypatch.setattr(multiroi, "open_trial", spy) - cmd = tmp_path / "cmd.h5" - trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) - a, b = read_stats(stats_path(movie)), read_stats(cmd) - for k in a["gain"]: - np.testing.assert_array_equal(a["gain"][k], b["gain"][k], err_msg=k) - with h5py.File(adata, "r+") as f: # as registered before the mask - del f["slap2/unlitMasked"] - assert not unlit_masked(adata) - trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) - assert masks == [True, False] +"""Samples taken behind the DMD curtain (GIAnT-Python#66). + +The synthetic recording's online offsets move the pattern by x in 1..3 +columns; the curtain's last lit column is 41 at the raster's top row and 39 +at its bottom row (the line shear), so the raster's right columns (up to 39) +move behind it at the larger offsets, and column 39 of rows 25-27 at all of +them. +""" + +import dataclasses +import types +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.extraction.raster.trial_data import RasterPixelFrames +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + _dmd_curtain, + lit_mirrors, + read_raster_samples, + unlit_samples, +) +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer + +from .synthetic import make_layout, online_offsets, write_recording + +# the layout, its online offsets (x, y_header, y_dmd) and the tissue's motion +# as the pattern sees it +CurtainRecording = tuple[RasterLayout, tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray] + +N_ROWS = 36 +CURTAIN = (0.05, 40.5 / 49 + 1 / 50) # last lit column 40 at zero shear +SHEAR = np.linspace(1.5, -1.5, N_ROWS) +STRIP = (np.array([25, 26, 27]), 39) # zero-based rows and column always unlit + + +@pytest.fixture(scope="module") +def curtain_recording(tmp_path_factory: pytest.TempPathFactory) -> CurtainRecording: + """Layout and online offsets of a recording with a DMD curtain. + + Returns + ------- + CurtainRecording + The layout, the online offsets and the tissue's motion as the pattern sees it. + """ + path = tmp_path_factory.mktemp("rec") / "curtain_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=900, seed=5, curtain=CURTAIN, shear=SHEAR) + online = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=online) + # the tissue's motion as the pattern sees it: the pattern follows the + # online offsets + seen = np.stack([truth[:, 0] - online[2], truth[:, 1] - online[0]], 1) + return layout, online, seen + + +def plain(layout: RasterLayout) -> RasterLayout: + """Return the same layout without a curtain. + + Returns + ------- + RasterLayout + A copy of layout with no DMD curtain and no line shear. + """ + return dataclasses.replace(layout, dmd_curtain=None, line_shear=None) + + +def unlit_by_definition( + layout: RasterLayout, online: tuple[np.ndarray, np.ndarray, np.ndarray], dmd_y: bool = True +) -> np.ndarray: + """(slots, cycles): True where the slot's mirror is behind the curtain. + + The line's offsets (header x, DMD y; the header's y with dmd_y=False) + put the slot's mirror there. + + Returns + ------- + np.ndarray + The (slots, cycles) bool array, True where the slot's mirror is behind the curtain. + """ + x, y = online[0], online[2] if dmd_y else online[1] + p = layout.lines_per_cycle + lines = np.arange(layout.num_cycles)[None, :] * p + layout.slot_line[:, None] + rows = (layout.slot_pixel - 1) // layout.n_cols + cols = (layout.slot_pixel - 1) % layout.n_cols + return ~lit_mirrors(layout, rows[:, None] + y[lines - 1], cols[:, None] + x[lines - 1]) + + +def test_curtain_from_metadata() -> None: + """The acquisition path's curtain and its DMD's line shear.""" + shear = np.arange(4.0) + meta = types.SimpleNamespace( + acquisitionPathName="Path2", + machineConfiguration=[ + { + "instanceName": "Path1", + "configuration": {"dmdCurtain": [0.0, 1.0], "hDmd": "DMD1"}, + }, + { + "instanceName": "Path2", + "configuration": { + "dmdCurtain": np.array([[0.1], [0.9]]), + # slap2_utils gives some strings as character codes + "hDmd": np.array([68, 77, 68, 50], dtype=np.uint16), + }, + }, + {"instanceName": "DMD2", "configuration": {"lineShear": shear}}, + ], + ) + curtain, got = _dmd_curtain(meta, 4) + np.testing.assert_array_equal(curtain, [0.1, 0.9]) + np.testing.assert_array_equal(got, shear) + # a shear without one value per DMD row is taken as none + np.testing.assert_array_equal(_dmd_curtain(meta, 5)[1], np.zeros(5)) + meta.acquisitionPathName = "Path3" + assert _dmd_curtain(meta, 4) == (None, None) + assert _dmd_curtain(types.SimpleNamespace(), 4) == (None, None) + + +def test_lit_mirrors_is_the_softwares_mask(curtain_recording: CurtainRecording) -> None: + """The acquisition software's curtain mask (makeDmdCurtainMask). + + Written out mirror by mirror. + """ + layout = curtain_recording[0] + n = layout.n_cols + want = np.zeros((layout.n_rows, n), dtype=bool) + for r in range(layout.n_rows): + for m in range(n): + frac = m / (n - 1) - SHEAR[r] / n + want[r, m] = CURTAIN[0] + 1 / n <= frac <= CURTAIN[1] - 1 / n + got = lit_mirrors(layout, np.arange(layout.n_rows)[:, None], np.arange(n)[None, :]) + np.testing.assert_array_equal(got, want) + last = n - 1 - np.argmax(got[:, ::-1], 1) + assert last[8] == 41 and last[27] == 39 + + +def test_unlit_samples_follow_the_offsets(curtain_recording: CurtainRecording) -> None: + """Exactly the samples behind the curtain are found. + + They hold no light, and only they are marked invalid. + """ + layout, online, _ = curtain_recording + n_c = layout.num_cycles + want = unlit_by_definition(layout, online) + assert 0 < want.mean() < 0.1 + s, c = unlit_samples(layout, (0, n_c)) + got = np.zeros_like(want) + got[s, c] = True + np.testing.assert_array_equal(got, want) + # the shear follows the y on the DMD, which switches 2-6 lines before + # the header records it + assert np.any(unlit_by_definition(layout, online, dmd_y=False) != want) + raw = read_raster_samples(layout, (0, n_c)) + assert np.all(raw[:, want] == 0) + masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) + assert np.all(masked[:, want] == INVALID_SAMPLE) + np.testing.assert_array_equal(masked[:, ~want], raw[:, ~want]) + # a part of the recording and some of the slots + cols = (layout.slot_pixel - 1) % layout.n_cols + sl = np.flatnonzero(cols >= 36) + part = read_raster_samples(layout, (100, 400), slots=sl, chunk_cycles=64, mask_unlit=True) + np.testing.assert_array_equal(part, masked[:, sl, 100:400]) + # without a curtain in the metadata, the raw values + np.testing.assert_array_equal( + read_raster_samples(plain(layout), (0, n_c), mask_unlit=True), raw + ) + assert unlit_samples(plain(layout), (0, n_c))[0].size == 0 + + +def kernel_hits( + layout: RasterLayout, unlit: np.ndarray, times: np.ndarray, reach: int, pixels: np.ndarray +) -> np.ndarray: + """(frames, pixels): True where a frame's kernel holds an unlit sample. + + The kernel reaches reach lines to each side; True where it holds an + unlit sample of the pixel. + + Returns + ------- + np.ndarray + The (frames, pixels) bool array, True where a frame's kernel holds an unlit sample. + """ + p = layout.lines_per_cycle + s, c = np.nonzero(unlit) + lines = c * p + layout.slot_line[s] + j = np.searchsorted(pixels, layout.slot_pixel[s]) + hit = np.zeros((times.size, pixels.size), dtype=bool) + for f, t in enumerate(times): + near = np.abs(lines - t) <= reach + hit[f, j[near]] = True + return hit + + +def test_frames_give_unlit_samples_no_weight(curtain_recording: CurtainRecording) -> None: + """Pixels whose samples in a frame are all behind the curtain are NaN. + + Pixels with some are the mean of the lit ones, and every other value is + unchanged bit for bit. + """ + layout, online, _ = curtain_recording + n_c = layout.num_cycles + raw = read_raster_samples(layout, (0, n_c)) + masked = read_raster_samples(layout, (0, n_c), mask_unlit=True) + times, dt = np.arange(30, layout.total_lines - 30, 97), 20 + former = FrameFormer(layout, masked, 0) + v_mask = former.frames(times, dt)[0].numpy() + v_raw = FrameFormer(layout, raw, 0).frames(times, dt)[0].numpy() + reach = max(3 * dt, layout.lines_per_cycle) # inclusive boundary + hit = kernel_hits( + layout, + unlit_by_definition(layout, online), + times, + reach, + former.pixels, + ) + assert hit.any() + np.testing.assert_array_equal(v_mask[:, ~hit], v_raw[:, ~hit]) + assert not np.isnan(v_raw).any() + assert not np.isnan(v_mask[:, ~hit]).any() + gone = np.isnan(v_mask[0]) + assert gone.any() and not gone[~hit].any() + # the strip is missing in every frame + strip = np.isin(former.pixels, STRIP[0] * layout.n_cols + STRIP[1] + 1) + assert strip.sum() == STRIP[0].size and gone[:, strip].all() + # where some samples are lit, the dark ones no longer pull values down + some = hit & ~gone + assert np.all(v_mask[:, some] >= v_raw[:, some]) + assert np.mean(v_mask[:, some] > v_raw[:, some]) > 0.5 + + +def test_extraction_frames_give_unlit_samples_no_weight( + curtain_recording: CurtainRecording, +) -> None: + """SILo's raw frames (rawFramesAt) leave out the same samples.""" + layout, online, _ = curtain_recording + ids = np.unique(layout.slot_pixel) + times, dt = np.arange(40, layout.total_lines - 40, 89), 8 + got = RasterPixelFrames(layout, ids, times, dt, [0, 1]).frames(times) + ref = RasterPixelFrames(plain(layout), ids, times, dt, [0, 1]).frames(times) + values = got[0][:, :-1].numpy() # (channels, pixels, frames) + before = ref[0][:, :-1].numpy() + # exclusive boundary: a kernel reaches max(3 dt, P) - 1 lines + reach = max(3 * dt, layout.lines_per_cycle) - 1 + hit = kernel_hits(layout, unlit_by_definition(layout, online), times, reach, ids).T + # equal to rounding: PixelFormer sums the weights of a band with an + # invalid sample in another order than those of a band without one + np.testing.assert_allclose(values[:, ~hit], before[:, ~hit], rtol=1e-14, atol=0) + assert not np.isnan(values[:, ~hit]).any() + strip = np.isin(ids, STRIP[0] * layout.n_cols + STRIP[1] + 1) + assert np.isnan(values[:, strip]).all() + assert not np.isnan(before).any() + + +def test_registration_window_ignores_the_curtain(curtain_recording: CurtainRecording) -> None: + """The registration window is the bounding box of the first frame's pixels. + + Those are the pixels the first frame samples, lit or not: a column behind + the curtain in that frame stays in the window. + """ + from giant_python.registration.sources import _window_pixels + + layout, online, _ = curtain_recording + x = online[0] + dt = 2 + reach = max(3 * dt, layout.lines_per_cycle) + # a frame whose kernel has x = 3 throughout: column 39 is unlit in + # every row + t = next( + t + for t in range(reach + 1, layout.total_lines - reach) + if np.all(x[t - reach - 1 : t + reach] == 3) + ) + n_c = layout.num_cycles + masked = FrameFormer(layout, read_raster_samples(layout, (0, n_c), mask_unlit=True), 0) + raw = FrameFormer(plain(layout), read_raster_samples(layout, (0, n_c)), 0) + values = masked.frames([t], dt)[0].sum(0)[0].numpy() + assert np.isnan(values[masked.cols == 39]).all() + init = np.array([t, t + 500]) + np.testing.assert_array_equal(_window_pixels(masked, init, dt), _window_pixels(raw, init, dt)) + assert _window_pixels(masked, init, dt)[masked.cols == 39].any() + + +def test_registration_leaves_out_the_strip( + curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Registration forms its frames without the unlit samples. + + The strip is missing from the registered movie, and the motion follows the + true motion (with the dark samples, which move with the offsets, it is off + by 0.2-0.5 px rms in this recording). + """ + layout, _, seen = curtain_recording + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + out = {} + for name, lay in (("curtain", layout), ("plain", plain(layout))): + monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) + res = multiroi.register_trial( + layout.files[0], + 1, + layout.total_lines - 200, + tmp_path / f"{name}.tif", + tmp_path / f"{name}.h5", + params, + ) + out[name] = (res, load_struct_h5(tmp_path / f"{name}.h5")) + res, a = out["curtain"] + dt = 1600 / 80 # the kernel that forms the frames + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + for i, est in enumerate((res.motion_r, res.motion_c)): + true = np.convolve(seen[:, i], kernel, "same")[res.ds_frames - 1] + err = est - true + assert np.sqrt(np.mean((err - np.median(err)) ** 2)) < 0.1 + # the registered movies ((frames, columns, rows) in the file): the strip + # is missing in nearly every frame; registration moves the frames by up + # to 2 px, so its neighbours are missing in part of them + trim_r = a["slap2"]["trimRows"].ravel().astype(int) + trim_c = a["slap2"]["trimCols"].ravel().astype(int) + pad = int(params.maxshift) + r = STRIP[0] + 1 - trim_r[0] + pad + c = STRIP[1] + 1 - trim_c[0] + pad + gone = {} + for name in out: + with h5py.File(tmp_path / f"{name}.tif", "r") as f: + gone[name] = np.isnan(f["data"][:, c, r]).mean(0) + assert np.all(gone["curtain"] > 0.9) + assert gone["curtain"].mean() > gone["plain"].mean() + 0.05 + + +def test_reg_stats_follow_the_alignment_file( + curtain_recording: CurtainRecording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """``giant reg-stats`` forms the frames as the registration did. + + Without the samples behind the curtain where the alignment file records + slap2/unlitMasked, with them in files registered before. + """ + from giant_python.pipeline.reg_stats import trial_stats + from giant_python.registration.stats.io import read_stats, stats_path + + layout = curtain_recording[0] + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + movie = tmp_path / "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + adata = tmp_path / "E1T1DMD1_ALIGNMENTDATA.h5" + last = layout.total_lines - 200 + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + multiroi.register_trial(layout.files[0], 1, last, movie, adata, params) + from giant_python.registration.outputs import unlit_masked + + assert unlit_masked(adata) + masks = [] + opened = multiroi.open_trial + + def spy(*args: object, **kwargs: object) -> object: + """Record whether each open_trial call masks the unlit samples. + + Returns + ------- + object + What open_trial returns for the same arguments. + """ + masks.append(args[5] if len(args) > 5 else kwargs["mask_unlit"]) + return opened(*args, **kwargs) + + monkeypatch.setattr(multiroi, "open_trial", spy) + cmd = tmp_path / "cmd.h5" + trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) + a, b = read_stats(stats_path(movie)), read_stats(cmd) + for k in a["gain"]: + np.testing.assert_array_equal(a["gain"][k], b["gain"][k], err_msg=k) + with h5py.File(adata, "r+") as f: # as registered before the mask + del f["slap2/unlitMasked"] + assert not unlit_masked(adata) + trial_stats(layout.files[0], 1, last, movie, adata, cmd, "cpu", {}) + assert masks == [True, False] diff --git a/tests/registration/test_growth.py b/tests/registration/test_growth.py index 9c6c4d4c..f091d768 100644 --- a/tests/registration/test_growth.py +++ b/tests/registration/test_growth.py @@ -1,321 +1,321 @@ -"""The growth schedule: wide search, scheduler pieces, end to end.""" - -from pathlib import Path - -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2_raster import RasterLayout -from giant_python.registration import multiroi -from giant_python.registration.growth import ( - GROWN, - REGROWN, - _runs, - seeds_from_consensus, -) -from giant_python.registration.matching import ( - correlation_map, - peak_margin, - shift_tables, - wide_correlation, -) -from giant_python.registration.template import ( - ConsensusResult, - TemplateState, -) - -from .synthetic import make_layout, write_recording - - -def test_wide_correlation_equals_matrix_form() -> None: - """FFT correlation over the padded template equals the GEMM form.""" - rng = np.random.default_rng(0) - h, w, m = 14, 19, 4 - tmpl = rng.random((h + 2 * m, w + 2 * m)) * 10 - tmpl[rng.random(tmpl.shape) < 0.15] = np.nan - frame = tmpl[m + 1 : m + 1 + h, m - 2 : m - 2 + w] + rng.normal(0, 0.3, (h, w)) - frame[rng.random(frame.shape) < 0.3] = np.nan - fresh = np.where(np.isnan(frame), 0, rng.random((h, w)) + 0.5) - wide = wide_correlation( - torch.from_numpy(frame)[None], - torch.from_numpy(fresh)[None], - torch.from_numpy(tmpl), - )[0].numpy() - rows, cols = np.nonzero(~np.isnan(frame)) - tables = shift_tables( - torch.from_numpy(tmpl), - torch.from_numpy(rows + m), - torch.from_numpy(cols + m), - m, - torch.float64, - ) - gemm = correlation_map( - torch.from_numpy(frame[rows, cols])[None], - torch.from_numpy(fresh[rows, cols])[None], - tables, - m, - )[0].numpy() - np.testing.assert_allclose(wide, gemm, atol=1e-9) - r, c = np.unravel_index(np.nanargmax(wide), wide.shape) - assert (r - m, c - m) == (1, -2) - - -def test_peak_margin_and_runs() -> None: - """Margin excludes the peak's neighbourhood; runs of True.""" - corr = torch.zeros(1, 9, 9, dtype=torch.float64) - corr[0, 4, 4] = 1.0 - corr[0, 5, 5] = 0.9 - corr[0, 0, 8] = 0.6 - np.testing.assert_allclose(peak_margin(corr).numpy(), [0.4]) - mask = np.array([0, 1, 1, 0, 0, 1, 0, 1, 1, 1], dtype=bool) - assert _runs(mask) == [(1, 3), (5, 6), (7, 10)] - - -def test_template_update_adds_and_removes() -> None: - """Batch add then remove restores the sums.""" - total = torch.ones(3, 3, dtype=torch.float64) * 4 - count = torch.ones(3, 3, dtype=torch.float64) - state = TemplateState(total.clone(), count.clone(), None, 1) - imgs = torch.rand(5, 3, 3) * 9 - imgs[0, 1, 1] = float("nan") - state.update(imgs) - assert state.count[1, 1] == 5 and state.count[0, 0] == 6 - state.update(imgs, sign=-1) - torch.testing.assert_close(state.total, total) - torch.testing.assert_close(state.count, count) - - -def test_seeds_from_consensus() -> None: - """Seeds are the nearest DS frames, with MATLAB's motion sign.""" - init = np.array([105, 300, 501, 700]) - ds = np.arange(1, 800, 20) - mot = np.zeros((2, 4, 4)) - mot[:, 0, 2] = [1.4, -2.6] - cons = ConsensusResult(np.eye(4), mot, reference=2, members=np.array([0, 2])) - seeds, cands, indep = seeds_from_consensus(cons, init, ds, reach=30) - assert seeds == [(5, -1, 3), (25, 0, 0)] - assert cands == [15, 35] - assert not indep[5] and not indep[25] and indep[15] - - -@pytest.fixture(scope="module") -def plain_recording(tmp_path_factory: pytest.TempPathFactory) -> tuple[RasterLayout, np.ndarray]: - """Synthetic recording without online offsets. - - Returns - ------- - tuple[RasterLayout, np.ndarray] - (layout, truth): the recording's layout and the truth written with it. - """ - path = tmp_path_factory.mktemp("rec") / "grow_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400, seed=5) - truth = write_recording(layout, seed=6) - return layout, truth - - -def test_grow_matches_sequential( - plain_recording: tuple[RasterLayout, np.ndarray], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Growth aligns every frame, like sequential, and saves its record.""" - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - out = {} - for sched in ("sequential", "grow"): - params = multiroi.MultiRoiRegistrationParams( - maxshift=6, schedule=sched, polish=sched == "grow" - ) - out[sched] = multiroi.register_trial( - layout.files[0], - 1, - 9000, - tmp_path / f"{sched}.tif", - tmp_path / f"{sched}.h5", - params, - ) - g = out["grow"].growth - assert np.all(np.isfinite(out["grow"].motion_r)) - assert g.seeds_accepted >= 1 and g.round.max() < 450 - diff = np.hypot( - out["grow"].motion_r - out["sequential"].motion_r, - out["grow"].motion_c - out["sequential"].motion_c, - ) - assert np.sqrt(np.mean(diff**2)) < 0.05 - qc = load_struct_h5(tmp_path / "grow.h5")["growthQC"] - assert qc["kind"].size == out["grow"].ds_frames.size - assert qc["seedsAccepted"].item() == g.seeds_accepted - - -def test_junction_regrows_a_wrong_island( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """An island shifted by 2 px is realigned from its neighbour.""" - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) - motion, _ = grower.run() - good = motion.copy() - bad = np.arange(200, 240) - grower._withdraw(bad) - grower._accept( - bad, - good[bad] + [2.0, 0.0], - grower.qc.peak[bad] - 0.2, - grower.qc.margin[bad], - np.full(bad.size, -1), - [GROWN] * bad.size, - [-7] * bad.size, - ) - grower.qc.anchor[240] = 241 # frame 240 was reached from the right - grower._check_junctions([240]) - assert grower.qc.junctions and grower.qc.junctions[-1][3] == "regrown" - assert np.all(grower.qc.kind[bad] == REGROWN) - err = np.hypot(*(grower.motion[bad] - good[bad]).T) - assert err.max() < 0.2 - - -def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch: pytest.MonkeyPatch) -> None: - """Seeds that align the last unaligned frame end the sub-round.""" - from giant_python.registration.growth import Grower - - class Frames: - """Stands in for a frame cache; only its length is used.""" - - def __len__(self) -> int: - """Five frames. - - Returns - ------- - int - The frame count, 5. - """ - return 5 - - params = multiroi.MultiRoiRegistrationParams(schedule="grow") - grower = Grower(Frames(), None, params, [], [4]) - grower.aligned[:4] = True - grower.motion[:4] = 0.0 - grower.root[:4] = 0 - - def seed(ks: list[int]) -> None: - """Align the candidates, as an accepted wide search would.""" - grower.aligned[ks] = True - grower.motion[ks] = 0.0 - - monkeypatch.setattr(grower, "_calibrated", lambda: True) - monkeypatch.setattr(grower, "try_seeds", seed) - grower._sub_round() - assert grower.aligned.all() - - -def test_growth_handles_a_frame_without_valid_samples( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """Inside the grower, a frame whose correlation is undefined keeps its anchor's motion. - - It does not stop a realignment chain. - - (register_grow leaves frames without samples out beforehand; this - covers frames whose correlation is undefined for other reasons.) - """ - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - taken = {k for k, _, _ in seeds} | set(cands) - k = next(i for i in range(200, ds.size) if i not in taken) - cache = FrameCache(source, ds) - cache.values[:, k] = float("nan") - cache.freshness[k] = 0 - grower = Grower(cache, state, params, seeds, cands, independent=indep) - motion, qc = grower.run() - assert grower.aligned.all() and np.all(np.isfinite(motion)) - assert np.isnan(qc.peak[k]) and qc.anchor[k] >= 0 - np.testing.assert_array_equal(motion[k], motion[qc.anchor[k]]) - chain, peak, _ = grower._chain([k], motion[k - 1]) - np.testing.assert_array_equal(chain[0], motion[k - 1]) - assert np.isnan(peak[0]) - - -def test_consensus_seeds_stay_within_maxshift( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """Seeds start inside the padded template even when the consensus motion exceeds maxshift. - - The consensus motion goes up to init_search. - """ - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=2, init_search=3, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 3000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 3000, init, ds, dt, False) - state, _cons = build_template(source, init, params, torch.float32) - grower = Grower(FrameCache(source, ds), state, params, [(10, 3, -3)], []) - assert grower.seeds == [(10, 2, -2)] - grower._seed_round() - assert grower.aligned[10] and np.all(np.isfinite(grower.motion[10])) - - -def test_seed_candidates_are_listed_once() -> None: - """Initial frames nearest the same DS frame give one candidate.""" - init = np.array([2, 4, 6, 105]) - ds = np.arange(1, 200, 20) - cons = ConsensusResult(np.eye(4), np.zeros((2, 4, 4)), reference=3, members=np.array([3])) - seeds, cands, _ = seeds_from_consensus(cons, init, ds) - assert seeds == [(5, 0, 0)] and cands == [0] - - -def test_a_seed_tried_twice_is_added_once( - plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch -) -> None: - """A frame passed twice to the wide search adds one contribution to the template, not two.""" - from giant_python.registration.growth import FrameCache, Grower - from giant_python.registration.multiroi import build_template, open_trial - from giant_python.registration.sources import make_source - - layout, _ = plain_recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") - lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) - source = make_source(lay, former, 1, 9000, init, ds, dt, False) - state, cons = build_template(source, init, params, torch.float32) - seeds, cands, indep = seeds_from_consensus(cons, init, ds) - grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) - grower.run() - peak = np.where( - (grower.qc.kind == GROWN) & indep & ~np.isin(np.arange(ds.size), list(grower.tried)), - grower.qc.peak, - -np.inf, - ) - k = int(np.argmax(peak)) - grower._withdraw([k]) - count = grower.state.count.clone() - accepted = grower.qc.seeds_accepted - grower.try_seeds([k, k]) - assert grower.aligned[k] and grower.qc.seeds_accepted == accepted + 1 - img = grower.cache.registered_sum([k], grower.motion[[k]], grower.m)[0] - added = grower.state.count - count - assert torch.equal(added, (~torch.isnan(img)).to(added.dtype)) +"""The growth schedule: wide search, scheduler pieces, end to end.""" + +from pathlib import Path + +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import load_struct_h5 +from giant_python.io.slap2_raster import RasterLayout +from giant_python.registration import multiroi +from giant_python.registration.growth import ( + GROWN, + REGROWN, + _runs, + seeds_from_consensus, +) +from giant_python.registration.matching import ( + correlation_map, + peak_margin, + shift_tables, + wide_correlation, +) +from giant_python.registration.template import ( + ConsensusResult, + TemplateState, +) + +from .synthetic import make_layout, write_recording + + +def test_wide_correlation_equals_matrix_form() -> None: + """FFT correlation over the padded template equals the GEMM form.""" + rng = np.random.default_rng(0) + h, w, m = 14, 19, 4 + tmpl = rng.random((h + 2 * m, w + 2 * m)) * 10 + tmpl[rng.random(tmpl.shape) < 0.15] = np.nan + frame = tmpl[m + 1 : m + 1 + h, m - 2 : m - 2 + w] + rng.normal(0, 0.3, (h, w)) + frame[rng.random(frame.shape) < 0.3] = np.nan + fresh = np.where(np.isnan(frame), 0, rng.random((h, w)) + 0.5) + wide = wide_correlation( + torch.from_numpy(frame)[None], + torch.from_numpy(fresh)[None], + torch.from_numpy(tmpl), + )[0].numpy() + rows, cols = np.nonzero(~np.isnan(frame)) + tables = shift_tables( + torch.from_numpy(tmpl), + torch.from_numpy(rows + m), + torch.from_numpy(cols + m), + m, + torch.float64, + ) + gemm = correlation_map( + torch.from_numpy(frame[rows, cols])[None], + torch.from_numpy(fresh[rows, cols])[None], + tables, + m, + )[0].numpy() + np.testing.assert_allclose(wide, gemm, atol=1e-9) + r, c = np.unravel_index(np.nanargmax(wide), wide.shape) + assert (r - m, c - m) == (1, -2) + + +def test_peak_margin_and_runs() -> None: + """Margin excludes the peak's neighbourhood; runs of True.""" + corr = torch.zeros(1, 9, 9, dtype=torch.float64) + corr[0, 4, 4] = 1.0 + corr[0, 5, 5] = 0.9 + corr[0, 0, 8] = 0.6 + np.testing.assert_allclose(peak_margin(corr).numpy(), [0.4]) + mask = np.array([0, 1, 1, 0, 0, 1, 0, 1, 1, 1], dtype=bool) + assert _runs(mask) == [(1, 3), (5, 6), (7, 10)] + + +def test_template_update_adds_and_removes() -> None: + """Batch add then remove restores the sums.""" + total = torch.ones(3, 3, dtype=torch.float64) * 4 + count = torch.ones(3, 3, dtype=torch.float64) + state = TemplateState(total.clone(), count.clone(), None, 1) + imgs = torch.rand(5, 3, 3) * 9 + imgs[0, 1, 1] = float("nan") + state.update(imgs) + assert state.count[1, 1] == 5 and state.count[0, 0] == 6 + state.update(imgs, sign=-1) + torch.testing.assert_close(state.total, total) + torch.testing.assert_close(state.count, count) + + +def test_seeds_from_consensus() -> None: + """Seeds are the nearest DS frames, with MATLAB's motion sign.""" + init = np.array([105, 300, 501, 700]) + ds = np.arange(1, 800, 20) + mot = np.zeros((2, 4, 4)) + mot[:, 0, 2] = [1.4, -2.6] + cons = ConsensusResult(np.eye(4), mot, reference=2, members=np.array([0, 2])) + seeds, cands, indep = seeds_from_consensus(cons, init, ds, reach=30) + assert seeds == [(5, -1, 3), (25, 0, 0)] + assert cands == [15, 35] + assert not indep[5] and not indep[25] and indep[15] + + +@pytest.fixture(scope="module") +def plain_recording(tmp_path_factory: pytest.TempPathFactory) -> tuple[RasterLayout, np.ndarray]: + """Synthetic recording without online offsets. + + Returns + ------- + tuple[RasterLayout, np.ndarray] + (layout, truth): the recording's layout and the truth written with it. + """ + path = tmp_path_factory.mktemp("rec") / "grow_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400, seed=5) + truth = write_recording(layout, seed=6) + return layout, truth + + +def test_grow_matches_sequential( + plain_recording: tuple[RasterLayout, np.ndarray], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Growth aligns every frame, like sequential, and saves its record.""" + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + out = {} + for sched in ("sequential", "grow"): + params = multiroi.MultiRoiRegistrationParams( + maxshift=6, schedule=sched, polish=sched == "grow" + ) + out[sched] = multiroi.register_trial( + layout.files[0], + 1, + 9000, + tmp_path / f"{sched}.tif", + tmp_path / f"{sched}.h5", + params, + ) + g = out["grow"].growth + assert np.all(np.isfinite(out["grow"].motion_r)) + assert g.seeds_accepted >= 1 and g.round.max() < 450 + diff = np.hypot( + out["grow"].motion_r - out["sequential"].motion_r, + out["grow"].motion_c - out["sequential"].motion_c, + ) + assert np.sqrt(np.mean(diff**2)) < 0.05 + qc = load_struct_h5(tmp_path / "grow.h5")["growthQC"] + assert qc["kind"].size == out["grow"].ds_frames.size + assert qc["seedsAccepted"].item() == g.seeds_accepted + + +def test_junction_regrows_a_wrong_island( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """An island shifted by 2 px is realigned from its neighbour.""" + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) + motion, _ = grower.run() + good = motion.copy() + bad = np.arange(200, 240) + grower._withdraw(bad) + grower._accept( + bad, + good[bad] + [2.0, 0.0], + grower.qc.peak[bad] - 0.2, + grower.qc.margin[bad], + np.full(bad.size, -1), + [GROWN] * bad.size, + [-7] * bad.size, + ) + grower.qc.anchor[240] = 241 # frame 240 was reached from the right + grower._check_junctions([240]) + assert grower.qc.junctions and grower.qc.junctions[-1][3] == "regrown" + assert np.all(grower.qc.kind[bad] == REGROWN) + err = np.hypot(*(grower.motion[bad] - good[bad]).T) + assert err.max() < 0.2 + + +def test_sub_round_ends_when_seeds_align_the_last_frame(monkeypatch: pytest.MonkeyPatch) -> None: + """Seeds that align the last unaligned frame end the sub-round.""" + from giant_python.registration.growth import Grower + + class Frames: + """Stands in for a frame cache; only its length is used.""" + + def __len__(self) -> int: + """Five frames. + + Returns + ------- + int + The frame count, 5. + """ + return 5 + + params = multiroi.MultiRoiRegistrationParams(schedule="grow") + grower = Grower(Frames(), None, params, [], [4]) + grower.aligned[:4] = True + grower.motion[:4] = 0.0 + grower.root[:4] = 0 + + def seed(ks: list[int]) -> None: + """Align the candidates, as an accepted wide search would.""" + grower.aligned[ks] = True + grower.motion[ks] = 0.0 + + monkeypatch.setattr(grower, "_calibrated", lambda: True) + monkeypatch.setattr(grower, "try_seeds", seed) + grower._sub_round() + assert grower.aligned.all() + + +def test_growth_handles_a_frame_without_valid_samples( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """Inside the grower, a frame whose correlation is undefined keeps its anchor's motion. + + It does not stop a realignment chain. + + (register_grow leaves frames without samples out beforehand; this + covers frames whose correlation is undefined for other reasons.) + """ + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + taken = {k for k, _, _ in seeds} | set(cands) + k = next(i for i in range(200, ds.size) if i not in taken) + cache = FrameCache(source, ds) + cache.values[:, k] = float("nan") + cache.freshness[k] = 0 + grower = Grower(cache, state, params, seeds, cands, independent=indep) + motion, qc = grower.run() + assert grower.aligned.all() and np.all(np.isfinite(motion)) + assert np.isnan(qc.peak[k]) and qc.anchor[k] >= 0 + np.testing.assert_array_equal(motion[k], motion[qc.anchor[k]]) + chain, peak, _ = grower._chain([k], motion[k - 1]) + np.testing.assert_array_equal(chain[0], motion[k - 1]) + assert np.isnan(peak[0]) + + +def test_consensus_seeds_stay_within_maxshift( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """Seeds start inside the padded template even when the consensus motion exceeds maxshift. + + The consensus motion goes up to init_search. + """ + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=2, init_search=3, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 3000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 3000, init, ds, dt, False) + state, _cons = build_template(source, init, params, torch.float32) + grower = Grower(FrameCache(source, ds), state, params, [(10, 3, -3)], []) + assert grower.seeds == [(10, 2, -2)] + grower._seed_round() + assert grower.aligned[10] and np.all(np.isfinite(grower.motion[10])) + + +def test_seed_candidates_are_listed_once() -> None: + """Initial frames nearest the same DS frame give one candidate.""" + init = np.array([2, 4, 6, 105]) + ds = np.arange(1, 200, 20) + cons = ConsensusResult(np.eye(4), np.zeros((2, 4, 4)), reference=3, members=np.array([3])) + seeds, cands, _ = seeds_from_consensus(cons, init, ds) + assert seeds == [(5, 0, 0)] and cands == [0] + + +def test_a_seed_tried_twice_is_added_once( + plain_recording: tuple[RasterLayout, np.ndarray], monkeypatch: pytest.MonkeyPatch +) -> None: + """A frame passed twice to the wide search adds one contribution to the template, not two.""" + from giant_python.registration.growth import FrameCache, Grower + from giant_python.registration.multiroi import build_template, open_trial + from giant_python.registration.sources import make_source + + layout, _ = plain_recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, schedule="grow") + lay, former, init, ds, dt = open_trial(layout.files[0], 1, 9000, params, torch.device("cpu")) + source = make_source(lay, former, 1, 9000, init, ds, dt, False) + state, cons = build_template(source, init, params, torch.float32) + seeds, cands, indep = seeds_from_consensus(cons, init, ds) + grower = Grower(FrameCache(source, ds), state, params, seeds, cands, independent=indep) + grower.run() + peak = np.where( + (grower.qc.kind == GROWN) & indep & ~np.isin(np.arange(ds.size), list(grower.tried)), + grower.qc.peak, + -np.inf, + ) + k = int(np.argmax(peak)) + grower._withdraw([k]) + count = grower.state.count.clone() + accepted = grower.qc.seeds_accepted + grower.try_seeds([k, k]) + assert grower.aligned[k] and grower.qc.seeds_accepted == accepted + 1 + img = grower.cache.registered_sum([k], grower.motion[[k]], grower.m)[0] + added = grower.state.count - count + assert torch.equal(added, (~torch.isnan(img)).to(added.dtype)) diff --git a/tests/registration/test_kernels.py b/tests/registration/test_kernels.py index ab58873a..e60cca8b 100644 --- a/tests/registration/test_kernels.py +++ b/tests/registration/test_kernels.py @@ -1,289 +1,289 @@ -"""Registration kernels against direct ports of the GIAnT-MATLAB code.""" - -import warnings -from collections.abc import Callable - -import numpy as np -import pytest -import torch - -from giant_python.registration.interpolation import interp_frame -from giant_python.registration.matching import ( - RegistrationError, - correlation_map, - match, - match_maps, - shift_tables, -) -from giant_python.registration.multiroi import matlab_colon -from giant_python.registration.outputs import ( - downsample2, - matlab_round, - rec_neg_err, -) -from giant_python.registration.template import TemplateState - - -def xcorr_reference( - frame: np.ndarray, fresh: np.ndarray, template: np.ndarray, s: int -) -> np.ndarray: - """Loop port of xcorr2_nans_weighted (correlation map only). - - Returns - ------- - np.ndarray - Weighted correlation at each shift, shape (2 * s + 1, 2 * s + 1). - """ - h, w = template.shape - rows, cols = np.nonzero(~np.isnan(frame)) - out = np.full((2 * s + 1, 2 * s + 1), np.nan) - for i, dr in enumerate(range(-s, s + 1)): - for j, dc in enumerate(range(-s, s + 1)): - r, c = rows + dr, cols + dc - ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) - t = np.full(rows.size, np.nan) - t[ok] = template[r[ok], c[ok]] - sel = ~np.isnan(t) - f, t, wt = frame[rows, cols][sel], t[sel], fresh[rows, cols][sel] - sw = wt.sum() - df = f - (wt * f).sum() / sw - dt = t - (wt * t).sum() / sw - out[i, j] = (wt * df * dt).sum() / np.sqrt((wt * dt**2).sum() * (wt * df**2).sum()) - return out - - -def interp_reference( - m1: np.ndarray, view_c: np.ndarray, view_r: np.ndarray, fresh: np.ndarray -) -> tuple[np.ndarray, np.ndarray]: - """Gather port of interpFrame (one-based view coordinates). - - Returns - ------- - frame : np.ndarray - The bilinearly interpolated frame, freshness-weighted. - vim : np.ndarray - Reciprocal of the summed bilinear freshness weights, NaN where infinite. - """ - h, w = m1.shape - - def corner( - rfun: Callable[[np.ndarray], np.ndarray], cfun: Callable[[np.ndarray], np.ndarray] - ) -> tuple[np.ndarray, np.ndarray]: - """Frame and freshness at one bilinear corner, NaN outside. - - Returns - ------- - frame : np.ndarray - The frame sampled at the corner, NaN outside the image. - fresh : np.ndarray - The freshness sampled at the corner, NaN outside the image. - """ - rr = rfun(view_r).astype(int) - cc = cfun(view_c).astype(int) - bad_r = (rr < 1) | (rr > h) - bad_c = (cc < 1) | (cc > w) - rr[bad_r], cc[bad_c] = 1, 1 - a = m1[np.ix_(rr - 1, cc - 1)].astype(np.float64) - f = fresh[np.ix_(rr - 1, cc - 1)].astype(np.float64) - for x in (a, f): - x[bad_r, :] = np.nan - x[:, bad_c] = np.nan - return a, f - - fc, fr = np.mod(view_c[0], 1), np.mod(view_r[0], 1) - coef = [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr] - funcs = [ - (np.floor, np.floor), - (np.floor, np.ceil), - (np.ceil, np.floor), - (np.ceil, np.ceil), - ] - num = den = 0 - for cf, (rf, cfun) in zip(coef, funcs): - a, f = corner(rf, cfun) - num = num + cf * f * a - den = den + cf * f - with np.errstate(divide="ignore", invalid="ignore"): - vim = 1 / den - vim[np.isinf(vim)] = np.nan - return num / den, vim - - -def random_frame( - rng: np.random.Generator, h: int = 18, w: int = 23, frac: float = 0.4 -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Smooth frame with a NaN pattern, its freshness and a template. - - Returns - ------- - frame : np.ndarray - Noisy smooth frame with NaN at random pixels. - fresh : np.ndarray - Freshness weights, 0 where the frame is NaN. - template : np.ndarray - Shifted copy of the underlying image with some NaN pixels. - """ - base = rng.random((h + 8, w + 8)) - img = (base[4:-4, 4:-4] + base[5:-3, 4:-4] + base[4:-4, 5:-3]) * 10 - frame = img + rng.normal(0, 0.5, img.shape) - fresh = rng.random(img.shape) + 0.2 - frame[rng.random(img.shape) < frac] = np.nan - fresh[np.isnan(frame)] = 0 - template = np.roll(img, (1, -2), (0, 1)) - template[rng.random(img.shape) < 0.2] = np.nan - return frame, fresh, template - - -@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) -def test_correlation_map_matches_matlab_loop(dtype: torch.dtype) -> None: - """Weighted NCC equals the MATLAB loop at every shift.""" - rng = np.random.default_rng(0) - frame, fresh, template = random_frame(rng) - s = 4 - rows, cols = np.nonzero(~np.isnan(frame)) - f = torch.from_numpy(frame[rows, cols])[None] - w = torch.from_numpy(fresh[rows, cols])[None] - tables = shift_tables( - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - s, - dtype, - ) - got = correlation_map(f, w, tables, s)[0].double().numpy() - want = xcorr_reference(frame, fresh, template, s) - tol = 1e-4 if dtype == torch.float32 else 1e-10 - np.testing.assert_allclose(got, want, atol=tol) - - -def test_match_recovers_shift_with_subpixel_sign() -> None: - """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" - rng = np.random.default_rng(1) - frame, _fresh, template = random_frame(rng, frac=0.0) - frame = np.roll(template, (-1, 2), (0, 1)) - frame[np.isnan(frame)] = 5.0 - rows, cols = np.nonzero(~np.isnan(frame)) - mot, peak = match( - torch.from_numpy(frame[rows, cols])[None], - torch.ones(1, rows.size, dtype=torch.float64), - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - 4, - torch.float64, - ) - np.testing.assert_allclose(mot[0].numpy(), [-1, 2], atol=0.05) - assert peak[0] > 0.9 - - -def test_frame_without_valid_samples_has_nan_motion() -> None: - """An undefined correlation map gives NaN motion, not a search edge. - - The other frame of the batch is unaffected, and match raises. - """ - rng = np.random.default_rng(1) - _, _, template = random_frame(rng, frac=0.0) - good = np.roll(template, (-1, 2), (0, 1)) - good[np.isnan(good)] = 5.0 - rows, cols = np.nonzero(~np.isnan(good)) - frames = torch.from_numpy(np.stack([good[rows, cols]] * 2)) - weights = torch.ones(2, rows.size, dtype=torch.float64) - frames[1] = float("nan") # no valid samples - weights[1] = 0 - args = ( - torch.from_numpy(template), - torch.from_numpy(rows), - torch.from_numpy(cols), - 4, - torch.float64, - ) - mot, peak, corr = match_maps(frames, weights, *args) - assert torch.isnan(corr[1]).all() - assert torch.isnan(peak[1]) and torch.isnan(mot[1]).all() - want, want_peak = match(frames[:1], weights[:1], *args) - np.testing.assert_allclose(mot[0].numpy(), want[0].numpy(), rtol=1e-12) - np.testing.assert_allclose(peak[0].item(), want_peak[0].item()) - with pytest.raises(RegistrationError): - match(frames, weights, *args) - - -def test_motion_failed_needs_two_frames_with_motion() -> None: - """Missing frames are left out of the SD. - - A trial of several frames with fewer than two with motion fails (SILo - cannot interpolate it). - """ - from giant_python.registration.multiroi import motion_failed - - nan = np.nan - assert not motion_failed(np.array([0.1, 0.3, nan]), np.zeros(3)) - assert motion_failed(np.array([0.0, 5.0, nan, -5.0]), np.zeros(4)) - assert motion_failed(np.array([nan, 0.2, nan]), np.zeros(3)) - assert motion_failed(np.full(3, nan), np.full(3, nan)) - assert motion_failed(np.array([0.1, 0.2]), np.array([0.0, nan])) - with warnings.catch_warnings(): # SD of one value: NaN, as before - warnings.simplefilter("ignore", RuntimeWarning) - assert not motion_failed(np.array([0.2]), np.array([0.1])) - assert motion_failed(np.array([nan]), np.array([nan])) - - -@pytest.mark.parametrize("mr,mc", [(0.0, 0.0), (0.3, -0.7), (-1.25, 2.5), (3.0, -0.4), (30, 2)]) -def test_interp_frame_matches_matlab(mr: float, mc: float) -> None: - """Resampling equals interpFrame, including NaN and edge behaviour.""" - rng = np.random.default_rng(2) - frame, fresh, _ = random_frame(rng) - frame = frame.astype(np.float32) - fresh = fresh.astype(np.float32) - m = 3 - h, w = frame.shape - view_r = np.arange(1, h + 2 * m + 1) - m + mr - view_c = np.arange(1, w + 2 * m + 1) - m + mc - want_im, want_v = interp_reference(frame, view_c, view_r, fresh) - im, v = interp_frame(torch.from_numpy(frame), torch.from_numpy(fresh), mr, mc, m) - np.testing.assert_array_equal(np.isnan(im.numpy()), np.isnan(want_im)) - np.testing.assert_allclose(im.numpy(), want_im, rtol=1e-5, atol=1e-5) - np.testing.assert_allclose(v.numpy(), want_v, rtol=1e-5) - - -def test_matlab_helpers() -> None: - """MATLAB rounding, colon and 2 x 2 downsampling semantics.""" - np.testing.assert_array_equal(matlab_round([-2.5, -0.5, 0.5, 1.5, 2.4]), [-3, -1, 1, 2, 2]) - ds = matlab_colon(1, 133.6, 1000) - assert ds[0] == 1 and ds.size == 8 and ds[-1] <= 1000 - x = np.arange(30, dtype=np.float32).reshape(5, 6) - x[0, 0] = np.nan - y = downsample2(x) - assert y.shape == (2, 3) and np.isnan(y[0, 0]) - assert y[1, 2] == x[2, 4] + x[2, 5] + x[3, 4] + x[3, 5] - - -def test_rec_neg_err_matches_definition() -> None: - """Template excess over frames, with MATLAB's NaN handling.""" - rng = np.random.default_rng(3) - movie = rng.random((30, 6, 7)).astype(np.float32) * 20 - movie[5, 2, 3] = np.nan - movie[:, 0, 0] = np.nan - err = rec_neg_err(movie, align_hz=80) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", RuntimeWarning) - tmpl = np.nanmedian(movie, 0) - tmpl[np.isnan(movie).mean(0) > 0.2] = np.nan - gam = np.sqrt(np.maximum(0, tmpl) + 10) - for k in (0, 5): - ex = (tmpl - movie[k]) / gam - num = np.nansum(np.maximum(0, ex) ** 2) / ex.size - den_v = (tmpl / gam) ** 2 + movie[k] * 0 - den = np.nanmean(den_v) - np.testing.assert_allclose(err[k], np.sqrt(num / den), rtol=1e-5) - - -def test_template_state_matches_matlab_rules() -> None: - """Sqrt of the mean, NaN below min_samples, and the T0 average.""" - total = torch.tensor([[4.0, 9.0], [0.0, 1.0]], dtype=torch.float64) - count = torch.tensor([[1.0, 1.0], [0.0, 1.0]], dtype=torch.float64) - t0 = torch.tensor([[1.0, float("nan")], [3.0, float("nan")]]) - state = TemplateState(total, count, t0.double(), min_samples=1) - np.testing.assert_allclose(state.template.numpy(), [[2, 3], [np.nan, 1]], equal_nan=True) - np.testing.assert_allclose(state.matching_template().numpy(), [[1.5, 3], [3, 1]]) - state.add(torch.tensor([[float("nan"), 7.0], [4.0, 3.0]])) - np.testing.assert_allclose(state.template.numpy(), [[2, np.sqrt(8)], [2, np.sqrt(2)]]) +"""Registration kernels against direct ports of the GIAnT-MATLAB code.""" + +import warnings +from collections.abc import Callable + +import numpy as np +import pytest +import torch + +from giant_python.registration.interpolation import interp_frame +from giant_python.registration.matching import ( + RegistrationError, + correlation_map, + match, + match_maps, + shift_tables, +) +from giant_python.registration.multiroi import matlab_colon +from giant_python.registration.outputs import ( + downsample2, + matlab_round, + rec_neg_err, +) +from giant_python.registration.template import TemplateState + + +def xcorr_reference( + frame: np.ndarray, fresh: np.ndarray, template: np.ndarray, s: int +) -> np.ndarray: + """Loop port of xcorr2_nans_weighted (correlation map only). + + Returns + ------- + np.ndarray + Weighted correlation at each shift, shape (2 * s + 1, 2 * s + 1). + """ + h, w = template.shape + rows, cols = np.nonzero(~np.isnan(frame)) + out = np.full((2 * s + 1, 2 * s + 1), np.nan) + for i, dr in enumerate(range(-s, s + 1)): + for j, dc in enumerate(range(-s, s + 1)): + r, c = rows + dr, cols + dc + ok = (r >= 0) & (r < h) & (c >= 0) & (c < w) + t = np.full(rows.size, np.nan) + t[ok] = template[r[ok], c[ok]] + sel = ~np.isnan(t) + f, t, wt = frame[rows, cols][sel], t[sel], fresh[rows, cols][sel] + sw = wt.sum() + df = f - (wt * f).sum() / sw + dt = t - (wt * t).sum() / sw + out[i, j] = (wt * df * dt).sum() / np.sqrt((wt * dt**2).sum() * (wt * df**2).sum()) + return out + + +def interp_reference( + m1: np.ndarray, view_c: np.ndarray, view_r: np.ndarray, fresh: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + """Gather port of interpFrame (one-based view coordinates). + + Returns + ------- + frame : np.ndarray + The bilinearly interpolated frame, freshness-weighted. + vim : np.ndarray + Reciprocal of the summed bilinear freshness weights, NaN where infinite. + """ + h, w = m1.shape + + def corner( + rfun: Callable[[np.ndarray], np.ndarray], cfun: Callable[[np.ndarray], np.ndarray] + ) -> tuple[np.ndarray, np.ndarray]: + """Frame and freshness at one bilinear corner, NaN outside. + + Returns + ------- + frame : np.ndarray + The frame sampled at the corner, NaN outside the image. + fresh : np.ndarray + The freshness sampled at the corner, NaN outside the image. + """ + rr = rfun(view_r).astype(int) + cc = cfun(view_c).astype(int) + bad_r = (rr < 1) | (rr > h) + bad_c = (cc < 1) | (cc > w) + rr[bad_r], cc[bad_c] = 1, 1 + a = m1[np.ix_(rr - 1, cc - 1)].astype(np.float64) + f = fresh[np.ix_(rr - 1, cc - 1)].astype(np.float64) + for x in (a, f): + x[bad_r, :] = np.nan + x[:, bad_c] = np.nan + return a, f + + fc, fr = np.mod(view_c[0], 1), np.mod(view_r[0], 1) + coef = [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr] + funcs = [ + (np.floor, np.floor), + (np.floor, np.ceil), + (np.ceil, np.floor), + (np.ceil, np.ceil), + ] + num = den = 0 + for cf, (rf, cfun) in zip(coef, funcs): + a, f = corner(rf, cfun) + num = num + cf * f * a + den = den + cf * f + with np.errstate(divide="ignore", invalid="ignore"): + vim = 1 / den + vim[np.isinf(vim)] = np.nan + return num / den, vim + + +def random_frame( + rng: np.random.Generator, h: int = 18, w: int = 23, frac: float = 0.4 +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Smooth frame with a NaN pattern, its freshness and a template. + + Returns + ------- + frame : np.ndarray + Noisy smooth frame with NaN at random pixels. + fresh : np.ndarray + Freshness weights, 0 where the frame is NaN. + template : np.ndarray + Shifted copy of the underlying image with some NaN pixels. + """ + base = rng.random((h + 8, w + 8)) + img = (base[4:-4, 4:-4] + base[5:-3, 4:-4] + base[4:-4, 5:-3]) * 10 + frame = img + rng.normal(0, 0.5, img.shape) + fresh = rng.random(img.shape) + 0.2 + frame[rng.random(img.shape) < frac] = np.nan + fresh[np.isnan(frame)] = 0 + template = np.roll(img, (1, -2), (0, 1)) + template[rng.random(img.shape) < 0.2] = np.nan + return frame, fresh, template + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) +def test_correlation_map_matches_matlab_loop(dtype: torch.dtype) -> None: + """Weighted NCC equals the MATLAB loop at every shift.""" + rng = np.random.default_rng(0) + frame, fresh, template = random_frame(rng) + s = 4 + rows, cols = np.nonzero(~np.isnan(frame)) + f = torch.from_numpy(frame[rows, cols])[None] + w = torch.from_numpy(fresh[rows, cols])[None] + tables = shift_tables( + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + s, + dtype, + ) + got = correlation_map(f, w, tables, s)[0].double().numpy() + want = xcorr_reference(frame, fresh, template, s) + tol = 1e-4 if dtype == torch.float32 else 1e-10 + np.testing.assert_allclose(got, want, atol=tol) + + +def test_match_recovers_shift_with_subpixel_sign() -> None: + """A template shifted by (+1, -2) gives motion (-1, +2), MATLAB's sign.""" + rng = np.random.default_rng(1) + frame, _fresh, template = random_frame(rng, frac=0.0) + frame = np.roll(template, (-1, 2), (0, 1)) + frame[np.isnan(frame)] = 5.0 + rows, cols = np.nonzero(~np.isnan(frame)) + mot, peak = match( + torch.from_numpy(frame[rows, cols])[None], + torch.ones(1, rows.size, dtype=torch.float64), + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + 4, + torch.float64, + ) + np.testing.assert_allclose(mot[0].numpy(), [-1, 2], atol=0.05) + assert peak[0] > 0.9 + + +def test_frame_without_valid_samples_has_nan_motion() -> None: + """An undefined correlation map gives NaN motion, not a search edge. + + The other frame of the batch is unaffected, and match raises. + """ + rng = np.random.default_rng(1) + _, _, template = random_frame(rng, frac=0.0) + good = np.roll(template, (-1, 2), (0, 1)) + good[np.isnan(good)] = 5.0 + rows, cols = np.nonzero(~np.isnan(good)) + frames = torch.from_numpy(np.stack([good[rows, cols]] * 2)) + weights = torch.ones(2, rows.size, dtype=torch.float64) + frames[1] = float("nan") # no valid samples + weights[1] = 0 + args = ( + torch.from_numpy(template), + torch.from_numpy(rows), + torch.from_numpy(cols), + 4, + torch.float64, + ) + mot, peak, corr = match_maps(frames, weights, *args) + assert torch.isnan(corr[1]).all() + assert torch.isnan(peak[1]) and torch.isnan(mot[1]).all() + want, want_peak = match(frames[:1], weights[:1], *args) + np.testing.assert_allclose(mot[0].numpy(), want[0].numpy(), rtol=1e-12) + np.testing.assert_allclose(peak[0].item(), want_peak[0].item()) + with pytest.raises(RegistrationError): + match(frames, weights, *args) + + +def test_motion_failed_needs_two_frames_with_motion() -> None: + """Missing frames are left out of the SD. + + A trial of several frames with fewer than two with motion fails (SILo + cannot interpolate it). + """ + from giant_python.registration.multiroi import motion_failed + + nan = np.nan + assert not motion_failed(np.array([0.1, 0.3, nan]), np.zeros(3)) + assert motion_failed(np.array([0.0, 5.0, nan, -5.0]), np.zeros(4)) + assert motion_failed(np.array([nan, 0.2, nan]), np.zeros(3)) + assert motion_failed(np.full(3, nan), np.full(3, nan)) + assert motion_failed(np.array([0.1, 0.2]), np.array([0.0, nan])) + with warnings.catch_warnings(): # SD of one value: NaN, as before + warnings.simplefilter("ignore", RuntimeWarning) + assert not motion_failed(np.array([0.2]), np.array([0.1])) + assert motion_failed(np.array([nan]), np.array([nan])) + + +@pytest.mark.parametrize("mr,mc", [(0.0, 0.0), (0.3, -0.7), (-1.25, 2.5), (3.0, -0.4), (30, 2)]) +def test_interp_frame_matches_matlab(mr: float, mc: float) -> None: + """Resampling equals interpFrame, including NaN and edge behaviour.""" + rng = np.random.default_rng(2) + frame, fresh, _ = random_frame(rng) + frame = frame.astype(np.float32) + fresh = fresh.astype(np.float32) + m = 3 + h, w = frame.shape + view_r = np.arange(1, h + 2 * m + 1) - m + mr + view_c = np.arange(1, w + 2 * m + 1) - m + mc + want_im, want_v = interp_reference(frame, view_c, view_r, fresh) + im, v = interp_frame(torch.from_numpy(frame), torch.from_numpy(fresh), mr, mc, m) + np.testing.assert_array_equal(np.isnan(im.numpy()), np.isnan(want_im)) + np.testing.assert_allclose(im.numpy(), want_im, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(v.numpy(), want_v, rtol=1e-5) + + +def test_matlab_helpers() -> None: + """MATLAB rounding, colon and 2 x 2 downsampling semantics.""" + np.testing.assert_array_equal(matlab_round([-2.5, -0.5, 0.5, 1.5, 2.4]), [-3, -1, 1, 2, 2]) + ds = matlab_colon(1, 133.6, 1000) + assert ds[0] == 1 and ds.size == 8 and ds[-1] <= 1000 + x = np.arange(30, dtype=np.float32).reshape(5, 6) + x[0, 0] = np.nan + y = downsample2(x) + assert y.shape == (2, 3) and np.isnan(y[0, 0]) + assert y[1, 2] == x[2, 4] + x[2, 5] + x[3, 4] + x[3, 5] + + +def test_rec_neg_err_matches_definition() -> None: + """Template excess over frames, with MATLAB's NaN handling.""" + rng = np.random.default_rng(3) + movie = rng.random((30, 6, 7)).astype(np.float32) * 20 + movie[5, 2, 3] = np.nan + movie[:, 0, 0] = np.nan + err = rec_neg_err(movie, align_hz=80) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + tmpl = np.nanmedian(movie, 0) + tmpl[np.isnan(movie).mean(0) > 0.2] = np.nan + gam = np.sqrt(np.maximum(0, tmpl) + 10) + for k in (0, 5): + ex = (tmpl - movie[k]) / gam + num = np.nansum(np.maximum(0, ex) ** 2) / ex.size + den_v = (tmpl / gam) ** 2 + movie[k] * 0 + den = np.nanmean(den_v) + np.testing.assert_allclose(err[k], np.sqrt(num / den), rtol=1e-5) + + +def test_template_state_matches_matlab_rules() -> None: + """Sqrt of the mean, NaN below min_samples, and the T0 average.""" + total = torch.tensor([[4.0, 9.0], [0.0, 1.0]], dtype=torch.float64) + count = torch.tensor([[1.0, 1.0], [0.0, 1.0]], dtype=torch.float64) + t0 = torch.tensor([[1.0, float("nan")], [3.0, float("nan")]]) + state = TemplateState(total, count, t0.double(), min_samples=1) + np.testing.assert_allclose(state.template.numpy(), [[2, 3], [np.nan, 1]], equal_nan=True) + np.testing.assert_allclose(state.matching_template().numpy(), [[1.5, 3], [3, 1]]) + state.add(torch.tensor([[float("nan"), 7.0], [4.0, 3.0]])) + np.testing.assert_allclose(state.template.numpy(), [[2, np.sqrt(8)], [2, np.sqrt(2)]]) diff --git a/tests/registration/test_reg_stats.py b/tests/registration/test_reg_stats.py index 17424f4e..638f4cef 100644 --- a/tests/registration/test_reg_stats.py +++ b/tests/registration/test_reg_stats.py @@ -1,987 +1,987 @@ -"""Registration summary statistics (registration.stats).""" - -from collections.abc import Iterator -from pathlib import Path -from typing import NoReturn - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import RasterLayout, read_raster_samples -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer -from giant_python.registration.interpolation import interp_frame -from giant_python.registration.multiroi import frame_times -from giant_python.registration.sources import ( - CompensatedFrames, - PlainFrames, - make_source, -) -from giant_python.registration.stats import ( - STATS_VERSION, - measure_gain_curves, - new_accumulator, - read_stats, - stats_path, -) -from giant_python.registration.stats.gain import ( - curve_from_sums, - next_slots, - pair_curve, - pair_sums, - slot_sums, -) -from giant_python.registration.stats.geometry import ( - FrameGeometry, - bilinear_corners, -) -from giant_python.registration.stats.session import combine_trials - -from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout, write_recording - -MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" -ADATA = "E1T1DMD1_ALIGNMENTDATA.h5" - - -@pytest.fixture(scope="module") -def recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: - """Layout and data file of a 6-second recording (moving scene). - - Returns - ------- - RasterLayout - The layout of the written recording. - """ - path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400) - write_recording(layout, invalid=0.0) - return layout - - -@pytest.fixture -def patched(recording: RasterLayout, monkeypatch: pytest.MonkeyPatch) -> RasterLayout: - """Patch registration to read the recording's layout. - - Returns - ------- - RasterLayout - The recording's layout. - """ - monkeypatch.setattr(multiroi, "raster_layout", lambda path: recording) - return recording - - -def _source( - layout: RasterLayout, samples: np.ndarray, first: float = 1.0, last: float = 3000.0 -) -> tuple[PlainFrames | CompensatedFrames, np.ndarray]: - """Frame source of samples over the layout (as registration's). - - Returns - ------- - source : PlainFrames or CompensatedFrames - The frame source of samples. - ds : np.ndarray - The frame times the source is read at. - """ - former = FrameFormer(layout, samples, 0) - dt = (1 / layout.line_period_s) / 80 - dtk = int(np.ceil(dt)) - init, ds = frame_times(first, last, dt, 40) - return make_source(layout, former, first, last, init, ds, dtk, False), ds - - -def _motion(n: int, seed: int = 0, jump: int | None = None) -> np.ndarray: - """Sub-pixel motion (rows, cols) with jitter. - - Returns - ------- - np.ndarray - (n, 2) row and column motion per frame, with a step at jump when given. - """ - rng = np.random.default_rng(seed) - t = np.arange(n) - m = np.stack( - [ - 0.7 * np.sin(t / 7.0) + rng.normal(0, 0.15, n), - 0.9 * np.cos(t / 11.0) + rng.normal(0, 0.15, n), - ], - 1, - ) - if jump is not None: - m[jump] += [1.3, -1.1] - return m - - -def _registered( - source: PlainFrames | CompensatedFrames, ds: np.ndarray, motion: np.ndarray, margin: int -) -> Iterator[tuple[list[torch.Tensor], torch.Tensor]]: - """Yield registered frames and variance factors (interp_frame). - - Yields - ------ - list of torch.Tensor - The registered frame of each channel. - torch.Tensor - The frame's variance factor. - """ - vals, fresh = source.frames(ds) - win = source.window - for k in range(ds.size): - fimg = win.image(fresh[k], 0.0) - regs = [ - interp_frame(win.image(vals[ch, k], float("nan")), fimg, *motion[k], margin) - for ch in range(vals.shape[0]) - ] - yield [r for r, _ in regs], regs[0][1] - - -# --------------------------------------------------------------- geometry - - -def _coefficients( - layout: RasterLayout, - source: PlainFrames | CompensatedFrames, - ds: np.ndarray, - motion: np.ndarray, - margin: int, - t: int, - p: int, -) -> dict[tuple[int, int], float]: - """Sample coefficients of registered frame t at output pixel p by the definition. - - This uses slow loops. - - Returns - ------- - dict - The coefficient of each (slot, cycle) sample, normalised to sum to 1. - """ - win = source.window - w_out = win.shape[1] + 2 * margin - ids = source.former.pixels[source.pixels.numpy()] - where = { - (int(r), int(c)): i for i, (r, c) in enumerate(zip(win.rows.numpy(), win.cols.numpy())) - } - dt = int(source.dt) - reach = max(3 * dt, layout.lines_per_cycle) - r, c = divmod(int(p), w_out) - off_r, off_c, coef, _ = bilinear_corners(*motion[t], margin) - parts, den = [], 0.0 - for k, (a, b) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))): - i = where.get((r + off_r + a, c + off_c + b)) - if i is None: - continue - slots = np.flatnonzero(layout.slot_pixel == ids[i]) - for s in slots: - for cyc in range(layout.num_cycles): - line = cyc * layout.lines_per_cycle + layout.slot_line[s] - if abs(ds[t] - line) <= reach: - wgt = coef[k] * np.exp(-abs(ds[t] - line) / dt) - parts.append(((s, cyc), wgt)) - den += wgt - out = {} - for key, v in parts: - out[key] = out.get(key, 0.0) + v / den - return out - - -def test_geometry_matches_definition(recording: RasterLayout) -> None: - """Photon-noise sums equal sums over the samples' coefficients.""" - layout = recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - source, ds = _source(layout, samples) - m = 6 - motion = _motion(ds.size, jump=12) - geo = FrameGeometry(source, ds, m) - assert geo.n_lags == 6 - vfs = torch.stack([vf.reshape(-1) for _, vf in - _registered(source, ds, motion, m)]) # fmt: skip - ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() - pix = ok[:: max(1, ok.numel() // 6)][:6] - f0, f1 = 8, 16 - e = f1 + geo.n_lags - res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) - for j, p in enumerate(pix.tolist()): - for t in range(f0, f1): - at = _coefficients(layout, source, ds, motion, m, t, p) - g0 = sum(v * v for v in at.values()) - r0 = sum(v**3 for v in at.values()) - assert res["G"][0, t - f0, j] == pytest.approx(g0, rel=1e-5) - assert res["R0"][t - f0, j] == pytest.approx(r0, rel=1e-5) - for lag in (1, 3, 6): - au = _coefficients(layout, source, ds, motion, m, t + lag, p) - g = sum(v * au.get(k, 0) for k, v in at.items()) - rr = sum(v * v * au.get(k, 0) for k, v in at.items()) - got = res["G"][lag, t - f0, j] - assert abs(got - g) <= 1e-5 * g0 - assert abs(res["R"][lag - 1, t - f0, j] - rr) <= 1e-5 * r0 - - -# ------------------------------------------------------------------- gains - - -def _compound_poisson( - rate: np.ndarray, rng: np.random.Generator, k: float = 5.0, theta: float = 22.0 -) -> np.ndarray: - """Draw samples: sums of Poisson(rate) integer gamma pulses (int16). - - Returns - ------- - np.ndarray - The samples, with the shape of rate, as int16. - """ - n = rng.poisson(rate) - out = np.zeros(rate.shape) - for j in range(int(n.max())): - use = n > j - out[use] += np.round(rng.gamma(k, theta, int(use.sum()))) - return out.astype(np.int16) - - -def scan_layout(path: Path, n_cycles: int) -> RasterLayout: - """Build a raster scanned row by row. - - Line r + 2 samples row 8 + r, columns 10-39 from left to right - (so consecutive samples on a line are horizontal neighbours); line 1 has - no samples. - - Returns - ------- - RasterLayout - The layout of the scanned raster (not written to a file). - """ - n_rows, n_cols, n_ch, rows = 36, 50, 2, 20 - p = rows + 1 - slot_line, slot_pos, slot_pixel = [], [], [] - for r in range(rows): - for j, c in enumerate(range(10, 40)): - slot_line.append(r + 2) - slot_pos.append(j) - slot_pixel.append((8 + r) * n_cols + c + 1) - n_per = np.array([0] + [30] * rows) - header_words = LINE_HEADER_BYTES // 2 - line_words = header_words + n_ch * n_per - line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) - return RasterLayout( - files=(str(path),), - file_cycles=np.array([n_cycles]), - file_offset_words=np.array([HEADER_WORDS]), - words_per_cycle=int(line_words.sum()), - lines_per_cycle=p, - n_rows=n_rows, - n_cols=n_cols, - num_channels=n_ch, - line_period_s=1 / 1600.0, - line_header_bytes=LINE_HEADER_BYTES, - line_header_words=line_header, - row_base=line_header + header_words, - n_per_channel=n_per, - line_fast_z=np.ones(p, dtype=np.int64), - fast_zs=np.array([-20.0]), - slot_line=np.array(slot_line), - slot_pos=np.array(slot_pos), - slot_pixel=np.array(slot_pixel), - ) - - -def _shared_pulses( - rate: np.ndarray, - nxt: np.ndarray, - rng: np.random.Generator, - p_split: float = 0.35, - k: float = 5.0, - theta: float = 22.0, -) -> np.ndarray: - """Draw compound-Poisson samples whose pulses are sometimes shared with the next sample. - - With probability p_split a fraction U(0, 0.5) of a pulse goes to - the next sample on the line. - - Returns - ------- - np.ndarray - The samples, with the shape of rate, as int16. - """ - n = rng.poisson(rate) - out = np.zeros(rate.shape) - has = nxt >= 0 - for j in range(int(n.max())): - use = n > j - a = np.zeros(rate.shape) - a[use] = np.round(rng.gamma(k, theta, int(use.sum()))) - split = (rng.random(rate.shape) < p_split) & has[..., :, None] - moved = np.round(a * rng.random(rate.shape) * 0.5) * split - out += a - moved - out[..., nxt[has], :] += moved[..., has, :] - return out.astype(np.int16) - - -def test_gain_groups_without_zeros_keep_their_gains() -> None: - """Bright groups that have no zero sample keep their gains. - - The non-zero rate comes from the groups that have zeros. - """ - rng = np.random.default_rng(4) - rate = np.repeat(np.geomspace(0.05, 60, 320)[:, None], 2000, 1) - x = (100 * rng.poisson(rate)).astype(np.int16) - curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) - assert curve.mu.size == 16 - assert np.isnan(curve.nu_per_mu[-1]) # no zeros at ~50 photons - np.testing.assert_allclose(curve.g2, 100, rtol=0.05) # >= 2000 photons - assert np.isfinite(curve.g3).all() - np.testing.assert_allclose(curve.g3[:8], 1e4, rtol=0.1) # dim: precise - at = curve.at(curve.mu) - assert np.isfinite(at["nu"]).all() - ok = np.isfinite(curve.nu_per_mu) - np.testing.assert_allclose(at["nu"][ok], (curve.mu * curve.nu_per_mu)[ok]) - one = curve.at(100.0) # a scalar mean too - assert one["g2"].shape == () and np.isfinite(one["g2"]) - assert np.isnan(curve.at(np.nan)["g2"]) - - -def test_gain_sums_do_not_overflow() -> None: - """Cubes of extreme second differences over a long trial would overflow int64. - - Those sums are float64 then (and exact int64 for ordinary trials). - """ - x = np.zeros((2, 150_000), dtype=np.int16) - x[:, ::3] = 32767 # d = 65534, -32767, -32767: cubes sum to > 2^63 - got = slot_sums(torch.from_numpy(x[None]), 0) - d = 2 * x[:, 1:-1].astype(object) - x[:, :-2] - x[:, 2:] - want = [sum(int(v) ** 3 for v in row) for row in d] - np.testing.assert_allclose(got[:, 6], np.array(want, float), rtol=1e-12) - assert abs(want[0]) > 2**63 # int64 would have overflowed - short = slot_sums(torch.from_numpy(x[None, :, :100]), 0) - assert short.dtype == np.int64 - # nor do a group's sums of large per-slot sums - rows = np.tile([100, 1000, 10, 98, 980, 6000, 3 * 10**18], (32, 1)) - curve = curve_from_sums(rows.astype(np.int64), n_bins=2) - np.testing.assert_allclose(curve.g3, 3e18 / (6 * 980), rtol=1e-12) - - -def test_components_of_tall_and_wide_inputs() -> None: - """The top components equal numpy's SVD whichever Gram matrix is smaller. - - That is, with more time bins than spatial bins, or fewer. - """ - from giant_python.registration.stats.svd import _components - - rng = np.random.default_rng(9) - for shape in ((40, 300), (300, 40)): - y = rng.normal(size=shape) + np.outer( - np.sin(np.arange(shape[0]) / 5), rng.normal(size=shape[1]) - ) - u, s, total = _components(y, 3) - uu, ss, _ = np.linalg.svd(y, full_matrices=False) - np.testing.assert_allclose(s, ss[:3], rtol=1e-9) - np.testing.assert_allclose(np.abs(u.T @ uu[:, :3]), np.eye(3), atol=1e-8) - assert (np.sum(y.T @ u, 0) >= 0).all() - assert total == pytest.approx(np.sum(y**2)) - # rank 1 (tall and wide): one component, finite, and weights for it - for shape in ((300, 40), (40, 300)): - a, b = rng.normal(size=shape[0]), rng.normal(size=shape[1]) - y = np.outer(a, b) - u, s, _ = _components(y, 3) - assert u.shape == (shape[0], 1) and np.isfinite(u).all() - np.testing.assert_allclose(s, [np.linalg.norm(a) * np.linalg.norm(b)]) - - -def test_regression_weights_of_undetermined_pixels() -> None: - """A pixel whose valid bins leave a time course flat gets NaN weights (not an error). - - The others are fitted. - """ - from giant_python.registration.stats.svd import regression_weights - - rng = np.random.default_rng(8) - nb = 280 - u = np.zeros((nb, 2)) - u[:100, 0] = rng.normal(size=100) # active in the first 100 bins only - u[:, 1] = rng.normal(size=nb) - u /= np.linalg.norm(u, axis=0) - y = 5 + u @ np.array([[3.0, 2.0, 1.0], [1.0, -1.0, 4.0]]) - y[:100, 1] = np.nan # pixel 1 misses the first course's activity - w = regression_weights(y, u) - np.testing.assert_allclose(w[[0, 2]], [[3.0, 1.0], [1.0, 4.0]]) - assert np.isnan(w[1]).all() - - -def test_gain_curve_of_compound_poisson() -> None: - """Gains equal E[A^2]/E[A] and E[A^3]/E[A] of the pulse heights.""" - rng = np.random.default_rng(3) - rate = np.repeat(np.geomspace(0.03, 3, 1600)[:, None], 3000, 1) - x = _compound_poisson(rate, rng) - pulses = np.round(rng.gamma(5.0, 22.0, 2_000_000)) - g2 = (pulses**2).mean() / pulses.mean() - g3 = (pulses**3).mean() / pulses.mean() - curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) - assert np.allclose(curve.g2, g2, rtol=0.03) # >= 9000 photons each - assert np.allclose(curve.g3, g3, rtol=0.08) - nu = curve.at(curve.mu)["nu"] - zero = (x == 0).mean(1) - mean = x.mean(1) - want = np.interp(curve.mu, mean, -np.log(zero)) - assert np.allclose(nu, want, rtol=0.05) - - -# --------------------------------------------------------------- the maps - - -def _stats( - layout: RasterLayout, samples: np.ndarray, motion_seed: int = 0, last: float = 9000.0 -) -> dict: - """Statistics of samples through registration's frame formation. - - Returns - ------- - dict - The finished accumulator's statistics (maps and curves). - """ - source, ds = _source(layout, samples, last=last) - acc = new_accumulator(source, ds, 6, layout.num_channels) - motion = _motion(ds.size, motion_seed) - for k, (regs, vf) in enumerate(_registered(source, ds, motion, 6)): - acc.add(k, regs, vf, tuple(motion[k])) - return acc.finish() - - -def _interior(maps: dict[str, np.ndarray]) -> np.ndarray: - """Pixels whose maps are defined in every channel. - - Returns - ------- - np.ndarray - Boolean mask of the pixels where the slow and fast maps are finite in all channels. - """ - return np.isfinite(maps["slow_rel"]).all(0) & np.isfinite(maps["fast_rel"]).all(0) - - -@pytest.fixture(scope="module") -def uniform( - tmp_path_factory: pytest.TempPathFactory, -) -> tuple[RasterLayout, np.ndarray, np.ndarray]: - """Simulate a uniform scene of compound-Poisson samples. - - 0.05 and 2 photons per sample in the two channels; no file needed. - - Returns - ------- - layout : RasterLayout - The layout of the simulated recording. - samples : np.ndarray - The compound-Poisson samples of both channels. - rate : np.ndarray - The photon rate per sample (channels, slots, cycles). - """ - path = tmp_path_factory.mktemp("uni") / "uniform_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1600) - rng = np.random.default_rng(5) - shape = (layout.slot_line.size, layout.num_cycles) - rate = np.stack([np.full(shape, 0.05), np.full(shape, 2.0)]) - return layout, _compound_poisson(rate, rng), rate - - -def test_photon_noise_maps_read_zero(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: - """Under photon noise alone the normalised maps are 0 at any brightness. - - Means over pixels: a variance from few blocks is unbiased but its median - is low, as for chi-square. - """ - layout, samples, _ = uniform - res = _stats(layout, samples, last=11000.0) - maps = res["maps"] - use = _interior(maps) - assert use.sum() > 300 - for ch in range(2): - for name, tol in ( - ("var_rel", 0.02), - ("fast_rel", 0.02), - ("slow_rel", 0.1), - ("fast_skew_rel", 0.06), - ("zero_excess", 0.003), - ): - mean = np.mean(maps[name][ch][use]) - assert abs(mean) < tol, (ch, name, mean) - gains = measure_gain_curves(torch.from_numpy(samples)) - assert np.allclose(gains[1].g2, 132.0, rtol=0.03) - assert res["svd"]["var_share"].shape == (2, 3) - - -def test_events_raise_fast_skewness(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: - """Positive transients raise the fast maps where they are.""" - layout, _, rate = uniform - rate = rate.copy() - rows = (layout.slot_pixel - 1) // layout.n_cols - cols = (layout.slot_pixel - 1) % layout.n_cols - src = (np.abs(rows - 17) <= 1) & (np.abs(cols - 24) <= 1) - p = layout.lines_per_cycle - t = (np.arange(layout.num_cycles) * p) * layout.line_period_s - kern = np.zeros(t.size) - for onset in np.arange(0.3, t[-1], 0.9): - kern += np.where(t >= onset, np.exp(-(t - onset) / 0.025), 0.0) - rate[1, src] += 4.0 * kern - samples = _compound_poisson(rate, np.random.default_rng(6)) - maps = _stats(layout, samples, last=11000.0)["maps"] - m = 6 - sk = maps["fast_skew_rel"][1] - fr = maps["fast_rel"][1] - at = sk[17 - 8 + m, 24 - 10 + m] - away = np.nanmedian(sk[m : m + 5]) # DMD rows 8-12 - assert at > 1.0 and abs(away) < 0.2 - assert fr[17 - 8 + m, 24 - 10 + m] > 1.0 - - -# ------------------------------------------------- registration and command - - -@pytest.mark.parametrize( - "device", - [ - "cpu", - pytest.param( - "cuda", - marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="no CUDA device"), - ), - ], -) -def test_registration_and_command_agree(patched: RasterLayout, tmp_path: Path, device: str) -> None: - """``giant reg-stats`` on registration's outputs gives the same maps. - - On a GPU registration's run on a thread and stream of their own, the - command's in line. The mean equals meanIM; statistics do not change - the movie. - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - out = {} - for stats in (True, False): - d = tmp_path / str(stats) - d.mkdir() - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - multiroi.register_trial( - layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params, - device=device, stats=stats, - ) # fmt: skip - with h5py.File(d / MOVIE) as f: - out[stats] = f["data"][()] - np.testing.assert_array_equal(out[True], out[False]) - assert not stats_path(tmp_path / "False" / MOVIE).exists() - d = tmp_path / "True" - a = read_stats(stats_path(d / MOVIE)) - assert a["attrs"]["stats_version"] == STATS_VERSION - with h5py.File(d / ADATA) as f: - mean_im = np.swapaxes(np.moveaxis(f["meanIM"][()], -1, 0), 1, 2) - np.testing.assert_array_equal(a["maps"]["mean"], mean_im) - cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name - trial_stats(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, cmd, device, - {"maxshift": 6}) # fmt: skip - b = read_stats(cmd) - for grp in ("maps", "svd", "gain"): - assert a[grp].keys() == b[grp].keys() - for k in a[grp]: - np.testing.assert_array_equal(a[grp][k], b[grp][k], err_msg=k) - - -@pytest.mark.parametrize("last", [2.0, 60.0]) -def test_short_trials_get_statistics(patched: RasterLayout, tmp_path: Path, last: float) -> None: - """A one-frame (or three-frame) trial gets a statistics file equal to the command's. - - Its maps are NaN where there are too few frames. - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, last, tmp_path / MOVIE, tmp_path / ADATA) - res = multiroi.register_trial(*args, params) - assert res.ds_frames.size <= 3 - a = read_stats(stats_path(tmp_path / MOVIE)) - assert np.isnan(a["maps"]["fast_rel"]).all() - assert np.nanmax(a["maps"]["n_valid"]) == res.ds_frames.size - b = trial_stats(*args, tmp_path / "cmd.h5", "cpu", {"maxshift": 6}) - for k in a["maps"]: - np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) - - -def test_command_treats_empty_frames_as_missing(patched: RasterLayout, tmp_path: Path) -> None: - """A frame without data counts as missing in the command. - - This holds even where the alignment file gives it a motion (as - GIAnT-MATLAB's may). - """ - from giant_python.pipeline.reg_stats import trial_stats - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) - multiroi.register_trial(*args, params) - with h5py.File(tmp_path / MOVIE, "r+") as f: - n_ch = layout.num_channels - f["data"][10 * n_ch : 11 * n_ch] = np.nan # frame 10 without data - finite = trial_stats(*args, tmp_path / "a.h5", "cpu", {"maxshift": 6}) - with h5py.File(tmp_path / ADATA, "r+") as f: - for key in ("motionDSr", "motionDSc"): - m = f[key][()] - m.reshape(-1)[10] = np.nan - f[key][...] = m - missing = trial_stats(*args, tmp_path / "b.h5", "cpu", {"maxshift": 6}) - for k in finite["maps"]: - np.testing.assert_array_equal(finite["maps"][k], missing["maps"][k], err_msg=k) - for k in ("spatial_factor", "pair_bin_factor"): # frame 10 left out - assert finite["attrs"][k] == missing["attrs"][k] - - -def test_rerun_without_stats_removes_old_file(patched: RasterLayout, tmp_path: Path) -> None: - """A registration without statistics leaves none from an earlier one.""" - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) - multiroi.register_trial(*args, params) - assert stats_path(tmp_path / MOVIE).exists() - multiroi.register_trial(*args, params, stats=False) - assert not stats_path(tmp_path / MOVIE).exists() - - -@pytest.mark.parametrize("step", ["start", "setup", "add", "finish", "write"]) -def test_failed_statistics_leave_registration( - patched: RasterLayout, - tmp_path: Path, - step: str, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, -) -> None: - """A statistics step that fails is logged. - - The step fails on the worker thread, or writing the file, with its - cleanup failing too. Registration publishes the same movie and alignment - file, without statistics (and removes an earlier statistics file). - """ - import pathlib - - from giant_python.registration.stats import accumulate, io - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - ref = tmp_path / "ref" - ref.mkdir() - multiroi.register_trial(layout.files[0], 1, 3000, ref / MOVIE, ref / ADATA, params, stats=False) - - def fail(*args: object, **kwargs: object) -> NoReturn: - """Fail as a broken step. - - Raises - ------ - RuntimeError - Always. - """ - raise RuntimeError("broken statistics") - - if step == "start": - monkeypatch.setattr(multiroi, "StatsWorker", fail) - elif step == "setup": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "__init__", fail) - elif step == "add": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_block", fail) - elif step == "finish": - monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_maps", fail) - else: - monkeypatch.setattr(io, "write_stats", fail) - unlink = pathlib.Path.unlink - - def locked(path: Path, *args: object, **kwargs: object) -> None: - """Path.unlink, refusing the partial statistics file. - - Raises - ------ - PermissionError - If the path is a partial statistics file, not the final one. - """ - if "REGSTATS" in path.name and path.name != STATS_NAME: - raise PermissionError("locked") - return unlink(path, *args, **kwargs) - - STATS_NAME = stats_path(tmp_path / MOVIE).name - monkeypatch.setattr(pathlib.Path, "unlink", locked) - d = tmp_path / "run" - d.mkdir() - stats_path(d / MOVIE).write_bytes(b"from an earlier registration") - multiroi.register_trial(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params) - assert "summary statistics" in caplog.text - assert not stats_path(d / MOVIE).exists() - assert sorted(p.name for p in d.iterdir()) == [ADATA, MOVIE] - with h5py.File(d / MOVIE) as f, h5py.File(ref / MOVIE) as g: - np.testing.assert_array_equal(f["data"][()], g["data"][()]) - with h5py.File(d / ADATA) as f, h5py.File(ref / ADATA) as g: - for k in ("motionDSr", "motionDSc", "meanIM"): - np.testing.assert_array_equal(f[k][()], g[k][()]) - - -def test_command_checks_online_compensation( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """For an online-compensated trial the command rebuilds the compensation registration saved. - - It gets the same maps and refuses a trial whose saved record differs. - """ - from giant_python.pipeline.reg_stats import trial_stats - - from .synthetic import online_offsets - - layout = make_layout(tmp_path / "online_DMD1-TRIAL000001.dat", n_cycles=1400, seed=5) - write_recording(layout, seed=6, online=online_offsets(layout.total_lines)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=True) - d = tmp_path / "reg" - d.mkdir() - args = (layout.files[0], 1, 6000, d / MOVIE, d / ADATA) - multiroi.register_trial(*args, params) - a = read_stats(stats_path(d / MOVIE)) - cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name - trial_stats(*args, cmd, "cpu", {"maxshift": 6}) - b = read_stats(cmd) - for k in a["maps"]: - np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) - with h5py.File(d / ADATA, "r+") as f: - lead = f["slap2/onlineCompensation/yLead"] - lead[...] = lead[()] + 1 - with pytest.raises(ValueError, match="yLead"): - trial_stats(*args, tmp_path / "other.h5", "cpu", {"maxshift": 6}) - - -def test_statistics_file_that_cannot_be_moved( - patched: RasterLayout, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, -) -> None: - """If the statistics file cannot be moved into place, the other outputs are published. - - The movie and the alignment file are published all the same, without - statistics (an earlier statistics file is removed). - """ - import os - - layout = patched - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - stale = stats_path(tmp_path / MOVIE) - stale.write_bytes(b"from an earlier registration") - replace = os.replace - - def refuse_stats(src: str | Path, dst: str | Path) -> None: - """os.replace, refusing the statistics file. - - Raises - ------ - PermissionError - If the destination is the statistics file. - """ - if Path(dst) == stale: - raise PermissionError("locked") - return replace(src, dst) - - monkeypatch.setattr(os, "replace", refuse_stats) - multiroi.register_trial(layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA, params) - assert "not published" in caplog.text - assert sorted(p.name for p in tmp_path.iterdir()) == [ADATA, MOVIE] - - -def test_reg_stats_command(patched: RasterLayout, tmp_path: Path) -> None: - """The CLI writes the statistics of a table's trials once.""" - from giant_python.cli import main - from giant_python.pipeline.reg_stats import reg_stats - from giant_python.pipeline.register import register_multiroi - - layout = patched - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[1.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - }, - ) - register_multiroi( - table, - {"maxshift": 5}, - execution={"device": "cpu", "max_workers": 1}, - stats=False, - ) - out = tmp_path / "stats" - assert main(["reg-stats", str(table), "--out", str(out), - "--device", "cpu"]) == 0 # fmt: skip - written = out / "E1T1DMD1_REGSTATS-80Hz.h5" - assert written.exists() - assert reg_stats(table, out, device="cpu") == [] # up to date - with h5py.File(written, "r+") as f: # as if the movie were rewritten - f.attrs["movie_size"] = int(f.attrs["movie_size"]) + 1 - assert len(reg_stats(table, out, device="cpu")) == 1 - assert read_stats(written)["attrs"]["validity_differs"] == [0, 0] - movie = tmp_path / "motion_correction" / MOVIE - movie.rename(movie.with_suffix(".moved")) # a requested trial is missing - assert main(["reg-stats", str(table), "--out", str(out), - "--device", "cpu"]) == 1 # fmt: skip - - -def test_validity_mismatch_counts_channels() -> None: - """Samples whose validity differs from the first channel's are counted per channel.""" - from giant_python.io.slap2_raster import INVALID_SAMPLE - from giant_python.registration.stats.gain import validity_mismatch - - x = np.ones((3, 300, 50), dtype=np.int16) - x[:, 0, :5] = INVALID_SAMPLE # all channels: no mismatch - x[1, 10, :7] = INVALID_SAMPLE - x[2, 200, :3] = INVALID_SAMPLE - x[0, 250, :2] = INVALID_SAMPLE # first channel only: both others - assert validity_mismatch(torch.from_numpy(x)) == [0, 9, 5] - - -def test_stats_path_names() -> None: - """Statistics files sit next to the movie, named after it.""" - assert stats_path(Path("d") / MOVIE).name == "E1T1DMD1_REGSTATS-80Hz.h5" - tif = Path("E2T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif") - assert stats_path(tif).name == "E2T3DMD2_REGSTATS-80Hz.h5" - assert stats_path(Path("m.h5")).name == "m_REGSTATS.h5" - - -# ----------------------------------------------------------------- session - - -def test_combine_trials_weights_by_frames() -> None: - """Session maps: shifted, frame-weighted means. - - Normalised maps are formed from the averages. - """ - shape = (1, 20, 30) - trials = [] - for t, (n, var) in enumerate(((100.0, 2.0), (300.0, 4.0))): - maps = {} - for k in ("n_valid", "n_blocks", "n_fast"): - maps[k] = np.full(shape, n) - for k in ("mean", "var", "var_q", "zero_share", "zero_ph", - "gain_g2", "gain_g3", "sigma8_ph", "slow_var", "slow_q", - "fast_var", "fast_q", "fast_m3", "fast_q3", - "fast_m3_ph"): # fmt: skip - maps[k] = np.full(shape, 1.0) - maps["var"] = np.full(shape, var) - for k in ("var_ph", "slow_var_ph", "fast_var_ph"): - maps[k] = np.full(shape, 2.0) - maps["mean"][0, :, 0] = np.nan - trials.append({"maps": maps}) - out = combine_trials(trials, shifts=np.array([[0.0, 0.0], [0.0, 1.0]])) - assert out["n_valid"][0, 5, 5] == pytest.approx(400.0) - assert out["var"][0, 5, 5] == pytest.approx((100 * 2 + 300 * 4) / 400) - assert out["var_rel"][0, 5, 5] == pytest.approx(3.5 / 2 - 1) - assert out["n_trials"][0, 5, 5] == 2 - # trial 2's first column is missing; shifted by one column it lands - # left of the frame, and its last column has no data - assert out["n_trials"][0, 5, -1] == 1 - - -def test_combine_trials_of_different_sizes() -> None: - """Trials of different registered sizes share the largest canvas (top left, as SILo's).""" - trials = [] - for shape in ((1, 20, 30), (1, 18, 32)): - maps = {k: np.full(shape, 50.0) for k in ("n_valid", "n_blocks", - "n_fast")} # fmt: skip - for k in ("mean", "var", "var_ph", "zero_share", "zero_ph"): - maps[k] = np.full(shape, 1.0) - trials.append({"maps": maps}) - out = combine_trials(trials, shifts=np.zeros((2, 2))) - assert out["n_valid"].shape == (1, 20, 32) - assert out["n_trials"][0, 5, 5] == 2 - assert out["n_trials"][0, 19, 5] == 1 # rows 18-19: the first only - assert out["n_trials"][0, 5, 31] == 1 # cols 30-31: the second only - assert out["n_trials"][0, 19, 31] == 0 - assert np.isnan(out["var"][0, 19, 31]) - two = {"maps": {k: np.concatenate([v, v]) for k, v in trials[1]["maps"].items()}} - with pytest.raises(ValueError, match="channels"): - combine_trials([trials[0], two], shifts=np.zeros((2, 2))) - # fractional shifts: interior pixels count every trial despite rounding - out = combine_trials([trials[0], trials[0]], shifts=np.array([[0.3, 0.7], [0.1, 0.9]])) - assert (out["n_trials"][0, 2:-2, 2:-2] == 2).all() - - -def test_pair_sums_match_definition(tmp_path: Path) -> None: - """Sums over pairs of consecutive samples equal their definition.""" - layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 600) - samples = np.ones((2, layout.slot_line.size, 600), dtype=np.int16) - source, ds = _source(layout, samples) - m = 6 - motion = _motion(ds.size, seed=3) - geo = FrameGeometry(source, ds, m) - assert (0, 1) in geo.directions - vfs = torch.stack([vf.reshape(-1) for _, vf in - _registered(source, ds, motion, m)]) # fmt: skip - ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() - pix = ok[:: max(1, ok.numel() // 6)][:6] - f0, f1 = 8, 14 - e = f1 + geo.n_lags - res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) - nxt = next_slots(layout.slot_line, layout.slot_pos) - for j, p in enumerate(pix.tolist()): - for t in range(f0, f1): - at = _coefficients(layout, source, ds, motion, m, t, p) - pairs = [ - (v, at[(nxt[s], c)]) - for (s, c), v in at.items() - if nxt[s] >= 0 and (nxt[s], c) in at - ] - g0 = sum(v * v for v in at.values()) - want = ( - sum(a * b for a, b in pairs), - sum(a * a * b for a, b in pairs), - sum(a * b * b for a, b in pairs), - ) - for name, ref in zip(("QA2", "QA3a", "QA3b"), want): - assert abs(res[name][t - f0, j] - ref) <= 1e-5 * g0 - - -def test_shared_pulses_read_zero(tmp_path: Path) -> None: - """Pulses shared by consecutive samples correlate neighbouring pixels. - - With the pair terms, photon noise still reads 0 after registration's - bilinear resampling mixes them. - """ - layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 1600) - nxt = next_slots(layout.slot_line, layout.slot_pos) - rng = np.random.default_rng(7) - shape = (layout.slot_line.size, layout.num_cycles) - rate = np.stack([np.full(shape, 0.1), np.full(shape, 2.0)]) - samples = _shared_pulses(rate, nxt, rng) - curve = pair_curve(pair_sums(torch.from_numpy(samples), 1, nxt)) - rho = np.median(curve["c2"]) / 132.0 - assert 0.05 < rho < 0.2 - res = _stats(layout, samples, last=11000.0) - maps = res["maps"] - use = _interior(maps) - assert use.sum() > 300 - for ch in range(2): - assert np.mean(maps["var_qa"][ch][use]) > 0 - # at this size the dim channel's skewness varies by about 0.08 - # between seeds (the pixels share the measured gains) - for name, tol in ( - ("var_rel", 0.03), - ("fast_rel", 0.03), - ("slow_rel", 0.1), - ("fast_skew_rel", 0.15 if ch == 0 else 0.06), - ("zero_excess", 0.005), - ): - mean = np.mean(maps[name][ch][use]) - assert abs(mean) < tol, (ch, name, mean) - # the shared modes' input is in photon-noise units: unit variance per - # 2 x 2 bin and 8-frame bin (centred over time), pairs inside included - svd = res["svd"] - unit = svd["total_var"] / (svd["n_space"] * (svd["n_bins"] - 1)) - np.testing.assert_allclose(unit, 1.0, atol=0.05) # 1.08-1.11 without +"""Registration summary statistics (registration.stats).""" + +from collections.abc import Iterator +from pathlib import Path +from typing import NoReturn + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import RasterLayout, read_raster_samples +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer +from giant_python.registration.interpolation import interp_frame +from giant_python.registration.multiroi import frame_times +from giant_python.registration.sources import ( + CompensatedFrames, + PlainFrames, + make_source, +) +from giant_python.registration.stats import ( + STATS_VERSION, + measure_gain_curves, + new_accumulator, + read_stats, + stats_path, +) +from giant_python.registration.stats.gain import ( + curve_from_sums, + next_slots, + pair_curve, + pair_sums, + slot_sums, +) +from giant_python.registration.stats.geometry import ( + FrameGeometry, + bilinear_corners, +) +from giant_python.registration.stats.session import combine_trials + +from .synthetic import HEADER_WORDS, LINE_HEADER_BYTES, make_layout, write_recording + +MOVIE = "E1T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" +ADATA = "E1T1DMD1_ALIGNMENTDATA.h5" + + +@pytest.fixture(scope="module") +def recording(tmp_path_factory: pytest.TempPathFactory) -> RasterLayout: + """Layout and data file of a 6-second recording (moving scene). + + Returns + ------- + RasterLayout + The layout of the written recording. + """ + path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400) + write_recording(layout, invalid=0.0) + return layout + + +@pytest.fixture +def patched(recording: RasterLayout, monkeypatch: pytest.MonkeyPatch) -> RasterLayout: + """Patch registration to read the recording's layout. + + Returns + ------- + RasterLayout + The recording's layout. + """ + monkeypatch.setattr(multiroi, "raster_layout", lambda path: recording) + return recording + + +def _source( + layout: RasterLayout, samples: np.ndarray, first: float = 1.0, last: float = 3000.0 +) -> tuple[PlainFrames | CompensatedFrames, np.ndarray]: + """Frame source of samples over the layout (as registration's). + + Returns + ------- + source : PlainFrames or CompensatedFrames + The frame source of samples. + ds : np.ndarray + The frame times the source is read at. + """ + former = FrameFormer(layout, samples, 0) + dt = (1 / layout.line_period_s) / 80 + dtk = int(np.ceil(dt)) + init, ds = frame_times(first, last, dt, 40) + return make_source(layout, former, first, last, init, ds, dtk, False), ds + + +def _motion(n: int, seed: int = 0, jump: int | None = None) -> np.ndarray: + """Sub-pixel motion (rows, cols) with jitter. + + Returns + ------- + np.ndarray + (n, 2) row and column motion per frame, with a step at jump when given. + """ + rng = np.random.default_rng(seed) + t = np.arange(n) + m = np.stack( + [ + 0.7 * np.sin(t / 7.0) + rng.normal(0, 0.15, n), + 0.9 * np.cos(t / 11.0) + rng.normal(0, 0.15, n), + ], + 1, + ) + if jump is not None: + m[jump] += [1.3, -1.1] + return m + + +def _registered( + source: PlainFrames | CompensatedFrames, ds: np.ndarray, motion: np.ndarray, margin: int +) -> Iterator[tuple[list[torch.Tensor], torch.Tensor]]: + """Yield registered frames and variance factors (interp_frame). + + Yields + ------ + list of torch.Tensor + The registered frame of each channel. + torch.Tensor + The frame's variance factor. + """ + vals, fresh = source.frames(ds) + win = source.window + for k in range(ds.size): + fimg = win.image(fresh[k], 0.0) + regs = [ + interp_frame(win.image(vals[ch, k], float("nan")), fimg, *motion[k], margin) + for ch in range(vals.shape[0]) + ] + yield [r for r, _ in regs], regs[0][1] + + +# --------------------------------------------------------------- geometry + + +def _coefficients( + layout: RasterLayout, + source: PlainFrames | CompensatedFrames, + ds: np.ndarray, + motion: np.ndarray, + margin: int, + t: int, + p: int, +) -> dict[tuple[int, int], float]: + """Sample coefficients of registered frame t at output pixel p by the definition. + + This uses slow loops. + + Returns + ------- + dict + The coefficient of each (slot, cycle) sample, normalised to sum to 1. + """ + win = source.window + w_out = win.shape[1] + 2 * margin + ids = source.former.pixels[source.pixels.numpy()] + where = { + (int(r), int(c)): i for i, (r, c) in enumerate(zip(win.rows.numpy(), win.cols.numpy())) + } + dt = int(source.dt) + reach = max(3 * dt, layout.lines_per_cycle) + r, c = divmod(int(p), w_out) + off_r, off_c, coef, _ = bilinear_corners(*motion[t], margin) + parts, den = [], 0.0 + for k, (a, b) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))): + i = where.get((r + off_r + a, c + off_c + b)) + if i is None: + continue + slots = np.flatnonzero(layout.slot_pixel == ids[i]) + for s in slots: + for cyc in range(layout.num_cycles): + line = cyc * layout.lines_per_cycle + layout.slot_line[s] + if abs(ds[t] - line) <= reach: + wgt = coef[k] * np.exp(-abs(ds[t] - line) / dt) + parts.append(((s, cyc), wgt)) + den += wgt + out = {} + for key, v in parts: + out[key] = out.get(key, 0.0) + v / den + return out + + +def test_geometry_matches_definition(recording: RasterLayout) -> None: + """Photon-noise sums equal sums over the samples' coefficients.""" + layout = recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + source, ds = _source(layout, samples) + m = 6 + motion = _motion(ds.size, jump=12) + geo = FrameGeometry(source, ds, m) + assert geo.n_lags == 6 + vfs = torch.stack([vf.reshape(-1) for _, vf in + _registered(source, ds, motion, m)]) # fmt: skip + ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() + pix = ok[:: max(1, ok.numel() // 6)][:6] + f0, f1 = 8, 16 + e = f1 + geo.n_lags + res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) + for j, p in enumerate(pix.tolist()): + for t in range(f0, f1): + at = _coefficients(layout, source, ds, motion, m, t, p) + g0 = sum(v * v for v in at.values()) + r0 = sum(v**3 for v in at.values()) + assert res["G"][0, t - f0, j] == pytest.approx(g0, rel=1e-5) + assert res["R0"][t - f0, j] == pytest.approx(r0, rel=1e-5) + for lag in (1, 3, 6): + au = _coefficients(layout, source, ds, motion, m, t + lag, p) + g = sum(v * au.get(k, 0) for k, v in at.items()) + rr = sum(v * v * au.get(k, 0) for k, v in at.items()) + got = res["G"][lag, t - f0, j] + assert abs(got - g) <= 1e-5 * g0 + assert abs(res["R"][lag - 1, t - f0, j] - rr) <= 1e-5 * r0 + + +# ------------------------------------------------------------------- gains + + +def _compound_poisson( + rate: np.ndarray, rng: np.random.Generator, k: float = 5.0, theta: float = 22.0 +) -> np.ndarray: + """Draw samples: sums of Poisson(rate) integer gamma pulses (int16). + + Returns + ------- + np.ndarray + The samples, with the shape of rate, as int16. + """ + n = rng.poisson(rate) + out = np.zeros(rate.shape) + for j in range(int(n.max())): + use = n > j + out[use] += np.round(rng.gamma(k, theta, int(use.sum()))) + return out.astype(np.int16) + + +def scan_layout(path: Path, n_cycles: int) -> RasterLayout: + """Build a raster scanned row by row. + + Line r + 2 samples row 8 + r, columns 10-39 from left to right + (so consecutive samples on a line are horizontal neighbours); line 1 has + no samples. + + Returns + ------- + RasterLayout + The layout of the scanned raster (not written to a file). + """ + n_rows, n_cols, n_ch, rows = 36, 50, 2, 20 + p = rows + 1 + slot_line, slot_pos, slot_pixel = [], [], [] + for r in range(rows): + for j, c in enumerate(range(10, 40)): + slot_line.append(r + 2) + slot_pos.append(j) + slot_pixel.append((8 + r) * n_cols + c + 1) + n_per = np.array([0] + [30] * rows) + header_words = LINE_HEADER_BYTES // 2 + line_words = header_words + n_ch * n_per + line_header = np.concatenate([[0], np.cumsum(line_words)[:-1]]) + return RasterLayout( + files=(str(path),), + file_cycles=np.array([n_cycles]), + file_offset_words=np.array([HEADER_WORDS]), + words_per_cycle=int(line_words.sum()), + lines_per_cycle=p, + n_rows=n_rows, + n_cols=n_cols, + num_channels=n_ch, + line_period_s=1 / 1600.0, + line_header_bytes=LINE_HEADER_BYTES, + line_header_words=line_header, + row_base=line_header + header_words, + n_per_channel=n_per, + line_fast_z=np.ones(p, dtype=np.int64), + fast_zs=np.array([-20.0]), + slot_line=np.array(slot_line), + slot_pos=np.array(slot_pos), + slot_pixel=np.array(slot_pixel), + ) + + +def _shared_pulses( + rate: np.ndarray, + nxt: np.ndarray, + rng: np.random.Generator, + p_split: float = 0.35, + k: float = 5.0, + theta: float = 22.0, +) -> np.ndarray: + """Draw compound-Poisson samples whose pulses are sometimes shared with the next sample. + + With probability p_split a fraction U(0, 0.5) of a pulse goes to + the next sample on the line. + + Returns + ------- + np.ndarray + The samples, with the shape of rate, as int16. + """ + n = rng.poisson(rate) + out = np.zeros(rate.shape) + has = nxt >= 0 + for j in range(int(n.max())): + use = n > j + a = np.zeros(rate.shape) + a[use] = np.round(rng.gamma(k, theta, int(use.sum()))) + split = (rng.random(rate.shape) < p_split) & has[..., :, None] + moved = np.round(a * rng.random(rate.shape) * 0.5) * split + out += a - moved + out[..., nxt[has], :] += moved[..., has, :] + return out.astype(np.int16) + + +def test_gain_groups_without_zeros_keep_their_gains() -> None: + """Bright groups that have no zero sample keep their gains. + + The non-zero rate comes from the groups that have zeros. + """ + rng = np.random.default_rng(4) + rate = np.repeat(np.geomspace(0.05, 60, 320)[:, None], 2000, 1) + x = (100 * rng.poisson(rate)).astype(np.int16) + curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) + assert curve.mu.size == 16 + assert np.isnan(curve.nu_per_mu[-1]) # no zeros at ~50 photons + np.testing.assert_allclose(curve.g2, 100, rtol=0.05) # >= 2000 photons + assert np.isfinite(curve.g3).all() + np.testing.assert_allclose(curve.g3[:8], 1e4, rtol=0.1) # dim: precise + at = curve.at(curve.mu) + assert np.isfinite(at["nu"]).all() + ok = np.isfinite(curve.nu_per_mu) + np.testing.assert_allclose(at["nu"][ok], (curve.mu * curve.nu_per_mu)[ok]) + one = curve.at(100.0) # a scalar mean too + assert one["g2"].shape == () and np.isfinite(one["g2"]) + assert np.isnan(curve.at(np.nan)["g2"]) + + +def test_gain_sums_do_not_overflow() -> None: + """Cubes of extreme second differences over a long trial would overflow int64. + + Those sums are float64 then (and exact int64 for ordinary trials). + """ + x = np.zeros((2, 150_000), dtype=np.int16) + x[:, ::3] = 32767 # d = 65534, -32767, -32767: cubes sum to > 2^63 + got = slot_sums(torch.from_numpy(x[None]), 0) + d = 2 * x[:, 1:-1].astype(object) - x[:, :-2] - x[:, 2:] + want = [sum(int(v) ** 3 for v in row) for row in d] + np.testing.assert_allclose(got[:, 6], np.array(want, float), rtol=1e-12) + assert abs(want[0]) > 2**63 # int64 would have overflowed + short = slot_sums(torch.from_numpy(x[None, :, :100]), 0) + assert short.dtype == np.int64 + # nor do a group's sums of large per-slot sums + rows = np.tile([100, 1000, 10, 98, 980, 6000, 3 * 10**18], (32, 1)) + curve = curve_from_sums(rows.astype(np.int64), n_bins=2) + np.testing.assert_allclose(curve.g3, 3e18 / (6 * 980), rtol=1e-12) + + +def test_components_of_tall_and_wide_inputs() -> None: + """The top components equal numpy's SVD whichever Gram matrix is smaller. + + That is, with more time bins than spatial bins, or fewer. + """ + from giant_python.registration.stats.svd import _components + + rng = np.random.default_rng(9) + for shape in ((40, 300), (300, 40)): + y = rng.normal(size=shape) + np.outer( + np.sin(np.arange(shape[0]) / 5), rng.normal(size=shape[1]) + ) + u, s, total = _components(y, 3) + uu, ss, _ = np.linalg.svd(y, full_matrices=False) + np.testing.assert_allclose(s, ss[:3], rtol=1e-9) + np.testing.assert_allclose(np.abs(u.T @ uu[:, :3]), np.eye(3), atol=1e-8) + assert (np.sum(y.T @ u, 0) >= 0).all() + assert total == pytest.approx(np.sum(y**2)) + # rank 1 (tall and wide): one component, finite, and weights for it + for shape in ((300, 40), (40, 300)): + a, b = rng.normal(size=shape[0]), rng.normal(size=shape[1]) + y = np.outer(a, b) + u, s, _ = _components(y, 3) + assert u.shape == (shape[0], 1) and np.isfinite(u).all() + np.testing.assert_allclose(s, [np.linalg.norm(a) * np.linalg.norm(b)]) + + +def test_regression_weights_of_undetermined_pixels() -> None: + """A pixel whose valid bins leave a time course flat gets NaN weights (not an error). + + The others are fitted. + """ + from giant_python.registration.stats.svd import regression_weights + + rng = np.random.default_rng(8) + nb = 280 + u = np.zeros((nb, 2)) + u[:100, 0] = rng.normal(size=100) # active in the first 100 bins only + u[:, 1] = rng.normal(size=nb) + u /= np.linalg.norm(u, axis=0) + y = 5 + u @ np.array([[3.0, 2.0, 1.0], [1.0, -1.0, 4.0]]) + y[:100, 1] = np.nan # pixel 1 misses the first course's activity + w = regression_weights(y, u) + np.testing.assert_allclose(w[[0, 2]], [[3.0, 1.0], [1.0, 4.0]]) + assert np.isnan(w[1]).all() + + +def test_gain_curve_of_compound_poisson() -> None: + """Gains equal E[A^2]/E[A] and E[A^3]/E[A] of the pulse heights.""" + rng = np.random.default_rng(3) + rate = np.repeat(np.geomspace(0.03, 3, 1600)[:, None], 3000, 1) + x = _compound_poisson(rate, rng) + pulses = np.round(rng.gamma(5.0, 22.0, 2_000_000)) + g2 = (pulses**2).mean() / pulses.mean() + g3 = (pulses**3).mean() / pulses.mean() + curve = curve_from_sums(slot_sums(torch.from_numpy(x[None]), 0)) + assert np.allclose(curve.g2, g2, rtol=0.03) # >= 9000 photons each + assert np.allclose(curve.g3, g3, rtol=0.08) + nu = curve.at(curve.mu)["nu"] + zero = (x == 0).mean(1) + mean = x.mean(1) + want = np.interp(curve.mu, mean, -np.log(zero)) + assert np.allclose(nu, want, rtol=0.05) + + +# --------------------------------------------------------------- the maps + + +def _stats( + layout: RasterLayout, samples: np.ndarray, motion_seed: int = 0, last: float = 9000.0 +) -> dict: + """Statistics of samples through registration's frame formation. + + Returns + ------- + dict + The finished accumulator's statistics (maps and curves). + """ + source, ds = _source(layout, samples, last=last) + acc = new_accumulator(source, ds, 6, layout.num_channels) + motion = _motion(ds.size, motion_seed) + for k, (regs, vf) in enumerate(_registered(source, ds, motion, 6)): + acc.add(k, regs, vf, tuple(motion[k])) + return acc.finish() + + +def _interior(maps: dict[str, np.ndarray]) -> np.ndarray: + """Pixels whose maps are defined in every channel. + + Returns + ------- + np.ndarray + Boolean mask of the pixels where the slow and fast maps are finite in all channels. + """ + return np.isfinite(maps["slow_rel"]).all(0) & np.isfinite(maps["fast_rel"]).all(0) + + +@pytest.fixture(scope="module") +def uniform( + tmp_path_factory: pytest.TempPathFactory, +) -> tuple[RasterLayout, np.ndarray, np.ndarray]: + """Simulate a uniform scene of compound-Poisson samples. + + 0.05 and 2 photons per sample in the two channels; no file needed. + + Returns + ------- + layout : RasterLayout + The layout of the simulated recording. + samples : np.ndarray + The compound-Poisson samples of both channels. + rate : np.ndarray + The photon rate per sample (channels, slots, cycles). + """ + path = tmp_path_factory.mktemp("uni") / "uniform_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1600) + rng = np.random.default_rng(5) + shape = (layout.slot_line.size, layout.num_cycles) + rate = np.stack([np.full(shape, 0.05), np.full(shape, 2.0)]) + return layout, _compound_poisson(rate, rng), rate + + +def test_photon_noise_maps_read_zero(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: + """Under photon noise alone the normalised maps are 0 at any brightness. + + Means over pixels: a variance from few blocks is unbiased but its median + is low, as for chi-square. + """ + layout, samples, _ = uniform + res = _stats(layout, samples, last=11000.0) + maps = res["maps"] + use = _interior(maps) + assert use.sum() > 300 + for ch in range(2): + for name, tol in ( + ("var_rel", 0.02), + ("fast_rel", 0.02), + ("slow_rel", 0.1), + ("fast_skew_rel", 0.06), + ("zero_excess", 0.003), + ): + mean = np.mean(maps[name][ch][use]) + assert abs(mean) < tol, (ch, name, mean) + gains = measure_gain_curves(torch.from_numpy(samples)) + assert np.allclose(gains[1].g2, 132.0, rtol=0.03) + assert res["svd"]["var_share"].shape == (2, 3) + + +def test_events_raise_fast_skewness(uniform: tuple[RasterLayout, np.ndarray, np.ndarray]) -> None: + """Positive transients raise the fast maps where they are.""" + layout, _, rate = uniform + rate = rate.copy() + rows = (layout.slot_pixel - 1) // layout.n_cols + cols = (layout.slot_pixel - 1) % layout.n_cols + src = (np.abs(rows - 17) <= 1) & (np.abs(cols - 24) <= 1) + p = layout.lines_per_cycle + t = (np.arange(layout.num_cycles) * p) * layout.line_period_s + kern = np.zeros(t.size) + for onset in np.arange(0.3, t[-1], 0.9): + kern += np.where(t >= onset, np.exp(-(t - onset) / 0.025), 0.0) + rate[1, src] += 4.0 * kern + samples = _compound_poisson(rate, np.random.default_rng(6)) + maps = _stats(layout, samples, last=11000.0)["maps"] + m = 6 + sk = maps["fast_skew_rel"][1] + fr = maps["fast_rel"][1] + at = sk[17 - 8 + m, 24 - 10 + m] + away = np.nanmedian(sk[m : m + 5]) # DMD rows 8-12 + assert at > 1.0 and abs(away) < 0.2 + assert fr[17 - 8 + m, 24 - 10 + m] > 1.0 + + +# ------------------------------------------------- registration and command + + +@pytest.mark.parametrize( + "device", + [ + "cpu", + pytest.param( + "cuda", + marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="no CUDA device"), + ), + ], +) +def test_registration_and_command_agree(patched: RasterLayout, tmp_path: Path, device: str) -> None: + """``giant reg-stats`` on registration's outputs gives the same maps. + + On a GPU registration's run on a thread and stream of their own, the + command's in line. The mean equals meanIM; statistics do not change + the movie. + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + out = {} + for stats in (True, False): + d = tmp_path / str(stats) + d.mkdir() + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + multiroi.register_trial( + layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params, + device=device, stats=stats, + ) # fmt: skip + with h5py.File(d / MOVIE) as f: + out[stats] = f["data"][()] + np.testing.assert_array_equal(out[True], out[False]) + assert not stats_path(tmp_path / "False" / MOVIE).exists() + d = tmp_path / "True" + a = read_stats(stats_path(d / MOVIE)) + assert a["attrs"]["stats_version"] == STATS_VERSION + with h5py.File(d / ADATA) as f: + mean_im = np.swapaxes(np.moveaxis(f["meanIM"][()], -1, 0), 1, 2) + np.testing.assert_array_equal(a["maps"]["mean"], mean_im) + cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name + trial_stats(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, cmd, device, + {"maxshift": 6}) # fmt: skip + b = read_stats(cmd) + for grp in ("maps", "svd", "gain"): + assert a[grp].keys() == b[grp].keys() + for k in a[grp]: + np.testing.assert_array_equal(a[grp][k], b[grp][k], err_msg=k) + + +@pytest.mark.parametrize("last", [2.0, 60.0]) +def test_short_trials_get_statistics(patched: RasterLayout, tmp_path: Path, last: float) -> None: + """A one-frame (or three-frame) trial gets a statistics file equal to the command's. + + Its maps are NaN where there are too few frames. + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, last, tmp_path / MOVIE, tmp_path / ADATA) + res = multiroi.register_trial(*args, params) + assert res.ds_frames.size <= 3 + a = read_stats(stats_path(tmp_path / MOVIE)) + assert np.isnan(a["maps"]["fast_rel"]).all() + assert np.nanmax(a["maps"]["n_valid"]) == res.ds_frames.size + b = trial_stats(*args, tmp_path / "cmd.h5", "cpu", {"maxshift": 6}) + for k in a["maps"]: + np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) + + +def test_command_treats_empty_frames_as_missing(patched: RasterLayout, tmp_path: Path) -> None: + """A frame without data counts as missing in the command. + + This holds even where the alignment file gives it a motion (as + GIAnT-MATLAB's may). + """ + from giant_python.pipeline.reg_stats import trial_stats + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) + multiroi.register_trial(*args, params) + with h5py.File(tmp_path / MOVIE, "r+") as f: + n_ch = layout.num_channels + f["data"][10 * n_ch : 11 * n_ch] = np.nan # frame 10 without data + finite = trial_stats(*args, tmp_path / "a.h5", "cpu", {"maxshift": 6}) + with h5py.File(tmp_path / ADATA, "r+") as f: + for key in ("motionDSr", "motionDSc"): + m = f[key][()] + m.reshape(-1)[10] = np.nan + f[key][...] = m + missing = trial_stats(*args, tmp_path / "b.h5", "cpu", {"maxshift": 6}) + for k in finite["maps"]: + np.testing.assert_array_equal(finite["maps"][k], missing["maps"][k], err_msg=k) + for k in ("spatial_factor", "pair_bin_factor"): # frame 10 left out + assert finite["attrs"][k] == missing["attrs"][k] + + +def test_rerun_without_stats_removes_old_file(patched: RasterLayout, tmp_path: Path) -> None: + """A registration without statistics leaves none from an earlier one.""" + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + args = (layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA) + multiroi.register_trial(*args, params) + assert stats_path(tmp_path / MOVIE).exists() + multiroi.register_trial(*args, params, stats=False) + assert not stats_path(tmp_path / MOVIE).exists() + + +@pytest.mark.parametrize("step", ["start", "setup", "add", "finish", "write"]) +def test_failed_statistics_leave_registration( + patched: RasterLayout, + tmp_path: Path, + step: str, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A statistics step that fails is logged. + + The step fails on the worker thread, or writing the file, with its + cleanup failing too. Registration publishes the same movie and alignment + file, without statistics (and removes an earlier statistics file). + """ + import pathlib + + from giant_python.registration.stats import accumulate, io + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + ref = tmp_path / "ref" + ref.mkdir() + multiroi.register_trial(layout.files[0], 1, 3000, ref / MOVIE, ref / ADATA, params, stats=False) + + def fail(*args: object, **kwargs: object) -> NoReturn: + """Fail as a broken step. + + Raises + ------ + RuntimeError + Always. + """ + raise RuntimeError("broken statistics") + + if step == "start": + monkeypatch.setattr(multiroi, "StatsWorker", fail) + elif step == "setup": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "__init__", fail) + elif step == "add": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_block", fail) + elif step == "finish": + monkeypatch.setattr(accumulate.TrialStatsAccumulator, "_maps", fail) + else: + monkeypatch.setattr(io, "write_stats", fail) + unlink = pathlib.Path.unlink + + def locked(path: Path, *args: object, **kwargs: object) -> None: + """Path.unlink, refusing the partial statistics file. + + Raises + ------ + PermissionError + If the path is a partial statistics file, not the final one. + """ + if "REGSTATS" in path.name and path.name != STATS_NAME: + raise PermissionError("locked") + return unlink(path, *args, **kwargs) + + STATS_NAME = stats_path(tmp_path / MOVIE).name + monkeypatch.setattr(pathlib.Path, "unlink", locked) + d = tmp_path / "run" + d.mkdir() + stats_path(d / MOVIE).write_bytes(b"from an earlier registration") + multiroi.register_trial(layout.files[0], 1, 3000, d / MOVIE, d / ADATA, params) + assert "summary statistics" in caplog.text + assert not stats_path(d / MOVIE).exists() + assert sorted(p.name for p in d.iterdir()) == [ADATA, MOVIE] + with h5py.File(d / MOVIE) as f, h5py.File(ref / MOVIE) as g: + np.testing.assert_array_equal(f["data"][()], g["data"][()]) + with h5py.File(d / ADATA) as f, h5py.File(ref / ADATA) as g: + for k in ("motionDSr", "motionDSc", "meanIM"): + np.testing.assert_array_equal(f[k][()], g[k][()]) + + +def test_command_checks_online_compensation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """For an online-compensated trial the command rebuilds the compensation registration saved. + + It gets the same maps and refuses a trial whose saved record differs. + """ + from giant_python.pipeline.reg_stats import trial_stats + + from .synthetic import online_offsets + + layout = make_layout(tmp_path / "online_DMD1-TRIAL000001.dat", n_cycles=1400, seed=5) + write_recording(layout, seed=6, online=online_offsets(layout.total_lines)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6, compensate_online=True) + d = tmp_path / "reg" + d.mkdir() + args = (layout.files[0], 1, 6000, d / MOVIE, d / ADATA) + multiroi.register_trial(*args, params) + a = read_stats(stats_path(d / MOVIE)) + cmd = tmp_path / "cmd" / stats_path(d / MOVIE).name + trial_stats(*args, cmd, "cpu", {"maxshift": 6}) + b = read_stats(cmd) + for k in a["maps"]: + np.testing.assert_array_equal(a["maps"][k], b["maps"][k], err_msg=k) + with h5py.File(d / ADATA, "r+") as f: + lead = f["slap2/onlineCompensation/yLead"] + lead[...] = lead[()] + 1 + with pytest.raises(ValueError, match="yLead"): + trial_stats(*args, tmp_path / "other.h5", "cpu", {"maxshift": 6}) + + +def test_statistics_file_that_cannot_be_moved( + patched: RasterLayout, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """If the statistics file cannot be moved into place, the other outputs are published. + + The movie and the alignment file are published all the same, without + statistics (an earlier statistics file is removed). + """ + import os + + layout = patched + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + stale = stats_path(tmp_path / MOVIE) + stale.write_bytes(b"from an earlier registration") + replace = os.replace + + def refuse_stats(src: str | Path, dst: str | Path) -> None: + """os.replace, refusing the statistics file. + + Raises + ------ + PermissionError + If the destination is the statistics file. + """ + if Path(dst) == stale: + raise PermissionError("locked") + return replace(src, dst) + + monkeypatch.setattr(os, "replace", refuse_stats) + multiroi.register_trial(layout.files[0], 1, 3000, tmp_path / MOVIE, tmp_path / ADATA, params) + assert "not published" in caplog.text + assert sorted(p.name for p in tmp_path.iterdir()) == [ADATA, MOVIE] + + +def test_reg_stats_command(patched: RasterLayout, tmp_path: Path) -> None: + """The CLI writes the statistics of a table's trials once.""" + from giant_python.cli import main + from giant_python.pipeline.reg_stats import reg_stats + from giant_python.pipeline.register import register_multiroi + + layout = patched + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[1.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + }, + ) + register_multiroi( + table, + {"maxshift": 5}, + execution={"device": "cpu", "max_workers": 1}, + stats=False, + ) + out = tmp_path / "stats" + assert main(["reg-stats", str(table), "--out", str(out), + "--device", "cpu"]) == 0 # fmt: skip + written = out / "E1T1DMD1_REGSTATS-80Hz.h5" + assert written.exists() + assert reg_stats(table, out, device="cpu") == [] # up to date + with h5py.File(written, "r+") as f: # as if the movie were rewritten + f.attrs["movie_size"] = int(f.attrs["movie_size"]) + 1 + assert len(reg_stats(table, out, device="cpu")) == 1 + assert read_stats(written)["attrs"]["validity_differs"] == [0, 0] + movie = tmp_path / "motion_correction" / MOVIE + movie.rename(movie.with_suffix(".moved")) # a requested trial is missing + assert main(["reg-stats", str(table), "--out", str(out), + "--device", "cpu"]) == 1 # fmt: skip + + +def test_validity_mismatch_counts_channels() -> None: + """Samples whose validity differs from the first channel's are counted per channel.""" + from giant_python.io.slap2_raster import INVALID_SAMPLE + from giant_python.registration.stats.gain import validity_mismatch + + x = np.ones((3, 300, 50), dtype=np.int16) + x[:, 0, :5] = INVALID_SAMPLE # all channels: no mismatch + x[1, 10, :7] = INVALID_SAMPLE + x[2, 200, :3] = INVALID_SAMPLE + x[0, 250, :2] = INVALID_SAMPLE # first channel only: both others + assert validity_mismatch(torch.from_numpy(x)) == [0, 9, 5] + + +def test_stats_path_names() -> None: + """Statistics files sit next to the movie, named after it.""" + assert stats_path(Path("d") / MOVIE).name == "E1T1DMD1_REGSTATS-80Hz.h5" + tif = Path("E2T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.tif") + assert stats_path(tif).name == "E2T3DMD2_REGSTATS-80Hz.h5" + assert stats_path(Path("m.h5")).name == "m_REGSTATS.h5" + + +# ----------------------------------------------------------------- session + + +def test_combine_trials_weights_by_frames() -> None: + """Session maps: shifted, frame-weighted means. + + Normalised maps are formed from the averages. + """ + shape = (1, 20, 30) + trials = [] + for t, (n, var) in enumerate(((100.0, 2.0), (300.0, 4.0))): + maps = {} + for k in ("n_valid", "n_blocks", "n_fast"): + maps[k] = np.full(shape, n) + for k in ("mean", "var", "var_q", "zero_share", "zero_ph", + "gain_g2", "gain_g3", "sigma8_ph", "slow_var", "slow_q", + "fast_var", "fast_q", "fast_m3", "fast_q3", + "fast_m3_ph"): # fmt: skip + maps[k] = np.full(shape, 1.0) + maps["var"] = np.full(shape, var) + for k in ("var_ph", "slow_var_ph", "fast_var_ph"): + maps[k] = np.full(shape, 2.0) + maps["mean"][0, :, 0] = np.nan + trials.append({"maps": maps}) + out = combine_trials(trials, shifts=np.array([[0.0, 0.0], [0.0, 1.0]])) + assert out["n_valid"][0, 5, 5] == pytest.approx(400.0) + assert out["var"][0, 5, 5] == pytest.approx((100 * 2 + 300 * 4) / 400) + assert out["var_rel"][0, 5, 5] == pytest.approx(3.5 / 2 - 1) + assert out["n_trials"][0, 5, 5] == 2 + # trial 2's first column is missing; shifted by one column it lands + # left of the frame, and its last column has no data + assert out["n_trials"][0, 5, -1] == 1 + + +def test_combine_trials_of_different_sizes() -> None: + """Trials of different registered sizes share the largest canvas (top left, as SILo's).""" + trials = [] + for shape in ((1, 20, 30), (1, 18, 32)): + maps = {k: np.full(shape, 50.0) for k in ("n_valid", "n_blocks", + "n_fast")} # fmt: skip + for k in ("mean", "var", "var_ph", "zero_share", "zero_ph"): + maps[k] = np.full(shape, 1.0) + trials.append({"maps": maps}) + out = combine_trials(trials, shifts=np.zeros((2, 2))) + assert out["n_valid"].shape == (1, 20, 32) + assert out["n_trials"][0, 5, 5] == 2 + assert out["n_trials"][0, 19, 5] == 1 # rows 18-19: the first only + assert out["n_trials"][0, 5, 31] == 1 # cols 30-31: the second only + assert out["n_trials"][0, 19, 31] == 0 + assert np.isnan(out["var"][0, 19, 31]) + two = {"maps": {k: np.concatenate([v, v]) for k, v in trials[1]["maps"].items()}} + with pytest.raises(ValueError, match="channels"): + combine_trials([trials[0], two], shifts=np.zeros((2, 2))) + # fractional shifts: interior pixels count every trial despite rounding + out = combine_trials([trials[0], trials[0]], shifts=np.array([[0.3, 0.7], [0.1, 0.9]])) + assert (out["n_trials"][0, 2:-2, 2:-2] == 2).all() + + +def test_pair_sums_match_definition(tmp_path: Path) -> None: + """Sums over pairs of consecutive samples equal their definition.""" + layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 600) + samples = np.ones((2, layout.slot_line.size, 600), dtype=np.int16) + source, ds = _source(layout, samples) + m = 6 + motion = _motion(ds.size, seed=3) + geo = FrameGeometry(source, ds, m) + assert (0, 1) in geo.directions + vfs = torch.stack([vf.reshape(-1) for _, vf in + _registered(source, ds, motion, m)]) # fmt: skip + ok = torch.nonzero(torch.isfinite(vfs[:30]).all(0)).ravel() + pix = ok[:: max(1, ok.numel() // 6)][:6] + f0, f1 = 8, 14 + e = f1 + geo.n_lags + res = geo.registered(f0, f1, e, pix, motion[f0:e], np.ones(e - f0, bool), vfs[f0:e][:, pix]) + nxt = next_slots(layout.slot_line, layout.slot_pos) + for j, p in enumerate(pix.tolist()): + for t in range(f0, f1): + at = _coefficients(layout, source, ds, motion, m, t, p) + pairs = [ + (v, at[(nxt[s], c)]) + for (s, c), v in at.items() + if nxt[s] >= 0 and (nxt[s], c) in at + ] + g0 = sum(v * v for v in at.values()) + want = ( + sum(a * b for a, b in pairs), + sum(a * a * b for a, b in pairs), + sum(a * b * b for a, b in pairs), + ) + for name, ref in zip(("QA2", "QA3a", "QA3b"), want): + assert abs(res[name][t - f0, j] - ref) <= 1e-5 * g0 + + +def test_shared_pulses_read_zero(tmp_path: Path) -> None: + """Pulses shared by consecutive samples correlate neighbouring pixels. + + With the pair terms, photon noise still reads 0 after registration's + bilinear resampling mixes them. + """ + layout = scan_layout(tmp_path / "scan_DMD1-TRIAL000001.dat", 1600) + nxt = next_slots(layout.slot_line, layout.slot_pos) + rng = np.random.default_rng(7) + shape = (layout.slot_line.size, layout.num_cycles) + rate = np.stack([np.full(shape, 0.1), np.full(shape, 2.0)]) + samples = _shared_pulses(rate, nxt, rng) + curve = pair_curve(pair_sums(torch.from_numpy(samples), 1, nxt)) + rho = np.median(curve["c2"]) / 132.0 + assert 0.05 < rho < 0.2 + res = _stats(layout, samples, last=11000.0) + maps = res["maps"] + use = _interior(maps) + assert use.sum() > 300 + for ch in range(2): + assert np.mean(maps["var_qa"][ch][use]) > 0 + # at this size the dim channel's skewness varies by about 0.08 + # between seeds (the pixels share the measured gains) + for name, tol in ( + ("var_rel", 0.03), + ("fast_rel", 0.03), + ("slow_rel", 0.1), + ("fast_skew_rel", 0.15 if ch == 0 else 0.06), + ("zero_excess", 0.005), + ): + mean = np.mean(maps[name][ch][use]) + assert abs(mean) < tol, (ch, name, mean) + # the shared modes' input is in photon-noise units: unit variance per + # 2 x 2 bin and 8-frame bin (centred over time), pairs inside included + svd = res["svd"] + unit = svd["total_var"] / (svd["n_space"] * (svd["n_bins"] - 1)) + np.testing.assert_allclose(unit, 1.0, atol=0.05) # 1.08-1.11 without diff --git a/tests/registration/test_synthetic.py b/tests/registration/test_synthetic.py index a6783287..33b77045 100644 --- a/tests/registration/test_synthetic.py +++ b/tests/registration/test_synthetic.py @@ -1,969 +1,969 @@ -"""Reader, frame formation and registration on a synthetic recording.""" - -import dataclasses -import hashlib -import json -import os -from collections.abc import Callable, Sequence -from pathlib import Path -from typing import NoReturn - -import h5py -import numpy as np -import pytest -import torch -from numpy.typing import ArrayLike - -from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 -from giant_python.io.slap2 import is_cycle_split -from giant_python.io.slap2_raster import ( - RasterLayout, - read_line_offsets, - read_raster_samples, -) -from giant_python.io.trial_table import read_trial_table -from giant_python.registration import multiroi -from giant_python.registration.frames import FrameFormer - -from .synthetic import HEADER_WORDS, make_layout, write_recording - -Recording = tuple[RasterLayout, np.ndarray] -"""A synthetic recording's layout and its true motion.""" - - -@pytest.fixture(scope="module") -def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: - """Layout, data file and true motion of a 6-second recording. - - Returns - ------- - Recording - The recording's layout and its true motion. - """ - path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=1400) - truth = write_recording(layout, invalid=0.002) - return layout, truth - - -def frames_reference( - layout: RasterLayout, samples: np.ndarray, times: np.ndarray, dt: float -) -> tuple[np.ndarray, np.ndarray]: - """Per-pixel weighted means by the definition (slow loops). - - Returns - ------- - num : np.ndarray - Weighted sums of the valid samples, (channels, frames, pixels). - den : np.ndarray - The corresponding sums of the weights, same shape. - """ - p, total = layout.lines_per_cycle, layout.total_lines - pix = np.unique(layout.slot_pixel) - dt_read = max(3 * dt, p) - num = np.zeros((layout.num_channels, len(times), pix.size)) - den = np.zeros_like(num) - for s in range(layout.slot_line.size): - j = np.searchsorted(pix, layout.slot_pixel[s]) - for f, t in enumerate(times): - lines = np.arange(max(1, t - dt_read), min(total, t + dt_read) + 1) - lines = lines[(lines - 1) % p + 1 == layout.slot_line[s]] - for ln in lines: - w = np.exp(-abs(t - ln) / dt) - for ch in range(layout.num_channels): - x = samples[ch, s, (ln - 1) // p] - if x != -32768: - num[ch, f, j] += w * x - den[ch, f, j] += w - return num, den - - -def test_reader_and_line_headers(recording: Recording) -> None: - """Samples land at their slots; header offsets decode.""" - layout, _ = recording - s = read_raster_samples(layout, (10, 20), chunk_cycles=3) - whole = read_raster_samples(layout, (0, layout.num_cycles)) - np.testing.assert_array_equal(s, whole[:, :, 10:20]) - p = layout.lines_per_cycle - lines = np.array([1, p, p + 3, 5 * p + 2]) - x, y, z = read_line_offsets(layout, lines) - cyc = (lines - 1) // p - np.testing.assert_array_equal(x, cyc % 3) - np.testing.assert_array_equal(y, -(cyc % 2)) - np.testing.assert_allclose(z, 0.25 * cyc) - - -def test_frame_former_matches_definition(recording: Recording) -> None: - """Exp-kernel sums equal the definition, invalid samples masked.""" - layout, _ = recording - samples = read_raster_samples(layout, (0, layout.num_cycles)) - times = np.array([1, 50, 333, 4000]) - former = FrameFormer(layout, samples, 0) - num, den = former.sums(times, 20) - want_num, want_den = frames_reference(layout, samples, times, 20) - np.testing.assert_allclose(num.numpy(), want_num, rtol=1e-12) - np.testing.assert_allclose(den.numpy(), want_den, rtol=1e-12) - part = FrameFormer(layout, samples[:, :, 40:200], 40) - np.testing.assert_allclose(part.sums([700], 20)[0].numpy(), former.sums([700], 20)[0].numpy()) - with pytest.raises(ValueError): - part.sums([20], 20) - - -def test_register_trial_recovers_motion( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Recovered motion follows the known motion (up to a constant).""" - layout, truth = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - n_lines = 9000 - res = multiroi.register_trial( - layout.files[0], - 1, - n_lines, - tmp_path / "m.tif", - tmp_path / "a.h5", - params, - ) - dt = 1600 / 80 - kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) - kernel /= kernel.sum() - true = np.stack([np.convolve(truth[:, i], kernel, "same")[res.ds_frames - 1] for i in (0, 1)]) - est = np.stack([res.motion_r, res.motion_c]) - err = est - true - err -= np.median(err, axis=1, keepdims=True) - assert np.sqrt(np.mean(err**2)) < 0.1 - a = load_struct_h5(tmp_path / "a.h5") - assert a["slap2"]["varFacDS"].shape == ( - a["meanIM"].shape[1], - a["meanIM"].shape[2], - res.ds_frames.size, - ) - np.testing.assert_array_equal(a["DSframes"].ravel(), res.ds_frames) - assert not (tmp_path / "a.h5.partial").exists() - - -def digests(*paths: str | Path) -> list[str]: - """SHA-256 of each file. - - Returns - ------- - list[str] - The hex digest of each of `paths`, in order. - """ - return [hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths] - - -@pytest.mark.parametrize("save_tif", [True, False]) -def test_failed_rerun_keeps_the_previous_outputs( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, save_tif: bool -) -> None: - """A run that fails while writing leaves an existing pair as it was.""" - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=save_tif) - movie = tmp_path / ("m.tif" if save_tif else "m.h5") - adata = tmp_path / "a.h5" - args = (layout.files[0], 1, 3000, movie, adata, params) - multiroi.register_trial(*args) - stats = movie.with_name(movie.stem + "_REGSTATS.h5") - before = digests(movie, adata, stats) - add = multiroi.OutputSink.add - - def fail_midway( - self: multiroi.OutputSink, - k: int, - regs: list[torch.Tensor], - var_factor: torch.Tensor, - *rest: object, - ) -> torch.Tensor: - """Write 50 frames, then fail. - - Returns - ------- - torch.Tensor - The sum of the frame's registered channels, from the original add. - - Raises - ------ - OSError - At frame 50. - """ - if k == 50: - raise OSError("disk full") - return add(self, k, regs, var_factor, *rest) - - def fail_at_the_end(*args: object, **kwargs: object) -> NoReturn: - """Fail after the movie is complete. - - Raises - ------ - OSError - Always. - """ - raise OSError("disk full") - - for target, name, fail in ( - (multiroi.OutputSink, "add", fail_midway), - (multiroi, "alignment_fields", fail_at_the_end), - ): - with monkeypatch.context() as m: - m.setattr(target, name, fail) - with pytest.raises(OSError): - multiroi.register_trial(*args) - assert digests(movie, adata, stats) == before - assert sorted(tmp_path.iterdir()) == sorted([movie, adata, stats]) - - -def test_interrupted_publish_leaves_no_alignment_file( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A pair that cannot be moved into place leaves no alignment file. - - The movie may then be new, but without an alignment file the trial is - not taken for registered. - """ - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) - movie, adata = tmp_path / "m.h5", tmp_path / "a.h5" - args = (layout.files[0], 1, 3000, movie, adata, params) - multiroi.register_trial(*args) - replace = os.replace - - def refuse_alignment_file(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: - """Fail to move the alignment file into place. - - Raises - ------ - PermissionError - If the destination is the alignment file. - """ - if Path(dst) == adata: - raise PermissionError("in use") - replace(src, dst) - - monkeypatch.setattr(os, "replace", refuse_alignment_file) - with pytest.raises(PermissionError): - multiroi.register_trial(*args) - # the new movie and its statistics are in place, the alignment file not - stats = movie.with_name(movie.stem + "_REGSTATS.h5") - assert sorted(tmp_path.iterdir()) == sorted([movie, stats]) - - -def blank_frames( - monkeypatch: pytest.MonkeyPatch, - blank: Callable[[np.ndarray], np.ndarray], - half: Callable[[np.ndarray], np.ndarray] | None = None, -) -> None: - """Frames formed at times where blank(times) holds have no samples. - - Where half(times) holds, the lower half of the raster has none. - """ - from giant_python.registration.frames import FrameFormer - - frames = FrameFormer.frames - - def blanked( - self: FrameFormer, times: ArrayLike, dt: int, channels: Sequence[int] | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """Form the frames, with the selected ones emptied. - - Returns - ------- - vals : torch.Tensor - The frame values, NaN in the emptied frames (and in the lower half where - half(times) holds). - fresh : torch.Tensor - The per-pixel freshness, zero where emptied. - """ - vals, fresh = frames(self, times, dt, channels) - t = np.asarray(times).ravel() - lower = self.rows > np.median(self.rows) - for i in np.flatnonzero(half(t) if half else []): - vals[:, i, lower] = float("nan") - fresh[i, lower] = 0 - hit = torch.as_tensor(blank(t), device=vals.device) - vals[:, hit] = float("nan") - fresh[hit] = 0 - return vals, fresh - - monkeypatch.setattr(FrameFormer, "frames", blanked) - - -@pytest.mark.parametrize("schedule", ["sequential", "grow"]) -def test_frame_without_samples_is_missing( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str -) -> None: - """A frame without valid samples in mid-trial gets NaN motion and an all-NaN movie frame. - - The other frames are registered exactly as in a run without that frame, - and the trial does not fail. - """ - from giant_python.registration.growth import MISSING - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) - dt = (1 / layout.line_period_s) / params.align_hz - init, ds = multiroi.frame_times(1, 3000, dt, params.init_frames) - k = 70 - assert ds[k] not in init - times = multiroi.frame_times - out = {} - for name in ("blank", "without"): - with monkeypatch.context() as m: - if name == "blank": - blank_frames(m, lambda t: t == ds[k]) - else: - m.setattr( - multiroi, - "frame_times", - lambda *a: (times(*a)[0], np.delete(times(*a)[1], k)), - ) - out[name] = multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"{name}.h5", - tmp_path / f"{name}_a.h5", - params, - ) - res, ref = out["blank"], out["without"] - assert not res.registration_failed - assert np.isnan([res.motion_r[k], res.motion_c[k], res.peak[k]]).all() - others = np.arange(ds.size) != k - for f in ("motion_r", "motion_c", "peak"): - np.testing.assert_array_equal(getattr(res, f)[others], getattr(ref, f)) - n_ch = layout.num_channels - with ( - h5py.File(tmp_path / "blank.h5") as a, - h5py.File(tmp_path / "without.h5") as b, - ): - pages = a["data"][()] - mine = np.s_[k * n_ch : (k + 1) * n_ch] - assert np.isnan(pages[mine]).all() - np.testing.assert_array_equal(np.delete(pages, mine, axis=0), b["data"][()]) - adata = load_struct_h5(tmp_path / "blank_a.h5") - want = load_struct_h5(tmp_path / "without_a.h5") - assert adata["registrationFailed"].item() == 0 - assert np.isnan(adata["motionDSr"].ravel()[k]) - assert np.isnan(adata["slap2"]["varFacDS"][..., k]).all() - np.testing.assert_array_equal(adata["meanIM"], want["meanIM"]) - if schedule == "grow": - assert adata["growthQC"]["kind"].ravel()[k] == MISSING - - -@pytest.mark.parametrize("schedule", ["sequential", "grow"]) -def test_trial_without_samples_at_its_start_or_at_all( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str -) -> None: - """A recording that starts late is registered from its first frames with samples. - - It is registered in the usual window even if the first of them covers only - part of the raster; a trial without any samples completes and is flagged. - """ - from giant_python.registration.sources import make_source - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) - args = (layout.files[0], 1, 3000) - lay, former, init, ds, dt = multiroi.open_trial(*args, params, torch.device("cpu")) - window = make_source(lay, former, 1, 3000, init, ds, dt, False).window - with monkeypatch.context() as m: - # the first initial frames have no samples, the next one only half - assert np.sum((init >= 1200) & (init < 1300)) == 1 - blank_frames(m, lambda t: t < 1200, lambda t: t < 1300) - late = multiroi.register_trial(*args, tmp_path / "late.h5", tmp_path / "late_a.h5", params) - early = late.ds_frames < 1200 - assert np.isnan(late.motion_r[early]).all() - assert np.isfinite(late.motion_r[late.ds_frames >= 1200]).all() - assert not late.registration_failed - trim = load_struct_h5(tmp_path / "late_a.h5")["slap2"] - np.testing.assert_array_equal(trim["trimRows"].ravel(), window.trim_rows) - np.testing.assert_array_equal(trim["trimCols"].ravel(), window.trim_cols) - with monkeypatch.context() as m: - blank_frames(m, lambda t: np.ones(t.shape, dtype=bool)) - empty = multiroi.register_trial( - *args, tmp_path / "empty.h5", tmp_path / "empty_a.h5", params - ) - assert np.isnan(empty.motion_r).all() and empty.registration_failed - with h5py.File(tmp_path / "empty.h5") as f: - assert np.isnan(f["data"][()]).all() - - -def test_register_trial_keeps_fractional_lines( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Fractional trial edges set the frame times, as in MATLAB. - - Trial tables of continuous recordings cut trials at linspace edges; - MultiRoiRegistration uses them unrounded: ceil(first:dt:last). - """ - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - first, last = 1000.4, 4000.7 - res = multiroi.register_trial( - layout.files[0], - first, - last, - tmp_path / "m.tif", - tmp_path / "a.h5", - params, - ) - dt = 1600 / 80 - n = int(np.floor((last - first) / dt)) + 1 - np.testing.assert_array_equal(res.ds_frames, np.ceil(first + dt * np.arange(n))) - assert res.ds_frames[0] == 1001 - - -def test_register_multiroi_updates_trial_table( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The pipeline writes MATLAB-named outputs and motion_correction.""" - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - name = dat.name - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - "motion_correction": {"keep_me": 7.0}, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert fields["fn_adata"][0, 0] == "E3T1DMD1_ALIGNMENTDATA.h5" - movie = tmp_path / "motion_correction" / fields["fn_reg_ds"][0, 0] - assert movie.name == "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" - with h5py.File(movie) as f: - assert f["data"].shape[0] == 2 * 150 - tt = read_trial_table(table) - mc = tt.motion_correction - assert mc["keep_me"].item() == 7.0 - assert mc["fn_adata"] == "E3T1DMD1_ALIGNMENTDATA.h5" - assert mc["align_params"]["alignHz"].item() == 80.0 - assert mc["registration_failed"].dtype == np.int8 - - -def one_trial_table(layout: RasterLayout, tmp_path: Path) -> Path: - """Write a MATLAB-style trial table with one 3000-line trial. - - Returns - ------- - Path - The trial table file. - """ - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[1.0]]), - "last_line": np.array([[3000.0]]), - }, - }, - ) - return table - - -def test_rerun_keeps_the_saved_failure_flag( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Reused outputs report the registrationFailed they were saved with.""" - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - run = { - "params": {"maxshift": 5, "save_tif": False}, - "execution": {"device": "cpu", "max_workers": 1}, - } - fields = register_multiroi(table, **run) - assert not fields["registration_failed"][0, 0] - adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] - with h5py.File(adata, "r+") as f: # as if the motion had been too large - f["registrationFailed"][...] = 1 - before = digests(adata) - fields = register_multiroi(table, **run) - assert digests(adata) == before # reused, not registered again - assert fields["registration_failed"][0, 0] - assert read_trial_table(table).motion_correction["registration_failed"] - - -def test_rerun_with_other_settings_registers_again( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Outputs are reused only if made with the requested settings.""" - from giant_python.pipeline.register import register_multiroi - from giant_python.registration.outputs import SETTINGS_ATTR - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - execution = {"device": "cpu", "max_workers": 1} - sequential = {"maxshift": 5, "save_tif": False} - grow = dict(sequential, schedule="grow") - fields = register_multiroi(table, sequential, execution=execution) - adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] - first = digests(adata) - assert "growthQC" not in load_struct_h5(adata) - - fields = register_multiroi(table, grow, execution=execution) - assert digests(adata) != first # registered again - assert "growthQC" in load_struct_h5(adata) - mc = read_trial_table(table).motion_correction - assert mc["align_params"]["schedule"] == "grow" - with h5py.File(adata) as f: - saved = json.loads(f.attrs[SETTINGS_ATTR]) - assert saved["schedule"] == "grow" and saved["maxshift"] == 5 - assert "overwriteExisting" not in saved - - grown = digests(adata) - register_multiroi(table, grow, execution=execution) - assert digests(adata) == grown # same settings: reused - - with h5py.File(adata, "r+") as f: # outputs that do not record them - del f.attrs[SETTINGS_ATTR] - register_multiroi(table, grow, execution=execution) - with h5py.File(adata) as f: - assert SETTINGS_ATTR in f.attrs - - -def test_failed_rerun_does_not_name_the_old_outputs( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A re-registration that raises leaves the old files on disk but clears their names. - - So the table never pairs them with new settings. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - table = one_trial_table(layout, tmp_path) - execution = {"device": "cpu", "max_workers": 1} - sequential = {"maxshift": 5, "save_tif": False} - fields = register_multiroi(table, sequential, execution=execution) - moco = tmp_path / "motion_correction" - files = [moco / fields["fn_reg_ds"][0, 0], moco / fields["fn_adata"][0, 0]] - before = digests(*files) - - def fail(*args: object, **kwargs: object) -> NoReturn: - """Fail before anything is published. - - Raises - ------ - OSError - Always. - """ - raise OSError("disk full") - - monkeypatch.setattr(multiroi, "register_trial", fail) - fields = register_multiroi(table, dict(sequential, schedule="grow"), execution=execution) - assert fields["fn_reg_ds"][0, 0] == fields["fn_adata"][0, 0] == "" - assert fields["registration_failed"][0, 0] - assert digests(*files) == before - mc = read_trial_table(table).motion_correction - assert mc["fn_reg_ds"] == mc["fn_adata"] == "" - assert mc["registration_failed"] - assert mc["align_params"]["schedule"] == "grow" - - -@pytest.mark.parametrize("case", ["row_major", "channels", "device"]) -def test_rejected_request_writes_nothing( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str -) -> None: - """A request that fails validation leaves outputs and table untouched. - - Such requests are a row-major table, an unsupported recording, an - unavailable device. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - lay = layout - if case == "channels": - lay = dataclasses.replace(layout, num_channels=3) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: lay) - table = one_trial_table(layout, tmp_path) - if case == "row_major": - with h5py.File(table, "r+") as f: - f["row_major"][...] = 1 - moco = tmp_path / "motion_correction" - moco.mkdir() - old = [ - moco / "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5", - moco / "E3T1DMD1_ALIGNMENTDATA.h5", - ] - for p in old: - p.write_bytes(b"from an earlier run") - before = digests(table, *old) - with pytest.raises(ValueError): - register_multiroi( - table, - {"maxshift": 5, "save_tif": False, "overwrite_existing": True}, - execution={ - "device": "cuda:99" if case == "device" else "cpu", - "max_workers": 1, - }, - ) - assert digests(table, *old) == before - assert sorted(moco.iterdir()) == sorted(old) - - -def test_ragged_table_skips_empty_cells( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A cell without a recording (one path has fewer trials) is skipped and flagged. - - It gets empty output names; the other cells register. - """ - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name, dat.name], [dat.name, ""]], dtype=object), - "epoch": np.array([[3.0, 3.0], [3.0, np.nan]]), - "true_trial_ix": np.array([[1.0, 2.0]]), - "slap2_info": { - "first_line": np.array([[1.0, 3001.0], [1.0, np.nan]]), - "last_line": np.array([[3000.0, 6000.0], [3000.0, np.nan]]), - }, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert fields["fn_reg_ds"][1, 1] == fields["fn_adata"][1, 1] == "" - np.testing.assert_array_equal(fields["registration_failed"], [[False, False], [False, True]]) - names = [ - fields[k][d, t] for k in ("fn_reg_ds", "fn_adata") for d, t in ((0, 0), (0, 1), (1, 0)) - ] - assert all(names) - moco = tmp_path / "motion_correction" - stats = [ - n.replace("_REGISTERED_DOWNSAMPLED-", "_REGSTATS-") for n in names if "_REGISTERED_" in n - ] - assert sorted(p.name for p in moco.iterdir()) == sorted(names + stats) - mc = read_trial_table(table).motion_correction - assert mc["fn_reg_ds"][1, 1] == mc["fn_adata"][1, 1] == "" - assert mc["registration_failed"][1, 1] == 1 - - -def test_trial_table_update_keeps_other_entries( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Only the registration fields are replaced, once all are written. - - Other entries of the group and their attributes are left untouched. - """ - from giant_python.pipeline import register - - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": "d", - "motion_correction": { - "keep_me": 7.0, - "fn_adata": "old.h5", - "align_params": {"old_only": 1.0}, - }, - }, - ) - with h5py.File(table, "r+") as f: - mc = f["motion_correction"] - mc.attrs["note"] = "kept" - mc["keep_me"].attrs["unit"] = "px" - mc.create_dataset("empty", shape=(0, 0), dtype=np.float64) - nested = mc.create_group("nested") - nested.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) - fields = { - "fn_adata": np.array([["new.h5"]], dtype=object), - "registration_failed": np.array([[True]]), - "align_params": {"alignHz": 80.0}, - } - write = register.write_matlab_value - - def fail_on_align_params(grp: h5py.Group, key: str, value: dict | ArrayLike) -> None: - """Fail while writing the last field. - - Raises - ------ - OSError - If key starts with align_params. - """ - if key.startswith("align_params"): - raise OSError("disk full") - write(grp, key, value) - - def entries() -> set[str]: - """Every entry under motion_correction. - - Returns - ------- - set[str] - The names of all groups and datasets under motion_correction in the table. - """ - names = [] - with h5py.File(table) as f: - f["motion_correction"].visit(names.append) - return set(names) - - kept = {"keep_me", "empty", "nested", "nested/row_major"} - with monkeypatch.context() as m: - m.setattr(register, "write_matlab_value", fail_on_align_params) - with pytest.raises(OSError): - register._update_trial_table(table, fields) - old = {"fn_adata", "align_params", "align_params/old_only"} - assert entries() == kept | old - assert load_struct_h5(table)["motion_correction"]["fn_adata"] == "old.h5" - register._update_trial_table(table, fields) - assert entries() == kept | { - "fn_adata", - "registration_failed", - "align_params", - "align_params/alignHz", - } - with h5py.File(table) as f: - mc = f["motion_correction"] - assert mc.attrs["note"] == "kept" - assert mc["keep_me"].attrs["unit"] == "px" - assert mc["empty"].shape == (0, 0) - mc = load_struct_h5(table)["motion_correction"] - assert mc["fn_adata"] == "new.h5" - assert mc["registration_failed"].item() == 1 - assert mc["align_params"]["alignHz"].item() == 80.0 - - -def test_register_multiroi_keeps_fractional_lines( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The pipeline passes the table's fractional trial edges on unrounded.""" - from giant_python.io.hdf5 import load_struct_h5 - from giant_python.pipeline.register import register_multiroi - - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - dat = Path(layout.files[0]) - table = tmp_path / "trial_table.h5" - first, last = 1000.4, 4000.7 - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name]], dtype=object), - "epoch": np.array([[3.0]]), - "true_trial_ix": np.array([[1.0]]), - "slap2_info": { - "first_line": np.array([[first]]), - "last_line": np.array([[last]]), - }, - }, - ) - fields = register_multiroi( - table, - {"maxshift": 5, "save_tif": False}, - execution={"device": "cpu", "max_workers": 1}, - ) - adata = load_struct_h5(tmp_path / "motion_correction" / fields["fn_adata"][0, 0]) - adata = adata.get("aData", adata) - dt = 1600 / 80 - n = int(np.floor((last - first) / dt)) + 1 - np.testing.assert_array_equal(np.ravel(adata["DSframes"]), np.ceil(first + dt * np.arange(n))) - - -def test_unsupported_options_raise() -> None: - """MATLAB options that are not ported are rejected.""" - with pytest.raises(NotImplementedError): - multiroi.MultiRoiRegistrationParams(ref_stack_template=True) - with pytest.raises(TypeError): - from giant_python.models.params import resolve_registration_options - - resolve_registration_options({"compensateOnline": True}) - - -def test_save_struct_h5_is_column_major(tmp_path: Path) -> None: - """Values come back in MATLAB orientation and MATLAB classes.""" - path = tmp_path / "s.h5" - save_struct_h5( - path, - { - "a": np.arange(6.0).reshape(2, 3), - "v": np.arange(4.0), - "flag": True, - "n": 3, - "s": "text", - "cells": np.array([["x"], ["yy"]], dtype=object), - "g": {"single": np.float32(2.5)}, - }, - ) - with h5py.File(path) as f: - assert f["a"].shape == (3, 2) and f["v"].shape == (4, 1) - assert f["flag"].dtype == np.int8 and f["n"].dtype == np.float64 - assert f["row_major"][()] == 0 - back = load_struct_h5(path) - np.testing.assert_array_equal(back["a"], np.arange(6.0).reshape(2, 3)) - assert back["v"].shape == (1, 4) - assert back["s"] == "text" - assert list(back["cells"].ravel()) == ["x", "yy"] - assert back["g"]["single"].dtype == np.float32 - - -def test_registration_runs_on_cuda_like_cpu( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """CUDA and CPU give the same motion (skipped without a GPU).""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - params = multiroi.MultiRoiRegistrationParams(maxshift=6) - out = [ - multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"{d}.tif", - tmp_path / f"{d}.h5", - params, - device=d, - ) - for d in ("cpu", "cuda") - ] - diff = np.hypot(out[0].motion_r - out[1].motion_r, out[0].motion_c - out[1].motion_c) - # float32 sums differ in order; a near-tie peak may resolve differently - assert np.median(diff) < 1e-3 and diff.max() < 0.1 - - -def test_var_factor_deflate_keeps_values( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Deflated varFacDS (default) holds the same values as uncompressed.""" - layout, _ = recording - monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) - for level in (0, 1): - params = multiroi.MultiRoiRegistrationParams( - maxshift=5, var_factor_deflate=level, save_tif=False - ) - multiroi.register_trial( - layout.files[0], - 1, - 3000, - tmp_path / f"m{level}.h5", - tmp_path / f"a{level}.h5", - params, - ) - with ( - h5py.File(tmp_path / "a0.h5") as a, - h5py.File(tmp_path / "a1.h5") as b, - ): - assert a["slap2/varFacDS"].compression is None - assert b["slap2/varFacDS"].compression == "gzip" - np.testing.assert_array_equal(a["slap2/varFacDS"][()], b["slap2/varFacDS"][()]) - with h5py.File(tmp_path / "m1.h5") as m: - assert m["data"].compression == "gzip" - assert m["data"].compression_opts == 1 - - -def test_cycle_split_names() -> None: - """Files of CYCLE-split recordings are recognised by name only.""" - assert is_cycle_split("acq_DMD1-TRIAL000001-CYCLE-000000.dat") - assert is_cycle_split("d/acq_DMD2-CYCLE-318000.dat") - assert is_cycle_split("acq_DMD1-CYCLE000000.dat") - assert not is_cycle_split("acq_DMD1-TRIAL000001.dat") - assert not is_cycle_split("CYCLE-1/acq_DMD1-TRIAL000001.dat") - - -def split_recording(layout: RasterLayout, k: int, tmp_path: Path) -> RasterLayout: - """Write the recording as two files, split before cycle k. - - Returns - ------- - RasterLayout - `layout` with its files replaced by the two split files. - """ - raw = np.fromfile(layout.files[0], dtype=np.int16) - head = raw[:HEADER_WORDS] - body = raw[HEADER_WORDS:].reshape(layout.num_cycles, -1) - files = [] - for name, part in (("a", body[:k]), ("b", body[k:])): - path = tmp_path / f"split_{name}.dat" - with open(path, "wb") as f: - f.write(head.tobytes()) - f.write(part.tobytes()) - files.append(str(path)) - return dataclasses.replace( - layout, - files=tuple(files), - file_cycles=np.array([k, layout.num_cycles - k]), - file_offset_words=np.array([HEADER_WORDS, HEADER_WORDS]), - ) - - -def test_split_recording_reads_and_registers_alike( - recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Reads and registration across two files equal those of one file.""" - layout, _ = recording - k = 500 - split = split_recording(layout, k, tmp_path) - for cycles in ((k - 7, k + 9), (0, layout.num_cycles), (k + 3, k + 40)): - np.testing.assert_array_equal( - read_raster_samples(split, cycles, chunk_cycles=5), - read_raster_samples(layout, cycles), - ) - p = layout.lines_per_cycle - lines = np.arange((k - 3) * p + 1, (k + 3) * p + 1) - for a, b in zip(read_line_offsets(split, lines), read_line_offsets(layout, lines)): - np.testing.assert_array_equal(a, b) - params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) - first, last = (k - 150) * p + 1, (k + 150) * p - out = {} - for name, lay in (("one", layout), ("two", split)): - monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) - out[name] = multiroi.register_trial( - lay.files[0], - first, - last, - tmp_path / f"m_{name}.h5", - tmp_path / f"a_{name}.h5", - params, - ) - for f in ("ds_frames", "motion_r", "motion_c", "peak"): - np.testing.assert_array_equal(getattr(out["one"], f), getattr(out["two"], f)) +"""Reader, frame formation and registration on a synthetic recording.""" + +import dataclasses +import hashlib +import json +import os +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import NoReturn + +import h5py +import numpy as np +import pytest +import torch +from numpy.typing import ArrayLike + +from giant_python.io.hdf5 import load_struct_h5, save_struct_h5 +from giant_python.io.slap2 import is_cycle_split +from giant_python.io.slap2_raster import ( + RasterLayout, + read_line_offsets, + read_raster_samples, +) +from giant_python.io.trial_table import read_trial_table +from giant_python.registration import multiroi +from giant_python.registration.frames import FrameFormer + +from .synthetic import HEADER_WORDS, make_layout, write_recording + +Recording = tuple[RasterLayout, np.ndarray] +"""A synthetic recording's layout and its true motion.""" + + +@pytest.fixture(scope="module") +def recording(tmp_path_factory: pytest.TempPathFactory) -> Recording: + """Layout, data file and true motion of a 6-second recording. + + Returns + ------- + Recording + The recording's layout and its true motion. + """ + path = tmp_path_factory.mktemp("rec") / "synthetic_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=1400) + truth = write_recording(layout, invalid=0.002) + return layout, truth + + +def frames_reference( + layout: RasterLayout, samples: np.ndarray, times: np.ndarray, dt: float +) -> tuple[np.ndarray, np.ndarray]: + """Per-pixel weighted means by the definition (slow loops). + + Returns + ------- + num : np.ndarray + Weighted sums of the valid samples, (channels, frames, pixels). + den : np.ndarray + The corresponding sums of the weights, same shape. + """ + p, total = layout.lines_per_cycle, layout.total_lines + pix = np.unique(layout.slot_pixel) + dt_read = max(3 * dt, p) + num = np.zeros((layout.num_channels, len(times), pix.size)) + den = np.zeros_like(num) + for s in range(layout.slot_line.size): + j = np.searchsorted(pix, layout.slot_pixel[s]) + for f, t in enumerate(times): + lines = np.arange(max(1, t - dt_read), min(total, t + dt_read) + 1) + lines = lines[(lines - 1) % p + 1 == layout.slot_line[s]] + for ln in lines: + w = np.exp(-abs(t - ln) / dt) + for ch in range(layout.num_channels): + x = samples[ch, s, (ln - 1) // p] + if x != -32768: + num[ch, f, j] += w * x + den[ch, f, j] += w + return num, den + + +def test_reader_and_line_headers(recording: Recording) -> None: + """Samples land at their slots; header offsets decode.""" + layout, _ = recording + s = read_raster_samples(layout, (10, 20), chunk_cycles=3) + whole = read_raster_samples(layout, (0, layout.num_cycles)) + np.testing.assert_array_equal(s, whole[:, :, 10:20]) + p = layout.lines_per_cycle + lines = np.array([1, p, p + 3, 5 * p + 2]) + x, y, z = read_line_offsets(layout, lines) + cyc = (lines - 1) // p + np.testing.assert_array_equal(x, cyc % 3) + np.testing.assert_array_equal(y, -(cyc % 2)) + np.testing.assert_allclose(z, 0.25 * cyc) + + +def test_frame_former_matches_definition(recording: Recording) -> None: + """Exp-kernel sums equal the definition, invalid samples masked.""" + layout, _ = recording + samples = read_raster_samples(layout, (0, layout.num_cycles)) + times = np.array([1, 50, 333, 4000]) + former = FrameFormer(layout, samples, 0) + num, den = former.sums(times, 20) + want_num, want_den = frames_reference(layout, samples, times, 20) + np.testing.assert_allclose(num.numpy(), want_num, rtol=1e-12) + np.testing.assert_allclose(den.numpy(), want_den, rtol=1e-12) + part = FrameFormer(layout, samples[:, :, 40:200], 40) + np.testing.assert_allclose(part.sums([700], 20)[0].numpy(), former.sums([700], 20)[0].numpy()) + with pytest.raises(ValueError): + part.sums([20], 20) + + +def test_register_trial_recovers_motion( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Recovered motion follows the known motion (up to a constant).""" + layout, truth = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + n_lines = 9000 + res = multiroi.register_trial( + layout.files[0], + 1, + n_lines, + tmp_path / "m.tif", + tmp_path / "a.h5", + params, + ) + dt = 1600 / 80 + kernel = np.exp(-np.abs(np.arange(-3 * dt, 3 * dt + 1)) / dt) + kernel /= kernel.sum() + true = np.stack([np.convolve(truth[:, i], kernel, "same")[res.ds_frames - 1] for i in (0, 1)]) + est = np.stack([res.motion_r, res.motion_c]) + err = est - true + err -= np.median(err, axis=1, keepdims=True) + assert np.sqrt(np.mean(err**2)) < 0.1 + a = load_struct_h5(tmp_path / "a.h5") + assert a["slap2"]["varFacDS"].shape == ( + a["meanIM"].shape[1], + a["meanIM"].shape[2], + res.ds_frames.size, + ) + np.testing.assert_array_equal(a["DSframes"].ravel(), res.ds_frames) + assert not (tmp_path / "a.h5.partial").exists() + + +def digests(*paths: str | Path) -> list[str]: + """SHA-256 of each file. + + Returns + ------- + list[str] + The hex digest of each of `paths`, in order. + """ + return [hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths] + + +@pytest.mark.parametrize("save_tif", [True, False]) +def test_failed_rerun_keeps_the_previous_outputs( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, save_tif: bool +) -> None: + """A run that fails while writing leaves an existing pair as it was.""" + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=save_tif) + movie = tmp_path / ("m.tif" if save_tif else "m.h5") + adata = tmp_path / "a.h5" + args = (layout.files[0], 1, 3000, movie, adata, params) + multiroi.register_trial(*args) + stats = movie.with_name(movie.stem + "_REGSTATS.h5") + before = digests(movie, adata, stats) + add = multiroi.OutputSink.add + + def fail_midway( + self: multiroi.OutputSink, + k: int, + regs: list[torch.Tensor], + var_factor: torch.Tensor, + *rest: object, + ) -> torch.Tensor: + """Write 50 frames, then fail. + + Returns + ------- + torch.Tensor + The sum of the frame's registered channels, from the original add. + + Raises + ------ + OSError + At frame 50. + """ + if k == 50: + raise OSError("disk full") + return add(self, k, regs, var_factor, *rest) + + def fail_at_the_end(*args: object, **kwargs: object) -> NoReturn: + """Fail after the movie is complete. + + Raises + ------ + OSError + Always. + """ + raise OSError("disk full") + + for target, name, fail in ( + (multiroi.OutputSink, "add", fail_midway), + (multiroi, "alignment_fields", fail_at_the_end), + ): + with monkeypatch.context() as m: + m.setattr(target, name, fail) + with pytest.raises(OSError): + multiroi.register_trial(*args) + assert digests(movie, adata, stats) == before + assert sorted(tmp_path.iterdir()) == sorted([movie, adata, stats]) + + +def test_interrupted_publish_leaves_no_alignment_file( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A pair that cannot be moved into place leaves no alignment file. + + The movie may then be new, but without an alignment file the trial is + not taken for registered. + """ + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) + movie, adata = tmp_path / "m.h5", tmp_path / "a.h5" + args = (layout.files[0], 1, 3000, movie, adata, params) + multiroi.register_trial(*args) + replace = os.replace + + def refuse_alignment_file(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: + """Fail to move the alignment file into place. + + Raises + ------ + PermissionError + If the destination is the alignment file. + """ + if Path(dst) == adata: + raise PermissionError("in use") + replace(src, dst) + + monkeypatch.setattr(os, "replace", refuse_alignment_file) + with pytest.raises(PermissionError): + multiroi.register_trial(*args) + # the new movie and its statistics are in place, the alignment file not + stats = movie.with_name(movie.stem + "_REGSTATS.h5") + assert sorted(tmp_path.iterdir()) == sorted([movie, stats]) + + +def blank_frames( + monkeypatch: pytest.MonkeyPatch, + blank: Callable[[np.ndarray], np.ndarray], + half: Callable[[np.ndarray], np.ndarray] | None = None, +) -> None: + """Frames formed at times where blank(times) holds have no samples. + + Where half(times) holds, the lower half of the raster has none. + """ + from giant_python.registration.frames import FrameFormer + + frames = FrameFormer.frames + + def blanked( + self: FrameFormer, times: ArrayLike, dt: int, channels: Sequence[int] | None = None + ) -> tuple[torch.Tensor, torch.Tensor]: + """Form the frames, with the selected ones emptied. + + Returns + ------- + vals : torch.Tensor + The frame values, NaN in the emptied frames (and in the lower half where + half(times) holds). + fresh : torch.Tensor + The per-pixel freshness, zero where emptied. + """ + vals, fresh = frames(self, times, dt, channels) + t = np.asarray(times).ravel() + lower = self.rows > np.median(self.rows) + for i in np.flatnonzero(half(t) if half else []): + vals[:, i, lower] = float("nan") + fresh[i, lower] = 0 + hit = torch.as_tensor(blank(t), device=vals.device) + vals[:, hit] = float("nan") + fresh[hit] = 0 + return vals, fresh + + monkeypatch.setattr(FrameFormer, "frames", blanked) + + +@pytest.mark.parametrize("schedule", ["sequential", "grow"]) +def test_frame_without_samples_is_missing( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str +) -> None: + """A frame without valid samples in mid-trial gets NaN motion and an all-NaN movie frame. + + The other frames are registered exactly as in a run without that frame, + and the trial does not fail. + """ + from giant_python.registration.growth import MISSING + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) + dt = (1 / layout.line_period_s) / params.align_hz + init, ds = multiroi.frame_times(1, 3000, dt, params.init_frames) + k = 70 + assert ds[k] not in init + times = multiroi.frame_times + out = {} + for name in ("blank", "without"): + with monkeypatch.context() as m: + if name == "blank": + blank_frames(m, lambda t: t == ds[k]) + else: + m.setattr( + multiroi, + "frame_times", + lambda *a: (times(*a)[0], np.delete(times(*a)[1], k)), + ) + out[name] = multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"{name}.h5", + tmp_path / f"{name}_a.h5", + params, + ) + res, ref = out["blank"], out["without"] + assert not res.registration_failed + assert np.isnan([res.motion_r[k], res.motion_c[k], res.peak[k]]).all() + others = np.arange(ds.size) != k + for f in ("motion_r", "motion_c", "peak"): + np.testing.assert_array_equal(getattr(res, f)[others], getattr(ref, f)) + n_ch = layout.num_channels + with ( + h5py.File(tmp_path / "blank.h5") as a, + h5py.File(tmp_path / "without.h5") as b, + ): + pages = a["data"][()] + mine = np.s_[k * n_ch : (k + 1) * n_ch] + assert np.isnan(pages[mine]).all() + np.testing.assert_array_equal(np.delete(pages, mine, axis=0), b["data"][()]) + adata = load_struct_h5(tmp_path / "blank_a.h5") + want = load_struct_h5(tmp_path / "without_a.h5") + assert adata["registrationFailed"].item() == 0 + assert np.isnan(adata["motionDSr"].ravel()[k]) + assert np.isnan(adata["slap2"]["varFacDS"][..., k]).all() + np.testing.assert_array_equal(adata["meanIM"], want["meanIM"]) + if schedule == "grow": + assert adata["growthQC"]["kind"].ravel()[k] == MISSING + + +@pytest.mark.parametrize("schedule", ["sequential", "grow"]) +def test_trial_without_samples_at_its_start_or_at_all( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, schedule: str +) -> None: + """A recording that starts late is registered from its first frames with samples. + + It is registered in the usual window even if the first of them covers only + part of the raster; a trial without any samples completes and is flagged. + """ + from giant_python.registration.sources import make_source + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False, schedule=schedule) + args = (layout.files[0], 1, 3000) + lay, former, init, ds, dt = multiroi.open_trial(*args, params, torch.device("cpu")) + window = make_source(lay, former, 1, 3000, init, ds, dt, False).window + with monkeypatch.context() as m: + # the first initial frames have no samples, the next one only half + assert np.sum((init >= 1200) & (init < 1300)) == 1 + blank_frames(m, lambda t: t < 1200, lambda t: t < 1300) + late = multiroi.register_trial(*args, tmp_path / "late.h5", tmp_path / "late_a.h5", params) + early = late.ds_frames < 1200 + assert np.isnan(late.motion_r[early]).all() + assert np.isfinite(late.motion_r[late.ds_frames >= 1200]).all() + assert not late.registration_failed + trim = load_struct_h5(tmp_path / "late_a.h5")["slap2"] + np.testing.assert_array_equal(trim["trimRows"].ravel(), window.trim_rows) + np.testing.assert_array_equal(trim["trimCols"].ravel(), window.trim_cols) + with monkeypatch.context() as m: + blank_frames(m, lambda t: np.ones(t.shape, dtype=bool)) + empty = multiroi.register_trial( + *args, tmp_path / "empty.h5", tmp_path / "empty_a.h5", params + ) + assert np.isnan(empty.motion_r).all() and empty.registration_failed + with h5py.File(tmp_path / "empty.h5") as f: + assert np.isnan(f["data"][()]).all() + + +def test_register_trial_keeps_fractional_lines( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fractional trial edges set the frame times, as in MATLAB. + + Trial tables of continuous recordings cut trials at linspace edges; + MultiRoiRegistration uses them unrounded: ceil(first:dt:last). + """ + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + first, last = 1000.4, 4000.7 + res = multiroi.register_trial( + layout.files[0], + first, + last, + tmp_path / "m.tif", + tmp_path / "a.h5", + params, + ) + dt = 1600 / 80 + n = int(np.floor((last - first) / dt)) + 1 + np.testing.assert_array_equal(res.ds_frames, np.ceil(first + dt * np.arange(n))) + assert res.ds_frames[0] == 1001 + + +def test_register_multiroi_updates_trial_table( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pipeline writes MATLAB-named outputs and motion_correction.""" + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + name = dat.name + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + "motion_correction": {"keep_me": 7.0}, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert fields["fn_adata"][0, 0] == "E3T1DMD1_ALIGNMENTDATA.h5" + movie = tmp_path / "motion_correction" / fields["fn_reg_ds"][0, 0] + assert movie.name == "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5" + with h5py.File(movie) as f: + assert f["data"].shape[0] == 2 * 150 + tt = read_trial_table(table) + mc = tt.motion_correction + assert mc["keep_me"].item() == 7.0 + assert mc["fn_adata"] == "E3T1DMD1_ALIGNMENTDATA.h5" + assert mc["align_params"]["alignHz"].item() == 80.0 + assert mc["registration_failed"].dtype == np.int8 + + +def one_trial_table(layout: RasterLayout, tmp_path: Path) -> Path: + """Write a MATLAB-style trial table with one 3000-line trial. + + Returns + ------- + Path + The trial table file. + """ + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[1.0]]), + "last_line": np.array([[3000.0]]), + }, + }, + ) + return table + + +def test_rerun_keeps_the_saved_failure_flag( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Reused outputs report the registrationFailed they were saved with.""" + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + run = { + "params": {"maxshift": 5, "save_tif": False}, + "execution": {"device": "cpu", "max_workers": 1}, + } + fields = register_multiroi(table, **run) + assert not fields["registration_failed"][0, 0] + adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] + with h5py.File(adata, "r+") as f: # as if the motion had been too large + f["registrationFailed"][...] = 1 + before = digests(adata) + fields = register_multiroi(table, **run) + assert digests(adata) == before # reused, not registered again + assert fields["registration_failed"][0, 0] + assert read_trial_table(table).motion_correction["registration_failed"] + + +def test_rerun_with_other_settings_registers_again( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Outputs are reused only if made with the requested settings.""" + from giant_python.pipeline.register import register_multiroi + from giant_python.registration.outputs import SETTINGS_ATTR + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + execution = {"device": "cpu", "max_workers": 1} + sequential = {"maxshift": 5, "save_tif": False} + grow = dict(sequential, schedule="grow") + fields = register_multiroi(table, sequential, execution=execution) + adata = tmp_path / "motion_correction" / fields["fn_adata"][0, 0] + first = digests(adata) + assert "growthQC" not in load_struct_h5(adata) + + fields = register_multiroi(table, grow, execution=execution) + assert digests(adata) != first # registered again + assert "growthQC" in load_struct_h5(adata) + mc = read_trial_table(table).motion_correction + assert mc["align_params"]["schedule"] == "grow" + with h5py.File(adata) as f: + saved = json.loads(f.attrs[SETTINGS_ATTR]) + assert saved["schedule"] == "grow" and saved["maxshift"] == 5 + assert "overwriteExisting" not in saved + + grown = digests(adata) + register_multiroi(table, grow, execution=execution) + assert digests(adata) == grown # same settings: reused + + with h5py.File(adata, "r+") as f: # outputs that do not record them + del f.attrs[SETTINGS_ATTR] + register_multiroi(table, grow, execution=execution) + with h5py.File(adata) as f: + assert SETTINGS_ATTR in f.attrs + + +def test_failed_rerun_does_not_name_the_old_outputs( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A re-registration that raises leaves the old files on disk but clears their names. + + So the table never pairs them with new settings. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + table = one_trial_table(layout, tmp_path) + execution = {"device": "cpu", "max_workers": 1} + sequential = {"maxshift": 5, "save_tif": False} + fields = register_multiroi(table, sequential, execution=execution) + moco = tmp_path / "motion_correction" + files = [moco / fields["fn_reg_ds"][0, 0], moco / fields["fn_adata"][0, 0]] + before = digests(*files) + + def fail(*args: object, **kwargs: object) -> NoReturn: + """Fail before anything is published. + + Raises + ------ + OSError + Always. + """ + raise OSError("disk full") + + monkeypatch.setattr(multiroi, "register_trial", fail) + fields = register_multiroi(table, dict(sequential, schedule="grow"), execution=execution) + assert fields["fn_reg_ds"][0, 0] == fields["fn_adata"][0, 0] == "" + assert fields["registration_failed"][0, 0] + assert digests(*files) == before + mc = read_trial_table(table).motion_correction + assert mc["fn_reg_ds"] == mc["fn_adata"] == "" + assert mc["registration_failed"] + assert mc["align_params"]["schedule"] == "grow" + + +@pytest.mark.parametrize("case", ["row_major", "channels", "device"]) +def test_rejected_request_writes_nothing( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + """A request that fails validation leaves outputs and table untouched. + + Such requests are a row-major table, an unsupported recording, an + unavailable device. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + lay = layout + if case == "channels": + lay = dataclasses.replace(layout, num_channels=3) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: lay) + table = one_trial_table(layout, tmp_path) + if case == "row_major": + with h5py.File(table, "r+") as f: + f["row_major"][...] = 1 + moco = tmp_path / "motion_correction" + moco.mkdir() + old = [ + moco / "E3T1DMD1_REGISTERED_DOWNSAMPLED-80Hz.h5", + moco / "E3T1DMD1_ALIGNMENTDATA.h5", + ] + for p in old: + p.write_bytes(b"from an earlier run") + before = digests(table, *old) + with pytest.raises(ValueError): + register_multiroi( + table, + {"maxshift": 5, "save_tif": False, "overwrite_existing": True}, + execution={ + "device": "cuda:99" if case == "device" else "cpu", + "max_workers": 1, + }, + ) + assert digests(table, *old) == before + assert sorted(moco.iterdir()) == sorted(old) + + +def test_ragged_table_skips_empty_cells( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A cell without a recording (one path has fewer trials) is skipped and flagged. + + It gets empty output names; the other cells register. + """ + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name, dat.name], [dat.name, ""]], dtype=object), + "epoch": np.array([[3.0, 3.0], [3.0, np.nan]]), + "true_trial_ix": np.array([[1.0, 2.0]]), + "slap2_info": { + "first_line": np.array([[1.0, 3001.0], [1.0, np.nan]]), + "last_line": np.array([[3000.0, 6000.0], [3000.0, np.nan]]), + }, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert fields["fn_reg_ds"][1, 1] == fields["fn_adata"][1, 1] == "" + np.testing.assert_array_equal(fields["registration_failed"], [[False, False], [False, True]]) + names = [ + fields[k][d, t] for k in ("fn_reg_ds", "fn_adata") for d, t in ((0, 0), (0, 1), (1, 0)) + ] + assert all(names) + moco = tmp_path / "motion_correction" + stats = [ + n.replace("_REGISTERED_DOWNSAMPLED-", "_REGSTATS-") for n in names if "_REGISTERED_" in n + ] + assert sorted(p.name for p in moco.iterdir()) == sorted(names + stats) + mc = read_trial_table(table).motion_correction + assert mc["fn_reg_ds"][1, 1] == mc["fn_adata"][1, 1] == "" + assert mc["registration_failed"][1, 1] == 1 + + +def test_trial_table_update_keeps_other_entries( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only the registration fields are replaced, once all are written. + + Other entries of the group and their attributes are left untouched. + """ + from giant_python.pipeline import register + + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": "d", + "motion_correction": { + "keep_me": 7.0, + "fn_adata": "old.h5", + "align_params": {"old_only": 1.0}, + }, + }, + ) + with h5py.File(table, "r+") as f: + mc = f["motion_correction"] + mc.attrs["note"] = "kept" + mc["keep_me"].attrs["unit"] = "px" + mc.create_dataset("empty", shape=(0, 0), dtype=np.float64) + nested = mc.create_group("nested") + nested.create_dataset("row_major", data=np.zeros((1, 1), np.uint8)) + fields = { + "fn_adata": np.array([["new.h5"]], dtype=object), + "registration_failed": np.array([[True]]), + "align_params": {"alignHz": 80.0}, + } + write = register.write_matlab_value + + def fail_on_align_params(grp: h5py.Group, key: str, value: dict | ArrayLike) -> None: + """Fail while writing the last field. + + Raises + ------ + OSError + If key starts with align_params. + """ + if key.startswith("align_params"): + raise OSError("disk full") + write(grp, key, value) + + def entries() -> set[str]: + """Every entry under motion_correction. + + Returns + ------- + set[str] + The names of all groups and datasets under motion_correction in the table. + """ + names = [] + with h5py.File(table) as f: + f["motion_correction"].visit(names.append) + return set(names) + + kept = {"keep_me", "empty", "nested", "nested/row_major"} + with monkeypatch.context() as m: + m.setattr(register, "write_matlab_value", fail_on_align_params) + with pytest.raises(OSError): + register._update_trial_table(table, fields) + old = {"fn_adata", "align_params", "align_params/old_only"} + assert entries() == kept | old + assert load_struct_h5(table)["motion_correction"]["fn_adata"] == "old.h5" + register._update_trial_table(table, fields) + assert entries() == kept | { + "fn_adata", + "registration_failed", + "align_params", + "align_params/alignHz", + } + with h5py.File(table) as f: + mc = f["motion_correction"] + assert mc.attrs["note"] == "kept" + assert mc["keep_me"].attrs["unit"] == "px" + assert mc["empty"].shape == (0, 0) + mc = load_struct_h5(table)["motion_correction"] + assert mc["fn_adata"] == "new.h5" + assert mc["registration_failed"].item() == 1 + assert mc["align_params"]["alignHz"].item() == 80.0 + + +def test_register_multiroi_keeps_fractional_lines( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pipeline passes the table's fractional trial edges on unrounded.""" + from giant_python.io.hdf5 import load_struct_h5 + from giant_python.pipeline.register import register_multiroi + + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + dat = Path(layout.files[0]) + table = tmp_path / "trial_table.h5" + first, last = 1000.4, 4000.7 + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name]], dtype=object), + "epoch": np.array([[3.0]]), + "true_trial_ix": np.array([[1.0]]), + "slap2_info": { + "first_line": np.array([[first]]), + "last_line": np.array([[last]]), + }, + }, + ) + fields = register_multiroi( + table, + {"maxshift": 5, "save_tif": False}, + execution={"device": "cpu", "max_workers": 1}, + ) + adata = load_struct_h5(tmp_path / "motion_correction" / fields["fn_adata"][0, 0]) + adata = adata.get("aData", adata) + dt = 1600 / 80 + n = int(np.floor((last - first) / dt)) + 1 + np.testing.assert_array_equal(np.ravel(adata["DSframes"]), np.ceil(first + dt * np.arange(n))) + + +def test_unsupported_options_raise() -> None: + """MATLAB options that are not ported are rejected.""" + with pytest.raises(NotImplementedError): + multiroi.MultiRoiRegistrationParams(ref_stack_template=True) + with pytest.raises(TypeError): + from giant_python.models.params import resolve_registration_options + + resolve_registration_options({"compensateOnline": True}) + + +def test_save_struct_h5_is_column_major(tmp_path: Path) -> None: + """Values come back in MATLAB orientation and MATLAB classes.""" + path = tmp_path / "s.h5" + save_struct_h5( + path, + { + "a": np.arange(6.0).reshape(2, 3), + "v": np.arange(4.0), + "flag": True, + "n": 3, + "s": "text", + "cells": np.array([["x"], ["yy"]], dtype=object), + "g": {"single": np.float32(2.5)}, + }, + ) + with h5py.File(path) as f: + assert f["a"].shape == (3, 2) and f["v"].shape == (4, 1) + assert f["flag"].dtype == np.int8 and f["n"].dtype == np.float64 + assert f["row_major"][()] == 0 + back = load_struct_h5(path) + np.testing.assert_array_equal(back["a"], np.arange(6.0).reshape(2, 3)) + assert back["v"].shape == (1, 4) + assert back["s"] == "text" + assert list(back["cells"].ravel()) == ["x", "yy"] + assert back["g"]["single"].dtype == np.float32 + + +def test_registration_runs_on_cuda_like_cpu( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """CUDA and CPU give the same motion (skipped without a GPU).""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + params = multiroi.MultiRoiRegistrationParams(maxshift=6) + out = [ + multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"{d}.tif", + tmp_path / f"{d}.h5", + params, + device=d, + ) + for d in ("cpu", "cuda") + ] + diff = np.hypot(out[0].motion_r - out[1].motion_r, out[0].motion_c - out[1].motion_c) + # float32 sums differ in order; a near-tie peak may resolve differently + assert np.median(diff) < 1e-3 and diff.max() < 0.1 + + +def test_var_factor_deflate_keeps_values( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Deflated varFacDS (default) holds the same values as uncompressed.""" + layout, _ = recording + monkeypatch.setattr(multiroi, "raster_layout", lambda path: layout) + for level in (0, 1): + params = multiroi.MultiRoiRegistrationParams( + maxshift=5, var_factor_deflate=level, save_tif=False + ) + multiroi.register_trial( + layout.files[0], + 1, + 3000, + tmp_path / f"m{level}.h5", + tmp_path / f"a{level}.h5", + params, + ) + with ( + h5py.File(tmp_path / "a0.h5") as a, + h5py.File(tmp_path / "a1.h5") as b, + ): + assert a["slap2/varFacDS"].compression is None + assert b["slap2/varFacDS"].compression == "gzip" + np.testing.assert_array_equal(a["slap2/varFacDS"][()], b["slap2/varFacDS"][()]) + with h5py.File(tmp_path / "m1.h5") as m: + assert m["data"].compression == "gzip" + assert m["data"].compression_opts == 1 + + +def test_cycle_split_names() -> None: + """Files of CYCLE-split recordings are recognised by name only.""" + assert is_cycle_split("acq_DMD1-TRIAL000001-CYCLE-000000.dat") + assert is_cycle_split("d/acq_DMD2-CYCLE-318000.dat") + assert is_cycle_split("acq_DMD1-CYCLE000000.dat") + assert not is_cycle_split("acq_DMD1-TRIAL000001.dat") + assert not is_cycle_split("CYCLE-1/acq_DMD1-TRIAL000001.dat") + + +def split_recording(layout: RasterLayout, k: int, tmp_path: Path) -> RasterLayout: + """Write the recording as two files, split before cycle k. + + Returns + ------- + RasterLayout + `layout` with its files replaced by the two split files. + """ + raw = np.fromfile(layout.files[0], dtype=np.int16) + head = raw[:HEADER_WORDS] + body = raw[HEADER_WORDS:].reshape(layout.num_cycles, -1) + files = [] + for name, part in (("a", body[:k]), ("b", body[k:])): + path = tmp_path / f"split_{name}.dat" + with open(path, "wb") as f: + f.write(head.tobytes()) + f.write(part.tobytes()) + files.append(str(path)) + return dataclasses.replace( + layout, + files=tuple(files), + file_cycles=np.array([k, layout.num_cycles - k]), + file_offset_words=np.array([HEADER_WORDS, HEADER_WORDS]), + ) + + +def test_split_recording_reads_and_registers_alike( + recording: Recording, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Reads and registration across two files equal those of one file.""" + layout, _ = recording + k = 500 + split = split_recording(layout, k, tmp_path) + for cycles in ((k - 7, k + 9), (0, layout.num_cycles), (k + 3, k + 40)): + np.testing.assert_array_equal( + read_raster_samples(split, cycles, chunk_cycles=5), + read_raster_samples(layout, cycles), + ) + p = layout.lines_per_cycle + lines = np.arange((k - 3) * p + 1, (k + 3) * p + 1) + for a, b in zip(read_line_offsets(split, lines), read_line_offsets(layout, lines)): + np.testing.assert_array_equal(a, b) + params = multiroi.MultiRoiRegistrationParams(maxshift=5, save_tif=False) + first, last = (k - 150) * p + 1, (k + 150) * p + out = {} + for name, lay in (("one", layout), ("two", split)): + monkeypatch.setattr(multiroi, "raster_layout", lambda path, lay=lay: lay) + out[name] = multiroi.register_trial( + lay.files[0], + first, + last, + tmp_path / f"m_{name}.h5", + tmp_path / f"a_{name}.h5", + params, + ) + for f in ("ds_frames", "motion_r", "motion_c", "peak"): + np.testing.assert_array_equal(getattr(out["one"], f), getattr(out["two"], f)) diff --git a/tests/simulation/__init__.py b/tests/simulation/__init__.py index e6392c55..16662977 100644 --- a/tests/simulation/__init__.py +++ b/tests/simulation/__init__.py @@ -1 +1 @@ -"""Tests of synthetic ground truth (event injection).""" +"""Tests of synthetic ground truth (event injection).""" diff --git a/tests/simulation/test_injection.py b/tests/simulation/test_injection.py index c5c4158d..0af0bddc 100644 --- a/tests/simulation/test_injection.py +++ b/tests/simulation/test_injection.py @@ -1,1517 +1,1517 @@ -"""Event injection into raw SLAP2 samples, on small synthetic recordings.""" - -import hashlib -import json -from collections.abc import Sequence -from dataclasses import replace -from pathlib import Path -from typing import Any - -import h5py -import numpy as np -import pytest -import torch - -from giant_python.io.hdf5 import save_struct_h5 -from giant_python.io.slap2_raster import ( - INVALID_SAMPLE, - RasterLayout, - read_raster_samples, -) -from giant_python.pipeline.register import register_multiroi -from giant_python.registration import multiroi -from giant_python.simulation import injection as inj -from giant_python.simulation.render import iter_registered_frames - -from ..registration.synthetic import ( - HEADER_WORDS, - make_layout, - online_offsets, - write_recording, -) - -N_CYCLES = 1400 - -# online offsets (x, y_header, y_dmd) per line, as online_offsets returns them -Offsets = tuple[np.ndarray, np.ndarray, np.ndarray] -# the layout, its online offsets and the true motion of the synthetic recording -OnlineRecording = tuple[RasterLayout, Offsets, np.ndarray] -# the injected copy's folder, its summary and the settings it was made with -Injected = tuple[Path, dict, inj.InjectionSettings] - - -def sha(path: str | Path) -> str: - """SHA-256 of a file. - - Returns - ------- - str - The hexadecimal SHA-256 digest of the file's bytes. - """ - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - - -# --------------------------------------------------------- pure functions - - -def test_time_course_peaks_at_one() -> None: - """Instant rise: exp decay from 1; short rise: peak 1 at its delay.""" - t = np.array([-0.01, 0.0, 0.024, 0.048]) - np.testing.assert_allclose(inj.time_course(t, 0.024), [0, 1, np.exp(-1), np.exp(-2)]) - tp = inj.peak_delay_s(0.024, 0.003) - assert 0 < tp < 0.024 - grid = np.linspace(0, 0.1, 100001) - k = inj.time_course(grid, 0.024, 0.003) - assert k.max() == pytest.approx(1.0, abs=1e-8) - assert grid[np.argmax(k)] == pytest.approx(tp, abs=2e-6) - assert inj.time_course(-1e-9, 0.024, 0.003) == 0 - - -def test_event_traces_sum_events() -> None: - """Traces are sums of size x time course at the line times.""" - s = inj.InjectionSettings(tau_s=0.01) - ev = inj.Events( - np.array([0, 0, 1]), - np.array([1, 1, 1]), - np.array([10.5, 30.0, 12.0]), - np.array([0, 1, 2]), - np.array([2.0, 3.0, 1.0]), - ) - tr = inj.event_traces(ev, 2, (5, 60), 0.001, s) - lines = np.arange(5, 61) - want0 = 2 * inj.time_course((lines - 10.5) * 1e-3, 0.01) + 3 * ( - inj.time_course((lines - 30.0) * 1e-3, 0.01) - ) - np.testing.assert_allclose(tr[0], want0, atol=1e-12) - assert tr[1, 12 - 5] == pytest.approx(1.0) - assert np.all(tr[1, : 12 - 5] == 0) - - -def test_draw_events_respect_edges_dead_time_and_classes() -> None: - """Onsets stay inside the edges, apart by the dead time; classes mix.""" - s = inj.InjectionSettings(rate_hz=4.0, min_interval_s=0.1, edge_s=0.5) - period = 1e-4 - ev = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) - assert np.all(ev.trial == 3) - assert ev.onset_line.min() >= 1 + 0.5 / period - assert ev.onset_line.max() <= 100001 - 0.5 / period - for j in range(200): - t = ev.onset_line[ev.source == j] - assert np.all(np.diff(t) >= 0.1 / period - 1e-6) - dur = 10.0 - 1.0 - rate = len(ev) / 200 / dur - assert rate == pytest.approx(1 / (0.1 + 1 / 4.0), rel=0.05) - counts = np.bincount(ev.size_class, minlength=6) - assert counts.min() > 0.8 * counts.mean() - np.testing.assert_array_equal(ev.size, np.asarray(s.size_classes)[ev.size_class]) - again = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) - np.testing.assert_array_equal(again.onset_line, ev.onset_line) - none = inj.draw_events(5, 1.0, 100001.0, period, replace(s, rate_hz=0.0), None) - assert len(none) == 0 - - -def _draw_events_before_sync( - n_sources: int, - first: float, - last: float, - period: float, - s: inj.InjectionSettings, - rng: np.random.Generator, -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Draw the events as they were drawn before sync_share existed. - - This is the loop of draw_events at GIAnT-Python a673714, kept here as - the reference: source, onset line and size class of every event. - - Returns - ------- - source : np.ndarray - Source index of every event. - onset_line : np.ndarray - Onset line of every event. - size_class : np.ndarray - Size class of every event. - """ - edge = s.edge_s / period - lo, hi = float(first) + edge, float(last) - edge - mean_gap = 1.0 / s.rate_hz / period - dead = s.min_interval_s / period - n_draw = int((hi - lo) / (mean_gap + dead) * 1.5) + 20 - src, onset, classes = [], [], [] - for j in range(n_sources): - while True: - gaps = rng.exponential(mean_gap, n_draw) + dead - gaps[0] -= dead - t = lo + np.cumsum(gaps) - if t[-1] > hi: - break - n_draw *= 2 - t = t[t <= hi] - cls = rng.choice(len(s.size_classes), t.size, p=s.weights) - src.append(np.full(t.size, j)) - onset.append(t) - classes.append(cls) - return np.concatenate(src), np.concatenate(onset), np.concatenate(classes) - - -def test_draw_events_with_common_onsets() -> None: - """sync_share gives every source the onsets of one common train beside its own. - - The common ones are in every source, the dead time holds, the rate is - about kept, and a share of 0 changes no draw. - """ - period = 1e-4 - s = inj.InjectionSettings(rate_hz=2.0, min_interval_s=0.1, edge_s=0.5) - args = (60, 1.0, 600001.0, period) # a minute - plain = inj.draw_events(*args, s, np.random.default_rng(3)) - # a share of 0 draws what the tool drew before the option existed: - # the same generator calls in the same order (the default setting, a - # high rate without dead time, weighted size classes) - for setting, n_src, seed in ( - (s, 60, 3), - (replace(s, rate_hz=40.0, min_interval_s=0.0), 7, 11), - (replace(s, class_weights=(1, 1, 1, 1, 1, 5)), 12, 5), - ): - got = inj.draw_events(n_src, *args[1:], setting, np.random.default_rng(seed)) - src, onset, cls = _draw_events_before_sync( - n_src, *args[1:], setting, np.random.default_rng(seed) - ) - np.testing.assert_array_equal(got.source, src) - np.testing.assert_array_equal(got.onset_line, onset) - np.testing.assert_array_equal(got.size_class, cls) - assert len(got) > 100 - rate0 = len(plain) / 60 / 59.0 - - def common_onsets(ev: inj.Events, n: int) -> np.ndarray: - """Onsets that every one of the n sources has. - - Returns - ------- - np.ndarray - The onset lines present in all n sources. - """ - t, counts = np.unique(ev.onset_line, return_counts=True) - return t[counts == n] - - assert common_onsets(plain, 60).size == 0 - for share in (0.5, 1.0): - ev = inj.draw_events(*args, replace(s, sync_share=share), np.random.default_rng(3)) - both = common_onsets(ev, 60) - assert both.size > 20 - for j in range(60): - t = ev.onset_line[ev.source == j] - assert np.all(np.diff(t) >= 0.1 / period - 1e-6) - in_common = np.isin(t, both).mean() - if share == 1.0: - assert in_common == 1.0 - else: - assert 0.35 < in_common < 0.7 - rate = len(ev) / 60 / 59.0 - assert rate == pytest.approx(rate0, rel=0.12) - if share == 1.0: # one train, sixty times, with sizes of their own - assert len(ev) == 60 * both.size - first = ev.size_class[ev.source == 0] - second = ev.size_class[ev.source == 1] - assert np.any(first != second) - # an own onset never falls within the dead time of a common one - ev = inj.draw_events(*args, replace(s, sync_share=0.5), np.random.default_rng(3)) - both = common_onsets(ev, 60) - own = ev.onset_line[~np.isin(ev.onset_line, both)] - k = np.searchsorted(both, own) - gap = np.minimum( - np.abs(both[np.minimum(k, both.size - 1)] - own), - np.abs(own - both[np.maximum(k - 1, 0)]), - ) - assert gap.min() >= 0.1 / period - 1e-6 - - -def test_settings_reject_bad_values() -> None: - """Invalid settings raise.""" - with pytest.raises(ValueError): - inj.InjectionSettings(rise_s=0.03) - with pytest.raises(ValueError): - inj.InjectionSettings(sync_share=1.5) - with pytest.raises(ValueError): - inj.InjectionSettings(class_weights=(1.0, 2.0)) - with pytest.raises(ValueError): - inj.InjectionSettings(rate_hz=-1) - - -def test_footprints() -> None: - """Gaussian peak 1 and cut at its radius; image footprints interpolate.""" - g = inj.GaussianFootprint(1.33, 4.0) - assert g(0.0, 0.0) == 1.0 - assert g(1.33, 0.0) == pytest.approx(np.exp(-0.5)) - assert g(5.4, 0.0) == 0.0 and g.radius == pytest.approx(5.32) - img = np.zeros((5, 5)) - img[2, 2], img[2, 3] = 4.0, 2.0 - f = inj.ImageFootprint(img) - assert f(0.0, 0.0) == 1.0 - assert f(0.0, 0.5) == pytest.approx(0.75) - assert f(0.0, 9.0) == 0.0 - patch, origin = inj.footprint_patch(g, (10.0, 20.4), 3) - assert origin == [7, 17] and patch.shape == (7, 7) - assert patch[3, 3] == pytest.approx(np.exp(-0.5 * (0.4 / 1.33) ** 2)) - - -def test_place_sources_follow_the_rules() -> None: - """Sources sit on labeled pixels, away from edges, others and each other.""" - rng = np.random.default_rng(0) - img = np.full((60, 80), 1.0) - img[20:24, 5:75] = 10.0 # a horizontal "dendrite" - img[30:50, 40:44] = 10.0 # a vertical one - img[:, :3] = np.nan - exclude = np.array([[22.0, 40.0]]) - s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) - pos, n_cand = inj.place_sources(img, 100, rng, s, exclude_rc=exclude) - assert 0 < pos.shape[0] < 100 and n_cand > pos.shape[0] - lab = inj.labeled_pixels(img) - r, c = pos.T.astype(int) - assert lab[r, c].all() - assert c.min() >= 3 + 5 - 1 # distance from the NaN columns - d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) - assert d[np.triu_indices(len(pos), 1)].min() >= 6 - assert np.hypot(*(pos - exclude).T).min() >= 8 - - -def test_place_sources_keep_apart_from_placed_ones() -> None: - """Candidates near sources placed already are dropped before any is chosen. - - Candidates within the minimum distance of sources placed already are - dropped first: one that is too near cannot stand in the way of a free - one behind it. - """ - img = np.full((40, 60), 1.0) - img[19:22, 20:41] = 10.0 # a short "dendrite" - s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) - placed = np.array([[20.0, 24.0]]) - for seed in range(8): - pos, n_cand = inj.place_sources( - img, 10, np.random.default_rng(seed), s, keep_apart_rc=placed - ) - _, n_free = inj.place_sources(img, 10, np.random.default_rng(seed), s) - # fewer candidates, and none of the chosen within 6 px of the - # placed source or of each other - assert 0 < n_cand < n_free and pos.shape[0] >= 1 - assert np.hypot(*(pos - placed).T).min() >= 6 - d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) - assert len(pos) < 2 or d[np.triu_indices(len(pos), 1)].min() >= 6 - # with one place wanted and only the pixels 4 and 8 px from the placed - # source as candidates, the far one is found whatever the order - two = np.full((40, 60), np.nan) - two[10:31, 10:51] = 1.0 - two[19:22, 27:30] = 10.0 - two[19:22, 31:34] = 10.0 - for seed in range(8): - pos, _ = inj.place_sources( - two, - 1, - np.random.default_rng(seed), - replace(s, edge_px=0), - keep_apart_rc=placed, - ) - assert pos.shape[0] == 1 - assert np.hypot(*(pos[0] - placed[0])) >= 6 - - -def test_align_images_recovers_subpixel_shift() -> None: - """A smooth random image moved by a known shift is found again.""" - from scipy.ndimage import gaussian_filter - - rng = np.random.default_rng(3) - ref = gaussian_filter(rng.random((90, 120)), 2.0) * 100 - ref[:, :10] = np.nan - s = np.array([1.3, -2.6]) - moved = inj.shift_image(ref, -s) # moved(p + s) = ref(p) - est = inj.align_images(ref, moved) - np.testing.assert_allclose(est, s, atol=0.08) - - -# ------------------------------------------------------ synthetic recordings - - -def write_static(layout: RasterLayout, gain: float, rate: float, seed: int = 0) -> None: - """Write samples gain * Poisson(rate * brightness) of a static scene.""" - rng = np.random.default_rng(seed) - words = np.zeros((layout.num_cycles, layout.words_per_cycle), np.int16) - bright = 1 + 9 * ((layout.slot_pixel * 7919) % 97) / 97.0 - for ch in range(layout.num_channels): - li = layout.slot_line - 1 - w = layout.row_base[li] + ch * layout.n_per_channel[li] - w = w + layout.slot_pos - lam = rate * bright - words[:, w] = (gain * rng.poisson(lam, (layout.num_cycles, lam.size))).astype(np.int16) - with open(layout.files[0], "wb") as f: - f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) - f.write(words.tobytes()) - - -def test_measure_raw_per_photon(tmp_path: Path) -> None: - """The variance-to-mean ratio of scaled Poisson samples is the gain.""" - layout = make_layout(tmp_path / "g_DMD1-TRIAL000001.dat", 400, seed=2) - write_static(layout, gain=110.0, rate=0.05) - g = inj.measure_raw_per_photon(layout, channel=0) - assert g.raw_per_photon == pytest.approx(110.0, rel=0.05) - assert g.mean_pulse == pytest.approx(110.0, rel=0.01) - assert g.cycles == (0, 400) and g.n_slots > 0 - - -@pytest.fixture(scope="module") -def online(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: - """Synthetic recording with known motion and online offsets. - - Returns - ------- - OnlineRecording - The layout, its online offsets and the true motion, as (layout, offs, truth). - """ - path = tmp_path_factory.mktemp("rec") / "inj_DMD1-TRIAL000001.dat" - layout = make_layout(path, n_cycles=N_CYCLES, seed=5) - offs = online_offsets(layout.total_lines) - truth = write_recording(layout, seed=6, online=offs) - path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) - return layout, offs, truth - - -def truth_geometry( - layout: RasterLayout, offs: Offsets, truth: np.ndarray, lines: tuple[int, int] -) -> inj.TrialGeometry: - """Geometry in the scene frame. - - The sample of DMD (r, c) on line l shows the scene at - (r + y_dmd - m_r, c + x - m_c). - - Returns - ------- - inj.TrialGeometry - The per-line shifts for lines lines[0] to lines[1], with the geometry in the - scene frame. - """ - x, _, y_dmd = offs - ln = np.arange(lines[0], lines[1] + 1) - shift = np.stack([y_dmd[ln - 1] - truth[ln - 1, 0], x[ln - 1] - truth[ln - 1, 1]], 1) - return inj.TrialGeometry(lines[0], shift.astype(np.float64), True) - - -def test_sample_model_follows_the_tissue(online: OnlineRecording) -> None: - """Expected counts follow the tissue, for every chunk of cycles. - - They are photon_scale x footprint at the sample's tissue position x the - trace at its line. - """ - layout, offs, truth = online - lines = (8, layout.total_lines - 3) - geo = truth_geometry(layout, offs, truth, lines) - pos = np.array([[17.3, 22.0], [12.0, 30.6]]) - fps = [inj.GaussianFootprint(1.33), inj.GaussianFootprint(2.0)] - n_l = lines[1] - lines[0] + 1 - rng = np.random.default_rng(0) - traces = rng.random((2, n_l)) - model = inj.SampleModel(layout, geo, pos, fps, traces, 25.0) - cycles = np.arange(0, 30) - got = model.expected(cycles) - pix = layout.slot_pixel[model.slots] - 1 - r0, c0 = pix // layout.n_cols, pix % layout.n_cols - ln = cycles[:, None] * layout.lines_per_cycle + layout.slot_line[model.slots] - inside = (ln >= lines[0]) & (ln <= lines[1]) - li = np.clip(ln - lines[0], 0, n_l - 1) - want = np.zeros(got.shape) - for j in range(2): - f = fps[j]( - r0 + geo.shift[li, 0] - pos[j, 0], - c0 + geo.shift[li, 1] - pos[j, 1], - ) - want += 25.0 * f * traces[j, li] - want[~inside] = 0 - np.testing.assert_allclose(got, want, rtol=1e-12, atol=1e-12) - # every slot whose footprint value can be non-zero is reachable - every = np.arange(layout.slot_line.size) - allpix = layout.slot_pixel[every] - 1 - near = np.zeros(every.size, bool) - for j in range(2): - for s in geo.shift[:: layout.lines_per_cycle]: - d = np.hypot( - allpix // layout.n_cols + s[0] - pos[j, 0], - allpix % layout.n_cols + s[1] - pos[j, 1], - ) - near |= d <= fps[j].radius - assert np.all(np.isin(every[near], model.slots)) - - -def registered_table( - layout: RasterLayout, tmp_path: Path, compensate: bool, trials: Sequence[tuple[int, int]] -) -> Path: - """Register line ranges of a recording through a trial table. - - Returns - ------- - Path - The path of the trial table that was registered. - """ - dat = Path(layout.files[0]) - n = len(trials) - table = tmp_path / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(dat.parent), - "savedr": str(tmp_path), - "filename": np.array([[dat.name] * n], dtype=object), - "epoch": np.ones((1, n)), - "true_trial_ix": np.arange(1.0, n + 1)[None, :], - "slap2_info": { - "first_line": np.array([[float(a) for a, _ in trials]]), - "last_line": np.array([[float(b) for _, b in trials]]), - }, - }, - ) - register_multiroi( - table, - {"maxshift": 6, "compensate_online": compensate}, - execution={"device": "cpu", "max_workers": 1}, - ) - return table - - -@pytest.fixture(scope="module") -def registered( - online: OnlineRecording, tmp_path_factory: pytest.TempPathFactory -) -> dict[bool, Path]: - """Register the online recording as two trials, both ways. - - Returns - ------- - dict[bool, Path] - The trial table registered with (True) and without (False) online compensation. - """ - layout, _, _ = online - out = {} - with pytest.MonkeyPatch.context() as mp: - mp.setattr(multiroi, "raster_layout", lambda path: layout) - for comp in (True, False): - d = tmp_path_factory.mktemp(f"reg{int(comp)}") - out[comp] = registered_table(layout, d, comp, [(1, 4800), (4801, 9700)]) - return out - - -@pytest.mark.parametrize("compensate", [True, False]) -def test_geometry_from_registration_tracks_true_motion( - online: OnlineRecording, registered: dict[bool, Path], compensate: bool -) -> None: - """The registered position of each line's samples follows the tissue. - - shift(l) equals the true scene shift up to a constant. - """ - layout, offs, truth = online - table = Path(registered[compensate]) - al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - assert (al.compensation is not None) == compensate - lines = (1, 4800) - geo = inj.trial_geometry(layout, al, lines) - want = truth_geometry(layout, offs, truth, lines).shift - if not compensate: - # uncompensated frames blur the offsets' steps (every 23-50 ms - # here) over their kernel: the motion can only follow that blur - k = np.exp(-np.abs(np.arange(-60, 61)) / 20.0) - want = np.stack( - [np.convolve(np.pad(w, 60, "edge"), k / k.sum(), "valid") for w in want.T], - 1, - ) - err = geo.shift - want - err -= np.median(err, axis=0) - # within the registration's own error (as its tests require) - assert np.sqrt(np.mean(err**2)) < 0.12 - - -def run_injection( - online: OnlineRecording, - table: Path, - out: Path, - monkeypatch: pytest.MonkeyPatch, - **kw: Any, # noqa: ANN401 -) -> dict: - """inject_session on the synthetic recording. - - Returns - ------- - dict - The summary returned by inject_session. - """ - layout, _, _ = online - monkeypatch.setattr(inj, "raster_layout", lambda path: layout) - return inj.inject_session(table, out, paths=(1,), **kw) - - -def test_no_events_leave_the_copy_identical( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Without events the copy equals the original byte for byte. - - The .meta file is copied. - """ - layout, _, _ = online - s = inj.InjectionSettings(rate_hz=0.0, raw_per_photon=1.0) - summary = run_injection(online, registered[True], tmp_path / "out", monkeypatch, settings=s) - src = Path(layout.files[0]) - dst = tmp_path / "out" / "raw" / src.name - assert sha(dst) == sha(src) - meta = src.with_name("inj_DMD1.meta") - assert sha(dst.with_name(meta.name)) == sha(meta) - assert summary["paths"][1]["n_events"] == 0 - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) - assert truth["paths"][1]["events"]["source"].size == 0 - - -BRIGHT = inj.InjectionSettings( - size_classes=(4.0, 8.0), - rate_hz=3.0, - min_interval_s=0.06, - edge_s=0.1, - tau_s=0.012, - raw_per_photon=2.0, - seed=11, - device="cpu", -) -BRIGHT_AT = {1: np.array([[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]])} - - -@pytest.fixture(scope="module") -def injected( - online: OnlineRecording, registered: dict[bool, Path], tmp_path_factory: pytest.TempPathFactory -) -> Injected: - """Bright events injected into both trials (compensated registration). - - Returns - ------- - Injected - The injected copy's folder, its summary and the settings it was made with. - """ - out = tmp_path_factory.mktemp("inj") - with pytest.MonkeyPatch.context() as mp: - summary = run_injection( - online, - registered[True], - out, - mp, - settings=BRIGHT, - positions=BRIGHT_AT, - ) - return out, summary, BRIGHT - - -def test_placed_sources_without_data_are_moved( - online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path -) -> None: - """A source the tool put on a pixel without data where its peaks are calibrated is moved. - - A source that the tool itself puts on a pixel without data in the - stretch its frame peaks are calibrated on is placed anew: at the - minimum distance from the sources that stay and from every place tried - before; the others stay. A position that was given is not moved (an - error, as before), and so is a move with no place left. - """ - first = np.array([[16.0, 20.0], [16.0, 200.0], [12.0, 27.0]]) - asked = [] - # the free candidates of the move, in the order they are drawn: the - # first is 4 px from a source that stays, the second is the place that - # had no data, the third is free - pools = [np.array([[16.0, 24.0], [16.0, 200.0], [18.0, 30.0]])] - - def place( - mean_im: np.ndarray, - n: int, - rng: np.random.Generator, - settings: inj.PlacementSettings | None = None, - valid: np.ndarray | None = None, - exclude_rc: np.ndarray | None = None, - keep_apart_rc: np.ndarray | None = None, - ) -> tuple[np.ndarray, int]: - """Stand-in for place_sources. - - A first placement with a source where no data is, then the - candidates of a move. - - Returns - ------- - positions : np.ndarray - (k, 2) source positions: first on the first call, the free candidates - of the move afterwards. - n_candidates : int - 3 for the first placement, 1 for a move. - """ - asked.append((n, exclude_rc, keep_apart_rc)) - if len(asked) == 1: # the path's placement: one where no data is - return first.copy(), 3 - # a move: the candidates on offer, less those within 6 px of the - # places to keep apart from (place_sources' rule, tested above) - pool = pools[min(len(asked) - 2, len(pools) - 1)] - far = [np.hypot(*(keep_apart_rc - q).T).min() >= 6 for q in pool] - return pool[np.array(far, dtype=bool)][:n], 1 - - out = tmp_path / "moved" - with pytest.MonkeyPatch.context() as mp: - mp.setattr(inj, "place_sources", place) - run_injection(online, registered[True], out, mp, settings=BRIGHT, n_sources=3) - # one move of one source; no external sources to keep away from; apart - # from the sources that stay and from the place that had no data - assert len(asked) == 2 and asked[1][0] == 1 and asked[1][1] is None - assert {tuple(q) for q in asked[1][2]} == {tuple(q) for q in first} - p = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(p["positions_rc"], [[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]]) - assert np.all(p["frame_peak"] > 0) and p["frame_peak"].size == 3 - assert set(p["events"]["source"]) == {0, 1, 2} - # the sources that stayed are calibrated as if the third had been - # where it ended up from the start - with pytest.MonkeyPatch.context() as mp: - run_injection( - online, - registered[True], - tmp_path / "given", - mp, - settings=BRIGHT, - positions={1: np.array(p["positions_rc"])}, - ) - given = inj.read_truth(tmp_path / "given" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_allclose(given["frame_peak"][[0, 2]], p["frame_peak"][[0, 2]], rtol=0.05) - # a position that was given and has no data is an error - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match=r"sources \[1\] have no data"), - ): - run_injection( - online, - registered[True], - tmp_path / "fixed", - mp, - settings=BRIGHT, - positions={1: np.array([[16.0, 20.0], [16.0, 200.0]])}, - ) - # no place left for the move: the only candidates are too near a - # source that stays, or the place that was tried - asked.clear() - pools[:] = [np.array([[16.0, 24.0], [16.0, 200.0], [13.0, 31.0]])] - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match="only 0 free places"), - ): - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "full", - mp, - settings=BRIGHT, - n_sources=3, - ) - # a place tried in an earlier round is not taken again: the first move - # lands without data, and the second is offered the path's first place - # (no longer any source's) before a free one - asked.clear() - pools[:] = [ - np.array([[16.0, 210.0]]), - np.array([[16.0, 200.0], [18.0, 30.0]]), - ] - with pytest.MonkeyPatch.context() as mp: - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "twice", - mp, - settings=BRIGHT, - n_sources=3, - ) - twice = inj.read_truth(tmp_path / "twice" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(twice["positions_rc"][1], [18.0, 30.0]) - assert len(asked) == 3 - # the second move keeps apart from the first place too, though no - # source is there any more - assert (16.0, 200.0) in {tuple(q) for q in asked[2][2]} - assert (16.0, 210.0) in {tuple(q) for q in asked[2][2]} - # moves that land without data every time: after REPLACE_ROUNDS the - # injection gives up - asked.clear() - pools[:] = [ - np.array([[16.0, 210.0 + 10 * k], [16.0, 200.0 + 10 * k]]) - for k in range(inj.REPLACE_ROUNDS) - ] - with ( - pytest.MonkeyPatch.context() as mp, - pytest.raises(ValueError, match="after 5 placements"), - ): - mp.setattr(inj, "place_sources", place) - run_injection( - online, - registered[True], - tmp_path / "again", - mp, - settings=BRIGHT, - n_sources=3, - ) - assert len(asked) == 1 + inj.REPLACE_ROUNDS - - -def test_injection_changes_only_injected_samples( - online: OnlineRecording, injected: Injected -) -> None: - """Only channel-0 raster samples change, never invalid ones. - - The added counts are the recorded ones. - """ - layout, _, _ = online - out, summary, s = injected - src = Path(layout.files[0]) - a = np.fromfile(src, np.int16) - b = np.fromfile(out / "raw" / src.name, np.int16) - changed = np.flatnonzero(a != b) - assert changed.size > 0 - words = changed - HEADER_WORDS - w = words % layout.words_per_cycle - li = layout.slot_line - 1 - ch0 = layout.row_base[li] + layout.slot_pos - assert np.all(np.isin(w, ch0)) - assert np.all(b[changed] > a[changed]) - total = sum(t["added_raw"] for t in summary["paths"][1]["trials"]) - assert int((b.astype(np.int64) - a).sum()) == total - stats = summary["paths"][1]["trials"] - drawn = sum(t["drawn_photons"] for t in stats) - lam = sum(t["expected_photons"] for t in stats) - assert abs(drawn - lam) < 5 * np.sqrt(lam) - assert total == pytest.approx(drawn * s.raw_per_photon, rel=1e-3) - - -def test_truth_file_describes_the_injection(online: OnlineRecording, injected: Injected) -> None: - """The truth has positions per trial, events and traces at frame lines.""" - _layout, _, _ = online - out, summary, _s = injected - truth = inj.read_truth(out / inj.TRUTH_NAME) - assert truth["seed"] == 11 - assert truth["settings"]["size_classes"] == [4.0, 8.0] - p = truth["paths"][1] - assert p["raw_per_photon"] == 2.0 - np.testing.assert_array_equal(p["trials"], [1, 2]) - np.testing.assert_allclose(p["trial_shift_rc"][0], 0.0) - ev = p["events"] - assert ev["source"].size == summary["paths"][1]["n_events"] > 0 - for t, (lo, hi) in ((1, (1, 4800)), (2, (4801, 9700))): - on = ev["onset_line"][ev["trial"] == t] - assert on.min() >= lo + 0.1 * 1600 and on.max() <= hi - 0.1 * 1600 - d = p["trials_detail"][t] - np.testing.assert_allclose( - d["positions_rc"], p["positions_rc"] + p["trial_shift_rc"][t - 1] - ) - fl = d["frame_lines"] - assert fl[0] == lo and np.all(np.diff(fl) == 8) - # the trace peaks at each event's size within one frame of onset - k = np.searchsorted(fl, on[0]) - j = ev["source"][ev["trial"] == t][0] - size = ev["size"][ev["trial"] == t][0] - assert d["trace"][j, k] <= size * 1.0001 + d["trace"][j].max() - assert d["trace"].shape == (3, fl.size) - assert p["footprint"]["patch"].shape[0] == 3 - with h5py.File(out / "trial_table.h5") as f: - assert "motion_correction" not in f - tt = inj.load_struct_h5(out / "trial_table.h5") - assert Path(tt["datadr"]) == out / "raw" - assert np.asarray(tt["slap2_info"]["last_line"]).ravel().tolist() == [ - 4800.0, - 9700.0, - ] - - -def test_injected_signal_is_still_and_as_expected( - online: OnlineRecording, registered: dict[bool, Path], injected: Injected -) -> None: - """In frames registered with the original's motion, the copy matches the expected counts. - - In registered frames made with the original's motion, the copy minus the - original matches the expected counts within Poisson noise, and a static - source's centroid stays put (drift < 0.1 px) across the online offsets' - switches. - """ - layout, _, _ = online - out, _, s = injected - table = Path(registered[True]) - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") - copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - orig = read_raster_samples(layout, (0, layout.num_cycles))[0] - new = read_raster_samples(copy, (0, layout.num_cycles))[0] - diff = np.where(orig == INVALID_SAMPLE, INVALID_SAMPLE, new - orig) - lines = (1, 4800) - geo = inj.trial_geometry(layout, al, lines) - pos = truth["trials_detail"][1]["positions_rc"] - fp = [inj.GaussianFootprint(1.33)] * 3 - ev = truth["events"] - sel = ev["trial"] == 1 - events = inj.Events( - ev["source"][sel], - ev["trial"][sel], - ev["onset_line"][sel], - ev["size_class"][sel], - ev["size"][sel] / truth["frame_peak"][ev["source"][sel]], - ) - tr = inj.event_traces(events, 3, lines, layout.line_period_s, s) - expect = inj.SampleModel(layout, geo, pos, fp, tr, 25.0) - static = inj.SampleModel(layout, geo, pos, fp, np.ones_like(tr), 25.0) - n_c = layout.num_cycles # the frame kernels reach past the trial - samples = np.zeros((3, layout.slot_line.size, n_c), np.float32) - samples[0] = diff[:, :n_c] - samples[1][expect.slots] = expect.expected(np.arange(n_c)).T - samples[2][static.slots] = static.expected(np.arange(n_c)).T - samples[:, orig[:, :n_c] == INVALID_SAMPLE] = INVALID_SAMPLE - times = al.ds_frames.astype(np.int64) - # frames whose kernel (60 lines) stays inside the trial - times = times[(times > lines[0] + 60) & (times < lines[1] - 60)] - acc_d = acc_e = 0.0 - drift = {j: [] for j in range(3)} - for idx, frames, _ in iter_registered_frames(layout, samples, 0, al, times, 20, chunk=50): - f = frames.numpy() - for j, (r, c) in enumerate(pos): - ri, ci = int(round(r)), int(round(c)) - win = f[:, :, ri - 3 : ri + 4, ci - 3 : ci + 4] - acc_d = acc_d + np.nansum(win[0]) - acc_e = acc_e + np.nansum(win[1]) - whole = ~np.isnan(win[2]).any((1, 2)) # not cut by an edge - st = win[2][whole] - rr, cc = np.mgrid[-3:4, -3:4] - m = st.sum((1, 2)) - cr = (st * rr).sum((1, 2)) / m + ri - r - cc_ = (st * cc).sum((1, 2)) / m + ci - c - drift[j].append(np.stack([cr, cc_], 1)) - for j in range(3): - d = np.concatenate(drift[j]) - assert d.shape[0] > 0.9 * times.size - assert np.abs(d - np.median(d, axis=0)).max() < 0.1 - assert np.abs(np.median(d, axis=0)).max() < 0.1 - # the summed signal at the sources: Poisson error of photons x g - se = np.sqrt(acc_e * s.raw_per_photon) * 3 - assert abs(acc_d - acc_e) < 5 * se - - -def test_registered_copy_keeps_the_motion( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Registering the injected copy gives the original's motion up to the grid's anchoring. - - The truth then records both. - """ - layout, _, _ = online - out = tmp_path / "inj" - run_injection( - online, - registered[True], - out, - monkeypatch, - settings=replace(BRIGHT, size_classes=(1.0, 2.0)), - positions=BRIGHT_AT, - ) - copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) - monkeypatch.setattr(multiroi, "raster_layout", lambda path: copy) - register_multiroi( - out / "trial_table.h5", - {"maxshift": 6, "compensate_online": True}, - execution={"device": "cpu", "max_workers": 1}, - ) - assert inj.main(["compare", str(out)]) == 0 - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - for t in (1, 2): - d = truth["trials_detail"][t] - assert d["copy_motion_rms_px"] < 0.05 - np.testing.assert_allclose(d["positions_copy_rc"], d["positions_rc"] + d["copy_shift_rc"]) - a = inj.read_alignment(d["alignment"]) - b = inj.read_alignment(d["copy_alignment"]) - off = inj.registration_offset(a, b) - np.testing.assert_allclose(off["shift_rc"], d["copy_shift_rc"]) - - -def test_saturation_invalid_samples_and_chunking(online: OnlineRecording, tmp_path: Path) -> None: - """Huge events saturate at 32767; invalid samples stay. - - Results do not depend on the chunk size. - """ - layout, offs, truth = online - src = Path(layout.files[0]) - data = np.fromfile(src, np.int16) - rng = np.random.default_rng(2) - li = layout.slot_line - 1 - ch0 = layout.row_base[li] + layout.slot_pos - rows = HEADER_WORDS + np.arange(N_CYCLES)[:, None] * layout.words_per_cycle - w = (rows + ch0[None, :]).ravel() - bad = w[rng.random(w.size) < 0.05] - data[bad] = INVALID_SAMPLE - outs = [] - lines = (1, layout.total_lines) - geo = truth_geometry(layout, offs, truth, lines) - tr = np.full((1, lines[1]), 2000.0) - for chunk in (7, 64): - dst = tmp_path / f"c{chunk}.dat" - data.tofile(dst) - lay = replace(layout, files=(str(dst),)) - model = inj.SampleModel(lay, geo, np.array([[18.0, 25.0]]), [inj.GaussianFootprint()], tr) - st = inj.inject_samples(lay, model, 3.0, 0, (5, 1, 1), chunk) - outs.append(np.fromfile(dst, np.int16)) - assert st.saturated > 0 and st.lost_raw > 0 - assert st.expected_photons_invalid > 0 - np.testing.assert_array_equal(outs[0], outs[1]) - assert np.all(outs[0][bad] == INVALID_SAMPLE) - assert outs[0].max() == inj.SAMPLE_MAX - - -def test_command_line( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """``python -m giant_python.simulation.injection`` runs a session.""" - layout, _, _ = online - monkeypatch.setattr(inj, "raster_layout", lambda path: layout) - pos = tmp_path / "pos.h5" - with h5py.File(pos, "w") as f: - f["path1"] = np.array([[16.0, 20.0]]) - code = inj.main([ - "inject", - str(registered[False]), - str(tmp_path / "cli"), - "--paths", - "1", - "--trials", - "2", - "--positions", - str(pos), - "--raw-per-photon", - "4", - "--sizes", - "8", - "--seed", - "3", - "--size-reference", - "tissue", - "--no-frame-traces", - ]) - assert code == 0 - summary = json.loads(capsys.readouterr().out) - assert summary["paths"]["1"]["n_sources"] == 1 - truth = inj.read_truth(tmp_path / "cli" / inj.TRUTH_NAME) - np.testing.assert_array_equal(truth["paths"][1]["trials"], [2]) - p = truth["paths"][1] - assert not p["trials_detail"][2]["compensated"] - np.testing.assert_array_equal(p["frame_peak"], [1.0]) - assert "trace_frames" not in p["trials_detail"][2] - - -def test_cuda_render_matches_cpu(online: OnlineRecording, registered: dict[bool, Path]) -> None: - """Rendering on CUDA equals the CPU.""" - if not torch.cuda.is_available(): - pytest.skip("no CUDA device") - layout, _, _ = online - table = Path(registered[True]) - al = inj.read_alignment(table.parent / "motion_correction" / "E1T2DMD1_ALIGNMENTDATA.h5") - s = read_raster_samples(layout, (0, layout.num_cycles))[:1] - times = al.ds_frames[:40].astype(np.int64) - cpu = next(iter_registered_frames(layout, s, 0, al, times, 20))[1] - gpu = next(iter_registered_frames(layout, s, 0, al, times, 20, "cuda"))[1] - np.testing.assert_allclose(gpu.cpu().numpy(), cpu.numpy(), rtol=1e-5, atol=1e-4, equal_nan=True) - - -def test_ragged_table_keeps_copy_columns( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A trial without a recording is skipped. - - The others keep their column of the copy's trial table. - """ - from giant_python.io.hdf5 import load_struct_h5 - - table = load_struct_h5(registered[False]) - table["filename"] = np.array([["", table["filename"][0, 1]]], object) - ragged = tmp_path / "trial_table.h5" - save_struct_h5(ragged, table) - s = inj.InjectionSettings(raw_per_photon=4.0, seed=1) - run_injection( - online, - ragged, - tmp_path / "out", - monkeypatch, - settings=s, - positions={1: np.array([[16.0, 20.0]])}, - moco_dir=Path(registered[False]).parent / "motion_correction", - ) - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME)["paths"][1] - assert list(truth["trials_detail"]) == [2] - assert truth["trials_detail"][2]["copy_trial"] == 2 - np.testing.assert_array_equal(np.unique(truth["events"]["trial"]), [2]) - - -def test_sizes_are_peaks_in_frames(online: OnlineRecording, injected: Injected) -> None: - """With sizes in frame units, an isolated event's noiseless peak is its size. - - The peak is taken in the 200 Hz frames at its source's peak pixel, and - equals the size on average. - """ - out, _, s = injected - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - fp = truth["frame_peak"] - assert np.all((fp > 0.2) & (fp < 1.0)) - ev = truth["events"] - reach = 24 # max(3 * 8, P) lines at 1600 Hz and 200 Hz frames - tail = 6 * s.tau_s * 1600 - ratios = [] - for t in (1, 2): - d = truth["trials_detail"][t] - fl, tf = d["frame_lines"], d["trace_frames"] - assert tf.shape == d["trace"].shape - # the ideal trace is sampled at frame lines: within a frame of each - # largest peak (overlapping events may add up) - top = np.array([ - ev["size"][(ev["trial"] == t) & (ev["source"] == j)].max() for j in range(3) - ]) - assert np.all(d["trace"].max(1) >= top * np.exp(-0.005 / s.tau_s)) - for j in range(3): - on = ev["onset_line"][(ev["trial"] == t) & (ev["source"] == j)] - size = ev["size"][(ev["trial"] == t) & (ev["source"] == j)] - for k, (t0, a) in enumerate(zip(on, size)): - alone = (k == 0 or t0 - on[k - 1] > 2 * tail) and ( - k == on.size - 1 or on[k + 1] - t0 > tail + reach - ) - sel = (fl >= t0 - reach) & (fl <= t0 + tail) - if alone and sel.any(): - ratios.append(np.nanmax(tf[j, sel]) / a) - assert len(ratios) > 20 - assert np.mean(ratios) == pytest.approx(1.0, abs=0.06) - - -def test_refuses_to_write_into_the_original( - online: OnlineRecording, registered: dict[bool, Path], monkeypatch: pytest.MonkeyPatch -) -> None: - """The copy's folder cannot be the original's data folder.""" - layout, _, _ = online - src = Path(layout.files[0]) - out = src.parent.parent / "same" - with pytest.raises(ValueError, match="original's data folder"): - run_injection( - online, - registered[True], - out, - monkeypatch, - data_dir=out / "raw", - ) - - -def test_registration_offset_includes_the_grid(registered: dict[bool, Path]) -> None: - """Different padding, window and reference offset move the copy's positions. - - Mixed compensation is refused. - """ - from dataclasses import replace as dc_replace - - moco = Path(registered[True]).parent / "motion_correction" - a = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - comp = dict(a.compensation, refOffset=a.compensation["refOffset"] + 1) - b = dc_replace( - a, - margin=a.margin + 3, - trim_r0=a.trim_r0 + 1, - motion_r=a.motion_r + 0.25, - compensation=comp, - ) - off = inj.registration_offset(a, b) - # continuous motion unchanged in columns; rows: +0.25 recorded, -1 from - # the reference (mapping swaps x and y) - np.testing.assert_allclose(off["motion_offset_rc"], [0.25 - 1, -1.0]) - np.testing.assert_allclose(off["shift_rc"], [3 - 1 - 1 - (0.25 - 1), 3 - 1 + 1]) - assert off["rms_px"] < 1e-9 - plain = inj.read_alignment( - Path(registered[False]).parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5" - ) - with pytest.raises(ValueError, match="online motion correction"): - inj.registration_offset(a, plain) - - -def test_frame_motion_uses_each_frames_own_reference(registered: dict[bool, Path]) -> None: - """A frame with another reference offset is moved by its own reference. - - The frame is at a registered frame's time but with another reference - offset, and is moved by its own reference, not the recorded motion. - """ - from giant_python.simulation.render import frame_motion - - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - t = al.ds_frames.astype(np.int64) - c = al.compensation - refs = np.stack([c["frameRefX"], c["frameRefY"]], 1) - ok = np.isfinite(al.motion_r) - same = frame_motion(al, t, refs) - np.testing.assert_allclose(same[ok, 0], al.motion_r[ok], atol=1e-9) - np.testing.assert_allclose(same[ok, 1], al.motion_c[ok], atol=1e-9) - other = frame_motion(al, t, refs + np.array([1, 0])) # x one more - np.testing.assert_allclose(other[ok, 1], al.motion_c[ok] - 1, atol=1e-9) - np.testing.assert_allclose(other[ok, 0], al.motion_r[ok], atol=1e-9) - - -def test_calibration_keeps_overlapping_sources_apart( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """Overlapping sources are calibrated in turns. - - A close neighbour does not change a source's frame peak. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = inj.GaussianFootprint(1.33) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.5) - pair = np.array([[16.0, 20.0], [16.0, 22.0], [10.0, 33.0]]) - np.testing.assert_array_equal(inj.overlap_classes(pair, [fp] * 3), [0, 1, 0]) - both = inj.calibrate_frame_peaks( - layout, - al, - geo, - pair, - (0.0, 0.0), - [fp] * 3, - s, - np.random.default_rng(0), - ) - alone = inj.calibrate_frame_peaks( - layout, - al, - geo, - pair[:1], - (0.0, 0.0), - [fp], - s, - np.random.default_rng(0), - ) - assert both[0] == pytest.approx(alone[0], rel=0.05) - - -def test_inputs_that_would_corrupt_a_dataset_are_refused( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Repeated trials or paths and an existing dataset are refused before writing. - - Repeated trials or paths, and an output folder that already holds a - dataset, are refused before anything is written. - """ - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - pos = {1: np.array([[16.0, 20.0]])} - with pytest.raises(ValueError, match="must not repeat"): - run_injection( - online, - registered[False], - tmp_path / "a", - monkeypatch, - settings=s, - positions=pos, - trials=[1, 1], - ) - with pytest.raises(ValueError, match="must not repeat"): - inj.inject_session( - registered[False], - tmp_path / "b", - paths=(1, 1), - settings=s, - positions=pos, - ) - assert not (tmp_path / "a").exists() and not (tmp_path / "b").exists() - out = tmp_path / "c" - (out / "motion_correction").mkdir(parents=True) - with pytest.raises(ValueError, match="already holds motion_correction"): - run_injection( - online, - registered[False], - out, - monkeypatch, - settings=s, - positions=pos, - ) - - -def test_copy_table_paths_and_absolute_folders( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The copy's table has absolute folders and no files for paths not copied.""" - from giant_python.io.hdf5 import load_struct_h5 - - table = { - "datadr": "x", - "savedr": "y", - "filename": np.array([["a1", "b1"], ["a2", "b2"]], dtype=object), - "epoch": np.ones((2, 2)), - "slap2_info": {"first_line": np.ones((2, 2))}, - "motion_correction": {"fn_adata": "z"}, - } - monkeypatch.chdir(tmp_path) - Path("rel").mkdir() - p = inj.write_copy_table(table, np.array([1]), Path("rel/raw"), Path("rel"), paths=[1]) - t = load_struct_h5(p) - assert Path(t["datadr"]).is_absolute() and Path(t["savedr"]).is_absolute() - assert Path(t["savedr"]) == tmp_path / "rel" - np.testing.assert_array_equal(np.asarray(t["filename"], dtype=object).ravel(), ["b1", ""]) - assert "motion_correction" not in t - - -def test_image_footprint_peak_and_calibration( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """An off-centre image footprint is calibrated at its maximum.""" - layout, _, _ = online - img = np.zeros((5, 5)) - img[2, 4] = 1.0 - fp = inj.ImageFootprint(img) - assert fp.peak_offset == (0.0, 2.0) - pos = np.array([[16.0, 20.0]]) - np.testing.assert_array_equal(inj.peak_pixels(pos, [fp]), [[16, 22]]) - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) - peak = inj.calibrate_frame_peaks( - layout, al, geo, pos, (0.0, 0.0), [fp], s, np.random.default_rng(0) - ) - assert 0.05 < peak[0] < 1.0 - - -def test_expected_frames_follow_the_trial_grid( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """A path-frame pixel outside the trial grid's size is still rendered. - - It is rendered where its trial position has data; channel 1 renders - with channel 0's freshness. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = [inj.GaussianFootprint(1.33)] - model = inj.SampleModel(layout, geo, np.array([[16.3, 20.4]]), fp, np.ones((1, 4800))) - fl = np.arange(200, 1200, 8) - here = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0) - far = inj.expected_frames(layout, al, model, fl, [[16 - 40, 20 + 60]], (40.3, -59.6), 200.0) - assert al.shape[1] < 80 and np.isfinite(far).all() - np.testing.assert_allclose(far, here, rtol=1e-6) - ch1 = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0, channel=1) - np.testing.assert_allclose(ch1, here, rtol=1e-6) # no invalid samples - - -def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected: Injected) -> None: - """Two trials of one file: frames reading the other trial's injections are NaN. - - Frames whose kernel reads the other trial's injected samples are NaN in - the truth's frame traces. - """ - out, _, _ = injected - truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] - reach = 24 - t1, t2 = truth["trials_detail"][1], truth["trials_detail"][2] - near1 = t1["frame_lines"] + reach >= 4801 - near2 = t2["frame_lines"] - reach <= 4800 - assert near1.any() and near2.any() - assert np.isnan(t1["trace_frames"][:, near1]).all() - assert np.isnan(t2["trace_frames"][:, near2]).all() - assert np.isfinite(t1["trace_frames"][:, ~near1]).mean() > 0.9 - - -def test_relative_registration_folder_is_stored_absolute( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A relative registration folder is recorded as an absolute path.""" - import os - - reg = Path(registered[False]).parent - monkeypatch.chdir(reg) - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - run_injection( - online, - registered[False], - tmp_path / "out", - monkeypatch, - settings=s, - positions={1: np.array([[16.0, 20.0]])}, - trials=[1], - moco_dir="motion_correction", - ) - truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) - al = Path(str(truth["paths"][1]["trials_detail"][1]["alignment"])) - assert al.is_absolute() and al.exists() - assert os.path.isabs(truth["origin"]["moco_dir"]) - - -def test_more_inputs_are_checked( - online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path -) -> None: - """Non-finite gains are refused; sources without data cannot be calibrated. - - Copies' filenames are their basenames; larger trial grids keep their - data when shifted into the path frame. - """ - from giant_python.io.hdf5 import load_struct_h5 - - for bad in (float("inf"), float("nan")): - with pytest.raises(ValueError, match="finite"): - inj.InjectionSettings(raw_per_photon=bad) - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - fp = inj.GaussianFootprint(1.33) - s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) - with pytest.raises(ValueError, match=r"sources \[1\] have no data"): - inj.calibrate_frame_peaks( - layout, - al, - geo, - np.array([[16.0, 20.0], [16.0, 200.0]]), - (0.0, 0.0), - [fp, fp], - s, - np.random.default_rng(0), - ) - table = { - "filename": np.array([["sub/a_DMD1.dat"], [""]], dtype=object), - "slap2_info": {"first_line": np.ones((2, 1))}, - } - p = inj.write_copy_table(table, np.array([0]), tmp_path, tmp_path) - names = np.asarray(load_struct_h5(p)["filename"], dtype=object).ravel() - np.testing.assert_array_equal(names, ["a_DMD1.dat", ""]) - big = np.arange(10 * 112, dtype=float).reshape(10, 112) - out = inj.shift_image(big, (0.0, 8.0), (10, 100)) - np.testing.assert_allclose(out, big[:, 8:108]) - - -def test_bad_chunks_and_name_collisions_are_refused( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A nonpositive chunk size and copies sharing a name are refused before writing. - - A nonpositive chunk size, and two recordings that would be copied under - one name, are refused before anything is written. - """ - import shutil - - from giant_python.io.hdf5 import load_struct_h5 - - layout, _, _ = online - s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") - with pytest.raises(ValueError, match="chunk_cycles"): - run_injection( - online, - registered[False], - tmp_path / "c", - monkeypatch, - settings=s, - chunk_cycles=0, - ) - assert not (tmp_path / "c").exists() - data = tmp_path / "data" - src = Path(layout.files[0]) - for sub in ("a", "b"): - (data / sub).mkdir(parents=True) - shutil.copyfile(src, data / sub / src.name) - table = load_struct_h5(registered[False]) - table["filename"] = np.array([[f"a/{src.name}", f"b/{src.name}"]], dtype=object) - twins = tmp_path / "twins.h5" - save_struct_h5(twins, table) - monkeypatch.setattr(inj, "raster_layout", lambda path: replace(layout, files=(str(path),))) - with pytest.raises(ValueError, match="would both be copied"): - inj.inject_session(twins, tmp_path / "t", paths=(1,), settings=s, data_dir=data) - assert not (tmp_path / "t").exists() - - -def test_neighbours_share_recording_files() -> None: - """Trials are neighbours when their recordings share a file. - - This holds whatever file each trial names. - """ - ctx = { - "names": ["c0.dat", "c1.dat", "other.dat"], - "files": { - 0: ("c0.dat", "c1.dat"), - 1: ("c0.dat", "c1.dat"), - 2: ("other.dat",), - }, - "first": [1.0, 101.0, 1.0], - "last": [100.0, 200.0, 50.0], - } - near = inj._neighbours(ctx, [0, 1, 2]) - assert near(0) == [(101.0, 200.0)] - assert near(1) == [(1.0, 100.0)] - assert near(2) == [] - - -def test_no_events_need_no_calibration( - online: OnlineRecording, - registered: dict[bool, Path], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Without events nothing is calibrated, and the copy stays identical. - - This holds even in a trial too short to calibrate. - """ - layout, _, _ = online - s = inj.InjectionSettings(rate_hz=0.0, edge_s=1.6, raw_per_photon=1.0) - run_injection(online, registered[True], tmp_path / "o", monkeypatch, settings=s) - src = Path(layout.files[0]) - assert sha(tmp_path / "o" / "raw" / src.name) == sha(src) - truth = inj.read_truth(tmp_path / "o" / inj.TRUTH_NAME)["paths"][1] - np.testing.assert_array_equal(truth["frame_peak"], 1.0) - - -def test_silo_frames_leave_out_the_kernels_edge( - online: OnlineRecording, registered: dict[bool, Path] -) -> None: - """Frame traces and calibration use SILo's extraction frames. - - These leave out the samples exactly at the kernel's reach. - """ - layout, _, _ = online - moco = Path(registered[True]).parent / "motion_correction" - al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") - geo = inj.trial_geometry(layout, al, (1, 4800)) - model = inj.SampleModel( - layout, - geo, - np.array([[16.0, 20.0]]), - [inj.GaussianFootprint()], - np.ones((1, 4800)), - ) - fl = np.arange(300, 900, 8) - got = inj.expected_frames(layout, al, model, fl, [[16, 21]], (0, 0), 200) - n_c = layout.num_cycles - smp = np.zeros((1, layout.slot_line.size, n_c), np.float32) - smp[0][model.slots] = model.expected(np.arange(n_c)).T - want = {} - for exclusive in (True, False): - out = [] - for _, f, _ in iter_registered_frames( - layout, smp, 0, al, fl, 8, chunk=200, exclusive=exclusive - ): - out.append(f[0][:, 16, 21].numpy()) - want[exclusive] = np.concatenate(out) - np.testing.assert_allclose(got[0], want[True], rtol=1e-6) - assert np.max(np.abs(want[True] - want[False])) > 1e-6 +"""Event injection into raw SLAP2 samples, on small synthetic recordings.""" + +import hashlib +import json +from collections.abc import Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import pytest +import torch + +from giant_python.io.hdf5 import save_struct_h5 +from giant_python.io.slap2_raster import ( + INVALID_SAMPLE, + RasterLayout, + read_raster_samples, +) +from giant_python.pipeline.register import register_multiroi +from giant_python.registration import multiroi +from giant_python.simulation import injection as inj +from giant_python.simulation.render import iter_registered_frames + +from ..registration.synthetic import ( + HEADER_WORDS, + make_layout, + online_offsets, + write_recording, +) + +N_CYCLES = 1400 + +# online offsets (x, y_header, y_dmd) per line, as online_offsets returns them +Offsets = tuple[np.ndarray, np.ndarray, np.ndarray] +# the layout, its online offsets and the true motion of the synthetic recording +OnlineRecording = tuple[RasterLayout, Offsets, np.ndarray] +# the injected copy's folder, its summary and the settings it was made with +Injected = tuple[Path, dict, inj.InjectionSettings] + + +def sha(path: str | Path) -> str: + """SHA-256 of a file. + + Returns + ------- + str + The hexadecimal SHA-256 digest of the file's bytes. + """ + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +# --------------------------------------------------------- pure functions + + +def test_time_course_peaks_at_one() -> None: + """Instant rise: exp decay from 1; short rise: peak 1 at its delay.""" + t = np.array([-0.01, 0.0, 0.024, 0.048]) + np.testing.assert_allclose(inj.time_course(t, 0.024), [0, 1, np.exp(-1), np.exp(-2)]) + tp = inj.peak_delay_s(0.024, 0.003) + assert 0 < tp < 0.024 + grid = np.linspace(0, 0.1, 100001) + k = inj.time_course(grid, 0.024, 0.003) + assert k.max() == pytest.approx(1.0, abs=1e-8) + assert grid[np.argmax(k)] == pytest.approx(tp, abs=2e-6) + assert inj.time_course(-1e-9, 0.024, 0.003) == 0 + + +def test_event_traces_sum_events() -> None: + """Traces are sums of size x time course at the line times.""" + s = inj.InjectionSettings(tau_s=0.01) + ev = inj.Events( + np.array([0, 0, 1]), + np.array([1, 1, 1]), + np.array([10.5, 30.0, 12.0]), + np.array([0, 1, 2]), + np.array([2.0, 3.0, 1.0]), + ) + tr = inj.event_traces(ev, 2, (5, 60), 0.001, s) + lines = np.arange(5, 61) + want0 = 2 * inj.time_course((lines - 10.5) * 1e-3, 0.01) + 3 * ( + inj.time_course((lines - 30.0) * 1e-3, 0.01) + ) + np.testing.assert_allclose(tr[0], want0, atol=1e-12) + assert tr[1, 12 - 5] == pytest.approx(1.0) + assert np.all(tr[1, : 12 - 5] == 0) + + +def test_draw_events_respect_edges_dead_time_and_classes() -> None: + """Onsets stay inside the edges, apart by the dead time; classes mix.""" + s = inj.InjectionSettings(rate_hz=4.0, min_interval_s=0.1, edge_s=0.5) + period = 1e-4 + ev = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) + assert np.all(ev.trial == 3) + assert ev.onset_line.min() >= 1 + 0.5 / period + assert ev.onset_line.max() <= 100001 - 0.5 / period + for j in range(200): + t = ev.onset_line[ev.source == j] + assert np.all(np.diff(t) >= 0.1 / period - 1e-6) + dur = 10.0 - 1.0 + rate = len(ev) / 200 / dur + assert rate == pytest.approx(1 / (0.1 + 1 / 4.0), rel=0.05) + counts = np.bincount(ev.size_class, minlength=6) + assert counts.min() > 0.8 * counts.mean() + np.testing.assert_array_equal(ev.size, np.asarray(s.size_classes)[ev.size_class]) + again = inj.draw_events(200, 1.0, 100001.0, period, s, np.random.default_rng(1), trial=3) + np.testing.assert_array_equal(again.onset_line, ev.onset_line) + none = inj.draw_events(5, 1.0, 100001.0, period, replace(s, rate_hz=0.0), None) + assert len(none) == 0 + + +def _draw_events_before_sync( + n_sources: int, + first: float, + last: float, + period: float, + s: inj.InjectionSettings, + rng: np.random.Generator, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Draw the events as they were drawn before sync_share existed. + + This is the loop of draw_events at GIAnT-Python a673714, kept here as + the reference: source, onset line and size class of every event. + + Returns + ------- + source : np.ndarray + Source index of every event. + onset_line : np.ndarray + Onset line of every event. + size_class : np.ndarray + Size class of every event. + """ + edge = s.edge_s / period + lo, hi = float(first) + edge, float(last) - edge + mean_gap = 1.0 / s.rate_hz / period + dead = s.min_interval_s / period + n_draw = int((hi - lo) / (mean_gap + dead) * 1.5) + 20 + src, onset, classes = [], [], [] + for j in range(n_sources): + while True: + gaps = rng.exponential(mean_gap, n_draw) + dead + gaps[0] -= dead + t = lo + np.cumsum(gaps) + if t[-1] > hi: + break + n_draw *= 2 + t = t[t <= hi] + cls = rng.choice(len(s.size_classes), t.size, p=s.weights) + src.append(np.full(t.size, j)) + onset.append(t) + classes.append(cls) + return np.concatenate(src), np.concatenate(onset), np.concatenate(classes) + + +def test_draw_events_with_common_onsets() -> None: + """sync_share gives every source the onsets of one common train beside its own. + + The common ones are in every source, the dead time holds, the rate is + about kept, and a share of 0 changes no draw. + """ + period = 1e-4 + s = inj.InjectionSettings(rate_hz=2.0, min_interval_s=0.1, edge_s=0.5) + args = (60, 1.0, 600001.0, period) # a minute + plain = inj.draw_events(*args, s, np.random.default_rng(3)) + # a share of 0 draws what the tool drew before the option existed: + # the same generator calls in the same order (the default setting, a + # high rate without dead time, weighted size classes) + for setting, n_src, seed in ( + (s, 60, 3), + (replace(s, rate_hz=40.0, min_interval_s=0.0), 7, 11), + (replace(s, class_weights=(1, 1, 1, 1, 1, 5)), 12, 5), + ): + got = inj.draw_events(n_src, *args[1:], setting, np.random.default_rng(seed)) + src, onset, cls = _draw_events_before_sync( + n_src, *args[1:], setting, np.random.default_rng(seed) + ) + np.testing.assert_array_equal(got.source, src) + np.testing.assert_array_equal(got.onset_line, onset) + np.testing.assert_array_equal(got.size_class, cls) + assert len(got) > 100 + rate0 = len(plain) / 60 / 59.0 + + def common_onsets(ev: inj.Events, n: int) -> np.ndarray: + """Onsets that every one of the n sources has. + + Returns + ------- + np.ndarray + The onset lines present in all n sources. + """ + t, counts = np.unique(ev.onset_line, return_counts=True) + return t[counts == n] + + assert common_onsets(plain, 60).size == 0 + for share in (0.5, 1.0): + ev = inj.draw_events(*args, replace(s, sync_share=share), np.random.default_rng(3)) + both = common_onsets(ev, 60) + assert both.size > 20 + for j in range(60): + t = ev.onset_line[ev.source == j] + assert np.all(np.diff(t) >= 0.1 / period - 1e-6) + in_common = np.isin(t, both).mean() + if share == 1.0: + assert in_common == 1.0 + else: + assert 0.35 < in_common < 0.7 + rate = len(ev) / 60 / 59.0 + assert rate == pytest.approx(rate0, rel=0.12) + if share == 1.0: # one train, sixty times, with sizes of their own + assert len(ev) == 60 * both.size + first = ev.size_class[ev.source == 0] + second = ev.size_class[ev.source == 1] + assert np.any(first != second) + # an own onset never falls within the dead time of a common one + ev = inj.draw_events(*args, replace(s, sync_share=0.5), np.random.default_rng(3)) + both = common_onsets(ev, 60) + own = ev.onset_line[~np.isin(ev.onset_line, both)] + k = np.searchsorted(both, own) + gap = np.minimum( + np.abs(both[np.minimum(k, both.size - 1)] - own), + np.abs(own - both[np.maximum(k - 1, 0)]), + ) + assert gap.min() >= 0.1 / period - 1e-6 + + +def test_settings_reject_bad_values() -> None: + """Invalid settings raise.""" + with pytest.raises(ValueError): + inj.InjectionSettings(rise_s=0.03) + with pytest.raises(ValueError): + inj.InjectionSettings(sync_share=1.5) + with pytest.raises(ValueError): + inj.InjectionSettings(class_weights=(1.0, 2.0)) + with pytest.raises(ValueError): + inj.InjectionSettings(rate_hz=-1) + + +def test_footprints() -> None: + """Gaussian peak 1 and cut at its radius; image footprints interpolate.""" + g = inj.GaussianFootprint(1.33, 4.0) + assert g(0.0, 0.0) == 1.0 + assert g(1.33, 0.0) == pytest.approx(np.exp(-0.5)) + assert g(5.4, 0.0) == 0.0 and g.radius == pytest.approx(5.32) + img = np.zeros((5, 5)) + img[2, 2], img[2, 3] = 4.0, 2.0 + f = inj.ImageFootprint(img) + assert f(0.0, 0.0) == 1.0 + assert f(0.0, 0.5) == pytest.approx(0.75) + assert f(0.0, 9.0) == 0.0 + patch, origin = inj.footprint_patch(g, (10.0, 20.4), 3) + assert origin == [7, 17] and patch.shape == (7, 7) + assert patch[3, 3] == pytest.approx(np.exp(-0.5 * (0.4 / 1.33) ** 2)) + + +def test_place_sources_follow_the_rules() -> None: + """Sources sit on labeled pixels, away from edges, others and each other.""" + rng = np.random.default_rng(0) + img = np.full((60, 80), 1.0) + img[20:24, 5:75] = 10.0 # a horizontal "dendrite" + img[30:50, 40:44] = 10.0 # a vertical one + img[:, :3] = np.nan + exclude = np.array([[22.0, 40.0]]) + s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) + pos, n_cand = inj.place_sources(img, 100, rng, s, exclude_rc=exclude) + assert 0 < pos.shape[0] < 100 and n_cand > pos.shape[0] + lab = inj.labeled_pixels(img) + r, c = pos.T.astype(int) + assert lab[r, c].all() + assert c.min() >= 3 + 5 - 1 # distance from the NaN columns + d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) + assert d[np.triu_indices(len(pos), 1)].min() >= 6 + assert np.hypot(*(pos - exclude).T).min() >= 8 + + +def test_place_sources_keep_apart_from_placed_ones() -> None: + """Candidates near sources placed already are dropped before any is chosen. + + Candidates within the minimum distance of sources placed already are + dropped first: one that is too near cannot stand in the way of a free + one behind it. + """ + img = np.full((40, 60), 1.0) + img[19:22, 20:41] = 10.0 # a short "dendrite" + s = inj.PlacementSettings(min_separation_px=6, edge_px=5, exclude_px=8) + placed = np.array([[20.0, 24.0]]) + for seed in range(8): + pos, n_cand = inj.place_sources( + img, 10, np.random.default_rng(seed), s, keep_apart_rc=placed + ) + _, n_free = inj.place_sources(img, 10, np.random.default_rng(seed), s) + # fewer candidates, and none of the chosen within 6 px of the + # placed source or of each other + assert 0 < n_cand < n_free and pos.shape[0] >= 1 + assert np.hypot(*(pos - placed).T).min() >= 6 + d = np.hypot(*(pos[:, None, :] - pos[None, :, :]).transpose(2, 0, 1)) + assert len(pos) < 2 or d[np.triu_indices(len(pos), 1)].min() >= 6 + # with one place wanted and only the pixels 4 and 8 px from the placed + # source as candidates, the far one is found whatever the order + two = np.full((40, 60), np.nan) + two[10:31, 10:51] = 1.0 + two[19:22, 27:30] = 10.0 + two[19:22, 31:34] = 10.0 + for seed in range(8): + pos, _ = inj.place_sources( + two, + 1, + np.random.default_rng(seed), + replace(s, edge_px=0), + keep_apart_rc=placed, + ) + assert pos.shape[0] == 1 + assert np.hypot(*(pos[0] - placed[0])) >= 6 + + +def test_align_images_recovers_subpixel_shift() -> None: + """A smooth random image moved by a known shift is found again.""" + from scipy.ndimage import gaussian_filter + + rng = np.random.default_rng(3) + ref = gaussian_filter(rng.random((90, 120)), 2.0) * 100 + ref[:, :10] = np.nan + s = np.array([1.3, -2.6]) + moved = inj.shift_image(ref, -s) # moved(p + s) = ref(p) + est = inj.align_images(ref, moved) + np.testing.assert_allclose(est, s, atol=0.08) + + +# ------------------------------------------------------ synthetic recordings + + +def write_static(layout: RasterLayout, gain: float, rate: float, seed: int = 0) -> None: + """Write samples gain * Poisson(rate * brightness) of a static scene.""" + rng = np.random.default_rng(seed) + words = np.zeros((layout.num_cycles, layout.words_per_cycle), np.int16) + bright = 1 + 9 * ((layout.slot_pixel * 7919) % 97) / 97.0 + for ch in range(layout.num_channels): + li = layout.slot_line - 1 + w = layout.row_base[li] + ch * layout.n_per_channel[li] + w = w + layout.slot_pos + lam = rate * bright + words[:, w] = (gain * rng.poisson(lam, (layout.num_cycles, lam.size))).astype(np.int16) + with open(layout.files[0], "wb") as f: + f.write(np.zeros(HEADER_WORDS, np.int16).tobytes()) + f.write(words.tobytes()) + + +def test_measure_raw_per_photon(tmp_path: Path) -> None: + """The variance-to-mean ratio of scaled Poisson samples is the gain.""" + layout = make_layout(tmp_path / "g_DMD1-TRIAL000001.dat", 400, seed=2) + write_static(layout, gain=110.0, rate=0.05) + g = inj.measure_raw_per_photon(layout, channel=0) + assert g.raw_per_photon == pytest.approx(110.0, rel=0.05) + assert g.mean_pulse == pytest.approx(110.0, rel=0.01) + assert g.cycles == (0, 400) and g.n_slots > 0 + + +@pytest.fixture(scope="module") +def online(tmp_path_factory: pytest.TempPathFactory) -> OnlineRecording: + """Synthetic recording with known motion and online offsets. + + Returns + ------- + OnlineRecording + The layout, its online offsets and the true motion, as (layout, offs, truth). + """ + path = tmp_path_factory.mktemp("rec") / "inj_DMD1-TRIAL000001.dat" + layout = make_layout(path, n_cycles=N_CYCLES, seed=5) + offs = online_offsets(layout.total_lines) + truth = write_recording(layout, seed=6, online=offs) + path.with_name("inj_DMD1.meta").write_bytes(b"meta" * 100) + return layout, offs, truth + + +def truth_geometry( + layout: RasterLayout, offs: Offsets, truth: np.ndarray, lines: tuple[int, int] +) -> inj.TrialGeometry: + """Geometry in the scene frame. + + The sample of DMD (r, c) on line l shows the scene at + (r + y_dmd - m_r, c + x - m_c). + + Returns + ------- + inj.TrialGeometry + The per-line shifts for lines lines[0] to lines[1], with the geometry in the + scene frame. + """ + x, _, y_dmd = offs + ln = np.arange(lines[0], lines[1] + 1) + shift = np.stack([y_dmd[ln - 1] - truth[ln - 1, 0], x[ln - 1] - truth[ln - 1, 1]], 1) + return inj.TrialGeometry(lines[0], shift.astype(np.float64), True) + + +def test_sample_model_follows_the_tissue(online: OnlineRecording) -> None: + """Expected counts follow the tissue, for every chunk of cycles. + + They are photon_scale x footprint at the sample's tissue position x the + trace at its line. + """ + layout, offs, truth = online + lines = (8, layout.total_lines - 3) + geo = truth_geometry(layout, offs, truth, lines) + pos = np.array([[17.3, 22.0], [12.0, 30.6]]) + fps = [inj.GaussianFootprint(1.33), inj.GaussianFootprint(2.0)] + n_l = lines[1] - lines[0] + 1 + rng = np.random.default_rng(0) + traces = rng.random((2, n_l)) + model = inj.SampleModel(layout, geo, pos, fps, traces, 25.0) + cycles = np.arange(0, 30) + got = model.expected(cycles) + pix = layout.slot_pixel[model.slots] - 1 + r0, c0 = pix // layout.n_cols, pix % layout.n_cols + ln = cycles[:, None] * layout.lines_per_cycle + layout.slot_line[model.slots] + inside = (ln >= lines[0]) & (ln <= lines[1]) + li = np.clip(ln - lines[0], 0, n_l - 1) + want = np.zeros(got.shape) + for j in range(2): + f = fps[j]( + r0 + geo.shift[li, 0] - pos[j, 0], + c0 + geo.shift[li, 1] - pos[j, 1], + ) + want += 25.0 * f * traces[j, li] + want[~inside] = 0 + np.testing.assert_allclose(got, want, rtol=1e-12, atol=1e-12) + # every slot whose footprint value can be non-zero is reachable + every = np.arange(layout.slot_line.size) + allpix = layout.slot_pixel[every] - 1 + near = np.zeros(every.size, bool) + for j in range(2): + for s in geo.shift[:: layout.lines_per_cycle]: + d = np.hypot( + allpix // layout.n_cols + s[0] - pos[j, 0], + allpix % layout.n_cols + s[1] - pos[j, 1], + ) + near |= d <= fps[j].radius + assert np.all(np.isin(every[near], model.slots)) + + +def registered_table( + layout: RasterLayout, tmp_path: Path, compensate: bool, trials: Sequence[tuple[int, int]] +) -> Path: + """Register line ranges of a recording through a trial table. + + Returns + ------- + Path + The path of the trial table that was registered. + """ + dat = Path(layout.files[0]) + n = len(trials) + table = tmp_path / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(dat.parent), + "savedr": str(tmp_path), + "filename": np.array([[dat.name] * n], dtype=object), + "epoch": np.ones((1, n)), + "true_trial_ix": np.arange(1.0, n + 1)[None, :], + "slap2_info": { + "first_line": np.array([[float(a) for a, _ in trials]]), + "last_line": np.array([[float(b) for _, b in trials]]), + }, + }, + ) + register_multiroi( + table, + {"maxshift": 6, "compensate_online": compensate}, + execution={"device": "cpu", "max_workers": 1}, + ) + return table + + +@pytest.fixture(scope="module") +def registered( + online: OnlineRecording, tmp_path_factory: pytest.TempPathFactory +) -> dict[bool, Path]: + """Register the online recording as two trials, both ways. + + Returns + ------- + dict[bool, Path] + The trial table registered with (True) and without (False) online compensation. + """ + layout, _, _ = online + out = {} + with pytest.MonkeyPatch.context() as mp: + mp.setattr(multiroi, "raster_layout", lambda path: layout) + for comp in (True, False): + d = tmp_path_factory.mktemp(f"reg{int(comp)}") + out[comp] = registered_table(layout, d, comp, [(1, 4800), (4801, 9700)]) + return out + + +@pytest.mark.parametrize("compensate", [True, False]) +def test_geometry_from_registration_tracks_true_motion( + online: OnlineRecording, registered: dict[bool, Path], compensate: bool +) -> None: + """The registered position of each line's samples follows the tissue. + + shift(l) equals the true scene shift up to a constant. + """ + layout, offs, truth = online + table = Path(registered[compensate]) + al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + assert (al.compensation is not None) == compensate + lines = (1, 4800) + geo = inj.trial_geometry(layout, al, lines) + want = truth_geometry(layout, offs, truth, lines).shift + if not compensate: + # uncompensated frames blur the offsets' steps (every 23-50 ms + # here) over their kernel: the motion can only follow that blur + k = np.exp(-np.abs(np.arange(-60, 61)) / 20.0) + want = np.stack( + [np.convolve(np.pad(w, 60, "edge"), k / k.sum(), "valid") for w in want.T], + 1, + ) + err = geo.shift - want + err -= np.median(err, axis=0) + # within the registration's own error (as its tests require) + assert np.sqrt(np.mean(err**2)) < 0.12 + + +def run_injection( + online: OnlineRecording, + table: Path, + out: Path, + monkeypatch: pytest.MonkeyPatch, + **kw: Any, # noqa: ANN401 +) -> dict: + """inject_session on the synthetic recording. + + Returns + ------- + dict + The summary returned by inject_session. + """ + layout, _, _ = online + monkeypatch.setattr(inj, "raster_layout", lambda path: layout) + return inj.inject_session(table, out, paths=(1,), **kw) + + +def test_no_events_leave_the_copy_identical( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Without events the copy equals the original byte for byte. + + The .meta file is copied. + """ + layout, _, _ = online + s = inj.InjectionSettings(rate_hz=0.0, raw_per_photon=1.0) + summary = run_injection(online, registered[True], tmp_path / "out", monkeypatch, settings=s) + src = Path(layout.files[0]) + dst = tmp_path / "out" / "raw" / src.name + assert sha(dst) == sha(src) + meta = src.with_name("inj_DMD1.meta") + assert sha(dst.with_name(meta.name)) == sha(meta) + assert summary["paths"][1]["n_events"] == 0 + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) + assert truth["paths"][1]["events"]["source"].size == 0 + + +BRIGHT = inj.InjectionSettings( + size_classes=(4.0, 8.0), + rate_hz=3.0, + min_interval_s=0.06, + edge_s=0.1, + tau_s=0.012, + raw_per_photon=2.0, + seed=11, + device="cpu", +) +BRIGHT_AT = {1: np.array([[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]])} + + +@pytest.fixture(scope="module") +def injected( + online: OnlineRecording, registered: dict[bool, Path], tmp_path_factory: pytest.TempPathFactory +) -> Injected: + """Bright events injected into both trials (compensated registration). + + Returns + ------- + Injected + The injected copy's folder, its summary and the settings it was made with. + """ + out = tmp_path_factory.mktemp("inj") + with pytest.MonkeyPatch.context() as mp: + summary = run_injection( + online, + registered[True], + out, + mp, + settings=BRIGHT, + positions=BRIGHT_AT, + ) + return out, summary, BRIGHT + + +def test_placed_sources_without_data_are_moved( + online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path +) -> None: + """A source the tool put on a pixel without data where its peaks are calibrated is moved. + + A source that the tool itself puts on a pixel without data in the + stretch its frame peaks are calibrated on is placed anew: at the + minimum distance from the sources that stay and from every place tried + before; the others stay. A position that was given is not moved (an + error, as before), and so is a move with no place left. + """ + first = np.array([[16.0, 20.0], [16.0, 200.0], [12.0, 27.0]]) + asked = [] + # the free candidates of the move, in the order they are drawn: the + # first is 4 px from a source that stays, the second is the place that + # had no data, the third is free + pools = [np.array([[16.0, 24.0], [16.0, 200.0], [18.0, 30.0]])] + + def place( + mean_im: np.ndarray, + n: int, + rng: np.random.Generator, + settings: inj.PlacementSettings | None = None, + valid: np.ndarray | None = None, + exclude_rc: np.ndarray | None = None, + keep_apart_rc: np.ndarray | None = None, + ) -> tuple[np.ndarray, int]: + """Stand-in for place_sources. + + A first placement with a source where no data is, then the + candidates of a move. + + Returns + ------- + positions : np.ndarray + (k, 2) source positions: first on the first call, the free candidates + of the move afterwards. + n_candidates : int + 3 for the first placement, 1 for a move. + """ + asked.append((n, exclude_rc, keep_apart_rc)) + if len(asked) == 1: # the path's placement: one where no data is + return first.copy(), 3 + # a move: the candidates on offer, less those within 6 px of the + # places to keep apart from (place_sources' rule, tested above) + pool = pools[min(len(asked) - 2, len(pools) - 1)] + far = [np.hypot(*(keep_apart_rc - q).T).min() >= 6 for q in pool] + return pool[np.array(far, dtype=bool)][:n], 1 + + out = tmp_path / "moved" + with pytest.MonkeyPatch.context() as mp: + mp.setattr(inj, "place_sources", place) + run_injection(online, registered[True], out, mp, settings=BRIGHT, n_sources=3) + # one move of one source; no external sources to keep away from; apart + # from the sources that stay and from the place that had no data + assert len(asked) == 2 and asked[1][0] == 1 and asked[1][1] is None + assert {tuple(q) for q in asked[1][2]} == {tuple(q) for q in first} + p = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(p["positions_rc"], [[16.0, 20.0], [18.0, 30.0], [12.0, 27.0]]) + assert np.all(p["frame_peak"] > 0) and p["frame_peak"].size == 3 + assert set(p["events"]["source"]) == {0, 1, 2} + # the sources that stayed are calibrated as if the third had been + # where it ended up from the start + with pytest.MonkeyPatch.context() as mp: + run_injection( + online, + registered[True], + tmp_path / "given", + mp, + settings=BRIGHT, + positions={1: np.array(p["positions_rc"])}, + ) + given = inj.read_truth(tmp_path / "given" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_allclose(given["frame_peak"][[0, 2]], p["frame_peak"][[0, 2]], rtol=0.05) + # a position that was given and has no data is an error + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match=r"sources \[1\] have no data"), + ): + run_injection( + online, + registered[True], + tmp_path / "fixed", + mp, + settings=BRIGHT, + positions={1: np.array([[16.0, 20.0], [16.0, 200.0]])}, + ) + # no place left for the move: the only candidates are too near a + # source that stays, or the place that was tried + asked.clear() + pools[:] = [np.array([[16.0, 24.0], [16.0, 200.0], [13.0, 31.0]])] + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match="only 0 free places"), + ): + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "full", + mp, + settings=BRIGHT, + n_sources=3, + ) + # a place tried in an earlier round is not taken again: the first move + # lands without data, and the second is offered the path's first place + # (no longer any source's) before a free one + asked.clear() + pools[:] = [ + np.array([[16.0, 210.0]]), + np.array([[16.0, 200.0], [18.0, 30.0]]), + ] + with pytest.MonkeyPatch.context() as mp: + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "twice", + mp, + settings=BRIGHT, + n_sources=3, + ) + twice = inj.read_truth(tmp_path / "twice" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(twice["positions_rc"][1], [18.0, 30.0]) + assert len(asked) == 3 + # the second move keeps apart from the first place too, though no + # source is there any more + assert (16.0, 200.0) in {tuple(q) for q in asked[2][2]} + assert (16.0, 210.0) in {tuple(q) for q in asked[2][2]} + # moves that land without data every time: after REPLACE_ROUNDS the + # injection gives up + asked.clear() + pools[:] = [ + np.array([[16.0, 210.0 + 10 * k], [16.0, 200.0 + 10 * k]]) + for k in range(inj.REPLACE_ROUNDS) + ] + with ( + pytest.MonkeyPatch.context() as mp, + pytest.raises(ValueError, match="after 5 placements"), + ): + mp.setattr(inj, "place_sources", place) + run_injection( + online, + registered[True], + tmp_path / "again", + mp, + settings=BRIGHT, + n_sources=3, + ) + assert len(asked) == 1 + inj.REPLACE_ROUNDS + + +def test_injection_changes_only_injected_samples( + online: OnlineRecording, injected: Injected +) -> None: + """Only channel-0 raster samples change, never invalid ones. + + The added counts are the recorded ones. + """ + layout, _, _ = online + out, summary, s = injected + src = Path(layout.files[0]) + a = np.fromfile(src, np.int16) + b = np.fromfile(out / "raw" / src.name, np.int16) + changed = np.flatnonzero(a != b) + assert changed.size > 0 + words = changed - HEADER_WORDS + w = words % layout.words_per_cycle + li = layout.slot_line - 1 + ch0 = layout.row_base[li] + layout.slot_pos + assert np.all(np.isin(w, ch0)) + assert np.all(b[changed] > a[changed]) + total = sum(t["added_raw"] for t in summary["paths"][1]["trials"]) + assert int((b.astype(np.int64) - a).sum()) == total + stats = summary["paths"][1]["trials"] + drawn = sum(t["drawn_photons"] for t in stats) + lam = sum(t["expected_photons"] for t in stats) + assert abs(drawn - lam) < 5 * np.sqrt(lam) + assert total == pytest.approx(drawn * s.raw_per_photon, rel=1e-3) + + +def test_truth_file_describes_the_injection(online: OnlineRecording, injected: Injected) -> None: + """The truth has positions per trial, events and traces at frame lines.""" + _layout, _, _ = online + out, summary, _s = injected + truth = inj.read_truth(out / inj.TRUTH_NAME) + assert truth["seed"] == 11 + assert truth["settings"]["size_classes"] == [4.0, 8.0] + p = truth["paths"][1] + assert p["raw_per_photon"] == 2.0 + np.testing.assert_array_equal(p["trials"], [1, 2]) + np.testing.assert_allclose(p["trial_shift_rc"][0], 0.0) + ev = p["events"] + assert ev["source"].size == summary["paths"][1]["n_events"] > 0 + for t, (lo, hi) in ((1, (1, 4800)), (2, (4801, 9700))): + on = ev["onset_line"][ev["trial"] == t] + assert on.min() >= lo + 0.1 * 1600 and on.max() <= hi - 0.1 * 1600 + d = p["trials_detail"][t] + np.testing.assert_allclose( + d["positions_rc"], p["positions_rc"] + p["trial_shift_rc"][t - 1] + ) + fl = d["frame_lines"] + assert fl[0] == lo and np.all(np.diff(fl) == 8) + # the trace peaks at each event's size within one frame of onset + k = np.searchsorted(fl, on[0]) + j = ev["source"][ev["trial"] == t][0] + size = ev["size"][ev["trial"] == t][0] + assert d["trace"][j, k] <= size * 1.0001 + d["trace"][j].max() + assert d["trace"].shape == (3, fl.size) + assert p["footprint"]["patch"].shape[0] == 3 + with h5py.File(out / "trial_table.h5") as f: + assert "motion_correction" not in f + tt = inj.load_struct_h5(out / "trial_table.h5") + assert Path(tt["datadr"]) == out / "raw" + assert np.asarray(tt["slap2_info"]["last_line"]).ravel().tolist() == [ + 4800.0, + 9700.0, + ] + + +def test_injected_signal_is_still_and_as_expected( + online: OnlineRecording, registered: dict[bool, Path], injected: Injected +) -> None: + """In frames registered with the original's motion, the copy matches the expected counts. + + In registered frames made with the original's motion, the copy minus the + original matches the expected counts within Poisson noise, and a static + source's centroid stays put (drift < 0.1 px) across the online offsets' + switches. + """ + layout, _, _ = online + out, _, s = injected + table = Path(registered[True]) + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + al = inj.read_alignment(table.parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5") + copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + orig = read_raster_samples(layout, (0, layout.num_cycles))[0] + new = read_raster_samples(copy, (0, layout.num_cycles))[0] + diff = np.where(orig == INVALID_SAMPLE, INVALID_SAMPLE, new - orig) + lines = (1, 4800) + geo = inj.trial_geometry(layout, al, lines) + pos = truth["trials_detail"][1]["positions_rc"] + fp = [inj.GaussianFootprint(1.33)] * 3 + ev = truth["events"] + sel = ev["trial"] == 1 + events = inj.Events( + ev["source"][sel], + ev["trial"][sel], + ev["onset_line"][sel], + ev["size_class"][sel], + ev["size"][sel] / truth["frame_peak"][ev["source"][sel]], + ) + tr = inj.event_traces(events, 3, lines, layout.line_period_s, s) + expect = inj.SampleModel(layout, geo, pos, fp, tr, 25.0) + static = inj.SampleModel(layout, geo, pos, fp, np.ones_like(tr), 25.0) + n_c = layout.num_cycles # the frame kernels reach past the trial + samples = np.zeros((3, layout.slot_line.size, n_c), np.float32) + samples[0] = diff[:, :n_c] + samples[1][expect.slots] = expect.expected(np.arange(n_c)).T + samples[2][static.slots] = static.expected(np.arange(n_c)).T + samples[:, orig[:, :n_c] == INVALID_SAMPLE] = INVALID_SAMPLE + times = al.ds_frames.astype(np.int64) + # frames whose kernel (60 lines) stays inside the trial + times = times[(times > lines[0] + 60) & (times < lines[1] - 60)] + acc_d = acc_e = 0.0 + drift = {j: [] for j in range(3)} + for idx, frames, _ in iter_registered_frames(layout, samples, 0, al, times, 20, chunk=50): + f = frames.numpy() + for j, (r, c) in enumerate(pos): + ri, ci = int(round(r)), int(round(c)) + win = f[:, :, ri - 3 : ri + 4, ci - 3 : ci + 4] + acc_d = acc_d + np.nansum(win[0]) + acc_e = acc_e + np.nansum(win[1]) + whole = ~np.isnan(win[2]).any((1, 2)) # not cut by an edge + st = win[2][whole] + rr, cc = np.mgrid[-3:4, -3:4] + m = st.sum((1, 2)) + cr = (st * rr).sum((1, 2)) / m + ri - r + cc_ = (st * cc).sum((1, 2)) / m + ci - c + drift[j].append(np.stack([cr, cc_], 1)) + for j in range(3): + d = np.concatenate(drift[j]) + assert d.shape[0] > 0.9 * times.size + assert np.abs(d - np.median(d, axis=0)).max() < 0.1 + assert np.abs(np.median(d, axis=0)).max() < 0.1 + # the summed signal at the sources: Poisson error of photons x g + se = np.sqrt(acc_e * s.raw_per_photon) * 3 + assert abs(acc_d - acc_e) < 5 * se + + +def test_registered_copy_keeps_the_motion( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Registering the injected copy gives the original's motion up to the grid's anchoring. + + The truth then records both. + """ + layout, _, _ = online + out = tmp_path / "inj" + run_injection( + online, + registered[True], + out, + monkeypatch, + settings=replace(BRIGHT, size_classes=(1.0, 2.0)), + positions=BRIGHT_AT, + ) + copy = replace(layout, files=(str(out / "raw" / Path(layout.files[0]).name),)) + monkeypatch.setattr(multiroi, "raster_layout", lambda path: copy) + register_multiroi( + out / "trial_table.h5", + {"maxshift": 6, "compensate_online": True}, + execution={"device": "cpu", "max_workers": 1}, + ) + assert inj.main(["compare", str(out)]) == 0 + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + for t in (1, 2): + d = truth["trials_detail"][t] + assert d["copy_motion_rms_px"] < 0.05 + np.testing.assert_allclose(d["positions_copy_rc"], d["positions_rc"] + d["copy_shift_rc"]) + a = inj.read_alignment(d["alignment"]) + b = inj.read_alignment(d["copy_alignment"]) + off = inj.registration_offset(a, b) + np.testing.assert_allclose(off["shift_rc"], d["copy_shift_rc"]) + + +def test_saturation_invalid_samples_and_chunking(online: OnlineRecording, tmp_path: Path) -> None: + """Huge events saturate at 32767; invalid samples stay. + + Results do not depend on the chunk size. + """ + layout, offs, truth = online + src = Path(layout.files[0]) + data = np.fromfile(src, np.int16) + rng = np.random.default_rng(2) + li = layout.slot_line - 1 + ch0 = layout.row_base[li] + layout.slot_pos + rows = HEADER_WORDS + np.arange(N_CYCLES)[:, None] * layout.words_per_cycle + w = (rows + ch0[None, :]).ravel() + bad = w[rng.random(w.size) < 0.05] + data[bad] = INVALID_SAMPLE + outs = [] + lines = (1, layout.total_lines) + geo = truth_geometry(layout, offs, truth, lines) + tr = np.full((1, lines[1]), 2000.0) + for chunk in (7, 64): + dst = tmp_path / f"c{chunk}.dat" + data.tofile(dst) + lay = replace(layout, files=(str(dst),)) + model = inj.SampleModel(lay, geo, np.array([[18.0, 25.0]]), [inj.GaussianFootprint()], tr) + st = inj.inject_samples(lay, model, 3.0, 0, (5, 1, 1), chunk) + outs.append(np.fromfile(dst, np.int16)) + assert st.saturated > 0 and st.lost_raw > 0 + assert st.expected_photons_invalid > 0 + np.testing.assert_array_equal(outs[0], outs[1]) + assert np.all(outs[0][bad] == INVALID_SAMPLE) + assert outs[0].max() == inj.SAMPLE_MAX + + +def test_command_line( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """``python -m giant_python.simulation.injection`` runs a session.""" + layout, _, _ = online + monkeypatch.setattr(inj, "raster_layout", lambda path: layout) + pos = tmp_path / "pos.h5" + with h5py.File(pos, "w") as f: + f["path1"] = np.array([[16.0, 20.0]]) + code = inj.main([ + "inject", + str(registered[False]), + str(tmp_path / "cli"), + "--paths", + "1", + "--trials", + "2", + "--positions", + str(pos), + "--raw-per-photon", + "4", + "--sizes", + "8", + "--seed", + "3", + "--size-reference", + "tissue", + "--no-frame-traces", + ]) + assert code == 0 + summary = json.loads(capsys.readouterr().out) + assert summary["paths"]["1"]["n_sources"] == 1 + truth = inj.read_truth(tmp_path / "cli" / inj.TRUTH_NAME) + np.testing.assert_array_equal(truth["paths"][1]["trials"], [2]) + p = truth["paths"][1] + assert not p["trials_detail"][2]["compensated"] + np.testing.assert_array_equal(p["frame_peak"], [1.0]) + assert "trace_frames" not in p["trials_detail"][2] + + +def test_cuda_render_matches_cpu(online: OnlineRecording, registered: dict[bool, Path]) -> None: + """Rendering on CUDA equals the CPU.""" + if not torch.cuda.is_available(): + pytest.skip("no CUDA device") + layout, _, _ = online + table = Path(registered[True]) + al = inj.read_alignment(table.parent / "motion_correction" / "E1T2DMD1_ALIGNMENTDATA.h5") + s = read_raster_samples(layout, (0, layout.num_cycles))[:1] + times = al.ds_frames[:40].astype(np.int64) + cpu = next(iter_registered_frames(layout, s, 0, al, times, 20))[1] + gpu = next(iter_registered_frames(layout, s, 0, al, times, 20, "cuda"))[1] + np.testing.assert_allclose(gpu.cpu().numpy(), cpu.numpy(), rtol=1e-5, atol=1e-4, equal_nan=True) + + +def test_ragged_table_keeps_copy_columns( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A trial without a recording is skipped. + + The others keep their column of the copy's trial table. + """ + from giant_python.io.hdf5 import load_struct_h5 + + table = load_struct_h5(registered[False]) + table["filename"] = np.array([["", table["filename"][0, 1]]], object) + ragged = tmp_path / "trial_table.h5" + save_struct_h5(ragged, table) + s = inj.InjectionSettings(raw_per_photon=4.0, seed=1) + run_injection( + online, + ragged, + tmp_path / "out", + monkeypatch, + settings=s, + positions={1: np.array([[16.0, 20.0]])}, + moco_dir=Path(registered[False]).parent / "motion_correction", + ) + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME)["paths"][1] + assert list(truth["trials_detail"]) == [2] + assert truth["trials_detail"][2]["copy_trial"] == 2 + np.testing.assert_array_equal(np.unique(truth["events"]["trial"]), [2]) + + +def test_sizes_are_peaks_in_frames(online: OnlineRecording, injected: Injected) -> None: + """With sizes in frame units, an isolated event's noiseless peak is its size. + + The peak is taken in the 200 Hz frames at its source's peak pixel, and + equals the size on average. + """ + out, _, s = injected + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + fp = truth["frame_peak"] + assert np.all((fp > 0.2) & (fp < 1.0)) + ev = truth["events"] + reach = 24 # max(3 * 8, P) lines at 1600 Hz and 200 Hz frames + tail = 6 * s.tau_s * 1600 + ratios = [] + for t in (1, 2): + d = truth["trials_detail"][t] + fl, tf = d["frame_lines"], d["trace_frames"] + assert tf.shape == d["trace"].shape + # the ideal trace is sampled at frame lines: within a frame of each + # largest peak (overlapping events may add up) + top = np.array([ + ev["size"][(ev["trial"] == t) & (ev["source"] == j)].max() for j in range(3) + ]) + assert np.all(d["trace"].max(1) >= top * np.exp(-0.005 / s.tau_s)) + for j in range(3): + on = ev["onset_line"][(ev["trial"] == t) & (ev["source"] == j)] + size = ev["size"][(ev["trial"] == t) & (ev["source"] == j)] + for k, (t0, a) in enumerate(zip(on, size)): + alone = (k == 0 or t0 - on[k - 1] > 2 * tail) and ( + k == on.size - 1 or on[k + 1] - t0 > tail + reach + ) + sel = (fl >= t0 - reach) & (fl <= t0 + tail) + if alone and sel.any(): + ratios.append(np.nanmax(tf[j, sel]) / a) + assert len(ratios) > 20 + assert np.mean(ratios) == pytest.approx(1.0, abs=0.06) + + +def test_refuses_to_write_into_the_original( + online: OnlineRecording, registered: dict[bool, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + """The copy's folder cannot be the original's data folder.""" + layout, _, _ = online + src = Path(layout.files[0]) + out = src.parent.parent / "same" + with pytest.raises(ValueError, match="original's data folder"): + run_injection( + online, + registered[True], + out, + monkeypatch, + data_dir=out / "raw", + ) + + +def test_registration_offset_includes_the_grid(registered: dict[bool, Path]) -> None: + """Different padding, window and reference offset move the copy's positions. + + Mixed compensation is refused. + """ + from dataclasses import replace as dc_replace + + moco = Path(registered[True]).parent / "motion_correction" + a = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + comp = dict(a.compensation, refOffset=a.compensation["refOffset"] + 1) + b = dc_replace( + a, + margin=a.margin + 3, + trim_r0=a.trim_r0 + 1, + motion_r=a.motion_r + 0.25, + compensation=comp, + ) + off = inj.registration_offset(a, b) + # continuous motion unchanged in columns; rows: +0.25 recorded, -1 from + # the reference (mapping swaps x and y) + np.testing.assert_allclose(off["motion_offset_rc"], [0.25 - 1, -1.0]) + np.testing.assert_allclose(off["shift_rc"], [3 - 1 - 1 - (0.25 - 1), 3 - 1 + 1]) + assert off["rms_px"] < 1e-9 + plain = inj.read_alignment( + Path(registered[False]).parent / "motion_correction" / "E1T1DMD1_ALIGNMENTDATA.h5" + ) + with pytest.raises(ValueError, match="online motion correction"): + inj.registration_offset(a, plain) + + +def test_frame_motion_uses_each_frames_own_reference(registered: dict[bool, Path]) -> None: + """A frame with another reference offset is moved by its own reference. + + The frame is at a registered frame's time but with another reference + offset, and is moved by its own reference, not the recorded motion. + """ + from giant_python.simulation.render import frame_motion + + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + t = al.ds_frames.astype(np.int64) + c = al.compensation + refs = np.stack([c["frameRefX"], c["frameRefY"]], 1) + ok = np.isfinite(al.motion_r) + same = frame_motion(al, t, refs) + np.testing.assert_allclose(same[ok, 0], al.motion_r[ok], atol=1e-9) + np.testing.assert_allclose(same[ok, 1], al.motion_c[ok], atol=1e-9) + other = frame_motion(al, t, refs + np.array([1, 0])) # x one more + np.testing.assert_allclose(other[ok, 1], al.motion_c[ok] - 1, atol=1e-9) + np.testing.assert_allclose(other[ok, 0], al.motion_r[ok], atol=1e-9) + + +def test_calibration_keeps_overlapping_sources_apart( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """Overlapping sources are calibrated in turns. + + A close neighbour does not change a source's frame peak. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = inj.GaussianFootprint(1.33) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.5) + pair = np.array([[16.0, 20.0], [16.0, 22.0], [10.0, 33.0]]) + np.testing.assert_array_equal(inj.overlap_classes(pair, [fp] * 3), [0, 1, 0]) + both = inj.calibrate_frame_peaks( + layout, + al, + geo, + pair, + (0.0, 0.0), + [fp] * 3, + s, + np.random.default_rng(0), + ) + alone = inj.calibrate_frame_peaks( + layout, + al, + geo, + pair[:1], + (0.0, 0.0), + [fp], + s, + np.random.default_rng(0), + ) + assert both[0] == pytest.approx(alone[0], rel=0.05) + + +def test_inputs_that_would_corrupt_a_dataset_are_refused( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Repeated trials or paths and an existing dataset are refused before writing. + + Repeated trials or paths, and an output folder that already holds a + dataset, are refused before anything is written. + """ + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + pos = {1: np.array([[16.0, 20.0]])} + with pytest.raises(ValueError, match="must not repeat"): + run_injection( + online, + registered[False], + tmp_path / "a", + monkeypatch, + settings=s, + positions=pos, + trials=[1, 1], + ) + with pytest.raises(ValueError, match="must not repeat"): + inj.inject_session( + registered[False], + tmp_path / "b", + paths=(1, 1), + settings=s, + positions=pos, + ) + assert not (tmp_path / "a").exists() and not (tmp_path / "b").exists() + out = tmp_path / "c" + (out / "motion_correction").mkdir(parents=True) + with pytest.raises(ValueError, match="already holds motion_correction"): + run_injection( + online, + registered[False], + out, + monkeypatch, + settings=s, + positions=pos, + ) + + +def test_copy_table_paths_and_absolute_folders( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The copy's table has absolute folders and no files for paths not copied.""" + from giant_python.io.hdf5 import load_struct_h5 + + table = { + "datadr": "x", + "savedr": "y", + "filename": np.array([["a1", "b1"], ["a2", "b2"]], dtype=object), + "epoch": np.ones((2, 2)), + "slap2_info": {"first_line": np.ones((2, 2))}, + "motion_correction": {"fn_adata": "z"}, + } + monkeypatch.chdir(tmp_path) + Path("rel").mkdir() + p = inj.write_copy_table(table, np.array([1]), Path("rel/raw"), Path("rel"), paths=[1]) + t = load_struct_h5(p) + assert Path(t["datadr"]).is_absolute() and Path(t["savedr"]).is_absolute() + assert Path(t["savedr"]) == tmp_path / "rel" + np.testing.assert_array_equal(np.asarray(t["filename"], dtype=object).ravel(), ["b1", ""]) + assert "motion_correction" not in t + + +def test_image_footprint_peak_and_calibration( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """An off-centre image footprint is calibrated at its maximum.""" + layout, _, _ = online + img = np.zeros((5, 5)) + img[2, 4] = 1.0 + fp = inj.ImageFootprint(img) + assert fp.peak_offset == (0.0, 2.0) + pos = np.array([[16.0, 20.0]]) + np.testing.assert_array_equal(inj.peak_pixels(pos, [fp]), [[16, 22]]) + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) + peak = inj.calibrate_frame_peaks( + layout, al, geo, pos, (0.0, 0.0), [fp], s, np.random.default_rng(0) + ) + assert 0.05 < peak[0] < 1.0 + + +def test_expected_frames_follow_the_trial_grid( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """A path-frame pixel outside the trial grid's size is still rendered. + + It is rendered where its trial position has data; channel 1 renders + with channel 0's freshness. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = [inj.GaussianFootprint(1.33)] + model = inj.SampleModel(layout, geo, np.array([[16.3, 20.4]]), fp, np.ones((1, 4800))) + fl = np.arange(200, 1200, 8) + here = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0) + far = inj.expected_frames(layout, al, model, fl, [[16 - 40, 20 + 60]], (40.3, -59.6), 200.0) + assert al.shape[1] < 80 and np.isfinite(far).all() + np.testing.assert_allclose(far, here, rtol=1e-6) + ch1 = inj.expected_frames(layout, al, model, fl, [[16, 20]], (0.3, 0.4), 200.0, channel=1) + np.testing.assert_allclose(ch1, here, rtol=1e-6) # no invalid samples + + +def test_trace_frames_skip_kernels_reaching_a_neighbour_trial(injected: Injected) -> None: + """Two trials of one file: frames reading the other trial's injections are NaN. + + Frames whose kernel reads the other trial's injected samples are NaN in + the truth's frame traces. + """ + out, _, _ = injected + truth = inj.read_truth(out / inj.TRUTH_NAME)["paths"][1] + reach = 24 + t1, t2 = truth["trials_detail"][1], truth["trials_detail"][2] + near1 = t1["frame_lines"] + reach >= 4801 + near2 = t2["frame_lines"] - reach <= 4800 + assert near1.any() and near2.any() + assert np.isnan(t1["trace_frames"][:, near1]).all() + assert np.isnan(t2["trace_frames"][:, near2]).all() + assert np.isfinite(t1["trace_frames"][:, ~near1]).mean() > 0.9 + + +def test_relative_registration_folder_is_stored_absolute( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A relative registration folder is recorded as an absolute path.""" + import os + + reg = Path(registered[False]).parent + monkeypatch.chdir(reg) + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + run_injection( + online, + registered[False], + tmp_path / "out", + monkeypatch, + settings=s, + positions={1: np.array([[16.0, 20.0]])}, + trials=[1], + moco_dir="motion_correction", + ) + truth = inj.read_truth(tmp_path / "out" / inj.TRUTH_NAME) + al = Path(str(truth["paths"][1]["trials_detail"][1]["alignment"])) + assert al.is_absolute() and al.exists() + assert os.path.isabs(truth["origin"]["moco_dir"]) + + +def test_more_inputs_are_checked( + online: OnlineRecording, registered: dict[bool, Path], tmp_path: Path +) -> None: + """Non-finite gains are refused; sources without data cannot be calibrated. + + Copies' filenames are their basenames; larger trial grids keep their + data when shifted into the path frame. + """ + from giant_python.io.hdf5 import load_struct_h5 + + for bad in (float("inf"), float("nan")): + with pytest.raises(ValueError, match="finite"): + inj.InjectionSettings(raw_per_photon=bad) + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + fp = inj.GaussianFootprint(1.33) + s = inj.InjectionSettings(tau_s=0.012, calibration_s=2.0) + with pytest.raises(ValueError, match=r"sources \[1\] have no data"): + inj.calibrate_frame_peaks( + layout, + al, + geo, + np.array([[16.0, 20.0], [16.0, 200.0]]), + (0.0, 0.0), + [fp, fp], + s, + np.random.default_rng(0), + ) + table = { + "filename": np.array([["sub/a_DMD1.dat"], [""]], dtype=object), + "slap2_info": {"first_line": np.ones((2, 1))}, + } + p = inj.write_copy_table(table, np.array([0]), tmp_path, tmp_path) + names = np.asarray(load_struct_h5(p)["filename"], dtype=object).ravel() + np.testing.assert_array_equal(names, ["a_DMD1.dat", ""]) + big = np.arange(10 * 112, dtype=float).reshape(10, 112) + out = inj.shift_image(big, (0.0, 8.0), (10, 100)) + np.testing.assert_allclose(out, big[:, 8:108]) + + +def test_bad_chunks_and_name_collisions_are_refused( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A nonpositive chunk size and copies sharing a name are refused before writing. + + A nonpositive chunk size, and two recordings that would be copied under + one name, are refused before anything is written. + """ + import shutil + + from giant_python.io.hdf5 import load_struct_h5 + + layout, _, _ = online + s = inj.InjectionSettings(raw_per_photon=4.0, frame_traces=False, size_reference="tissue") + with pytest.raises(ValueError, match="chunk_cycles"): + run_injection( + online, + registered[False], + tmp_path / "c", + monkeypatch, + settings=s, + chunk_cycles=0, + ) + assert not (tmp_path / "c").exists() + data = tmp_path / "data" + src = Path(layout.files[0]) + for sub in ("a", "b"): + (data / sub).mkdir(parents=True) + shutil.copyfile(src, data / sub / src.name) + table = load_struct_h5(registered[False]) + table["filename"] = np.array([[f"a/{src.name}", f"b/{src.name}"]], dtype=object) + twins = tmp_path / "twins.h5" + save_struct_h5(twins, table) + monkeypatch.setattr(inj, "raster_layout", lambda path: replace(layout, files=(str(path),))) + with pytest.raises(ValueError, match="would both be copied"): + inj.inject_session(twins, tmp_path / "t", paths=(1,), settings=s, data_dir=data) + assert not (tmp_path / "t").exists() + + +def test_neighbours_share_recording_files() -> None: + """Trials are neighbours when their recordings share a file. + + This holds whatever file each trial names. + """ + ctx = { + "names": ["c0.dat", "c1.dat", "other.dat"], + "files": { + 0: ("c0.dat", "c1.dat"), + 1: ("c0.dat", "c1.dat"), + 2: ("other.dat",), + }, + "first": [1.0, 101.0, 1.0], + "last": [100.0, 200.0, 50.0], + } + near = inj._neighbours(ctx, [0, 1, 2]) + assert near(0) == [(101.0, 200.0)] + assert near(1) == [(1.0, 100.0)] + assert near(2) == [] + + +def test_no_events_need_no_calibration( + online: OnlineRecording, + registered: dict[bool, Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Without events nothing is calibrated, and the copy stays identical. + + This holds even in a trial too short to calibrate. + """ + layout, _, _ = online + s = inj.InjectionSettings(rate_hz=0.0, edge_s=1.6, raw_per_photon=1.0) + run_injection(online, registered[True], tmp_path / "o", monkeypatch, settings=s) + src = Path(layout.files[0]) + assert sha(tmp_path / "o" / "raw" / src.name) == sha(src) + truth = inj.read_truth(tmp_path / "o" / inj.TRUTH_NAME)["paths"][1] + np.testing.assert_array_equal(truth["frame_peak"], 1.0) + + +def test_silo_frames_leave_out_the_kernels_edge( + online: OnlineRecording, registered: dict[bool, Path] +) -> None: + """Frame traces and calibration use SILo's extraction frames. + + These leave out the samples exactly at the kernel's reach. + """ + layout, _, _ = online + moco = Path(registered[True]).parent / "motion_correction" + al = inj.read_alignment(moco / "E1T1DMD1_ALIGNMENTDATA.h5") + geo = inj.trial_geometry(layout, al, (1, 4800)) + model = inj.SampleModel( + layout, + geo, + np.array([[16.0, 20.0]]), + [inj.GaussianFootprint()], + np.ones((1, 4800)), + ) + fl = np.arange(300, 900, 8) + got = inj.expected_frames(layout, al, model, fl, [[16, 21]], (0, 0), 200) + n_c = layout.num_cycles + smp = np.zeros((1, layout.slot_line.size, n_c), np.float32) + smp[0][model.slots] = model.expected(np.arange(n_c)).T + want = {} + for exclusive in (True, False): + out = [] + for _, f, _ in iter_registered_frames( + layout, smp, 0, al, fl, 8, chunk=200, exclusive=exclusive + ): + out.append(f[0][:, 16, 21].numpy()) + want[exclusive] = np.concatenate(out) + np.testing.assert_allclose(got[0], want[True], rtol=1e-6) + assert np.max(np.abs(want[True] - want[False])) > 1e-6 diff --git a/tests/spine/__init__.py b/tests/spine/__init__.py index d84fd25f..291c0378 100644 --- a/tests/spine/__init__.py +++ b/tests/spine/__init__.py @@ -1 +1 @@ -"""Tests of the spine-size readout (:mod:`giant_python.spine`).""" +"""Tests of the spine-size readout (:mod:`giant_python.spine`).""" diff --git a/tests/spine/synthetic.py b/tests/spine/synthetic.py index 4e15614f..c4ca1fc3 100644 --- a/tests/spine/synthetic.py +++ b/tests/spine/synthetic.py @@ -1,375 +1,375 @@ -"""A small synthetic session for the spine-size tests. - -One run folder with experiment_summary.h5 and per_trial_summary.h5 -in GIAnT-MATLAB's schema, a trial_table.h5, a motion-correction folder -with _ALIGNMENTDATA.h5 files (recNegErr) and a baseline folder -with _BASELINE-80Hz.h5 files, for two imaging paths. - -Each trial's registered image is the consensus scene shifted by a whole -number of pixels (trial pixel = consensus pixel + shift), so a trial's -image resampled into the consensus frame equals the scene exactly where it -is covered. -""" - -from __future__ import annotations - -import json -from collections.abc import Callable -from pathlib import Path - -import h5py -import numpy as np - -from giant_python.io.hdf5 import save_struct_h5 - -H, W = 24, 30 -N_TRIALS = 4 -N_FRAMES = 160 -ALIGN_HZ = 80.0 -SHIFTS = [(0, 0), (1, 0), (0, -2), (2, 1)] -"""Each trial's shift (rows, cols): trial pixel = consensus pixel + shift.""" - -SOURCES = [(8.0, 9.0), (15.0, 20.0), (12.0, 14.0)] -"""Centres (row, col) of the sources' footprints.""" - - -def scene(path: int) -> np.ndarray: - """Build the consensus F0 scene of a path: smooth and positive. - - Returns - ------- - np.ndarray - The scene, (H, W). - """ - rr, cc = np.mgrid[0:H, 0:W].astype(float) - return 50 + 10 * path + 2 * rr + 0.5 * cc - - -def trial_scale(t: int) -> float: - """Each trial's brightness factor (e.g. bleaching). - - Returns - ------- - float - The factor of trial `t`, falling by 0.05 per trial from 1. - """ - return 1.0 - 0.05 * t - - -def footprints() -> np.ndarray: - """Build the sources' footprints (sources, rows, cols). - - Returns - ------- - np.ndarray - Gaussian footprints centred on SOURCES, each normalized to sum to 1. - """ - rr, cc = np.mgrid[0:H, 0:W].astype(float) - out = np.zeros((len(SOURCES), H, W)) - for k, (r0, c0) in enumerate(SOURCES): - f = np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) - f[f < 0.01 * f.max()] = 0 - out[k] = f / f.sum() - return out - - -def trial_image(path: int, t: int) -> np.ndarray: - """Build a trial's registered F0 image (NaN where the shift leaves no data). - - Returns - ------- - np.ndarray - The trial's image, (H, W): the scaled scene shifted by the trial's shift. - """ - s = scene(path) * trial_scale(t) - dr, dc = SHIFTS[t] - out = np.full((H, W), np.nan) - # trial pixel (r + dr, c + dc) shows consensus pixel (r, c) - rs = slice(max(0, dr), H + min(0, dr)) - cs = slice(max(0, dc), W + min(0, dc)) - rs0 = slice(max(0, -dr), H - max(0, dr)) - cs0 = slice(max(0, -dc), W - max(0, dc)) - out[rs, cs] = s[rs0, cs0] - return out - - -def consensus_trial(path: int, t: int) -> np.ndarray: - """Show what a trial's image looks like in the consensus frame. - - Returns - ------- - np.ndarray - The trial's scaled scene, (H, W), NaN where the trial does not cover the - consensus pixel. - """ - out = scene(path) * trial_scale(t) - dr, dc = SHIFTS[t] - rr, cc = np.mgrid[0:H, 0:W] - ok = (rr + dr >= 0) & (rr + dr < H) & (cc + dc >= 0) & (cc + dc < W) - return np.where(ok, out, np.nan) - - -def _trial_maps(affine: np.ndarray | None, displacement: bool) -> dict: - """Build the frame_info trial maps. - - affine (default: the shifts SHIFTS), or with displacement the - shifts as a displacement field beside identity affine maps. - - Returns - ------- - dict - trial_alignment_affine and, with displacement, trial_alignment_displacement. - """ - if displacement: - disp = np.broadcast_to( - np.asarray(SHIFTS, float)[:, :, None, None], (N_TRIALS, 2, H, W) - ).copy() - eye = np.zeros((N_TRIALS, 2, 3)) - eye[:, :, :2] = np.eye(2) - return { - "trial_alignment_affine": eye, - "trial_alignment_displacement": disp, - } - if affine is None: - affine = np.zeros((N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - affine[:, :, 2] = np.asarray(SHIFTS, float) - return {"trial_alignment_affine": affine} - - -def _in_box(images: np.ndarray, box: tuple[slice, slice] | None) -> np.ndarray: - """``images`` ((..., H, W)) with NaN outside box. - - box is rows, cols slices; None keeps every pixel. - - Returns - ------- - np.ndarray - `images` unchanged if `box` is None, else a copy with NaN outside `box`. - """ - if box is None: - return images - keep = np.zeros((H, W), bool) - keep[box] = True - return np.where(keep, images, np.nan) - - -def make_session( - root: Path, - with_f0_silo: bool = True, - activity_channel: int = 1, - missing_trial: int | None = None, - discard_initial_s: float | None = None, - affine: np.ndarray | None = None, - displacement: bool = False, - f0_silo_box: tuple | None = None, -) -> dict: - """Write the synthetic session under root; return its folders. - - dF_ls counts up through the frames in file channel 1 and from 1000 - in file channel 2; activity_channel is the run's - params/activityChannel. missing_trial (zero-based) gets NaN - traces, as a trial without extracted sources. discard_initial_s - is recorded as the run's params/discardInitial_s (not recorded if - None). affine replaces the trial maps ((trials, 2, 3), written - as given; default: the shifts SHIFTS). With displacement the - shifts are written as a displacement field - (trial_alignment_displacement, as patchwise alignment saves it) and - the affine maps are the identity, so only the field puts the trials in - place. f0_silo_box (rows, cols slices) limits the run's own F0 - images to a box, as they have values only at the pixels SILo fitted. - - Returns - ------- - dict - The session's folders: run, moco, baselines and the table file. - """ - root = Path(root) - run = root / "run" - moco = root / "motion_correction" - base = root / "baselines" - for d in (run, moco, base): - d.mkdir(parents=True, exist_ok=True) - maps = _trial_maps(affine, displacement) - fp = footprints() - exp: dict = { - "params": { - "activityChannel": float(activity_channel), - "numChannels": 2.0, - } - } - if discard_initial_s is not None: - exp["params"]["discardInitial_s"] = float(discard_initial_s) - per: dict = {} - dF = np.tile(np.arange(N_TRIALS * 10, dtype=float), (len(SOURCES), 2, 1)) - dF[:, 1] += 1000 - ev = np.zeros((len(SOURCES), 2, N_TRIALS * 10)) - ev[:, 1] = 1.0 # events only in file channel 2 - if missing_trial is not None: - dF[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan - ev[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan - rng = np.random.default_rng(0) - for p in (1, 2): - imgs = np.stack([consensus_trial(p, t) for t in range(N_TRIALS)]) - mean_t = np.stack([imgs * 1.2, imgs * 0.1], axis=1) # T x C x H x W - exp[f"Path{p}"] = { - "visualizations": { - "mean_im": np.nanmean(mean_t, axis=0)[:, None], - "act_im": rng.random((1, H, W)), - }, - "sources": { - "spatial": {"profiles": fp[:, None]}, - "temporal": {"dF_ls": dF, "events": ev}, - }, - "frame_info": { - "trial_num_frames": np.full((1, N_TRIALS), 10.0), - **maps, - }, - "user_rois": { - "labels": np.array([["roi A", "roi B"]], dtype=object), - "mask": np.stack([ - np.pad(np.ones((4, 4)), ((2, H - 6), (2, W - 6))), - np.pad(np.ones((3, 5)), ((10, H - 13), (20, W - 25))), - ])[:, None] - > 0, - }, - } - per[f"Path{p}"] = {"visualizations": {"per_trial_mean_im": mean_t[:, :, None]}} - if with_f0_silo: - f0 = np.stack([imgs, imgs * 0.1], axis=1)[:, :, None] - per[f"Path{p}"]["visualizations"]["per_trial_F0_im"] = _in_box(f0, f0_silo_box) - for t in range(N_TRIALS): - stem = f"E1T{t + 1}DMD{p}" - img = trial_image(p, t) - frames = np.repeat(img.T[None], N_FRAMES, axis=0) # frame, col, row - frames[:5] = 1e4 # the trimmed start: must not enter - with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: - f.create_dataset("baseline", data=frames.astype(np.float16)) - f.attrs["checkpoint"] = "synthetic.pt" - f.attrs["step"] = 1 - with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["recNegErr"] = np.zeros((N_FRAMES, 1)) - save_struct_h5(run / "experiment_summary.h5", exp) - save_struct_h5(run / "per_trial_summary.h5", per) - fn = np.array( - [ - [f"E1T{t + 1}DMD{p}_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in range(N_TRIALS)] - for p in (1, 2) - ], - dtype=object, - ) - raw = np.array( - [[f"activity_x_DMD{p}-TRIAL{t + 2:06d}.dat" for t in range(N_TRIALS)] for p in (1, 2)], - dtype=object, - ) - table = root / "trial_table.h5" - save_struct_h5( - table, - { - "datadr": str(root / "raw"), - "savedr": str(root / "guard"), - "filename": raw, - "motion_correction": {"fn_reg_ds": fn}, - }, - ) - return {"run": run, "moco": moco, "baselines": base, "table": table} - - -PLAN_HASH = "plan-a" -"""The synthetic plans' settings hash.""" - -RESULT_ATTRS = {"plan_hash": PLAN_HASH, "solve_science": "science-a"} -"""Attributes of the synthetic results files (with a container hash).""" - - -def write_results(path: Path, subproblems: dict, **attrs: str | int) -> None: - """Write a results file with subproblems (index -> (pixels, info)).""" - with h5py.File(path, "w") as f: - for k, v in {**RESULT_ATTRS, "container_hash": "c", **attrs}.items(): - f.attrs[k] = v - f["subproblems/index"] = np.array(sorted(subproblems)) - for k, (pix, info) in subproblems.items(): - g = f.create_group(f"subproblems/{k}") - g["pixels"] = np.asarray(pix) - g.attrs["info"] = json.dumps(info) - - -def baseline_record(path: Path) -> str: - """Build the network_baseline attribute SILo's results record for a baseline file. - - The attribute holds the file's identity and network. - - Returns - ------- - str - The attribute as a JSON string with the file's name, size and mtime_ns and - the synthetic network. - """ - st = Path(path).stat() - return json.dumps( - { - "file": { - "name": Path(path).name, - "size": st.st_size, - "mtime_ns": st.st_mtime_ns, - }, - "network": {"checkpoint": "synthetic.pt", "step": 1}, - }, - sort_keys=True, - ) - - -def make_gain_work( - root: Path, - gain_of_trial: Callable[[int], float], - baselines: str | Path | None = None, -) -> Path: - """Write a minimal 'gain'-mode work folder. - - A plan per path with the selected pixels, and per trial-path one results - file with two overlapping subproblems whose gains are gain_of_trial(t) - and twice that. - - With baselines (the session's folder) the results record its files - as the baselines the gains were fitted against. - - Returns - ------- - Path - The work folder. - """ - work = Path(root) / "work" - (work / "plan").mkdir(parents=True, exist_ok=True) - (work / "results").mkdir(parents=True, exist_ok=True) - sel = np.zeros((H, W), bool) - sel[4:14, 5:15] = True - n_sel = int(sel.sum()) - for p in (1, 2): - with h5py.File(work / "plan" / f"path{p}.h5", "w") as f: - f["sources/sel"] = sel.astype(np.uint8) - f.attrs["settings_hash"] = PLAN_HASH - halves = ( - np.arange(0, n_sel // 2 + 1), - np.arange(n_sel // 2, n_sel), - ) - for t in range(N_TRIALS): - g0 = float(gain_of_trial(t)) - extra = {} - if baselines is not None: - extra["network_baseline"] = baseline_record( - Path(baselines) / f"E1T{t + 1}DMD{p}_BASELINE-80Hz.h5" - ) - write_results( - work / "results" / f"path{p}_trial{t + 1:04d}.h5", - { - k: ( - pix, - {"baseline_step": {"gain": [g0 * (k + 1)] * pix.size}}, - ) - for k, pix in enumerate(halves) - }, - container_hash=f"c{p}-{t}", - n_subproblems=2, - **extra, - ) - return work +"""A small synthetic session for the spine-size tests. + +One run folder with experiment_summary.h5 and per_trial_summary.h5 +in GIAnT-MATLAB's schema, a trial_table.h5, a motion-correction folder +with _ALIGNMENTDATA.h5 files (recNegErr) and a baseline folder +with _BASELINE-80Hz.h5 files, for two imaging paths. + +Each trial's registered image is the consensus scene shifted by a whole +number of pixels (trial pixel = consensus pixel + shift), so a trial's +image resampled into the consensus frame equals the scene exactly where it +is covered. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from pathlib import Path + +import h5py +import numpy as np + +from giant_python.io.hdf5 import save_struct_h5 + +H, W = 24, 30 +N_TRIALS = 4 +N_FRAMES = 160 +ALIGN_HZ = 80.0 +SHIFTS = [(0, 0), (1, 0), (0, -2), (2, 1)] +"""Each trial's shift (rows, cols): trial pixel = consensus pixel + shift.""" + +SOURCES = [(8.0, 9.0), (15.0, 20.0), (12.0, 14.0)] +"""Centres (row, col) of the sources' footprints.""" + + +def scene(path: int) -> np.ndarray: + """Build the consensus F0 scene of a path: smooth and positive. + + Returns + ------- + np.ndarray + The scene, (H, W). + """ + rr, cc = np.mgrid[0:H, 0:W].astype(float) + return 50 + 10 * path + 2 * rr + 0.5 * cc + + +def trial_scale(t: int) -> float: + """Each trial's brightness factor (e.g. bleaching). + + Returns + ------- + float + The factor of trial `t`, falling by 0.05 per trial from 1. + """ + return 1.0 - 0.05 * t + + +def footprints() -> np.ndarray: + """Build the sources' footprints (sources, rows, cols). + + Returns + ------- + np.ndarray + Gaussian footprints centred on SOURCES, each normalized to sum to 1. + """ + rr, cc = np.mgrid[0:H, 0:W].astype(float) + out = np.zeros((len(SOURCES), H, W)) + for k, (r0, c0) in enumerate(SOURCES): + f = np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / (2 * 1.3**2)) + f[f < 0.01 * f.max()] = 0 + out[k] = f / f.sum() + return out + + +def trial_image(path: int, t: int) -> np.ndarray: + """Build a trial's registered F0 image (NaN where the shift leaves no data). + + Returns + ------- + np.ndarray + The trial's image, (H, W): the scaled scene shifted by the trial's shift. + """ + s = scene(path) * trial_scale(t) + dr, dc = SHIFTS[t] + out = np.full((H, W), np.nan) + # trial pixel (r + dr, c + dc) shows consensus pixel (r, c) + rs = slice(max(0, dr), H + min(0, dr)) + cs = slice(max(0, dc), W + min(0, dc)) + rs0 = slice(max(0, -dr), H - max(0, dr)) + cs0 = slice(max(0, -dc), W - max(0, dc)) + out[rs, cs] = s[rs0, cs0] + return out + + +def consensus_trial(path: int, t: int) -> np.ndarray: + """Show what a trial's image looks like in the consensus frame. + + Returns + ------- + np.ndarray + The trial's scaled scene, (H, W), NaN where the trial does not cover the + consensus pixel. + """ + out = scene(path) * trial_scale(t) + dr, dc = SHIFTS[t] + rr, cc = np.mgrid[0:H, 0:W] + ok = (rr + dr >= 0) & (rr + dr < H) & (cc + dc >= 0) & (cc + dc < W) + return np.where(ok, out, np.nan) + + +def _trial_maps(affine: np.ndarray | None, displacement: bool) -> dict: + """Build the frame_info trial maps. + + affine (default: the shifts SHIFTS), or with displacement the + shifts as a displacement field beside identity affine maps. + + Returns + ------- + dict + trial_alignment_affine and, with displacement, trial_alignment_displacement. + """ + if displacement: + disp = np.broadcast_to( + np.asarray(SHIFTS, float)[:, :, None, None], (N_TRIALS, 2, H, W) + ).copy() + eye = np.zeros((N_TRIALS, 2, 3)) + eye[:, :, :2] = np.eye(2) + return { + "trial_alignment_affine": eye, + "trial_alignment_displacement": disp, + } + if affine is None: + affine = np.zeros((N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + affine[:, :, 2] = np.asarray(SHIFTS, float) + return {"trial_alignment_affine": affine} + + +def _in_box(images: np.ndarray, box: tuple[slice, slice] | None) -> np.ndarray: + """``images`` ((..., H, W)) with NaN outside box. + + box is rows, cols slices; None keeps every pixel. + + Returns + ------- + np.ndarray + `images` unchanged if `box` is None, else a copy with NaN outside `box`. + """ + if box is None: + return images + keep = np.zeros((H, W), bool) + keep[box] = True + return np.where(keep, images, np.nan) + + +def make_session( + root: Path, + with_f0_silo: bool = True, + activity_channel: int = 1, + missing_trial: int | None = None, + discard_initial_s: float | None = None, + affine: np.ndarray | None = None, + displacement: bool = False, + f0_silo_box: tuple | None = None, +) -> dict: + """Write the synthetic session under root; return its folders. + + dF_ls counts up through the frames in file channel 1 and from 1000 + in file channel 2; activity_channel is the run's + params/activityChannel. missing_trial (zero-based) gets NaN + traces, as a trial without extracted sources. discard_initial_s + is recorded as the run's params/discardInitial_s (not recorded if + None). affine replaces the trial maps ((trials, 2, 3), written + as given; default: the shifts SHIFTS). With displacement the + shifts are written as a displacement field + (trial_alignment_displacement, as patchwise alignment saves it) and + the affine maps are the identity, so only the field puts the trials in + place. f0_silo_box (rows, cols slices) limits the run's own F0 + images to a box, as they have values only at the pixels SILo fitted. + + Returns + ------- + dict + The session's folders: run, moco, baselines and the table file. + """ + root = Path(root) + run = root / "run" + moco = root / "motion_correction" + base = root / "baselines" + for d in (run, moco, base): + d.mkdir(parents=True, exist_ok=True) + maps = _trial_maps(affine, displacement) + fp = footprints() + exp: dict = { + "params": { + "activityChannel": float(activity_channel), + "numChannels": 2.0, + } + } + if discard_initial_s is not None: + exp["params"]["discardInitial_s"] = float(discard_initial_s) + per: dict = {} + dF = np.tile(np.arange(N_TRIALS * 10, dtype=float), (len(SOURCES), 2, 1)) + dF[:, 1] += 1000 + ev = np.zeros((len(SOURCES), 2, N_TRIALS * 10)) + ev[:, 1] = 1.0 # events only in file channel 2 + if missing_trial is not None: + dF[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan + ev[:, :, missing_trial * 10 : (missing_trial + 1) * 10] = np.nan + rng = np.random.default_rng(0) + for p in (1, 2): + imgs = np.stack([consensus_trial(p, t) for t in range(N_TRIALS)]) + mean_t = np.stack([imgs * 1.2, imgs * 0.1], axis=1) # T x C x H x W + exp[f"Path{p}"] = { + "visualizations": { + "mean_im": np.nanmean(mean_t, axis=0)[:, None], + "act_im": rng.random((1, H, W)), + }, + "sources": { + "spatial": {"profiles": fp[:, None]}, + "temporal": {"dF_ls": dF, "events": ev}, + }, + "frame_info": { + "trial_num_frames": np.full((1, N_TRIALS), 10.0), + **maps, + }, + "user_rois": { + "labels": np.array([["roi A", "roi B"]], dtype=object), + "mask": np.stack([ + np.pad(np.ones((4, 4)), ((2, H - 6), (2, W - 6))), + np.pad(np.ones((3, 5)), ((10, H - 13), (20, W - 25))), + ])[:, None] + > 0, + }, + } + per[f"Path{p}"] = {"visualizations": {"per_trial_mean_im": mean_t[:, :, None]}} + if with_f0_silo: + f0 = np.stack([imgs, imgs * 0.1], axis=1)[:, :, None] + per[f"Path{p}"]["visualizations"]["per_trial_F0_im"] = _in_box(f0, f0_silo_box) + for t in range(N_TRIALS): + stem = f"E1T{t + 1}DMD{p}" + img = trial_image(p, t) + frames = np.repeat(img.T[None], N_FRAMES, axis=0) # frame, col, row + frames[:5] = 1e4 # the trimmed start: must not enter + with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: + f.create_dataset("baseline", data=frames.astype(np.float16)) + f.attrs["checkpoint"] = "synthetic.pt" + f.attrs["step"] = 1 + with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["recNegErr"] = np.zeros((N_FRAMES, 1)) + save_struct_h5(run / "experiment_summary.h5", exp) + save_struct_h5(run / "per_trial_summary.h5", per) + fn = np.array( + [ + [f"E1T{t + 1}DMD{p}_REGISTERED_DOWNSAMPLED-80Hz.tif" for t in range(N_TRIALS)] + for p in (1, 2) + ], + dtype=object, + ) + raw = np.array( + [[f"activity_x_DMD{p}-TRIAL{t + 2:06d}.dat" for t in range(N_TRIALS)] for p in (1, 2)], + dtype=object, + ) + table = root / "trial_table.h5" + save_struct_h5( + table, + { + "datadr": str(root / "raw"), + "savedr": str(root / "guard"), + "filename": raw, + "motion_correction": {"fn_reg_ds": fn}, + }, + ) + return {"run": run, "moco": moco, "baselines": base, "table": table} + + +PLAN_HASH = "plan-a" +"""The synthetic plans' settings hash.""" + +RESULT_ATTRS = {"plan_hash": PLAN_HASH, "solve_science": "science-a"} +"""Attributes of the synthetic results files (with a container hash).""" + + +def write_results(path: Path, subproblems: dict, **attrs: str | int) -> None: + """Write a results file with subproblems (index -> (pixels, info)).""" + with h5py.File(path, "w") as f: + for k, v in {**RESULT_ATTRS, "container_hash": "c", **attrs}.items(): + f.attrs[k] = v + f["subproblems/index"] = np.array(sorted(subproblems)) + for k, (pix, info) in subproblems.items(): + g = f.create_group(f"subproblems/{k}") + g["pixels"] = np.asarray(pix) + g.attrs["info"] = json.dumps(info) + + +def baseline_record(path: Path) -> str: + """Build the network_baseline attribute SILo's results record for a baseline file. + + The attribute holds the file's identity and network. + + Returns + ------- + str + The attribute as a JSON string with the file's name, size and mtime_ns and + the synthetic network. + """ + st = Path(path).stat() + return json.dumps( + { + "file": { + "name": Path(path).name, + "size": st.st_size, + "mtime_ns": st.st_mtime_ns, + }, + "network": {"checkpoint": "synthetic.pt", "step": 1}, + }, + sort_keys=True, + ) + + +def make_gain_work( + root: Path, + gain_of_trial: Callable[[int], float], + baselines: str | Path | None = None, +) -> Path: + """Write a minimal 'gain'-mode work folder. + + A plan per path with the selected pixels, and per trial-path one results + file with two overlapping subproblems whose gains are gain_of_trial(t) + and twice that. + + With baselines (the session's folder) the results record its files + as the baselines the gains were fitted against. + + Returns + ------- + Path + The work folder. + """ + work = Path(root) / "work" + (work / "plan").mkdir(parents=True, exist_ok=True) + (work / "results").mkdir(parents=True, exist_ok=True) + sel = np.zeros((H, W), bool) + sel[4:14, 5:15] = True + n_sel = int(sel.sum()) + for p in (1, 2): + with h5py.File(work / "plan" / f"path{p}.h5", "w") as f: + f["sources/sel"] = sel.astype(np.uint8) + f.attrs["settings_hash"] = PLAN_HASH + halves = ( + np.arange(0, n_sel // 2 + 1), + np.arange(n_sel // 2, n_sel), + ) + for t in range(N_TRIALS): + g0 = float(gain_of_trial(t)) + extra = {} + if baselines is not None: + extra["network_baseline"] = baseline_record( + Path(baselines) / f"E1T{t + 1}DMD{p}_BASELINE-80Hz.h5" + ) + write_results( + work / "results" / f"path{p}_trial{t + 1:04d}.h5", + { + k: ( + pix, + {"baseline_step": {"gain": [g0 * (k + 1)] * pix.size}}, + ) + for k, pix in enumerate(halves) + }, + container_hash=f"c{p}-{t}", + n_subproblems=2, + **extra, + ) + return work diff --git a/tests/spine/test_spine_gains.py b/tests/spine/test_spine_gains.py index 21bba126..b23f18dc 100644 --- a/tests/spine/test_spine_gains.py +++ b/tests/spine/test_spine_gains.py @@ -1,246 +1,246 @@ -"""Tests of the gain-rescaled F0 (:mod:`giant_python.spine.gains`).""" - -import json -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.spine.gains import ( - gain_maps, - results_files, - selected_pixels, - trial_gains, -) -from giant_python.spine.pipeline import make_spine_summary -from giant_python.spine.product import read_product -from giant_python.spine.readout import project - -from . import synthetic as syn - - -def test_gain_maps_average_overlapping_subproblems(tmp_path: Path) -> None: - """A pixel in two subproblems gets the mean of its gains. - - Their spread is reported. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0 + 0.1 * t) - rows, cols, shape = selected_pixels(work / "plan" / "path1.h5") - gain, spread, n_files = gain_maps(work, 1, syn.N_TRIALS) - assert gain.shape == (syn.N_TRIALS,) + shape - assert (n_files == 1).all() - n = rows.size - overlap = n // 2 - g1 = 1.1 # trial 2 - np.testing.assert_allclose(gain[1, rows[0], cols[0]], g1) - np.testing.assert_allclose(gain[1, rows[-1], cols[-1]], 2 * g1) - np.testing.assert_allclose(gain[1, rows[overlap], cols[overlap]], 1.5 * g1, rtol=1e-6) - np.testing.assert_allclose(spread[1, rows[overlap], cols[overlap]], g1, rtol=1e-6) - assert spread[1, rows[0], cols[0]] == 0 - assert np.isnan(gain[1, 0, 0]) - - -def test_trial_gains_needs_a_gain_record(tmp_path: Path) -> None: - """Results of a mode without gains are refused.""" - path = tmp_path / "r.h5" - with h5py.File(path, "w") as f: - f["subproblems/index"] = np.array([0]) - g = f.create_group("subproblems/0") - g["pixels"] = np.arange(3) - g.attrs["info"] = json.dumps({"iterations": 3}) - with pytest.raises(ValueError, match="no gain record"): - trial_gains([path]) - - -def test_readout_adds_the_gain_image(tmp_path: Path) -> None: - """f0_gain is the gain times the network's image, at the selected pixels.""" - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - rep = make_spine_summary( - s["run"], - s["table"], - tmp_path / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - gain_work_dir=work, - ) - p = read_product(rep["output"])["paths"][1] - gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) - ok = np.isfinite(p["images"]["f0_gain"]) - assert ok.any() - np.testing.assert_allclose( - p["images"]["f0_gain"][ok], - (gain * p["images"]["f0_net"])[ok], - rtol=1e-6, - ) - assert not np.isfinite(p["images"]["f0_gain"][:, 0, 0]).any() - assert rep["paths"][1]["gain"]["median"] > 1.0 - # every image is read in the same windows: the source inside the - # selected pixels reads gain x f0_net in the field images' window - src = p["readout"]["sources"] - expect, _ = project(gain * p["images"]["f0_net"], p["rois"]["sources"], p["valid"]) - np.testing.assert_allclose(src["f0_gain"][:, 0], expect[:, 0], rtol=1e-5) - # the gains (selected pixels only) do not shrink the other images' - # windows: the sources and user ROIs outside them keep their readouts, - # and the report counts the windows f0_gain leaves out - assert np.isfinite(src["f0_net"]).all() - assert np.isnan(src["f0_gain"][:, 1]).all() - assert np.isfinite(p["readout"]["user"]["f0_net"]).all() - gaps = rep["paths"][1]["not_covered"] - assert gaps == {"sources": {"f0_gain": 2}, "user": {"f0_gain": 2}} - assert rep["paths"][1]["window_images"] == [ - "mean_ch1", - "mean_ch2", - "f0_net", - ] - # its normalization uses the sources it covers; the others' is unchanged - norm = p["normalized"]["sources"] - assert norm["ok"].all() - np.testing.assert_allclose(norm["f0_gain"][:, 0], 0, atol=1e-6) - assert np.isnan(norm["f0_gain"][:, 1:]).all() - with pytest.raises(ValueError, match="needs --baseline-dir"): - make_spine_summary(s["run"], s["table"], tmp_path, gain_work_dir=work) - - -def test_results_files_select_the_plan_and_the_exact_trial(tmp_path: Path) -> None: - """Results of another plan are left out. - - A longer trial number with the same prefix is not this trial, and two - solves of the plan are refused. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0) - res = work / "results" - info = {"baseline_step": {"gain": [9.0]}} - syn.write_results(res / "path1_trial0001_s9.h5", {0: ([0], info)}, plan_hash="old-plan") - assert [f.name for f in results_files(work, 1, 0)] == ["path1_trial0001.h5"] - syn.write_results(res / "path1_trial1000.h5", {0: ([0], info)}) - syn.write_results(res / "path1_trial10000.h5", {0: ([0], info)}) - assert [f.name for f in results_files(work, 1, 999)] == ["path1_trial1000.h5"] - syn.write_results( - res / "path1_trial0002_s1.h5", - {0: ([0], info)}, - solve_science="science-b", - container_hash="c1-1", - ) - with pytest.raises(ValueError, match="more than one solve"): - results_files(work, 1, 1) - # other numerical settings (solve_settings) of the same science - syn.write_results( - res / "path1_trial0003_s1.h5", - {0: ([0], info)}, - container_hash="c1-2", - solve_settings="other-iterations", - ) - with pytest.raises(ValueError, match="more than one solve"): - results_files(work, 1, 2) - - -def test_trial_gains_counts_a_copied_subproblem_once(tmp_path: Path) -> None: - """A subproblem in two files (identical copies) is one subproblem. - - Two different copies are refused. - """ - work = syn.make_gain_work(tmp_path, lambda t: 1.0) - rows, cols, _ = selected_pixels(work / "plan" / "path1.h5") - n = rows.size - first = np.arange(0, n // 2 + 1) - copy = {0: (first, {"baseline_step": {"gain": [1.0] * first.size}})} - syn.write_results(work / "results" / "path1_trial0001_s1.h5", copy, container_hash="c1-0") - gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) - k = n // 2 # the pixel in both subproblems: gains 1 and 2 - np.testing.assert_allclose(gain[0, rows[k], cols[k]], 1.5, rtol=1e-6) - other = {0: (first, {"baseline_step": {"gain": [3.0] * first.size}})} - syn.write_results( - work / "results" / "path1_trial0001_s1.h5", - other, - container_hash="c1-0", - ) - with pytest.raises(ValueError, match="two different results"): - gain_maps(work, 1, syn.N_TRIALS) - - -def test_trial_gains_refuses_a_shared_time_course(tmp_path: Path) -> None: - """'gain_shared' subproblems are read only while their shared time course is 1. - - Then the baseline is still gain x network baseline. - """ - path = tmp_path / "r.h5" - step = {"gain": [2.0, 2.0], "shared": [1.0, 1.0, 1.0]} - syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) - pix, g = trial_gains([path]) - assert pix.tolist() == [0, 1] and g.tolist() == [2.0, 2.0] - step["shared"] = [1.0, 1.1, 0.9] - syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) - with pytest.raises(ValueError, match="shared baseline time course"): - trial_gains([path]) - - -def test_summary_key_follows_the_gain_plan(tmp_path: Path) -> None: - """A changed plan gives a new summary, not the old one reused.""" - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = { - "baseline_dir": s["baselines"], - "moco_dir": s["moco"], - "trim_s": 0.1, - "gain_work_dir": work, - } - rep = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - with h5py.File(work / "plan" / "path1.h5", "a") as f: - f.attrs["note"] = "replanned" - rep2 = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - assert rep2["key"] != rep["key"] and not rep2["reused"] - - -def test_gains_need_the_images_baseline_files(tmp_path: Path) -> None: - """Gains are used only with the baseline files they were fitted against. - - A baseline predicted again after the solve, or results that record no - network baseline, are refused. - """ - import os - - s = syn.make_session(tmp_path) - work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) - kw = { - "baseline_dir": s["baselines"], - "moco_dir": s["moco"], - "trim_s": 0.1, - "gain_work_dir": work, - } - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - b = s["baselines"] / "E1T2DMD1_BASELINE-80Hz.h5" - st = b.stat() - os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - with pytest.raises(ValueError, match="Path1 trial 2: the gains were"): - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns)) - plain = syn.make_gain_work(tmp_path / "plain", lambda t: 1.0) - kw["gain_work_dir"] = plain - with pytest.raises(ValueError, match="record no network baseline"): - make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) - - -def test_trial_gains_needs_every_subproblem(tmp_path: Path) -> None: - """As in the collect stage, a trial's results must hold all of its subproblems. - - A missing shard, or files that disagree on the number of subproblems, - are refused; a trial too short to extract is not. - """ - info = {"baseline_step": {"gain": [1.0, 1.0]}} - a, b = tmp_path / "a.h5", tmp_path / "b.h5" - syn.write_results(a, {0: ([0, 1], info)}, n_subproblems=2) - with pytest.raises(ValueError, match="1 of 2 subproblems"): - trial_gains([a]) - syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=2) - pix, _ = trial_gains([a, b]) - assert sorted(pix.tolist()) == [0, 1, 2, 3] - syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=3) - with pytest.raises(ValueError, match="3 subproblems here but 2"): - trial_gains([a, b]) - short = tmp_path / "short.h5" - syn.write_results(short, {}, n_subproblems=4, extracted=0) - pix, _ = trial_gains([short]) - assert pix.size == 0 +"""Tests of the gain-rescaled F0 (:mod:`giant_python.spine.gains`).""" + +import json +from pathlib import Path + +import h5py +import numpy as np +import pytest + +from giant_python.spine.gains import ( + gain_maps, + results_files, + selected_pixels, + trial_gains, +) +from giant_python.spine.pipeline import make_spine_summary +from giant_python.spine.product import read_product +from giant_python.spine.readout import project + +from . import synthetic as syn + + +def test_gain_maps_average_overlapping_subproblems(tmp_path: Path) -> None: + """A pixel in two subproblems gets the mean of its gains. + + Their spread is reported. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0 + 0.1 * t) + rows, cols, shape = selected_pixels(work / "plan" / "path1.h5") + gain, spread, n_files = gain_maps(work, 1, syn.N_TRIALS) + assert gain.shape == (syn.N_TRIALS,) + shape + assert (n_files == 1).all() + n = rows.size + overlap = n // 2 + g1 = 1.1 # trial 2 + np.testing.assert_allclose(gain[1, rows[0], cols[0]], g1) + np.testing.assert_allclose(gain[1, rows[-1], cols[-1]], 2 * g1) + np.testing.assert_allclose(gain[1, rows[overlap], cols[overlap]], 1.5 * g1, rtol=1e-6) + np.testing.assert_allclose(spread[1, rows[overlap], cols[overlap]], g1, rtol=1e-6) + assert spread[1, rows[0], cols[0]] == 0 + assert np.isnan(gain[1, 0, 0]) + + +def test_trial_gains_needs_a_gain_record(tmp_path: Path) -> None: + """Results of a mode without gains are refused.""" + path = tmp_path / "r.h5" + with h5py.File(path, "w") as f: + f["subproblems/index"] = np.array([0]) + g = f.create_group("subproblems/0") + g["pixels"] = np.arange(3) + g.attrs["info"] = json.dumps({"iterations": 3}) + with pytest.raises(ValueError, match="no gain record"): + trial_gains([path]) + + +def test_readout_adds_the_gain_image(tmp_path: Path) -> None: + """f0_gain is the gain times the network's image, at the selected pixels.""" + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + rep = make_spine_summary( + s["run"], + s["table"], + tmp_path / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + gain_work_dir=work, + ) + p = read_product(rep["output"])["paths"][1] + gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) + ok = np.isfinite(p["images"]["f0_gain"]) + assert ok.any() + np.testing.assert_allclose( + p["images"]["f0_gain"][ok], + (gain * p["images"]["f0_net"])[ok], + rtol=1e-6, + ) + assert not np.isfinite(p["images"]["f0_gain"][:, 0, 0]).any() + assert rep["paths"][1]["gain"]["median"] > 1.0 + # every image is read in the same windows: the source inside the + # selected pixels reads gain x f0_net in the field images' window + src = p["readout"]["sources"] + expect, _ = project(gain * p["images"]["f0_net"], p["rois"]["sources"], p["valid"]) + np.testing.assert_allclose(src["f0_gain"][:, 0], expect[:, 0], rtol=1e-5) + # the gains (selected pixels only) do not shrink the other images' + # windows: the sources and user ROIs outside them keep their readouts, + # and the report counts the windows f0_gain leaves out + assert np.isfinite(src["f0_net"]).all() + assert np.isnan(src["f0_gain"][:, 1]).all() + assert np.isfinite(p["readout"]["user"]["f0_net"]).all() + gaps = rep["paths"][1]["not_covered"] + assert gaps == {"sources": {"f0_gain": 2}, "user": {"f0_gain": 2}} + assert rep["paths"][1]["window_images"] == [ + "mean_ch1", + "mean_ch2", + "f0_net", + ] + # its normalization uses the sources it covers; the others' is unchanged + norm = p["normalized"]["sources"] + assert norm["ok"].all() + np.testing.assert_allclose(norm["f0_gain"][:, 0], 0, atol=1e-6) + assert np.isnan(norm["f0_gain"][:, 1:]).all() + with pytest.raises(ValueError, match="needs --baseline-dir"): + make_spine_summary(s["run"], s["table"], tmp_path, gain_work_dir=work) + + +def test_results_files_select_the_plan_and_the_exact_trial(tmp_path: Path) -> None: + """Results of another plan are left out. + + A longer trial number with the same prefix is not this trial, and two + solves of the plan are refused. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0) + res = work / "results" + info = {"baseline_step": {"gain": [9.0]}} + syn.write_results(res / "path1_trial0001_s9.h5", {0: ([0], info)}, plan_hash="old-plan") + assert [f.name for f in results_files(work, 1, 0)] == ["path1_trial0001.h5"] + syn.write_results(res / "path1_trial1000.h5", {0: ([0], info)}) + syn.write_results(res / "path1_trial10000.h5", {0: ([0], info)}) + assert [f.name for f in results_files(work, 1, 999)] == ["path1_trial1000.h5"] + syn.write_results( + res / "path1_trial0002_s1.h5", + {0: ([0], info)}, + solve_science="science-b", + container_hash="c1-1", + ) + with pytest.raises(ValueError, match="more than one solve"): + results_files(work, 1, 1) + # other numerical settings (solve_settings) of the same science + syn.write_results( + res / "path1_trial0003_s1.h5", + {0: ([0], info)}, + container_hash="c1-2", + solve_settings="other-iterations", + ) + with pytest.raises(ValueError, match="more than one solve"): + results_files(work, 1, 2) + + +def test_trial_gains_counts_a_copied_subproblem_once(tmp_path: Path) -> None: + """A subproblem in two files (identical copies) is one subproblem. + + Two different copies are refused. + """ + work = syn.make_gain_work(tmp_path, lambda t: 1.0) + rows, cols, _ = selected_pixels(work / "plan" / "path1.h5") + n = rows.size + first = np.arange(0, n // 2 + 1) + copy = {0: (first, {"baseline_step": {"gain": [1.0] * first.size}})} + syn.write_results(work / "results" / "path1_trial0001_s1.h5", copy, container_hash="c1-0") + gain, _, _ = gain_maps(work, 1, syn.N_TRIALS) + k = n // 2 # the pixel in both subproblems: gains 1 and 2 + np.testing.assert_allclose(gain[0, rows[k], cols[k]], 1.5, rtol=1e-6) + other = {0: (first, {"baseline_step": {"gain": [3.0] * first.size}})} + syn.write_results( + work / "results" / "path1_trial0001_s1.h5", + other, + container_hash="c1-0", + ) + with pytest.raises(ValueError, match="two different results"): + gain_maps(work, 1, syn.N_TRIALS) + + +def test_trial_gains_refuses_a_shared_time_course(tmp_path: Path) -> None: + """'gain_shared' subproblems are read only while their shared time course is 1. + + Then the baseline is still gain x network baseline. + """ + path = tmp_path / "r.h5" + step = {"gain": [2.0, 2.0], "shared": [1.0, 1.0, 1.0]} + syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) + pix, g = trial_gains([path]) + assert pix.tolist() == [0, 1] and g.tolist() == [2.0, 2.0] + step["shared"] = [1.0, 1.1, 0.9] + syn.write_results(path, {0: ([0, 1], {"baseline_step": step})}) + with pytest.raises(ValueError, match="shared baseline time course"): + trial_gains([path]) + + +def test_summary_key_follows_the_gain_plan(tmp_path: Path) -> None: + """A changed plan gives a new summary, not the old one reused.""" + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + kw = { + "baseline_dir": s["baselines"], + "moco_dir": s["moco"], + "trim_s": 0.1, + "gain_work_dir": work, + } + rep = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + with h5py.File(work / "plan" / "path1.h5", "a") as f: + f.attrs["note"] = "replanned" + rep2 = make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + assert rep2["key"] != rep["key"] and not rep2["reused"] + + +def test_gains_need_the_images_baseline_files(tmp_path: Path) -> None: + """Gains are used only with the baseline files they were fitted against. + + A baseline predicted again after the solve, or results that record no + network baseline, are refused. + """ + import os + + s = syn.make_session(tmp_path) + work = syn.make_gain_work(tmp_path, lambda t: 1.0, s["baselines"]) + kw = { + "baseline_dir": s["baselines"], + "moco_dir": s["moco"], + "trim_s": 0.1, + "gain_work_dir": work, + } + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + b = s["baselines"] / "E1T2DMD1_BASELINE-80Hz.h5" + st = b.stat() + os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + with pytest.raises(ValueError, match="Path1 trial 2: the gains were"): + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns)) + plain = syn.make_gain_work(tmp_path / "plain", lambda t: 1.0) + kw["gain_work_dir"] = plain + with pytest.raises(ValueError, match="record no network baseline"): + make_spine_summary(s["run"], s["table"], tmp_path / "out", **kw) + + +def test_trial_gains_needs_every_subproblem(tmp_path: Path) -> None: + """As in the collect stage, a trial's results must hold all of its subproblems. + + A missing shard, or files that disagree on the number of subproblems, + are refused; a trial too short to extract is not. + """ + info = {"baseline_step": {"gain": [1.0, 1.0]}} + a, b = tmp_path / "a.h5", tmp_path / "b.h5" + syn.write_results(a, {0: ([0, 1], info)}, n_subproblems=2) + with pytest.raises(ValueError, match="1 of 2 subproblems"): + trial_gains([a]) + syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=2) + pix, _ = trial_gains([a, b]) + assert sorted(pix.tolist()) == [0, 1, 2, 3] + syn.write_results(b, {1: ([2, 3], info)}, n_subproblems=3) + with pytest.raises(ValueError, match="3 subproblems here but 2"): + trial_gains([a, b]) + short = tmp_path / "short.h5" + syn.write_results(short, {}, n_subproblems=4, extracted=0) + pix, _ = trial_gains([short]) + assert pix.size == 0 diff --git a/tests/spine/test_spine_qc.py b/tests/spine/test_spine_qc.py index 443415a2..e2d86d76 100644 --- a/tests/spine/test_spine_qc.py +++ b/tests/spine/test_spine_qc.py @@ -1,179 +1,179 @@ -"""Tests of the readout's quality columns and default image. - -The module under test is :mod:`giant_python.spine.qc`. -""" - -from collections.abc import Sequence - -import numpy as np -import pytest - -from giant_python.spine.qc import ( - primary_image, - structural_change, - structural_image, - window_motion, -) -from giant_python.spine.rois import sources_roiset -from giant_python.spine.summary_io import TrialMap -from giant_python.spine.trends import shared_mode, step_at - -from . import synthetic as syn - - -def _shift_field( - shifts: Sequence[Sequence[float]], bump: tuple[int, int, int, float] | None = None -) -> TrialMap: - """Build a displacement field per trial: the shifts everywhere, plus a bump. - - bump = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) of - extra row displacement. - - Returns - ------- - TrialMap - Identity affines with the per-trial displacement fields. - """ - T = len(shifts) - disp = np.broadcast_to(np.asarray(shifts, float)[:, :, None, None], (T, 2, syn.H, syn.W)).copy() - if bump is not None: - t, r0, c0, a = bump - rr, cc = np.mgrid[0 : syn.H, 0 : syn.W] - disp[t, 0] += a * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0) - eye = np.zeros((T, 2, 3)) - eye[:, :, :2] = np.eye(2) - return TrialMap(eye, disp) - - -def test_primary_and_structural_images() -> None: - """The default image and the structural image are chosen in order. - - The default image is f0_gain, then f0_net, then the run's own F0 and the - mean of the activity channel; the structural image is the first mean image - of another channel. - """ - names = ["mean_ch1", "mean_ch2", "f0_net", "f0_gain", "f0_silo_ch1"] - assert primary_image(names, 1) == "f0_gain" - assert primary_image(names[:3], 1) == "f0_net" - assert primary_image(["mean_ch1", "mean_ch2", "f0_silo_ch2"], 2) == ("f0_silo_ch2") - assert primary_image(["mean_ch1", "mean_ch2"], 2) == "mean_ch2" - assert primary_image(["f0_silo_ch1"], 2) is None - assert structural_image(names, 1) == "mean_ch2" - assert structural_image(names, 2) == "mean_ch1" - assert structural_image(["mean_ch3", "mean_ch2", "mean_ch1"], 1) == ("mean_ch2") - assert structural_image(["mean_ch1", "f0_net"], 1) is None - - -def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp() -> None: - """Shifts move every window alike (0). - - A local warp in one trial moves the window it covers and hardly the others. - """ - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - trials = np.arange(syn.N_TRIALS) - shape = (syn.H, syn.W) - m0 = window_motion(_shift_field(syn.SHIFTS), rs, valid, trials, shape) - np.testing.assert_allclose(m0, 0, atol=1e-12) - r0, c0 = syn.SOURCES[0] - tm = _shift_field(syn.SHIFTS, bump=(2, r0, c0, 0.8)) - m = window_motion(tm, rs, valid, trials, shape) - assert m[0] > 0.2 - assert m[1] < 0.05 * m[0] - # one trial's offset among four: the spread of (0, 0, a, 0) in rows - idx, w = rs.pixels(0) - w = w / w.sum() - rr, cc = np.divmod(idx, syn.W) - a = (0.8 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0)) @ w - assert m[0] == pytest.approx(np.std([0, 0, a, 0], ddof=1), rel=0.05) - - -def test_window_motion_of_affine_maps_ignores_the_index_base() -> None: - """A rotation moves windows away from the centre. - - The index base only moves the translation, which the column removes. - """ - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - T = 3 - aff = np.zeros((T, 2, 3)) - for t, ang in enumerate((0.0, 0.01, -0.01)): - c, s = np.cos(ang), np.sin(ang) - aff[t] = [[c, -s, 1.0], [s, c, -0.5]] - shifted = aff.copy() - shifted[:, :, 2] += aff[:, :, 0] + aff[:, :, 1] - 1 - shape = (syn.H, syn.W) - m = window_motion(TrialMap(aff), rs, valid, np.arange(T), shape) - m1 = window_motion(TrialMap(shifted), rs, valid, np.arange(T), shape) - assert (m > 0).all() - np.testing.assert_allclose(m, m1, atol=1e-9) - - -def test_window_motion_without_trials_or_pixels_is_nan() -> None: - """Fewer than two aligned trials, or no valid pixel, give NaN.""" - rs = sources_roiset(syn.footprints()) - valid = np.ones((syn.H, syn.W), bool) - shape = (syn.H, syn.W) - tm = _shift_field(syn.SHIFTS) - assert np.isnan(window_motion(tm, rs, valid, [1], shape)).all() - none = np.zeros_like(valid) - assert np.isnan(window_motion(tm, rs, none, [0, 1], shape)).all() - # a trial without a map is left out - tm.displacement[1] = np.nan - m = window_motion(tm, rs, valid, [0, 1, 2], shape) - np.testing.assert_allclose(m, 0, atol=1e-12) - - -def test_structural_change_is_the_step_beyond_the_trend_at_the_split() -> None: - """The structural channel's change at given splits. - - With its own shared trend removed, it is the mean after minus the mean - before. - """ - rng = np.random.default_rng(5) - T, n = 12, 20 - # a shared drift orthogonal to the planted step - step = (np.arange(T) >= 6) - 0.5 - drift = np.linspace(-0.1, 0.1, T) - drift -= (drift @ step) / (step @ step) * step - L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) - L[6:, 0] += 0.15 - L = L - L.mean(0) - ok = np.ones(n, bool) - ok[3] = False - L[2, 4] = np.nan - k = np.full(n, 6) - k[7] = 0 # no split - d = structural_change(L, ok, k) - use = ok & np.isfinite(L).all(0) - x = L[:, use].T - v, _ = shared_mode(x) - _, dd = step_at(x - np.outer(x @ v, v), k[use]) - np.testing.assert_allclose(d[use], dd) - assert np.isnan(d[3]) and np.isnan(d[4]) and np.isnan(d[7]) - assert d[0] == pytest.approx(0.15, abs=0.03) - # too few trials: nothing - assert np.isnan(structural_change(L[:2], ok, np.ones(n, int))).all() - - -def test_structural_change_centres_a_subset_of_trials() -> None: - """Over a subset of the trials the series are not centred. - - An offset per source must not take the place of the shared trend. - """ - rng = np.random.default_rng(8) - T, n = 12, 20 - step = (np.arange(T) >= 6) - 0.5 - drift = np.linspace(-0.1, 0.1, T) - drift -= (drift @ step) / (step @ step) * step - L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) - L[6:, 0] += 0.15 - L = L - L.mean(0) - ok = np.ones(n, bool) - k = np.full(n, 6) - offsets = rng.normal(size=n) * 0.5 - np.testing.assert_allclose( - structural_change(L + offsets, ok, k), - structural_change(L, ok, k), - atol=1e-12, - ) +"""Tests of the readout's quality columns and default image. + +The module under test is :mod:`giant_python.spine.qc`. +""" + +from collections.abc import Sequence + +import numpy as np +import pytest + +from giant_python.spine.qc import ( + primary_image, + structural_change, + structural_image, + window_motion, +) +from giant_python.spine.rois import sources_roiset +from giant_python.spine.summary_io import TrialMap +from giant_python.spine.trends import shared_mode, step_at + +from . import synthetic as syn + + +def _shift_field( + shifts: Sequence[Sequence[float]], bump: tuple[int, int, int, float] | None = None +) -> TrialMap: + """Build a displacement field per trial: the shifts everywhere, plus a bump. + + bump = (trial, row, col, amplitude): a Gaussian bump (sigma 2 px) of + extra row displacement. + + Returns + ------- + TrialMap + Identity affines with the per-trial displacement fields. + """ + T = len(shifts) + disp = np.broadcast_to(np.asarray(shifts, float)[:, :, None, None], (T, 2, syn.H, syn.W)).copy() + if bump is not None: + t, r0, c0, a = bump + rr, cc = np.mgrid[0 : syn.H, 0 : syn.W] + disp[t, 0] += a * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0) + eye = np.zeros((T, 2, 3)) + eye[:, :, :2] = np.eye(2) + return TrialMap(eye, disp) + + +def test_primary_and_structural_images() -> None: + """The default image and the structural image are chosen in order. + + The default image is f0_gain, then f0_net, then the run's own F0 and the + mean of the activity channel; the structural image is the first mean image + of another channel. + """ + names = ["mean_ch1", "mean_ch2", "f0_net", "f0_gain", "f0_silo_ch1"] + assert primary_image(names, 1) == "f0_gain" + assert primary_image(names[:3], 1) == "f0_net" + assert primary_image(["mean_ch1", "mean_ch2", "f0_silo_ch2"], 2) == ("f0_silo_ch2") + assert primary_image(["mean_ch1", "mean_ch2"], 2) == "mean_ch2" + assert primary_image(["f0_silo_ch1"], 2) is None + assert structural_image(names, 1) == "mean_ch2" + assert structural_image(names, 2) == "mean_ch1" + assert structural_image(["mean_ch3", "mean_ch2", "mean_ch1"], 1) == ("mean_ch2") + assert structural_image(["mean_ch1", "f0_net"], 1) is None + + +def test_window_motion_is_zero_for_shifts_and_finds_a_local_warp() -> None: + """Shifts move every window alike (0). + + A local warp in one trial moves the window it covers and hardly the others. + """ + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + trials = np.arange(syn.N_TRIALS) + shape = (syn.H, syn.W) + m0 = window_motion(_shift_field(syn.SHIFTS), rs, valid, trials, shape) + np.testing.assert_allclose(m0, 0, atol=1e-12) + r0, c0 = syn.SOURCES[0] + tm = _shift_field(syn.SHIFTS, bump=(2, r0, c0, 0.8)) + m = window_motion(tm, rs, valid, trials, shape) + assert m[0] > 0.2 + assert m[1] < 0.05 * m[0] + # one trial's offset among four: the spread of (0, 0, a, 0) in rows + idx, w = rs.pixels(0) + w = w / w.sum() + rr, cc = np.divmod(idx, syn.W) + a = (0.8 * np.exp(-((rr - r0) ** 2 + (cc - c0) ** 2) / 8.0)) @ w + assert m[0] == pytest.approx(np.std([0, 0, a, 0], ddof=1), rel=0.05) + + +def test_window_motion_of_affine_maps_ignores_the_index_base() -> None: + """A rotation moves windows away from the centre. + + The index base only moves the translation, which the column removes. + """ + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + T = 3 + aff = np.zeros((T, 2, 3)) + for t, ang in enumerate((0.0, 0.01, -0.01)): + c, s = np.cos(ang), np.sin(ang) + aff[t] = [[c, -s, 1.0], [s, c, -0.5]] + shifted = aff.copy() + shifted[:, :, 2] += aff[:, :, 0] + aff[:, :, 1] - 1 + shape = (syn.H, syn.W) + m = window_motion(TrialMap(aff), rs, valid, np.arange(T), shape) + m1 = window_motion(TrialMap(shifted), rs, valid, np.arange(T), shape) + assert (m > 0).all() + np.testing.assert_allclose(m, m1, atol=1e-9) + + +def test_window_motion_without_trials_or_pixels_is_nan() -> None: + """Fewer than two aligned trials, or no valid pixel, give NaN.""" + rs = sources_roiset(syn.footprints()) + valid = np.ones((syn.H, syn.W), bool) + shape = (syn.H, syn.W) + tm = _shift_field(syn.SHIFTS) + assert np.isnan(window_motion(tm, rs, valid, [1], shape)).all() + none = np.zeros_like(valid) + assert np.isnan(window_motion(tm, rs, none, [0, 1], shape)).all() + # a trial without a map is left out + tm.displacement[1] = np.nan + m = window_motion(tm, rs, valid, [0, 1, 2], shape) + np.testing.assert_allclose(m, 0, atol=1e-12) + + +def test_structural_change_is_the_step_beyond_the_trend_at_the_split() -> None: + """The structural channel's change at given splits. + + With its own shared trend removed, it is the mean after minus the mean + before. + """ + rng = np.random.default_rng(5) + T, n = 12, 20 + # a shared drift orthogonal to the planted step + step = (np.arange(T) >= 6) - 0.5 + drift = np.linspace(-0.1, 0.1, T) + drift -= (drift @ step) / (step @ step) * step + L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) + L[6:, 0] += 0.15 + L = L - L.mean(0) + ok = np.ones(n, bool) + ok[3] = False + L[2, 4] = np.nan + k = np.full(n, 6) + k[7] = 0 # no split + d = structural_change(L, ok, k) + use = ok & np.isfinite(L).all(0) + x = L[:, use].T + v, _ = shared_mode(x) + _, dd = step_at(x - np.outer(x @ v, v), k[use]) + np.testing.assert_allclose(d[use], dd) + assert np.isnan(d[3]) and np.isnan(d[4]) and np.isnan(d[7]) + assert d[0] == pytest.approx(0.15, abs=0.03) + # too few trials: nothing + assert np.isnan(structural_change(L[:2], ok, np.ones(n, int))).all() + + +def test_structural_change_centres_a_subset_of_trials() -> None: + """Over a subset of the trials the series are not centred. + + An offset per source must not take the place of the shared trend. + """ + rng = np.random.default_rng(8) + T, n = 12, 20 + step = (np.arange(T) >= 6) - 0.5 + drift = np.linspace(-0.1, 0.1, T) + drift -= (drift @ step) / (step @ step) * step + L = rng.normal(size=(T, n)) * 0.01 + drift[:, None] * rng.normal(size=n) + L[6:, 0] += 0.15 + L = L - L.mean(0) + ok = np.ones(n, bool) + k = np.full(n, 6) + offsets = rng.normal(size=n) * 0.5 + np.testing.assert_allclose( + structural_change(L + offsets, ok, k), + structural_change(L, ok, k), + atol=1e-12, + ) diff --git a/tests/spine/test_spine_readout.py b/tests/spine/test_spine_readout.py index 5e78f00d..47afb310 100644 --- a/tests/spine/test_spine_readout.py +++ b/tests/spine/test_spine_readout.py @@ -1,151 +1,151 @@ -"""Tests of the spine-size windows and readout. - -The modules tested are :mod:`giant_python.spine.rois` and -:mod:`giant_python.spine.readout`. -""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.spine.readout import ( - common_valid, - mask_mean, - norm_log, - project, -) -from giant_python.spine.rois import ( - disks_roiset, - masks_roiset, - nearest, - read_marks, - sources_roiset, - write_marks, -) - -from . import synthetic as syn - - -def test_sources_roiset_is_sparse_and_centred() -> None: - """Footprints are stored as their positive pixels, centroids weighted.""" - fp = syn.footprints() - rs = sources_roiset(fp) - assert len(rs) == len(syn.SOURCES) - for k, (r0, c0) in enumerate(syn.SOURCES): - np.testing.assert_allclose(rs.image(k), fp[k]) - assert abs(rs.rows[k] - r0) < 0.05 and abs(rs.cols[k] - c0) < 0.05 - idx, w = rs.pixels(k) - assert (w > 0).all() and idx.size == (fp[k] > 0).sum() - - -def test_masks_roiset_needs_one_label_per_mask() -> None: - """Labels and masks must agree in number.""" - with pytest.raises(ValueError, match="labels"): - masks_roiset(np.zeros((2, 4, 4), bool), ["a"]) - - -def test_project_is_the_matlab_formula() -> None: - """F = (h . x) / (h . h) with h normalized over the valid pixels.""" - rng = np.random.default_rng(2) - fp = syn.footprints() - imgs = 100 + rng.random((5, syn.H, syn.W)) - valid = np.ones((syn.H, syn.W), bool) - valid[8, 9] = False # the first source's peak pixel is left out - rs = sources_roiset(fp) - got, n_pix = project(imgs, rs, valid) - for k in range(len(rs)): - h = np.where(valid, fp[k], 0).ravel() - h = h / h.sum() - expect = imgs.reshape(5, -1) @ h / (h @ h) - np.testing.assert_allclose(got[:, k], expect) - assert n_pix[0] == (fp[0] > 0).sum() - 1 - - -def test_project_is_scale_equivariant() -> None: - """A uniform brightness change scales every readout by the same factor. - - So it cancels in the normalization. - """ - fp = syn.footprints() - img = syn.scene(1)[None] - rs = sources_roiset(fp) - valid = np.ones(img.shape[1:], bool) - a, _ = project(img, rs, valid) - b, _ = project(0.8 * img, rs, valid) - np.testing.assert_allclose(b, 0.8 * a) - - -def test_common_valid_requires_every_trial_and_stack() -> None: - """A pixel missing in one trial of one stack is not valid.""" - a = np.ones((3, 4, 5)) - b = np.ones((3, 4, 5)) - a[1, 0, 0] = np.nan - b[2, 3, 4] = np.nan - ok = common_valid([a, b], [0, 1, 2]) - assert not ok[0, 0] and not ok[3, 4] and ok.sum() == 18 - assert common_valid([a, b], [0])[0, 0] - # without trials nothing can be compared, so no pixel is valid - assert not common_valid([a, b], []).any() - - -def test_mask_mean_and_coverage() -> None: - """Mean over the mask's pixels with a value; coverage is their share.""" - masks = np.zeros((1, 4, 4), bool) - masks[0, :2, :2] = True - rs = masks_roiset(masks, ["r"]) - imgs = np.ones((2, 4, 4)) * np.array([1.0, 3.0])[:, None, None] - imgs[1, 0, 0] = np.nan - v, cov = mask_mean(imgs, rs) - np.testing.assert_allclose(v[:, 0], [1.0, 3.0]) - np.testing.assert_allclose(cov[:, 0], [1.0, 0.75]) - - -def test_norm_log_matches_spinetrends() -> None: - """Log F, minus each trial's median over the ok ROIs, minus each ROI's mean. - - This is normLog of spineTrends.m. - """ - rng = np.random.default_rng(3) - f = np.exp(rng.normal(size=(7, 9))) - ok = np.ones(9, bool) - ok[4] = False - lg = np.log(f) - expect = lg - np.median(lg[:, ok], axis=1, keepdims=True) - expect = expect - expect.mean(axis=0, keepdims=True) - np.testing.assert_allclose(norm_log(f, ok), expect) - - -def test_norm_log_removes_a_shared_trend() -> None: - """A brightness factor shared by all ROIs (bleaching) leaves zeros.""" - sizes = np.array([1.0, 2.0, 3.0]) - trend = np.array([1.0, 0.9, 0.8, 0.7]) - out = norm_log(trend[:, None] * sizes[None]) - np.testing.assert_allclose(out, 0, atol=1e-12) - - -def test_nearest_and_disks() -> None: - """Points find the nearest ROI within a distance.""" - rs = disks_roiset([5.0, 10.0], [5.0, 20.0], 2.0, (20, 30)) - assert rs.meta["radius"] == 2.0 - np.testing.assert_array_equal(nearest(rs, [5.5, 10.0, 0.0], [5.0, 21.0, 0.0], 2.5), [0, 1, -1]) - - -def test_marks_round_trip(tmp_path: Path) -> None: - """Marks keep GIAnT-MATLAB's spine_marks.csv columns.""" - marks = [ - { - "Path": 1, - "Source": 59, - "Label": "Growing", - "Note": "", - "Row0": 72.5, - "Col0": 585.45, - "Updated": "2026-10-30 15:54:36", - } - ] - path = tmp_path / "spine_marks.csv" - write_marks(path, marks) - back = read_marks(path) - assert back[0]["Path"] == 1 and back[0]["Label"] == "Growing" - assert back[0]["Row0"] == pytest.approx(72.5) +"""Tests of the spine-size windows and readout. + +The modules tested are :mod:`giant_python.spine.rois` and +:mod:`giant_python.spine.readout`. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.spine.readout import ( + common_valid, + mask_mean, + norm_log, + project, +) +from giant_python.spine.rois import ( + disks_roiset, + masks_roiset, + nearest, + read_marks, + sources_roiset, + write_marks, +) + +from . import synthetic as syn + + +def test_sources_roiset_is_sparse_and_centred() -> None: + """Footprints are stored as their positive pixels, centroids weighted.""" + fp = syn.footprints() + rs = sources_roiset(fp) + assert len(rs) == len(syn.SOURCES) + for k, (r0, c0) in enumerate(syn.SOURCES): + np.testing.assert_allclose(rs.image(k), fp[k]) + assert abs(rs.rows[k] - r0) < 0.05 and abs(rs.cols[k] - c0) < 0.05 + idx, w = rs.pixels(k) + assert (w > 0).all() and idx.size == (fp[k] > 0).sum() + + +def test_masks_roiset_needs_one_label_per_mask() -> None: + """Labels and masks must agree in number.""" + with pytest.raises(ValueError, match="labels"): + masks_roiset(np.zeros((2, 4, 4), bool), ["a"]) + + +def test_project_is_the_matlab_formula() -> None: + """F = (h . x) / (h . h) with h normalized over the valid pixels.""" + rng = np.random.default_rng(2) + fp = syn.footprints() + imgs = 100 + rng.random((5, syn.H, syn.W)) + valid = np.ones((syn.H, syn.W), bool) + valid[8, 9] = False # the first source's peak pixel is left out + rs = sources_roiset(fp) + got, n_pix = project(imgs, rs, valid) + for k in range(len(rs)): + h = np.where(valid, fp[k], 0).ravel() + h = h / h.sum() + expect = imgs.reshape(5, -1) @ h / (h @ h) + np.testing.assert_allclose(got[:, k], expect) + assert n_pix[0] == (fp[0] > 0).sum() - 1 + + +def test_project_is_scale_equivariant() -> None: + """A uniform brightness change scales every readout by the same factor. + + So it cancels in the normalization. + """ + fp = syn.footprints() + img = syn.scene(1)[None] + rs = sources_roiset(fp) + valid = np.ones(img.shape[1:], bool) + a, _ = project(img, rs, valid) + b, _ = project(0.8 * img, rs, valid) + np.testing.assert_allclose(b, 0.8 * a) + + +def test_common_valid_requires_every_trial_and_stack() -> None: + """A pixel missing in one trial of one stack is not valid.""" + a = np.ones((3, 4, 5)) + b = np.ones((3, 4, 5)) + a[1, 0, 0] = np.nan + b[2, 3, 4] = np.nan + ok = common_valid([a, b], [0, 1, 2]) + assert not ok[0, 0] and not ok[3, 4] and ok.sum() == 18 + assert common_valid([a, b], [0])[0, 0] + # without trials nothing can be compared, so no pixel is valid + assert not common_valid([a, b], []).any() + + +def test_mask_mean_and_coverage() -> None: + """Mean over the mask's pixels with a value; coverage is their share.""" + masks = np.zeros((1, 4, 4), bool) + masks[0, :2, :2] = True + rs = masks_roiset(masks, ["r"]) + imgs = np.ones((2, 4, 4)) * np.array([1.0, 3.0])[:, None, None] + imgs[1, 0, 0] = np.nan + v, cov = mask_mean(imgs, rs) + np.testing.assert_allclose(v[:, 0], [1.0, 3.0]) + np.testing.assert_allclose(cov[:, 0], [1.0, 0.75]) + + +def test_norm_log_matches_spinetrends() -> None: + """Log F, minus each trial's median over the ok ROIs, minus each ROI's mean. + + This is normLog of spineTrends.m. + """ + rng = np.random.default_rng(3) + f = np.exp(rng.normal(size=(7, 9))) + ok = np.ones(9, bool) + ok[4] = False + lg = np.log(f) + expect = lg - np.median(lg[:, ok], axis=1, keepdims=True) + expect = expect - expect.mean(axis=0, keepdims=True) + np.testing.assert_allclose(norm_log(f, ok), expect) + + +def test_norm_log_removes_a_shared_trend() -> None: + """A brightness factor shared by all ROIs (bleaching) leaves zeros.""" + sizes = np.array([1.0, 2.0, 3.0]) + trend = np.array([1.0, 0.9, 0.8, 0.7]) + out = norm_log(trend[:, None] * sizes[None]) + np.testing.assert_allclose(out, 0, atol=1e-12) + + +def test_nearest_and_disks() -> None: + """Points find the nearest ROI within a distance.""" + rs = disks_roiset([5.0, 10.0], [5.0, 20.0], 2.0, (20, 30)) + assert rs.meta["radius"] == 2.0 + np.testing.assert_array_equal(nearest(rs, [5.5, 10.0, 0.0], [5.0, 21.0, 0.0], 2.5), [0, 1, -1]) + + +def test_marks_round_trip(tmp_path: Path) -> None: + """Marks keep GIAnT-MATLAB's spine_marks.csv columns.""" + marks = [ + { + "Path": 1, + "Source": 59, + "Label": "Growing", + "Note": "", + "Row0": 72.5, + "Col0": 585.45, + "Updated": "2026-10-30 15:54:36", + } + ] + path = tmp_path / "spine_marks.csv" + write_marks(path, marks) + back = read_marks(path) + assert back[0]["Path"] == 1 and back[0]["Label"] == "Growing" + assert back[0]["Row0"] == pytest.approx(72.5) diff --git a/tests/spine/test_spine_view.py b/tests/spine/test_spine_view.py index 740aaf91..b43af805 100644 --- a/tests/spine/test_spine_view.py +++ b/tests/spine/test_spine_view.py @@ -1,842 +1,842 @@ -"""Tests of the spine viewer's data, API and HTML export. - -The viewer is :mod:`giant_python.spine.view`; the tests run on a synthetic -session. -""" - -import base64 -import gzip -import json -import re -import threading -import urllib.request -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.cli import main -from giant_python.spine.pipeline import make_spine_summary -from giant_python.spine.product import read_product -from giant_python.spine.rois import read_marks -from giant_python.spine.view.data import ( - SpineStore, - blur_nan, - late_trials, - robust_z, -) -from giant_python.spine.view.export import export_html, field_key, pack -from giant_python.spine.view.server import make_server - -from . import synthetic as syn - - -@pytest.fixture -def product(tmp_path: Path) -> str: - """Make a synthetic session's spine summary (with network images). - - Returns - ------- - str - Path of the spine summary file. - """ - s = syn.make_session(tmp_path) - rep = make_spine_summary( - s["run"], - s["table"], - tmp_path / "out", - baseline_dir=s["baselines"], - moco_dir=s["moco"], - trim_s=0.1, - n_perm=100, - ) - return rep["output"] - - -def test_blur_nan_ignores_nan() -> None: - """NaN stays NaN and does not pull its neighbours down.""" - img = np.ones((9, 9), np.float32) - img[4, 4] = np.nan - out = blur_nan(img) - assert np.isnan(out[4, 4]) - np.testing.assert_allclose(out[np.isfinite(out)], 1.0, rtol=1e-6) - - -def test_robust_z_and_late_trials() -> None: - """Median and MAD z-scores. - - Late trials are the last block, or the second half of one block. - """ - z = robust_z(np.array([[0.0, 1.0, 2.0, np.nan]])) - assert z[0, 1] == 0 and np.isnan(z[0, 3]) - np.testing.assert_array_equal(late_trials([0, 0, 1, 1, 1]), [0, 0, 1, 1, 1]) - np.testing.assert_array_equal(late_trials([0, 0, 0, 0]), [0, 0, 1, 1]) - - -def test_normalized_field_and_change(product: str) -> None: - """Each trial is divided by its median over the common pixels. - - The change view compares blurred trials, with a brightness in [0, 1]. - """ - store = SpineStore([(None, product)]) - pr = store.products[0] - stack = read_product(product)["paths"][1]["images"]["mean_ch1"] - nz = pr.normalized(1, "mean_ch1") - common = np.isfinite(stack).all(axis=0) - for t in range(stack.shape[0]): - med = np.median(stack[t][common]) - np.testing.assert_allclose(nz["stack"][t], stack[t] / med, rtol=1e-6) - np.testing.assert_allclose( - pr.field(1, "mean_ch1", -1, "image", "")[0], - np.nanmean(nz["stack"], axis=0), - rtol=1e-6, - ) - ch = pr.field(1, "mean_ch1", 2, "change", "average") - assert ch.shape == (2,) + stack.shape[1:] - b = ch[1] - assert np.nanmin(b) >= 0 and np.nanmax(b) <= 1 - cp = pr.change_prep(1, "mean_ch1") - expect = cp["blurred"][2] / cp["mean"] - 1 - np.testing.assert_allclose(ch[0], expect, rtol=1e-5, equal_nan=True) - prev = pr.field(1, "mean_ch1", 2, "change", "previous")[0] - np.testing.assert_allclose( - prev, - cp["blurred"][2] / cp["blurred"][1] - 1, - rtol=1e-5, - equal_nan=True, - ) - # the first trial of a block has no previous trial - assert np.isnan(pr.field(1, "mean_ch1", 0, "change", "previous")[0]).all() - act = pr.field(1, "", -1, "activity", "") - assert act.shape == (1,) + stack.shape[1:] - - -def test_store_sources_roi_and_crops(product: str) -> None: - """Sources carry sizes and trends. - - A window and its crops sit on the same grid around the source. - """ - store = SpineStore([("syn", product)], crop_half=4) - meta = store.meta() - p1 = meta["products"][0]["paths"][1] - assert meta["products"][0]["name"] == "syn" - assert "f0_net" in p1["trends"] and p1["n_sources"] == len(syn.SOURCES) - src = store.sources(0, 1) - prod = read_product(product)["paths"][1] - np.testing.assert_allclose( - np.array(src["normalized"]["f0_net"], float), - prod["normalized"]["sources"]["f0_net"], - ) - assert src["trends"]["f0_net"]["attrs"]["n_perm"] == 100 - roi = store.roi(0, 1, 0) - assert roi["size"] == 9 and np.array(roi["weights"]).shape == (9, 9) - r0, c0 = roi["origin"] - w = prod["rois"]["sources"].image(0) - np.testing.assert_allclose(np.array(roi["weights"]), w[r0 : r0 + 9, c0 : c0 + 9], atol=1e-6) - crops = store.crops(0, 1, 0, "mean_ch1", "image", "average") - n_t = len(prod["trials"]["acquisition"]) - assert crops.shape == (1, n_t + 1, 9, 9) - full = store.products[0].normalized(1, "mean_ch1")["stack"] - np.testing.assert_allclose(crops[0, 1:], full[:, r0 : r0 + 9, c0 : c0 + 9], rtol=1e-6) - ch = store.crops(0, 1, 0, "mean_ch1", "change", "average") - assert ch.shape == (2, n_t + 1, 9, 9) - - -def test_marks_attach_by_position(product: str, tmp_path: Path) -> None: - """A mark is stored with its source's position. - - It attaches to the nearest source within 2.5 px; clearing removes it. - """ - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - got = store.set_mark(0, 1, 1, "Growing", "a note") - assert got["by_source"][1]["label"] == "Growing" - rows = read_marks(marks) - assert rows[0]["Source"] == "2" and rows[0]["Note"] == "a note" - rs = read_product(product)["paths"][1]["rois"]["sources"] - assert rows[0]["Row0"] == pytest.approx(rs.rows[1]) - # a second mark on the same source replaces the first - store.set_mark(0, 1, 1, "Shrinking", "") - assert len(read_marks(marks)) == 1 - assert store.marks_for(0, 1)["by_source"][1]["label"] == "Shrinking" - # a mark far from every source does not attach - rows = read_marks(marks) + [dict(rows[0], Row0=0.0, Col0=0.0, Label="Unsure")] - from giant_python.spine.rois import write_marks - - write_marks(marks, rows) - assert store.marks_for(0, 1)["unattached"] == 1 - store.set_mark(0, 1, 1, "", "") - assert 1 not in store.marks_for(0, 1)["by_source"] - with pytest.raises(ValueError, match="unknown mark"): - store.set_mark(0, 1, 1, "Big", "") - - -def test_product_is_read_again_when_it_changes(product: str, tmp_path: Path) -> None: - """A rewritten product shows on the next request.""" - import os - import shutil - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - store = SpineStore([(None, copy)]) - first = store.sources(0, 1)["normalized"]["f0_net"] - import h5py - - with h5py.File(copy, "r+") as f: - d = f["Path1/normalized/sources/f0_net"] - d[...] = d[()] + 1 - st = os.stat(copy) - os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - again = store.sources(0, 1)["normalized"]["f0_net"] - a = np.array(first, float) - np.testing.assert_allclose(np.array(again, float), a + 1) - - -def _get(url: str) -> dict | np.ndarray: - """GET and decode JSON or float32. - - Returns - ------- - dict or np.ndarray - The parsed JSON for a JSON response, else the float32 array shaped by X-Shape. - """ - with urllib.request.urlopen(url) as r: - body = r.read() - if r.headers.get("Content-Type") == "application/json": - return json.loads(body) - shape = json.loads(r.headers["X-Shape"]) - return np.frombuffer(body, np.float32).reshape(shape) - - -def test_server_answers_the_api(product: str, tmp_path: Path) -> None: - """The page and every API route answer; a mark is written by POST.""" - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - base = f"http://127.0.0.1:{srv.server_address[1]}" - try: - with urllib.request.urlopen(base + "/") as r: - assert b"Spine size viewer" in r.read() - meta = _get(base + "/api/meta") - assert meta["products"][0]["paths"]["1"]["n_sources"] == 3 - src = _get(base + "/api/sources?prod=0&path=1") - assert src["n"] == 3 - f = _get(base + "/api/field?prod=0&path=1&image=f0_net&trial=1") - assert f.shape == (1, syn.H, syn.W) - c = _get(base + "/api/crops?prod=0&path=1&id=0&image=f0_net&view=change") - assert c.shape[0] == 2 - roi = _get(base + "/api/roi?prod=0&path=1&id=2") - assert roi["id"] == 2 - req = urllib.request.Request( - base + "/api/mark", - data=json.dumps({"prod": 0, "path": 1, "id": 0, "label": "Unsure"}).encode(), - headers={"Content-Type": "application/json"}, - ) - with urllib.request.urlopen(req) as r: - assert json.loads(r.read())["by_source"]["0"]["label"] == "Unsure" - assert read_marks(marks)[0]["Label"] == "Unsure" - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(base + "/api/field?prod=0&path=7&image=x") - assert e.value.code == 404 - finally: - srv.shutdown() - srv.server_close() - - -def _static(page: str) -> dict: - """Extract the data embedded in an exported page. - - Returns - ------- - dict - The page's decoded static data. - """ - m = re.search( - r'", - page, - ) - return json.loads(gzip.decompress(base64.b64decode(m.group(1)))) - - -def _unpack(e: dict) -> np.ndarray: - """Decode an embedded array (as the page's unpack). - - Returns - ------- - np.ndarray - The decoded layers (NaN where the code is 255), shaped as e["shape"]. - """ - parts = [] - for layer in e["layers"]: - q = np.frombuffer(base64.b64decode(layer["b64"]), np.uint8) - v = layer["offset"] + layer["scale"] * q.astype(np.float64) - parts.append(np.where(q == 255, np.nan, v)) - return np.concatenate(parts).reshape(e["shape"]) - - -def test_pack_round_trips_within_a_code() -> None: - """uint8 codes keep values within half a step and NaN as NaN.""" - rng = np.random.default_rng(0) - a = rng.normal(1, 0.1, (1, 20, 30)).astype(np.float32) - a[0, 3, 4] = np.nan - e = pack(a, "image") - back = _unpack(e) - assert np.isnan(back[0, 3, 4]) - step = e["layers"][0]["scale"] - inside = np.isfinite(a) & (a >= e["layers"][0]["offset"]) - inside &= a <= e["layers"][0]["offset"] + 254 * step - np.testing.assert_allclose(back[inside], a[inside], atol=step / 2 + 1e-7) - ch = np.stack([np.full((4, 4), 0.1), np.full((4, 4), 0.5)]) - back = _unpack(pack(ch, "change")) - np.testing.assert_allclose(back, ch, atol=0.003) - - -def test_export_html_embeds_the_viewer_data(product: str, tmp_path: Path) -> None: - """The page holds the meta, the sources, the mean fields and some crops. - - The crops are those of the chosen sources; the page holds nothing that - needs the server. - """ - out = tmp_path / "page.html" - rep = export_html(product, out, sources=[2], name="syn") - page = out.read_text(encoding="utf-8") - assert "Spine sizes syn" in page - data = _static(page) - assert data["meta"]["marks_file"] is None - assert data["sources"]["1"]["n"] == 3 - key = field_key(1, "f0_net", -1, "image", "") - assert key in data["fields"] - assert field_key(1, "f0_net", -1, "change", "") in data["fields"] - assert rep["sources"][1] == [2] - assert "1|1" in data["rois"] and "1|0" not in data["rois"] - crop_keys = [k for k in data["crops"] if k.startswith("1|1|")] - assert crop_keys and all("f0_" in k for k in crop_keys) - store = SpineStore([(None, product)]) - mean = store.products[0].field(1, "f0_net", -1, "image", "") - e = data["fields"][key] - back = _unpack(e) - fin = np.isfinite(mean) - step = e["layers"][0]["scale"] - lo = e["layers"][0]["offset"] - inside = fin & (mean >= lo) & (mean <= lo + 254 * step) - np.testing.assert_allclose(back[inside], mean[inside], atol=step) - - -def test_cli_export(product: str, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """Giant spine export-html writes the page and reports it.""" - out = tmp_path / "e.html" - assert main(["spine", "export-html", product, "--out", str(out), "--top", "1"]) == 0 - rep = json.loads(capsys.readouterr().out) - assert rep["output"] == str(out) and out.is_file() - - -def test_pick_sources_marked_first_then_by_q_and_size() -> None: - """The export's crops go to the marked sources, then by q. - - Ties at the permutation floor go to the larger statistic. - """ - from giant_python.spine.view.export import pick_sources - - nan = float("nan") - tr = { - "step_q": [0.5, 1e-4, 1e-4, nan, 0.02], - "step_t": [1.0, 3.0, 6.0, nan, 2.5], - "brief_q": [0.9, 0.9, 0.9, nan, 0.9], - "brief_t": [1.0, 1.0, 1.0, nan, 1.0], - "resid_q": [0.04, 0.9, 0.9, nan, 0.9], - "resid_t": [2.0, 1.0, 1.0, nan, 1.0], - } - src = {"n": 5, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} - assert pick_sources(src, "f0", 3) == [0, 2, 1, 4] - assert pick_sources(src, "f0", 0) == [0] - - -def test_marks_need_json_from_this_server(product: str, tmp_path: Path) -> None: - """The mark endpoint refuses bodies that are not JSON and foreign origins. - - Bodies that are not JSON could be sent by a cross-origin page without a - preflight; requests whose Origin is another site are refused too. - """ - marks = tmp_path / "marks.csv" - store = SpineStore([(None, product)], marks) - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - base = f"http://127.0.0.1:{srv.server_address[1]}" - body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() - try: - for headers, code in ( - ({"Content-Type": "text/plain"}, 415), - ( - { - "Content-Type": "application/json", - "Origin": "http://example.com", - }, - 403, - ), - ): - req = urllib.request.Request(base + "/api/mark", data=body, headers=headers) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == code - assert not marks.exists() - req = urllib.request.Request( - base + "/api/mark", - data=body, - headers={"Content-Type": "application/json", "Origin": base}, - ) - with urllib.request.urlopen(req) as r: - assert r.status == 200 - assert read_marks(marks)[0]["Label"] == "Unsure" - finally: - srv.shutdown() - srv.server_close() - - -def test_sources_without_sources_keep_the_fields(product: str, tmp_path: Path) -> None: - """A path without sources answers with the same, empty, fields.""" - store = SpineStore([(None, product)]) - pr = store.products[0] - pr.small()["paths"][1]["rois"].pop("sources") - src = store.sources(0, 1) - assert src["n"] == 0 and src["trends"] == {} and src["ids"] == [] - assert src["marks"] == {"by_source": {}, "unattached": 0} - - -def test_cache_keys_follow_the_file(product: str, tmp_path: Path) -> None: - """A result made from the old file is not served after the file changes. - - Even if it lands in the cache after the reload. - """ - import os - import shutil - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - store = SpineStore([(None, copy)]) - pr = store.products[0] - old = pr.normalized(1, "mean_ch1") - gen = pr._gen - st = os.stat(copy) - os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) - pr.small() - assert pr._gen == gen + 1 - # a late insert under the old generation's key is never read - pr._cache.get((gen, "norm", 1, "mean_ch1"), lambda: "stale") - new = pr.normalized(1, "mean_ch1") - assert new is not old and not isinstance(new, str) - - -def test_server_refuses_untrusted_hosts(product: str, tmp_path: Path) -> None: - """Requests naming another host (DNS rebinding) get nothing. - - Marks from an origin that is not this server's trusted names are refused. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - srv = make_server(store, port=0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - port = srv.server_address[1] - base = f"http://127.0.0.1:{port}" - try: - req = urllib.request.Request(base + "/api/meta", headers={"Host": f"evil.example:{port}"}) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == 403 - req = urllib.request.Request(base + "/api/meta", headers={"Host": f"localhost:{port}"}) - with urllib.request.urlopen(req) as r: - assert r.status == 200 - body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() - for origin in ( - f"http://evil.example:{port}", - f"https://127.0.0.1:{port}", - ): - req = urllib.request.Request( - base + "/api/mark", - data=body, - headers={ - "Content-Type": "application/json", - "Origin": origin, - "Host": f"127.0.0.1:{port}", - }, - ) - with pytest.raises(urllib.error.HTTPError) as e: - urllib.request.urlopen(req) - assert e.value.code == 403 - finally: - srv.shutdown() - srv.server_close() - - -def test_export_refuses_unknown_paths(product: str, tmp_path: Path) -> None: - """Asking for a path the summary does not have is an error. - - Not an empty page. - """ - with pytest.raises(ValueError, match="no path"): - export_html(product, tmp_path / "p.html", paths=[7]) - assert not (tmp_path / "p.html").exists() - - -def test_pick_sources_uses_the_strongest_test_at_the_smallest_q() -> None: - """Among tests tied at a source's smallest q, the largest statistic wins. - - It breaks ties between sources. - """ - from giant_python.spine.view.export import pick_sources - - tr = { - "step_q": [1e-3, 1e-3], - "step_t": [2.0, 6.0], - "brief_q": [1e-3, 0.5], - "brief_t": [20.0, 1.0], - "resid_q": [0.9, 0.9], - "resid_t": [1.0, 1.0], - } - src = {"n": 2, "trends": {"f0": tr}, "marks": {}} - assert pick_sources(src, "f0", 1) == [0] - - -def test_marks_keep_their_order_within_a_path(product: str, tmp_path: Path) -> None: - """Two marks with the same time that land on one source. - - The one written later wins, whatever their rows. - """ - from giant_python.spine.rois import write_marks - - store = SpineStore([(None, product)], tmp_path / "marks.csv") - rs = read_product(product)["paths"][1]["rois"]["sources"] - r, c = float(rs.rows[0]), float(rs.cols[0]) - base = { - "Path": 1, - "Source": 1, - "Note": "", - "Col0": c, - "Updated": "2026-01-01 00:00:00", - } - write_marks( - tmp_path / "marks.csv", - [ - dict(base, Label="Growing", Row0=r + 0.5), - dict(base, Label="Shrinking", Row0=r - 0.5), - ], - ) - assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" - # a write through the store keeps the order within the path - store.set_mark(0, 1, 1, "Unsure", "") - rows = read_marks(tmp_path / "marks.csv") - assert [m["Label"] for m in rows] == ["Growing", "Shrinking", "Unsure"] - assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" - - -def test_pick_sources_keeps_infinite_statistics_first() -> None: - """An infinite statistic (a change without noise) ranks first. - - Among equal q-values. - """ - from giant_python.spine.view.export import pick_sources - - inf = float("inf") - tr = {f"{t}_{f}": [None, None] for t in ("brief", "resid") for f in ("q", "t")} - tr.update({"step_q": [1e-4, 1e-4], "step_t": [6.0, inf]}) - src = {"n": 2, "trends": {"f0": tr}, "marks": {}} - assert pick_sources(src, "f0", 1) == [1] - - -def test_summary_without_rois_loads(product: str, tmp_path: Path) -> None: - """A summary with no sources and no user ROIs (no rois group) loads.""" - import shutil - - import h5py - - copy = tmp_path / "copy.h5" - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - for n in ("Path1", "Path2"): - if f"{n}/rois" in f: - del f[f"{n}/rois"] - store = SpineStore([(None, copy)]) - assert store.sources(0, 1)["n"] == 0 - assert store.meta()["products"][0]["paths"][1]["n_sources"] == 0 - - -def test_server_on_ipv6_loopback_and_port_80_names(product: str) -> None: - """The server binds an IPv6 literal, and at port 80 trusts portless names. - - Those are the names without a port, as browsers send them. - """ - import socket as so - - from giant_python.spine.view.server import _bracket, allowed_hosts - - assert _bracket("::1") == "[::1]" and _bracket("localhost") == "localhost" - at80 = allowed_hosts("127.0.0.1", 80) - assert "127.0.0.1" in at80 and "localhost:80" in at80 - assert "127.0.0.1" not in allowed_hosts("127.0.0.1", 8790) - assert allowed_hosts("0.0.0.0", 8790) == frozenset() - if not so.has_ipv6: - pytest.skip("no IPv6") - store = SpineStore([(None, product)]) - try: - srv = make_server(store, host="::1", port=0) - except OSError: - pytest.skip("no IPv6 loopback") - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - port = srv.server_address[1] - try: - assert f"[::1]:{port}" in srv.RequestHandlerClass.allowed - with urllib.request.urlopen(f"http://[::1]:{port}/api/meta") as r: - assert r.status == 200 - finally: - srv.shutdown() - srv.server_close() - - -def test_a_note_alone_keeps_the_label(product: str, tmp_path: Path) -> None: - """A note saved on its own keeps the label the source has at that moment. - - Unsure without one. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - got = store.set_mark(0, 1, 0, None, "first note") - assert got["by_source"][0]["label"] == "Unsure" - store.set_mark(0, 1, 0, "Growing", "first note") - got = store.set_mark(0, 1, 0, None, "second note") - assert got["by_source"][0] == { - "label": "Growing", - "note": "second note", - "updated": got["by_source"][0]["updated"], - } - assert len(read_marks(tmp_path / "marks.csv")) == 1 - - -def test_export_refuses_unknown_sources_and_images(product: str, tmp_path: Path) -> None: - """Source numbers and crop images the summary lacks are errors.""" - with pytest.raises(ValueError, match="no source"): - export_html(product, tmp_path / "p.html", sources=[99]) - with pytest.raises(ValueError, match="no image"): - export_html(product, tmp_path / "p.html", crop_images=["f0_nope"]) - assert not (tmp_path / "p.html").exists() - - -def test_export_crops_only_the_images_asked_for(product: str, tmp_path: Path) -> None: - """With --crop-images, a path that lacks them gets no crops. - - Rather than every image. - """ - import h5py - - out = tmp_path / "p.html" - copy = tmp_path / "copy.h5" - import shutil - - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - del f["Path2/images/f0_net"] - export_html(copy, out, sources=[1], crop_images=["f0_net"]) - data = _static(out.read_text(encoding="utf-8")) - assert any(k.startswith("1|0|f0_net|") for k in data["crops"]) - assert not [k for k in data["crops"] if k.startswith("2|")] - - -def test_cache_makes_a_value_once_for_concurrent_requests() -> None: - """Concurrent requests for a value being made wait for it. - - Instead of making it again. - """ - import time as _t - - from giant_python.spine.view.data import _Lru - - cache = _Lru(4) - calls = [] - - def make() -> str: - """Make a slow value. - - Returns - ------- - str - The value, "v". - """ - calls.append(1) - _t.sleep(0.2) - return "v" - - out = [] - ths = [threading.Thread(target=lambda: out.append(cache.get("k", make))) for _ in range(5)] - for th in ths: - th.start() - for th in ths: - th.join() - assert out == ["v"] * 5 and len(calls) == 1 - assert cache.making == {} - - -def test_cache_is_bounded_by_bytes() -> None: - """Values are evicted, oldest first, once their arrays exceed the budget. - - The newest stays even when it alone is larger. - """ - from giant_python.spine.view.data import _Lru - - cache = _Lru(3000) - for k in range(4): - cache.get(k, lambda: {"a": np.zeros(125)}) # 1000 bytes each - assert list(cache.d) == [1, 2, 3] - cache.get("big", lambda: np.zeros(1000)) - assert list(cache.d) == ["big"] - - -def test_cache_lock_stays_while_requests_wait() -> None: - """The lock of a key being made stays while any request still uses it. - - Even if the value is evicted meanwhile: a later request for the key waits - on the same lock instead of computing in parallel. - """ - import time as _t - - from giant_python.spine.view.data import _Lru - - cache = _Lru(1) # every new value evicts the previous one - running = [] - peak = [] - - def make() -> np.ndarray: - """Make a slow value that records how many are being made at once. - - Returns - ------- - np.ndarray - A zero array of 10 values. - """ - running.append(1) - peak.append(len(running)) - _t.sleep(0.05) - running.pop() - return np.zeros(10) - - def worker() -> None: - """Ask for the key, then for another (evicting it).""" - cache.get("k", make) - cache.get(object(), lambda: np.zeros(10)) - - ths = [threading.Thread(target=worker) for _ in range(6)] - for th in ths: - th.start() - for th in ths: - th.join() - assert max(peak) == 1 - assert cache.making == {} - - -def test_mark_refused_when_the_source_moved(product: str, tmp_path: Path) -> None: - """A mark that names a position other than the source's is refused. - - The summary changed under an open page; the mark writes nothing. - """ - store = SpineStore([(None, product)], tmp_path / "marks.csv") - rs = read_product(product)["paths"][1]["rois"]["sources"] - with pytest.raises(ValueError, match="changed"): - store.set_mark(0, 1, 1, "Growing", "", row=0.0, col=0.0) - assert not (tmp_path / "marks.csv").exists() - got = store.set_mark(0, 1, 1, "Growing", "", row=float(rs.rows[1]), col=float(rs.cols[1])) - assert got["by_source"][1]["label"] == "Growing" - - -def test_change_needs_only_its_own_cache_entry(product: str) -> None: - """change() reads everything it needs from the change record. - - So it does not reload the normalized stack (no thrashing when the two do - not fit together in the cache). - """ - store = SpineStore([(None, product)]) - pr = store.products[0] - pr.change_prep(1, "mean_ch1") - calls = [] - real = pr.normalized - pr.normalized = lambda *a: calls.append(a) or real(*a) - for t in (-1, 0, 2): - pr.change(1, "mean_ch1", t, "average") - assert calls == [] - - -def test_default_image_calls_and_window_motion_reach_the_page(product: str) -> None: - """The page gets the default image, the calls and the windows' motion. - - That is, the summary's default image, the calls and structural change of - each image's tests, and the windows' motion. - """ - store = SpineStore([(None, product)]) - p1 = store.meta()["products"][0]["paths"][1] - assert p1["primary_image"] == "f0_net" - src = store.sources(0, 1) - assert len(src["align_px"]) == src["n"] - assert src["trends"]["f0_net"]["attrs"]["structural_image"] == "mean_ch2" - assert len(src["trends"]["f0_net"]["call"]) == src["n"] - assert len(src["trends"]["f0_net"]["structural_d"]) == src["n"] - from importlib.resources import files - - page = files("giant_python.spine.view").joinpath("page.html").read_text(encoding="utf-8") - for key in ('["call", "call"]', '"structural_d"', '"align_px"'): - assert key in page - - -def test_summaries_before_format_4_still_load(product: str, tmp_path: Path) -> None: - """Summaries before format 4 still load. - - Without the default image, the calls or the window motion (format 3), the - page gets None for the image and NaN (null) motion. - """ - import shutil - - import h5py - - copy = tmp_path / "v3.h5" - shutil.copy(product, copy) - with h5py.File(copy, "r+") as f: - for n in ("Path1", "Path2"): - g = f[n] - del g.attrs["primary_image"] - del g["readout/sources/align_px"] - for name in g["trends/sources"]: - t = g[f"trends/sources/{name}"] - for k in ("call", "structural_d"): - if k in t: - del t[k] - store = SpineStore([(None, copy)]) - assert store.meta()["products"][0]["paths"][1]["primary_image"] is None - src = store.sources(0, 1) - assert np.isnan(np.array(src["align_px"], float)).all() - assert "call" not in src["trends"]["f0_net"] - assert read_product(copy)["paths"][1]["primary_image"] is None - - -def test_pick_sources_takes_the_calls_first() -> None: - """The export's crops go to the marked sources, then to the calls. - - The calls are taken by q, then the rest by the smallest q. - """ - from giant_python.spine.view.export import pick_sources, primary_image - - tr = { - "step_q": [0.5, 1e-4, 0.2, 0.9], - "step_t": [1.0, 6.0, 2.0, 1.0], - "brief_q": [0.9, 0.9, 0.9, 0.9], - "brief_t": [1.0, 1.0, 1.0, 1.0], - "resid_q": [0.9, 0.9, 0.05, 0.01], - "resid_t": [1.0, 1.0, 3.0, 4.0], - "call": [False, False, True, True], - } - src = {"n": 4, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} - assert pick_sources(src, "f0", 3) == [0, 3, 2, 1] - # a marked call does not take one of the top places - src["marks"] = {"by_source": {"3": {}}} - assert pick_sources(src, "f0", 1) == [3, 2] - assert primary_image(["f0_net", "f0_gain"], "f0_net") == "f0_net" - assert primary_image(["f0_net", "f0_gain"], "gone") == "f0_gain" - assert primary_image(["f0_net", "f0_gain"]) == "f0_gain" +"""Tests of the spine viewer's data, API and HTML export. + +The viewer is :mod:`giant_python.spine.view`; the tests run on a synthetic +session. +""" + +import base64 +import gzip +import json +import re +import threading +import urllib.request +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.cli import main +from giant_python.spine.pipeline import make_spine_summary +from giant_python.spine.product import read_product +from giant_python.spine.rois import read_marks +from giant_python.spine.view.data import ( + SpineStore, + blur_nan, + late_trials, + robust_z, +) +from giant_python.spine.view.export import export_html, field_key, pack +from giant_python.spine.view.server import make_server + +from . import synthetic as syn + + +@pytest.fixture +def product(tmp_path: Path) -> str: + """Make a synthetic session's spine summary (with network images). + + Returns + ------- + str + Path of the spine summary file. + """ + s = syn.make_session(tmp_path) + rep = make_spine_summary( + s["run"], + s["table"], + tmp_path / "out", + baseline_dir=s["baselines"], + moco_dir=s["moco"], + trim_s=0.1, + n_perm=100, + ) + return rep["output"] + + +def test_blur_nan_ignores_nan() -> None: + """NaN stays NaN and does not pull its neighbours down.""" + img = np.ones((9, 9), np.float32) + img[4, 4] = np.nan + out = blur_nan(img) + assert np.isnan(out[4, 4]) + np.testing.assert_allclose(out[np.isfinite(out)], 1.0, rtol=1e-6) + + +def test_robust_z_and_late_trials() -> None: + """Median and MAD z-scores. + + Late trials are the last block, or the second half of one block. + """ + z = robust_z(np.array([[0.0, 1.0, 2.0, np.nan]])) + assert z[0, 1] == 0 and np.isnan(z[0, 3]) + np.testing.assert_array_equal(late_trials([0, 0, 1, 1, 1]), [0, 0, 1, 1, 1]) + np.testing.assert_array_equal(late_trials([0, 0, 0, 0]), [0, 0, 1, 1]) + + +def test_normalized_field_and_change(product: str) -> None: + """Each trial is divided by its median over the common pixels. + + The change view compares blurred trials, with a brightness in [0, 1]. + """ + store = SpineStore([(None, product)]) + pr = store.products[0] + stack = read_product(product)["paths"][1]["images"]["mean_ch1"] + nz = pr.normalized(1, "mean_ch1") + common = np.isfinite(stack).all(axis=0) + for t in range(stack.shape[0]): + med = np.median(stack[t][common]) + np.testing.assert_allclose(nz["stack"][t], stack[t] / med, rtol=1e-6) + np.testing.assert_allclose( + pr.field(1, "mean_ch1", -1, "image", "")[0], + np.nanmean(nz["stack"], axis=0), + rtol=1e-6, + ) + ch = pr.field(1, "mean_ch1", 2, "change", "average") + assert ch.shape == (2,) + stack.shape[1:] + b = ch[1] + assert np.nanmin(b) >= 0 and np.nanmax(b) <= 1 + cp = pr.change_prep(1, "mean_ch1") + expect = cp["blurred"][2] / cp["mean"] - 1 + np.testing.assert_allclose(ch[0], expect, rtol=1e-5, equal_nan=True) + prev = pr.field(1, "mean_ch1", 2, "change", "previous")[0] + np.testing.assert_allclose( + prev, + cp["blurred"][2] / cp["blurred"][1] - 1, + rtol=1e-5, + equal_nan=True, + ) + # the first trial of a block has no previous trial + assert np.isnan(pr.field(1, "mean_ch1", 0, "change", "previous")[0]).all() + act = pr.field(1, "", -1, "activity", "") + assert act.shape == (1,) + stack.shape[1:] + + +def test_store_sources_roi_and_crops(product: str) -> None: + """Sources carry sizes and trends. + + A window and its crops sit on the same grid around the source. + """ + store = SpineStore([("syn", product)], crop_half=4) + meta = store.meta() + p1 = meta["products"][0]["paths"][1] + assert meta["products"][0]["name"] == "syn" + assert "f0_net" in p1["trends"] and p1["n_sources"] == len(syn.SOURCES) + src = store.sources(0, 1) + prod = read_product(product)["paths"][1] + np.testing.assert_allclose( + np.array(src["normalized"]["f0_net"], float), + prod["normalized"]["sources"]["f0_net"], + ) + assert src["trends"]["f0_net"]["attrs"]["n_perm"] == 100 + roi = store.roi(0, 1, 0) + assert roi["size"] == 9 and np.array(roi["weights"]).shape == (9, 9) + r0, c0 = roi["origin"] + w = prod["rois"]["sources"].image(0) + np.testing.assert_allclose(np.array(roi["weights"]), w[r0 : r0 + 9, c0 : c0 + 9], atol=1e-6) + crops = store.crops(0, 1, 0, "mean_ch1", "image", "average") + n_t = len(prod["trials"]["acquisition"]) + assert crops.shape == (1, n_t + 1, 9, 9) + full = store.products[0].normalized(1, "mean_ch1")["stack"] + np.testing.assert_allclose(crops[0, 1:], full[:, r0 : r0 + 9, c0 : c0 + 9], rtol=1e-6) + ch = store.crops(0, 1, 0, "mean_ch1", "change", "average") + assert ch.shape == (2, n_t + 1, 9, 9) + + +def test_marks_attach_by_position(product: str, tmp_path: Path) -> None: + """A mark is stored with its source's position. + + It attaches to the nearest source within 2.5 px; clearing removes it. + """ + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + got = store.set_mark(0, 1, 1, "Growing", "a note") + assert got["by_source"][1]["label"] == "Growing" + rows = read_marks(marks) + assert rows[0]["Source"] == "2" and rows[0]["Note"] == "a note" + rs = read_product(product)["paths"][1]["rois"]["sources"] + assert rows[0]["Row0"] == pytest.approx(rs.rows[1]) + # a second mark on the same source replaces the first + store.set_mark(0, 1, 1, "Shrinking", "") + assert len(read_marks(marks)) == 1 + assert store.marks_for(0, 1)["by_source"][1]["label"] == "Shrinking" + # a mark far from every source does not attach + rows = read_marks(marks) + [dict(rows[0], Row0=0.0, Col0=0.0, Label="Unsure")] + from giant_python.spine.rois import write_marks + + write_marks(marks, rows) + assert store.marks_for(0, 1)["unattached"] == 1 + store.set_mark(0, 1, 1, "", "") + assert 1 not in store.marks_for(0, 1)["by_source"] + with pytest.raises(ValueError, match="unknown mark"): + store.set_mark(0, 1, 1, "Big", "") + + +def test_product_is_read_again_when_it_changes(product: str, tmp_path: Path) -> None: + """A rewritten product shows on the next request.""" + import os + import shutil + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + store = SpineStore([(None, copy)]) + first = store.sources(0, 1)["normalized"]["f0_net"] + import h5py + + with h5py.File(copy, "r+") as f: + d = f["Path1/normalized/sources/f0_net"] + d[...] = d[()] + 1 + st = os.stat(copy) + os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + again = store.sources(0, 1)["normalized"]["f0_net"] + a = np.array(first, float) + np.testing.assert_allclose(np.array(again, float), a + 1) + + +def _get(url: str) -> dict | np.ndarray: + """GET and decode JSON or float32. + + Returns + ------- + dict or np.ndarray + The parsed JSON for a JSON response, else the float32 array shaped by X-Shape. + """ + with urllib.request.urlopen(url) as r: + body = r.read() + if r.headers.get("Content-Type") == "application/json": + return json.loads(body) + shape = json.loads(r.headers["X-Shape"]) + return np.frombuffer(body, np.float32).reshape(shape) + + +def test_server_answers_the_api(product: str, tmp_path: Path) -> None: + """The page and every API route answer; a mark is written by POST.""" + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + try: + with urllib.request.urlopen(base + "/") as r: + assert b"Spine size viewer" in r.read() + meta = _get(base + "/api/meta") + assert meta["products"][0]["paths"]["1"]["n_sources"] == 3 + src = _get(base + "/api/sources?prod=0&path=1") + assert src["n"] == 3 + f = _get(base + "/api/field?prod=0&path=1&image=f0_net&trial=1") + assert f.shape == (1, syn.H, syn.W) + c = _get(base + "/api/crops?prod=0&path=1&id=0&image=f0_net&view=change") + assert c.shape[0] == 2 + roi = _get(base + "/api/roi?prod=0&path=1&id=2") + assert roi["id"] == 2 + req = urllib.request.Request( + base + "/api/mark", + data=json.dumps({"prod": 0, "path": 1, "id": 0, "label": "Unsure"}).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req) as r: + assert json.loads(r.read())["by_source"]["0"]["label"] == "Unsure" + assert read_marks(marks)[0]["Label"] == "Unsure" + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + "/api/field?prod=0&path=7&image=x") + assert e.value.code == 404 + finally: + srv.shutdown() + srv.server_close() + + +def _static(page: str) -> dict: + """Extract the data embedded in an exported page. + + Returns + ------- + dict + The page's decoded static data. + """ + m = re.search( + r'", + page, + ) + return json.loads(gzip.decompress(base64.b64decode(m.group(1)))) + + +def _unpack(e: dict) -> np.ndarray: + """Decode an embedded array (as the page's unpack). + + Returns + ------- + np.ndarray + The decoded layers (NaN where the code is 255), shaped as e["shape"]. + """ + parts = [] + for layer in e["layers"]: + q = np.frombuffer(base64.b64decode(layer["b64"]), np.uint8) + v = layer["offset"] + layer["scale"] * q.astype(np.float64) + parts.append(np.where(q == 255, np.nan, v)) + return np.concatenate(parts).reshape(e["shape"]) + + +def test_pack_round_trips_within_a_code() -> None: + """uint8 codes keep values within half a step and NaN as NaN.""" + rng = np.random.default_rng(0) + a = rng.normal(1, 0.1, (1, 20, 30)).astype(np.float32) + a[0, 3, 4] = np.nan + e = pack(a, "image") + back = _unpack(e) + assert np.isnan(back[0, 3, 4]) + step = e["layers"][0]["scale"] + inside = np.isfinite(a) & (a >= e["layers"][0]["offset"]) + inside &= a <= e["layers"][0]["offset"] + 254 * step + np.testing.assert_allclose(back[inside], a[inside], atol=step / 2 + 1e-7) + ch = np.stack([np.full((4, 4), 0.1), np.full((4, 4), 0.5)]) + back = _unpack(pack(ch, "change")) + np.testing.assert_allclose(back, ch, atol=0.003) + + +def test_export_html_embeds_the_viewer_data(product: str, tmp_path: Path) -> None: + """The page holds the meta, the sources, the mean fields and some crops. + + The crops are those of the chosen sources; the page holds nothing that + needs the server. + """ + out = tmp_path / "page.html" + rep = export_html(product, out, sources=[2], name="syn") + page = out.read_text(encoding="utf-8") + assert "Spine sizes syn" in page + data = _static(page) + assert data["meta"]["marks_file"] is None + assert data["sources"]["1"]["n"] == 3 + key = field_key(1, "f0_net", -1, "image", "") + assert key in data["fields"] + assert field_key(1, "f0_net", -1, "change", "") in data["fields"] + assert rep["sources"][1] == [2] + assert "1|1" in data["rois"] and "1|0" not in data["rois"] + crop_keys = [k for k in data["crops"] if k.startswith("1|1|")] + assert crop_keys and all("f0_" in k for k in crop_keys) + store = SpineStore([(None, product)]) + mean = store.products[0].field(1, "f0_net", -1, "image", "") + e = data["fields"][key] + back = _unpack(e) + fin = np.isfinite(mean) + step = e["layers"][0]["scale"] + lo = e["layers"][0]["offset"] + inside = fin & (mean >= lo) & (mean <= lo + 254 * step) + np.testing.assert_allclose(back[inside], mean[inside], atol=step) + + +def test_cli_export(product: str, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Giant spine export-html writes the page and reports it.""" + out = tmp_path / "e.html" + assert main(["spine", "export-html", product, "--out", str(out), "--top", "1"]) == 0 + rep = json.loads(capsys.readouterr().out) + assert rep["output"] == str(out) and out.is_file() + + +def test_pick_sources_marked_first_then_by_q_and_size() -> None: + """The export's crops go to the marked sources, then by q. + + Ties at the permutation floor go to the larger statistic. + """ + from giant_python.spine.view.export import pick_sources + + nan = float("nan") + tr = { + "step_q": [0.5, 1e-4, 1e-4, nan, 0.02], + "step_t": [1.0, 3.0, 6.0, nan, 2.5], + "brief_q": [0.9, 0.9, 0.9, nan, 0.9], + "brief_t": [1.0, 1.0, 1.0, nan, 1.0], + "resid_q": [0.04, 0.9, 0.9, nan, 0.9], + "resid_t": [2.0, 1.0, 1.0, nan, 1.0], + } + src = {"n": 5, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} + assert pick_sources(src, "f0", 3) == [0, 2, 1, 4] + assert pick_sources(src, "f0", 0) == [0] + + +def test_marks_need_json_from_this_server(product: str, tmp_path: Path) -> None: + """The mark endpoint refuses bodies that are not JSON and foreign origins. + + Bodies that are not JSON could be sent by a cross-origin page without a + preflight; requests whose Origin is another site are refused too. + """ + marks = tmp_path / "marks.csv" + store = SpineStore([(None, product)], marks) + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + base = f"http://127.0.0.1:{srv.server_address[1]}" + body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() + try: + for headers, code in ( + ({"Content-Type": "text/plain"}, 415), + ( + { + "Content-Type": "application/json", + "Origin": "http://example.com", + }, + 403, + ), + ): + req = urllib.request.Request(base + "/api/mark", data=body, headers=headers) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == code + assert not marks.exists() + req = urllib.request.Request( + base + "/api/mark", + data=body, + headers={"Content-Type": "application/json", "Origin": base}, + ) + with urllib.request.urlopen(req) as r: + assert r.status == 200 + assert read_marks(marks)[0]["Label"] == "Unsure" + finally: + srv.shutdown() + srv.server_close() + + +def test_sources_without_sources_keep_the_fields(product: str, tmp_path: Path) -> None: + """A path without sources answers with the same, empty, fields.""" + store = SpineStore([(None, product)]) + pr = store.products[0] + pr.small()["paths"][1]["rois"].pop("sources") + src = store.sources(0, 1) + assert src["n"] == 0 and src["trends"] == {} and src["ids"] == [] + assert src["marks"] == {"by_source": {}, "unattached": 0} + + +def test_cache_keys_follow_the_file(product: str, tmp_path: Path) -> None: + """A result made from the old file is not served after the file changes. + + Even if it lands in the cache after the reload. + """ + import os + import shutil + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + store = SpineStore([(None, copy)]) + pr = store.products[0] + old = pr.normalized(1, "mean_ch1") + gen = pr._gen + st = os.stat(copy) + os.utime(copy, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) + pr.small() + assert pr._gen == gen + 1 + # a late insert under the old generation's key is never read + pr._cache.get((gen, "norm", 1, "mean_ch1"), lambda: "stale") + new = pr.normalized(1, "mean_ch1") + assert new is not old and not isinstance(new, str) + + +def test_server_refuses_untrusted_hosts(product: str, tmp_path: Path) -> None: + """Requests naming another host (DNS rebinding) get nothing. + + Marks from an origin that is not this server's trusted names are refused. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + srv = make_server(store, port=0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + port = srv.server_address[1] + base = f"http://127.0.0.1:{port}" + try: + req = urllib.request.Request(base + "/api/meta", headers={"Host": f"evil.example:{port}"}) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == 403 + req = urllib.request.Request(base + "/api/meta", headers={"Host": f"localhost:{port}"}) + with urllib.request.urlopen(req) as r: + assert r.status == 200 + body = json.dumps({"path": 1, "id": 0, "label": "Unsure"}).encode() + for origin in ( + f"http://evil.example:{port}", + f"https://127.0.0.1:{port}", + ): + req = urllib.request.Request( + base + "/api/mark", + data=body, + headers={ + "Content-Type": "application/json", + "Origin": origin, + "Host": f"127.0.0.1:{port}", + }, + ) + with pytest.raises(urllib.error.HTTPError) as e: + urllib.request.urlopen(req) + assert e.value.code == 403 + finally: + srv.shutdown() + srv.server_close() + + +def test_export_refuses_unknown_paths(product: str, tmp_path: Path) -> None: + """Asking for a path the summary does not have is an error. + + Not an empty page. + """ + with pytest.raises(ValueError, match="no path"): + export_html(product, tmp_path / "p.html", paths=[7]) + assert not (tmp_path / "p.html").exists() + + +def test_pick_sources_uses_the_strongest_test_at_the_smallest_q() -> None: + """Among tests tied at a source's smallest q, the largest statistic wins. + + It breaks ties between sources. + """ + from giant_python.spine.view.export import pick_sources + + tr = { + "step_q": [1e-3, 1e-3], + "step_t": [2.0, 6.0], + "brief_q": [1e-3, 0.5], + "brief_t": [20.0, 1.0], + "resid_q": [0.9, 0.9], + "resid_t": [1.0, 1.0], + } + src = {"n": 2, "trends": {"f0": tr}, "marks": {}} + assert pick_sources(src, "f0", 1) == [0] + + +def test_marks_keep_their_order_within_a_path(product: str, tmp_path: Path) -> None: + """Two marks with the same time that land on one source. + + The one written later wins, whatever their rows. + """ + from giant_python.spine.rois import write_marks + + store = SpineStore([(None, product)], tmp_path / "marks.csv") + rs = read_product(product)["paths"][1]["rois"]["sources"] + r, c = float(rs.rows[0]), float(rs.cols[0]) + base = { + "Path": 1, + "Source": 1, + "Note": "", + "Col0": c, + "Updated": "2026-01-01 00:00:00", + } + write_marks( + tmp_path / "marks.csv", + [ + dict(base, Label="Growing", Row0=r + 0.5), + dict(base, Label="Shrinking", Row0=r - 0.5), + ], + ) + assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" + # a write through the store keeps the order within the path + store.set_mark(0, 1, 1, "Unsure", "") + rows = read_marks(tmp_path / "marks.csv") + assert [m["Label"] for m in rows] == ["Growing", "Shrinking", "Unsure"] + assert store.marks_for(0, 1)["by_source"][0]["label"] == "Shrinking" + + +def test_pick_sources_keeps_infinite_statistics_first() -> None: + """An infinite statistic (a change without noise) ranks first. + + Among equal q-values. + """ + from giant_python.spine.view.export import pick_sources + + inf = float("inf") + tr = {f"{t}_{f}": [None, None] for t in ("brief", "resid") for f in ("q", "t")} + tr.update({"step_q": [1e-4, 1e-4], "step_t": [6.0, inf]}) + src = {"n": 2, "trends": {"f0": tr}, "marks": {}} + assert pick_sources(src, "f0", 1) == [1] + + +def test_summary_without_rois_loads(product: str, tmp_path: Path) -> None: + """A summary with no sources and no user ROIs (no rois group) loads.""" + import shutil + + import h5py + + copy = tmp_path / "copy.h5" + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + for n in ("Path1", "Path2"): + if f"{n}/rois" in f: + del f[f"{n}/rois"] + store = SpineStore([(None, copy)]) + assert store.sources(0, 1)["n"] == 0 + assert store.meta()["products"][0]["paths"][1]["n_sources"] == 0 + + +def test_server_on_ipv6_loopback_and_port_80_names(product: str) -> None: + """The server binds an IPv6 literal, and at port 80 trusts portless names. + + Those are the names without a port, as browsers send them. + """ + import socket as so + + from giant_python.spine.view.server import _bracket, allowed_hosts + + assert _bracket("::1") == "[::1]" and _bracket("localhost") == "localhost" + at80 = allowed_hosts("127.0.0.1", 80) + assert "127.0.0.1" in at80 and "localhost:80" in at80 + assert "127.0.0.1" not in allowed_hosts("127.0.0.1", 8790) + assert allowed_hosts("0.0.0.0", 8790) == frozenset() + if not so.has_ipv6: + pytest.skip("no IPv6") + store = SpineStore([(None, product)]) + try: + srv = make_server(store, host="::1", port=0) + except OSError: + pytest.skip("no IPv6 loopback") + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + port = srv.server_address[1] + try: + assert f"[::1]:{port}" in srv.RequestHandlerClass.allowed + with urllib.request.urlopen(f"http://[::1]:{port}/api/meta") as r: + assert r.status == 200 + finally: + srv.shutdown() + srv.server_close() + + +def test_a_note_alone_keeps_the_label(product: str, tmp_path: Path) -> None: + """A note saved on its own keeps the label the source has at that moment. + + Unsure without one. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + got = store.set_mark(0, 1, 0, None, "first note") + assert got["by_source"][0]["label"] == "Unsure" + store.set_mark(0, 1, 0, "Growing", "first note") + got = store.set_mark(0, 1, 0, None, "second note") + assert got["by_source"][0] == { + "label": "Growing", + "note": "second note", + "updated": got["by_source"][0]["updated"], + } + assert len(read_marks(tmp_path / "marks.csv")) == 1 + + +def test_export_refuses_unknown_sources_and_images(product: str, tmp_path: Path) -> None: + """Source numbers and crop images the summary lacks are errors.""" + with pytest.raises(ValueError, match="no source"): + export_html(product, tmp_path / "p.html", sources=[99]) + with pytest.raises(ValueError, match="no image"): + export_html(product, tmp_path / "p.html", crop_images=["f0_nope"]) + assert not (tmp_path / "p.html").exists() + + +def test_export_crops_only_the_images_asked_for(product: str, tmp_path: Path) -> None: + """With --crop-images, a path that lacks them gets no crops. + + Rather than every image. + """ + import h5py + + out = tmp_path / "p.html" + copy = tmp_path / "copy.h5" + import shutil + + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + del f["Path2/images/f0_net"] + export_html(copy, out, sources=[1], crop_images=["f0_net"]) + data = _static(out.read_text(encoding="utf-8")) + assert any(k.startswith("1|0|f0_net|") for k in data["crops"]) + assert not [k for k in data["crops"] if k.startswith("2|")] + + +def test_cache_makes_a_value_once_for_concurrent_requests() -> None: + """Concurrent requests for a value being made wait for it. + + Instead of making it again. + """ + import time as _t + + from giant_python.spine.view.data import _Lru + + cache = _Lru(4) + calls = [] + + def make() -> str: + """Make a slow value. + + Returns + ------- + str + The value, "v". + """ + calls.append(1) + _t.sleep(0.2) + return "v" + + out = [] + ths = [threading.Thread(target=lambda: out.append(cache.get("k", make))) for _ in range(5)] + for th in ths: + th.start() + for th in ths: + th.join() + assert out == ["v"] * 5 and len(calls) == 1 + assert cache.making == {} + + +def test_cache_is_bounded_by_bytes() -> None: + """Values are evicted, oldest first, once their arrays exceed the budget. + + The newest stays even when it alone is larger. + """ + from giant_python.spine.view.data import _Lru + + cache = _Lru(3000) + for k in range(4): + cache.get(k, lambda: {"a": np.zeros(125)}) # 1000 bytes each + assert list(cache.d) == [1, 2, 3] + cache.get("big", lambda: np.zeros(1000)) + assert list(cache.d) == ["big"] + + +def test_cache_lock_stays_while_requests_wait() -> None: + """The lock of a key being made stays while any request still uses it. + + Even if the value is evicted meanwhile: a later request for the key waits + on the same lock instead of computing in parallel. + """ + import time as _t + + from giant_python.spine.view.data import _Lru + + cache = _Lru(1) # every new value evicts the previous one + running = [] + peak = [] + + def make() -> np.ndarray: + """Make a slow value that records how many are being made at once. + + Returns + ------- + np.ndarray + A zero array of 10 values. + """ + running.append(1) + peak.append(len(running)) + _t.sleep(0.05) + running.pop() + return np.zeros(10) + + def worker() -> None: + """Ask for the key, then for another (evicting it).""" + cache.get("k", make) + cache.get(object(), lambda: np.zeros(10)) + + ths = [threading.Thread(target=worker) for _ in range(6)] + for th in ths: + th.start() + for th in ths: + th.join() + assert max(peak) == 1 + assert cache.making == {} + + +def test_mark_refused_when_the_source_moved(product: str, tmp_path: Path) -> None: + """A mark that names a position other than the source's is refused. + + The summary changed under an open page; the mark writes nothing. + """ + store = SpineStore([(None, product)], tmp_path / "marks.csv") + rs = read_product(product)["paths"][1]["rois"]["sources"] + with pytest.raises(ValueError, match="changed"): + store.set_mark(0, 1, 1, "Growing", "", row=0.0, col=0.0) + assert not (tmp_path / "marks.csv").exists() + got = store.set_mark(0, 1, 1, "Growing", "", row=float(rs.rows[1]), col=float(rs.cols[1])) + assert got["by_source"][1]["label"] == "Growing" + + +def test_change_needs_only_its_own_cache_entry(product: str) -> None: + """change() reads everything it needs from the change record. + + So it does not reload the normalized stack (no thrashing when the two do + not fit together in the cache). + """ + store = SpineStore([(None, product)]) + pr = store.products[0] + pr.change_prep(1, "mean_ch1") + calls = [] + real = pr.normalized + pr.normalized = lambda *a: calls.append(a) or real(*a) + for t in (-1, 0, 2): + pr.change(1, "mean_ch1", t, "average") + assert calls == [] + + +def test_default_image_calls_and_window_motion_reach_the_page(product: str) -> None: + """The page gets the default image, the calls and the windows' motion. + + That is, the summary's default image, the calls and structural change of + each image's tests, and the windows' motion. + """ + store = SpineStore([(None, product)]) + p1 = store.meta()["products"][0]["paths"][1] + assert p1["primary_image"] == "f0_net" + src = store.sources(0, 1) + assert len(src["align_px"]) == src["n"] + assert src["trends"]["f0_net"]["attrs"]["structural_image"] == "mean_ch2" + assert len(src["trends"]["f0_net"]["call"]) == src["n"] + assert len(src["trends"]["f0_net"]["structural_d"]) == src["n"] + from importlib.resources import files + + page = files("giant_python.spine.view").joinpath("page.html").read_text(encoding="utf-8") + for key in ('["call", "call"]', '"structural_d"', '"align_px"'): + assert key in page + + +def test_summaries_before_format_4_still_load(product: str, tmp_path: Path) -> None: + """Summaries before format 4 still load. + + Without the default image, the calls or the window motion (format 3), the + page gets None for the image and NaN (null) motion. + """ + import shutil + + import h5py + + copy = tmp_path / "v3.h5" + shutil.copy(product, copy) + with h5py.File(copy, "r+") as f: + for n in ("Path1", "Path2"): + g = f[n] + del g.attrs["primary_image"] + del g["readout/sources/align_px"] + for name in g["trends/sources"]: + t = g[f"trends/sources/{name}"] + for k in ("call", "structural_d"): + if k in t: + del t[k] + store = SpineStore([(None, copy)]) + assert store.meta()["products"][0]["paths"][1]["primary_image"] is None + src = store.sources(0, 1) + assert np.isnan(np.array(src["align_px"], float)).all() + assert "call" not in src["trends"]["f0_net"] + assert read_product(copy)["paths"][1]["primary_image"] is None + + +def test_pick_sources_takes_the_calls_first() -> None: + """The export's crops go to the marked sources, then to the calls. + + The calls are taken by q, then the rest by the smallest q. + """ + from giant_python.spine.view.export import pick_sources, primary_image + + tr = { + "step_q": [0.5, 1e-4, 0.2, 0.9], + "step_t": [1.0, 6.0, 2.0, 1.0], + "brief_q": [0.9, 0.9, 0.9, 0.9], + "brief_t": [1.0, 1.0, 1.0, 1.0], + "resid_q": [0.9, 0.9, 0.05, 0.01], + "resid_t": [1.0, 1.0, 3.0, 4.0], + "call": [False, False, True, True], + } + src = {"n": 4, "trends": {"f0": tr}, "marks": {"by_source": {"0": {}}}} + assert pick_sources(src, "f0", 3) == [0, 3, 2, 1] + # a marked call does not take one of the top places + src["marks"] = {"by_source": {"3": {}}} + assert pick_sources(src, "f0", 1) == [3, 2] + assert primary_image(["f0_net", "f0_gain"], "f0_net") == "f0_net" + assert primary_image(["f0_net", "f0_gain"], "gone") == "f0_gain" + assert primary_image(["f0_net", "f0_gain"]) == "f0_gain" diff --git a/tests/trial_table/__init__.py b/tests/trial_table/__init__.py index 475c7f0f..29b8cf3a 100644 --- a/tests/trial_table/__init__.py +++ b/tests/trial_table/__init__.py @@ -1 +1 @@ -"""Tests of the SLAP2 trial-table builder.""" +"""Tests of the SLAP2 trial-table builder.""" diff --git a/tests/trial_table/test_build_slap2.py b/tests/trial_table/test_build_slap2.py index ae99200f..86ee71a5 100644 --- a/tests/trial_table/test_build_slap2.py +++ b/tests/trial_table/test_build_slap2.py @@ -1,625 +1,625 @@ -"""Tests of the SLAP2 trial-table builder (ports of GIAnT-MATLAB's tests). - -The per-file reader is replaced by a table of line counts and first-line -times, so no SLAP2 data are needed; reference stacks are small TIFFs with -SLAP2's per-page JSON descriptions. A separate test builds a MATLAB v7.3 -datetime by hand to check the .meta decoder. -""" - -import datetime -import json -import math -import os -import struct -import warnings -from collections.abc import Sequence -from pathlib import Path - -import h5py -import numpy as np -import pytest - -from giant_python.io.hdf5 import load_struct_h5 -from giant_python.io.slap2 import first_line_timestamp, read_mat_datetime_ms -from giant_python.pipeline import trial_table as tt -from giant_python.pipeline.trial_table import ( - DatInfo, - TrialTableWarning, - acquisition_order, - build_trial_table_slap2, - matlab_linspace, - trim_trial_table, -) - -LINE_PERIOD_S = 1e-4 -START = datetime.datetime(2024, 2, 1, 12, 0, 0) - - -def datenum(t: datetime.datetime) -> float: - """MATLAB datenum of a naive local datetime. - - Returns - ------- - float - Days since MATLAB's datenum origin, with the time of day as a fraction. - """ - midnight = t.replace(hour=0, minute=0, second=0, microsecond=0) - return t.toordinal() + 366 + (t - midnight).total_seconds() / 86400 - - -class FakeSession: - """A data folder whose .dat files are empty, with a fake reader.""" - - def __init__(self, root: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Create the data folder and put the fake reader in place.""" - self.dir = root / "data" - self.dir.mkdir() - self.info = {} - monkeypatch.setattr(tt, "read_dat_info", self.read) - - def read(self, path: str | Path) -> DatInfo: - """Read a file's line count and first-line time (the fake reader). - - Returns - ------- - DatInfo - The line count, first-line time and line period registered for the file. - """ - lines, first = self.info[Path(path).name] - return DatInfo(lines, first, LINE_PERIOD_S) - - def dat( - self, - name: str, - lines: int | np.integer, - mtime: datetime.datetime, - first_line: datetime.datetime | None = None, - ) -> None: - """Add an empty .dat file with its line count, file time and first-line time.""" - p = self.dir / name - p.write_bytes(b"") - stamp = mtime.timestamp() - os.utime(p, (stamp, stamp)) - first = math.nan if first_line is None else datenum(first_line) - self.info[name] = (lines, first) - - def triggered( - self, lines1: Sequence[int], lines2: Sequence[int] - ) -> tuple[list[str], list[str]]: - """Add triggered recordings of both paths with the given line counts. - - Returns - ------- - dmd1 : list of str - File names of path 1's recordings. - dmd2 : list of str - File names of path 2's recordings. - """ - dmd1 = [f"acq_DMD1-TRIAL{k:06d}.dat" for k in range(1, len(lines1) + 1)] - dmd2 = [f"acq_DMD2-TRIAL{k:06d}.dat" for k in range(1, len(lines2) + 1)] - for k, (name, n) in enumerate(zip(dmd1, lines1), start=1): - self.dat(name, n, START + datetime.timedelta(minutes=k)) - for k, (name, n) in enumerate(zip(dmd2, lines2), start=1): - self.dat(name, n, START + datetime.timedelta(minutes=k)) - return dmd1, dmd2 - - def references(self) -> None: - """Write a small reference stack per path, described as SLAP2 does.""" - import tifffile - - ref = self.dir / "reference" - ref.mkdir() - rng = np.random.default_rng(0) - for dmd in (1, 2): - with tifffile.TiffWriter(ref / f"acq_DMD{dmd}_CONFIG1-REFERENCE.tif") as tw: - for z in (0, 1, 2): - for ch in (1, 2): - desc = { - "channel": ch, - "z": z, - "dmdPixel2SampleTransform": np.eye(3).tolist(), - } - page = rng.random((8, 6)).astype(np.float32) - tw.write(page, description=json.dumps(desc), metadata=None) - - def mtimes(self, names: Sequence[str]) -> np.ndarray: - """Return the files' modification times as MATLAB datenums. - - Returns - ------- - np.ndarray - One datenum per file name, in the order given. - """ - return np.array([tt._mtime_datenum(self.dir / n) for n in names]) - - def build(self, save_dir: Path, **kw: float | bool | None) -> dict: - """Build the trial table of this folder. - - Returns - ------- - dict - The trial table built by build_trial_table_slap2. - """ - return build_trial_table_slap2(self.dir, save_dir, **kw) - - -@pytest.fixture -def session(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> FakeSession: - """Provide a fake session in a temporary folder. - - Returns - ------- - FakeSession - A session whose reader is replaced by a fake one. - """ - return FakeSession(tmp_path, monkeypatch) - - -def test_triggered_trials(session: FakeSession, tmp_path: Path) -> None: - """Triggered recordings of both paths give one trial per file pair.""" - lines = [100000, 120000, 110000] - dmd1, dmd2 = session.triggered(lines, lines) - session.references() - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["epoch"], np.ones((2, 3))) - np.testing.assert_array_equal(t["true_trial_ix"], np.tile([1, 2, 3], (2, 1))) - s2 = t["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.ones((2, 3))) - np.testing.assert_array_equal(s2["last_line"], np.tile(lines, (2, 1))) - ends = session.mtimes(dmd1) - np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), ends, rtol=0, atol=1e-9) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - ends - np.array(lines) * LINE_PERIOD_S / 86400, - rtol=0, - atol=1e-9, - ) - - -def test_triggered_trial_line_mismatch(session: FakeSession, tmp_path: Path) -> None: - """A file holding two trials back to back is lined up with the other path.""" - # DMD1's trial number failed to increment: its second file holds DMD2's - # second and third trials back to back - dmd1, dmd2 = session.triggered([100000, 220000], [100000, 100000, 120000]) - session.references() - s = session.build(tmp_path / "out") - assert s["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] - s2 = s["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], [[1, 1, 100001], [1, 1, 1]]) - np.testing.assert_array_equal( - s2["last_line"], [[100000, 100000, 220000], [100000, 100000, 120000]] - ) - dn1, dn2 = session.mtimes(dmd1), session.mtimes(dmd2) - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - [dn1[0], dn2[1], dn1[1]], - rtol=0, - atol=1e-9, - ) - - -def test_order_from_file_names_not_mod_times(session: FakeSession, tmp_path: Path) -> None: - """Acquisitions are ordered by the time in their names, not by file times.""" - # copies carry upload times: DMD1's are scrambled within a few seconds, - # DMD2's identical; the earlier acquisition sorts last alphabetically - acqs = [("spont_20250314_101500", 2), ("activity_20250314_111223", 12)] - dmd1 = [f"{a}_DMD1-TRIAL{k:06d}.dat" for a, n in acqs for k in range(1, n + 1)] - dmd2 = [n.replace("DMD1", "DMD2") for n in dmd1] - lines = 100000 + 100 * np.arange(1, len(dmd1) + 1) - upload = datetime.datetime(2026, 8, 27, 10, 53, 33) - for k, (a, b) in enumerate(zip(dmd1, dmd2), start=1): - session.dat(a, lines[k - 1], upload + datetime.timedelta(seconds=(7 * k) % 5)) - session.dat(b, lines[k - 1], upload) - session.references() - with pytest.warns(TrialTableWarning, match="do not look like acquisition times"): - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["true_trial_ix"][0], np.arange(1, len(dmd1) + 1)) - np.testing.assert_array_equal(t["slap2_info"]["last_line"], np.tile(lines, (2, 1))) - np.testing.assert_allclose( - t["slap2_info"]["trial_end_time_from_pc"].ravel(), - session.mtimes(dmd1), - rtol=0, - atol=1e-9, - ) - - -def test_file_order_falls_back_to_mod_time(session: FakeSession, tmp_path: Path) -> None: - """Without a time in the names, files are ordered by modification time.""" - names = ["b_DMD1.dat", "a_DMD1.dat"] - for k, n in enumerate(names, start=1): - t = START + datetime.timedelta(minutes=k) - session.dat(n, 100000, t) - session.dat(n.replace("DMD1", "DMD2"), 100000, t) - session.references() - with pytest.warns(TrialTableWarning, match="modification time"): - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [ - names, - [n.replace("DMD1", "DMD2") for n in names], - ] - - -def test_trial_times_from_line_clock(session: FakeSession, tmp_path: Path) -> None: - """Trial times come from the line clock, which shows gaps the line counts hide.""" - # DMD1's second file holds trials 2 and 3, with a 0.5 s gap that the line - # count alone doesn't show; mtimes are identical upload times - starts = [ - datetime.datetime(2025, 3, 14, 11, 12, 55) + datetime.timedelta(seconds=s) - for s in (0, 10.5, 21) - ] - upload = datetime.datetime(2026, 8, 27, 10, 53, 33) - dmd1 = [f"activity_20250314_111223_DMD1-TRIAL{k:06d}.dat" for k in (1, 2)] - dmd2 = [f"activity_20250314_111223_DMD2-TRIAL{k:06d}.dat" for k in (1, 2, 3)] - session.dat(dmd1[0], 100000, upload, starts[0]) - session.dat(dmd1[1], 220000, upload, starts[1]) - for name, n, s in zip(dmd2, (100000, 100000, 120000), starts): - session.dat(name, n, upload, s) - session.references() - with warnings.catch_warnings(): - warnings.simplefilter("error") - t = session.build(tmp_path / "out") - assert t["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] - days = np.array([datenum(s) for s in starts]) - s2 = t["slap2_info"] - np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days, rtol=0, atol=1e-9) - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - days + np.array([100000, 100000, 120000]) * LINE_PERIOD_S / 86400, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_trials_and_times(session: FakeSession, tmp_path: Path) -> None: - """A continuous recording is cut into trials with times from the line clock.""" - lines = 450000 - t0 = datetime.datetime(2025, 3, 14, 11, 12, 55) - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START, t0) - # later files of the recording are skipped (their line counts unknown) - for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): - (session.dir / n).write_bytes(b"") - session.references() - t = session.build(tmp_path / "out") - edges = np.array([1, 150001, 300001, 450001], dtype=float) - assert t["filename"].tolist() == [[names[0]] * 3, [names[1]] * 3] - s2 = t["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.tile(edges[:3], (2, 1))) - np.testing.assert_array_equal(s2["last_line"], np.tile(edges[1:], (2, 1))) - days = datenum(t0) + (edges - 1) * LINE_PERIOD_S / 86400 - np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days[:3], rtol=0, atol=1e-9) - np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), days[1:], rtol=0, atol=1e-9) - - -def test_multicycle_times_from_mtime(session: FakeSession, tmp_path: Path) -> None: - """Without the line clock, a continuous recording's times come from file times.""" - lines = 450000 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - edges = np.array([1, 150001, 300001, 450001], dtype=float) - dn = session.mtimes(names[:1])[0] - to_days = LINE_PERIOD_S / 86400 - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - dn - (lines - edges[1:]) * to_days, - rtol=0, - atol=1e-9, - ) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - dn - (lines - edges[:3]) * to_days, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_times_from_last_file_mtime(session: FakeSession, tmp_path: Path) -> None: - """Without the line clock, a CYCLE-split recording ends at its last file's modification time. - - MATLAB takes the first file's. - """ - lines = 450000 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - end = START + datetime.timedelta(seconds=30) - for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): - (session.dir / n).write_bytes(b"") - os.utime(session.dir / n, (end.timestamp(), end.timestamp())) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - last = session.mtimes(["acq_DMD1-CYCLE-000001.dat"])[0] - edges = np.array([1, 150001, 300001, 450001], dtype=float) - to_days = LINE_PERIOD_S / 86400 - np.testing.assert_allclose( - s2["trial_end_time_from_pc"].ravel(), - last - (lines - edges[1:]) * to_days, - rtol=0, - atol=1e-9, - ) - np.testing.assert_allclose( - s2["trial_start_time_inferred"].ravel(), - last - (lines - edges[:3]) * to_days, - rtol=0, - atol=1e-9, - ) - - -def test_multicycle_edges_are_matlab_linspace(session: FakeSession, tmp_path: Path) -> None: - """The trial edges of a continuous recording are MATLAB's linspace values.""" - # 3 trials of 599838 lines: the edges are fractional, as MATLAB's - lines = 599837 - names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] - for n in names: - session.dat(n, lines, START) - session.references() - s2 = session.build(tmp_path / "out")["slap2_info"] - edges = matlab_linspace(1, lines + 1, 4) - assert edges[1] != round(edges[1]) - np.testing.assert_array_equal(s2["first_line"][0], edges[:3]) - np.testing.assert_array_equal(s2["last_line"][0], edges[1:]) - - -def test_matlab_linspace_values() -> None: - """matlab_linspace reproduces values computed in MATLAB.""" - # values from MATLAB R2023b: linspace(1, 599838, 4) - y = matlab_linspace(1, 599838, 4) - assert y[0] == 1 and y[-1] == 599838 - assert y[1] == 1 + (1 * (599838 - 1)) / 3 - assert y[2] == 1 + (2 * (599838 - 1)) / 3 - - -def test_reference_stack(session: FakeSession, tmp_path: Path) -> None: - """Each path's reference stack is found and stored.""" - session.triggered([100000], [100000]) - session.references() - t = session.build(tmp_path / "out") - for path in ("Path1", "Path2"): - ref = t["slap2_info"]["ref_stack"][path] - np.testing.assert_array_equal(ref["channels"], [1, 2]) - np.testing.assert_array_equal(ref["Zs"], [0, 1, 2]) - np.testing.assert_array_equal(ref["dmdPixel2SampleTransform"], np.eye(3)) - assert ref["IM"].shape == ( - 6, - 8, - 6, - ) # columns x rows x pages, as MATLAB - assert ref["IM"].dtype == np.float32 - - -def test_write_trial_table_h5(session: FakeSession, tmp_path: Path) -> None: - """The written trial_table.h5 holds the table in MATLAB's column-major layout.""" - dmd1, dmd2 = session.triggered([100000, 120000], [100000, 120000]) - session.references() - out = tmp_path / "out" - built = session.build(out) - t = load_struct_h5(out / "trial_table.h5") - assert t["datadr"] == str(session.dir) - assert t["savedr"] == str(out) - assert t["filename"].tolist() == [dmd1, dmd2] - np.testing.assert_array_equal(t["slap2_info"]["last_line"], [[100000, 120000]] * 2) - np.testing.assert_array_equal( - t["slap2_info"]["ref_stack"]["Path1"]["IM"], - built["slap2_info"]["ref_stack"]["Path1"]["IM"], - ) - with h5py.File(out / "trial_table.h5", "r") as h: - # stored column-major, as MATLAB's saveStructToH5 writes it - assert h["filename"].shape == (2, 2) - assert h["slap2_info/first_line"].shape == (2, 2) - assert h["slap2_info/ref_stack/Path1/IM"].shape == (6, 8, 6) - assert h["slap2_info/ref_stack/Path1/Zs"].shape == (3, 1) - assert h["row_major"][()].item() == 0 - - -def test_max_duration_trims_and_keeps_untrimmed(session: FakeSession, tmp_path: Path) -> None: - """max_duration_s trims the table and also writes the untrimmed one.""" - session.triggered([100000, 120000, 110000], [100000, 120000, 110000]) - session.references() - out = tmp_path / "out" - t = session.build(out, max_duration_s=15.0) # 10 s + 5 s of the 12 s trial - assert (out / "trial_table_untrimmed.h5").exists() - s2 = load_struct_h5(out / "trial_table.h5")["slap2_info"] - np.testing.assert_array_equal(s2["first_line"], np.ones((2, 2))) - np.testing.assert_array_equal(s2["last_line"], [[100000, 50000]] * 2) - assert t["filename"].shape == (2, 2) - assert np.asarray(s2["trial_start_time_inferred"]).size == 2 - full = load_struct_h5(out / "trial_table_untrimmed.h5") - assert full["filename"].shape == (2, 3) - - -def test_trim_keeps_whole_trials_before_the_limit() -> None: - """Trimming keeps the trials that start before the limit and shortens the last.""" - table = { - "filename": np.array([["a", "b"], ["c", "d"]], dtype=object), - "true_trial_ix": np.array([[1.0, 2.0], [1.0, 2.0]]), - "epoch": np.ones((2, 2)), - "slap2_info": { - "first_line": np.ones((2, 2)), - "last_line": np.full((2, 2), 1000.0), - "trial_end_time_from_pc": np.array([[1.0, 2.0]]), - "trial_start_time_inferred": np.array([[0.5, 1.5]]), - }, - } - out, info = trim_trial_table(table, 0.15, 1e-4) # 0.1 s trials - assert info["n_trials_kept"] == 2 and info["last_trial_shortened"] - keep = math.floor((0.15 - 1000 * 1e-4) / 1e-4) # 499 in floating point, as in MATLAB - np.testing.assert_array_equal(out["slap2_info"]["last_line"], [[1000, keep]] * 2) - out, info = trim_trial_table(table, 1.0, 1e-4) - assert info["n_trials_kept"] == 2 and not info["last_trial_shortened"] - with pytest.raises(ValueError): - trim_trial_table(table, 0.0, 1e-4) - - -def test_no_reference_stack_error(session: FakeSession, tmp_path: Path) -> None: - """A session without a reference stack raises FileNotFoundError.""" - session.triggered([100000], [100000]) - with pytest.raises(FileNotFoundError): - session.build(tmp_path / "out") - - -def test_unaligned_dmds_error(session: FakeSession, tmp_path: Path) -> None: - """Paths whose recordings do not line up raise an error.""" - session.triggered([100000], [150000]) - session.references() - with pytest.raises(ValueError, match="lining up"): - session.build(tmp_path / "out") - - -def test_unmatched_trailing_recordings_warn(session: FakeSession, tmp_path: Path) -> None: - """Data left after the last trial that lines up is left out, as in MATLAB, with a warning.""" - session.triggered([100000, 100000], [100000]) - session.references() - with pytest.warns(TrialTableWarning, match="100000 lines of DMD1"): - t = session.build(tmp_path / "out") - assert t["filename"].shape == (2, 1) - - -def test_no_trials_error(session: FakeSession, tmp_path: Path) -> None: - """A session in which no trial lines up warns and raises.""" - session.triggered([100000], []) - session.references() - with pytest.warns(TrialTableWarning, match="left out"): - with pytest.raises(ValueError, match="No trials"): - session.build(tmp_path / "out") - - -@pytest.mark.filterwarnings("ignore:Could not read acquisition times") -def test_mixed_continuous_and_triggered_error(session: FakeSession, tmp_path: Path) -> None: - """Continuous and triggered recordings in one folder raise an error.""" - session.triggered([100000], [100000]) - for n in ("acq2_DMD1-CYCLE-000000.dat", "acq2_DMD2-CYCLE-000000.dat"): - session.dat(n, 450000, START + datetime.timedelta(minutes=5)) - session.references() - with pytest.raises(ValueError, match="both continuous"): - session.build(tmp_path / "out") - - -def test_acquisition_order() -> None: - """Files sort by acquisition time and trial number; ambiguous names are refused.""" - names = [ - "a_20250314_111223_DMD1-TRIAL000010.dat", - "a_20250314_111223_DMD1-TRIAL000002.dat", - "b_20250314_101500_DMD1-TRIAL000001.dat", - ] - order, ok = acquisition_order(names) - assert ok and order.tolist() == [2, 1, 0] - order, ok = acquisition_order(["x_DMD1-TRIAL000002.dat", "x_DMD1-TRIAL000001.dat"]) - assert ok and order.tolist() == [1, 0] - _, ok = acquisition_order(["b_DMD1.dat", "a_DMD1.dat"]) - assert not ok - _, ok = acquisition_order(["x_DMD1.dat", "x_DMD1-CYCLE-000000.dat"]) - assert not ok # same position - - -def _write_mat_datetime(path: Path, ms: complex, tz: str = "") -> None: - """Write a v7.3 MAT file holding fpgaTimeReference as MATLAB writes it. - - The ``FileWrapper__`` blob lists strings, one class (datetime) and one - object whose properties are data (cell 0) and, when given, tz - (cell 1). - """ - strings = [b"data", b"datetime", b"fmt", b"tz"] - names = b"".join(s + b"\0" for s in strings) - names += b"\0" * (-len(names) % 8) - classes = struct.pack("<8I", 0, 0, 0, 0, 0, 2, 0, 0) - objects = struct.pack("<12I", 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1) - props = [(1, 1, 0)] + ([(4, 1, 1)] if tz else []) - words = [0, 0, len(props)] + [v for p in props for v in p] - words += [0] * (len(words) % 2) - sets = struct.pack(f"<{len(words)}I", *words) - o0 = 40 + len(names) - o1 = o0 + len(classes) - o2 = o1 - o3 = o2 + len(objects) - o4 = o3 + len(sets) - header = struct.pack(" None: - """The .meta decoder reads an unzoned MATLAB datetime.""" - # 2025-03-14 09:30:20.5 wall clock, unzoned - ms = ( - datetime.datetime(2025, 3, 14, 9, 30, 20, 500000) - datetime.datetime(1970, 1, 1) - ).total_seconds() * 1000 - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(ms, -8.6e-5)) - assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 8.6e-5, abs=1e-9) - assert read_mat_datetime_ms(p, "missing") is None - # zoned: data is UTC; the wall clock in Los Angeles is 7 h earlier in March - _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") - assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 7 * 3600e3) - - -def test_read_mat_datetime_offset_across_dst(tmp_path: Path) -> None: - """The offset is elapsed time. - - 01:30 PST plus two hours on the day DST starts is 04:30 PDT (MATLAB: - datetime + seconds). - """ - utc = datetime.datetime(2025, 3, 9, 9, 30) # 01:30 in Los Angeles (PST) - ms = (utc - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") - wall = read_mat_datetime_ms(p, "fpgaTimeReference", offset_ms=2 * 3600e3) - expected = datetime.datetime(2025, 3, 9, 4, 30) - datetime.datetime(1970, 1, 1) - assert wall == pytest.approx(expected.total_seconds() * 1000, abs=1e-6) - - -@pytest.mark.parametrize("n", [0, 2]) -def test_read_mat_datetime_needs_one_value(tmp_path: Path, n: int) -> None: - """An empty or multi-element reference gives None, not an error or the first value. - - File times are used instead. - """ - p = tmp_path / "a.meta" - _write_mat_datetime(p, complex(1.7e12, 0)) - with h5py.File(p, "r+") as h: - del h["#refs#/c"] - h["#refs#"].create_dataset("c", data=np.zeros((1, n), [("real", " None: - """The first line's timestamp is read from the .dat file, after a magic-number check.""" - - class File: - """A stand-in for the SLAP2 data-file object.""" - - datFileName = str(tmp_path / "x.dat") - header = {"firstCycleOffsetBytes": 16} - - line = struct.pack(" float: + """MATLAB datenum of a naive local datetime. + + Returns + ------- + float + Days since MATLAB's datenum origin, with the time of day as a fraction. + """ + midnight = t.replace(hour=0, minute=0, second=0, microsecond=0) + return t.toordinal() + 366 + (t - midnight).total_seconds() / 86400 + + +class FakeSession: + """A data folder whose .dat files are empty, with a fake reader.""" + + def __init__(self, root: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Create the data folder and put the fake reader in place.""" + self.dir = root / "data" + self.dir.mkdir() + self.info = {} + monkeypatch.setattr(tt, "read_dat_info", self.read) + + def read(self, path: str | Path) -> DatInfo: + """Read a file's line count and first-line time (the fake reader). + + Returns + ------- + DatInfo + The line count, first-line time and line period registered for the file. + """ + lines, first = self.info[Path(path).name] + return DatInfo(lines, first, LINE_PERIOD_S) + + def dat( + self, + name: str, + lines: int | np.integer, + mtime: datetime.datetime, + first_line: datetime.datetime | None = None, + ) -> None: + """Add an empty .dat file with its line count, file time and first-line time.""" + p = self.dir / name + p.write_bytes(b"") + stamp = mtime.timestamp() + os.utime(p, (stamp, stamp)) + first = math.nan if first_line is None else datenum(first_line) + self.info[name] = (lines, first) + + def triggered( + self, lines1: Sequence[int], lines2: Sequence[int] + ) -> tuple[list[str], list[str]]: + """Add triggered recordings of both paths with the given line counts. + + Returns + ------- + dmd1 : list of str + File names of path 1's recordings. + dmd2 : list of str + File names of path 2's recordings. + """ + dmd1 = [f"acq_DMD1-TRIAL{k:06d}.dat" for k in range(1, len(lines1) + 1)] + dmd2 = [f"acq_DMD2-TRIAL{k:06d}.dat" for k in range(1, len(lines2) + 1)] + for k, (name, n) in enumerate(zip(dmd1, lines1), start=1): + self.dat(name, n, START + datetime.timedelta(minutes=k)) + for k, (name, n) in enumerate(zip(dmd2, lines2), start=1): + self.dat(name, n, START + datetime.timedelta(minutes=k)) + return dmd1, dmd2 + + def references(self) -> None: + """Write a small reference stack per path, described as SLAP2 does.""" + import tifffile + + ref = self.dir / "reference" + ref.mkdir() + rng = np.random.default_rng(0) + for dmd in (1, 2): + with tifffile.TiffWriter(ref / f"acq_DMD{dmd}_CONFIG1-REFERENCE.tif") as tw: + for z in (0, 1, 2): + for ch in (1, 2): + desc = { + "channel": ch, + "z": z, + "dmdPixel2SampleTransform": np.eye(3).tolist(), + } + page = rng.random((8, 6)).astype(np.float32) + tw.write(page, description=json.dumps(desc), metadata=None) + + def mtimes(self, names: Sequence[str]) -> np.ndarray: + """Return the files' modification times as MATLAB datenums. + + Returns + ------- + np.ndarray + One datenum per file name, in the order given. + """ + return np.array([tt._mtime_datenum(self.dir / n) for n in names]) + + def build(self, save_dir: Path, **kw: float | bool | None) -> dict: + """Build the trial table of this folder. + + Returns + ------- + dict + The trial table built by build_trial_table_slap2. + """ + return build_trial_table_slap2(self.dir, save_dir, **kw) + + +@pytest.fixture +def session(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> FakeSession: + """Provide a fake session in a temporary folder. + + Returns + ------- + FakeSession + A session whose reader is replaced by a fake one. + """ + return FakeSession(tmp_path, monkeypatch) + + +def test_triggered_trials(session: FakeSession, tmp_path: Path) -> None: + """Triggered recordings of both paths give one trial per file pair.""" + lines = [100000, 120000, 110000] + dmd1, dmd2 = session.triggered(lines, lines) + session.references() + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["epoch"], np.ones((2, 3))) + np.testing.assert_array_equal(t["true_trial_ix"], np.tile([1, 2, 3], (2, 1))) + s2 = t["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.ones((2, 3))) + np.testing.assert_array_equal(s2["last_line"], np.tile(lines, (2, 1))) + ends = session.mtimes(dmd1) + np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), ends, rtol=0, atol=1e-9) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + ends - np.array(lines) * LINE_PERIOD_S / 86400, + rtol=0, + atol=1e-9, + ) + + +def test_triggered_trial_line_mismatch(session: FakeSession, tmp_path: Path) -> None: + """A file holding two trials back to back is lined up with the other path.""" + # DMD1's trial number failed to increment: its second file holds DMD2's + # second and third trials back to back + dmd1, dmd2 = session.triggered([100000, 220000], [100000, 100000, 120000]) + session.references() + s = session.build(tmp_path / "out") + assert s["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] + s2 = s["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], [[1, 1, 100001], [1, 1, 1]]) + np.testing.assert_array_equal( + s2["last_line"], [[100000, 100000, 220000], [100000, 100000, 120000]] + ) + dn1, dn2 = session.mtimes(dmd1), session.mtimes(dmd2) + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + [dn1[0], dn2[1], dn1[1]], + rtol=0, + atol=1e-9, + ) + + +def test_order_from_file_names_not_mod_times(session: FakeSession, tmp_path: Path) -> None: + """Acquisitions are ordered by the time in their names, not by file times.""" + # copies carry upload times: DMD1's are scrambled within a few seconds, + # DMD2's identical; the earlier acquisition sorts last alphabetically + acqs = [("spont_20250314_101500", 2), ("activity_20250314_111223", 12)] + dmd1 = [f"{a}_DMD1-TRIAL{k:06d}.dat" for a, n in acqs for k in range(1, n + 1)] + dmd2 = [n.replace("DMD1", "DMD2") for n in dmd1] + lines = 100000 + 100 * np.arange(1, len(dmd1) + 1) + upload = datetime.datetime(2026, 8, 27, 10, 53, 33) + for k, (a, b) in enumerate(zip(dmd1, dmd2), start=1): + session.dat(a, lines[k - 1], upload + datetime.timedelta(seconds=(7 * k) % 5)) + session.dat(b, lines[k - 1], upload) + session.references() + with pytest.warns(TrialTableWarning, match="do not look like acquisition times"): + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["true_trial_ix"][0], np.arange(1, len(dmd1) + 1)) + np.testing.assert_array_equal(t["slap2_info"]["last_line"], np.tile(lines, (2, 1))) + np.testing.assert_allclose( + t["slap2_info"]["trial_end_time_from_pc"].ravel(), + session.mtimes(dmd1), + rtol=0, + atol=1e-9, + ) + + +def test_file_order_falls_back_to_mod_time(session: FakeSession, tmp_path: Path) -> None: + """Without a time in the names, files are ordered by modification time.""" + names = ["b_DMD1.dat", "a_DMD1.dat"] + for k, n in enumerate(names, start=1): + t = START + datetime.timedelta(minutes=k) + session.dat(n, 100000, t) + session.dat(n.replace("DMD1", "DMD2"), 100000, t) + session.references() + with pytest.warns(TrialTableWarning, match="modification time"): + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [ + names, + [n.replace("DMD1", "DMD2") for n in names], + ] + + +def test_trial_times_from_line_clock(session: FakeSession, tmp_path: Path) -> None: + """Trial times come from the line clock, which shows gaps the line counts hide.""" + # DMD1's second file holds trials 2 and 3, with a 0.5 s gap that the line + # count alone doesn't show; mtimes are identical upload times + starts = [ + datetime.datetime(2025, 3, 14, 11, 12, 55) + datetime.timedelta(seconds=s) + for s in (0, 10.5, 21) + ] + upload = datetime.datetime(2026, 8, 27, 10, 53, 33) + dmd1 = [f"activity_20250314_111223_DMD1-TRIAL{k:06d}.dat" for k in (1, 2)] + dmd2 = [f"activity_20250314_111223_DMD2-TRIAL{k:06d}.dat" for k in (1, 2, 3)] + session.dat(dmd1[0], 100000, upload, starts[0]) + session.dat(dmd1[1], 220000, upload, starts[1]) + for name, n, s in zip(dmd2, (100000, 100000, 120000), starts): + session.dat(name, n, upload, s) + session.references() + with warnings.catch_warnings(): + warnings.simplefilter("error") + t = session.build(tmp_path / "out") + assert t["filename"].tolist() == [[dmd1[0], dmd1[1], dmd1[1]], dmd2] + days = np.array([datenum(s) for s in starts]) + s2 = t["slap2_info"] + np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days, rtol=0, atol=1e-9) + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + days + np.array([100000, 100000, 120000]) * LINE_PERIOD_S / 86400, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_trials_and_times(session: FakeSession, tmp_path: Path) -> None: + """A continuous recording is cut into trials with times from the line clock.""" + lines = 450000 + t0 = datetime.datetime(2025, 3, 14, 11, 12, 55) + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START, t0) + # later files of the recording are skipped (their line counts unknown) + for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): + (session.dir / n).write_bytes(b"") + session.references() + t = session.build(tmp_path / "out") + edges = np.array([1, 150001, 300001, 450001], dtype=float) + assert t["filename"].tolist() == [[names[0]] * 3, [names[1]] * 3] + s2 = t["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.tile(edges[:3], (2, 1))) + np.testing.assert_array_equal(s2["last_line"], np.tile(edges[1:], (2, 1))) + days = datenum(t0) + (edges - 1) * LINE_PERIOD_S / 86400 + np.testing.assert_allclose(s2["trial_start_time_inferred"].ravel(), days[:3], rtol=0, atol=1e-9) + np.testing.assert_allclose(s2["trial_end_time_from_pc"].ravel(), days[1:], rtol=0, atol=1e-9) + + +def test_multicycle_times_from_mtime(session: FakeSession, tmp_path: Path) -> None: + """Without the line clock, a continuous recording's times come from file times.""" + lines = 450000 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + edges = np.array([1, 150001, 300001, 450001], dtype=float) + dn = session.mtimes(names[:1])[0] + to_days = LINE_PERIOD_S / 86400 + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + dn - (lines - edges[1:]) * to_days, + rtol=0, + atol=1e-9, + ) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + dn - (lines - edges[:3]) * to_days, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_times_from_last_file_mtime(session: FakeSession, tmp_path: Path) -> None: + """Without the line clock, a CYCLE-split recording ends at its last file's modification time. + + MATLAB takes the first file's. + """ + lines = 450000 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + end = START + datetime.timedelta(seconds=30) + for n in ("acq_DMD1-CYCLE-000001.dat", "acq_DMD2-CYCLE-000001.dat"): + (session.dir / n).write_bytes(b"") + os.utime(session.dir / n, (end.timestamp(), end.timestamp())) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + last = session.mtimes(["acq_DMD1-CYCLE-000001.dat"])[0] + edges = np.array([1, 150001, 300001, 450001], dtype=float) + to_days = LINE_PERIOD_S / 86400 + np.testing.assert_allclose( + s2["trial_end_time_from_pc"].ravel(), + last - (lines - edges[1:]) * to_days, + rtol=0, + atol=1e-9, + ) + np.testing.assert_allclose( + s2["trial_start_time_inferred"].ravel(), + last - (lines - edges[:3]) * to_days, + rtol=0, + atol=1e-9, + ) + + +def test_multicycle_edges_are_matlab_linspace(session: FakeSession, tmp_path: Path) -> None: + """The trial edges of a continuous recording are MATLAB's linspace values.""" + # 3 trials of 599838 lines: the edges are fractional, as MATLAB's + lines = 599837 + names = ["acq_DMD1-CYCLE-000000.dat", "acq_DMD2-CYCLE-000000.dat"] + for n in names: + session.dat(n, lines, START) + session.references() + s2 = session.build(tmp_path / "out")["slap2_info"] + edges = matlab_linspace(1, lines + 1, 4) + assert edges[1] != round(edges[1]) + np.testing.assert_array_equal(s2["first_line"][0], edges[:3]) + np.testing.assert_array_equal(s2["last_line"][0], edges[1:]) + + +def test_matlab_linspace_values() -> None: + """matlab_linspace reproduces values computed in MATLAB.""" + # values from MATLAB R2023b: linspace(1, 599838, 4) + y = matlab_linspace(1, 599838, 4) + assert y[0] == 1 and y[-1] == 599838 + assert y[1] == 1 + (1 * (599838 - 1)) / 3 + assert y[2] == 1 + (2 * (599838 - 1)) / 3 + + +def test_reference_stack(session: FakeSession, tmp_path: Path) -> None: + """Each path's reference stack is found and stored.""" + session.triggered([100000], [100000]) + session.references() + t = session.build(tmp_path / "out") + for path in ("Path1", "Path2"): + ref = t["slap2_info"]["ref_stack"][path] + np.testing.assert_array_equal(ref["channels"], [1, 2]) + np.testing.assert_array_equal(ref["Zs"], [0, 1, 2]) + np.testing.assert_array_equal(ref["dmdPixel2SampleTransform"], np.eye(3)) + assert ref["IM"].shape == ( + 6, + 8, + 6, + ) # columns x rows x pages, as MATLAB + assert ref["IM"].dtype == np.float32 + + +def test_write_trial_table_h5(session: FakeSession, tmp_path: Path) -> None: + """The written trial_table.h5 holds the table in MATLAB's column-major layout.""" + dmd1, dmd2 = session.triggered([100000, 120000], [100000, 120000]) + session.references() + out = tmp_path / "out" + built = session.build(out) + t = load_struct_h5(out / "trial_table.h5") + assert t["datadr"] == str(session.dir) + assert t["savedr"] == str(out) + assert t["filename"].tolist() == [dmd1, dmd2] + np.testing.assert_array_equal(t["slap2_info"]["last_line"], [[100000, 120000]] * 2) + np.testing.assert_array_equal( + t["slap2_info"]["ref_stack"]["Path1"]["IM"], + built["slap2_info"]["ref_stack"]["Path1"]["IM"], + ) + with h5py.File(out / "trial_table.h5", "r") as h: + # stored column-major, as MATLAB's saveStructToH5 writes it + assert h["filename"].shape == (2, 2) + assert h["slap2_info/first_line"].shape == (2, 2) + assert h["slap2_info/ref_stack/Path1/IM"].shape == (6, 8, 6) + assert h["slap2_info/ref_stack/Path1/Zs"].shape == (3, 1) + assert h["row_major"][()].item() == 0 + + +def test_max_duration_trims_and_keeps_untrimmed(session: FakeSession, tmp_path: Path) -> None: + """max_duration_s trims the table and also writes the untrimmed one.""" + session.triggered([100000, 120000, 110000], [100000, 120000, 110000]) + session.references() + out = tmp_path / "out" + t = session.build(out, max_duration_s=15.0) # 10 s + 5 s of the 12 s trial + assert (out / "trial_table_untrimmed.h5").exists() + s2 = load_struct_h5(out / "trial_table.h5")["slap2_info"] + np.testing.assert_array_equal(s2["first_line"], np.ones((2, 2))) + np.testing.assert_array_equal(s2["last_line"], [[100000, 50000]] * 2) + assert t["filename"].shape == (2, 2) + assert np.asarray(s2["trial_start_time_inferred"]).size == 2 + full = load_struct_h5(out / "trial_table_untrimmed.h5") + assert full["filename"].shape == (2, 3) + + +def test_trim_keeps_whole_trials_before_the_limit() -> None: + """Trimming keeps the trials that start before the limit and shortens the last.""" + table = { + "filename": np.array([["a", "b"], ["c", "d"]], dtype=object), + "true_trial_ix": np.array([[1.0, 2.0], [1.0, 2.0]]), + "epoch": np.ones((2, 2)), + "slap2_info": { + "first_line": np.ones((2, 2)), + "last_line": np.full((2, 2), 1000.0), + "trial_end_time_from_pc": np.array([[1.0, 2.0]]), + "trial_start_time_inferred": np.array([[0.5, 1.5]]), + }, + } + out, info = trim_trial_table(table, 0.15, 1e-4) # 0.1 s trials + assert info["n_trials_kept"] == 2 and info["last_trial_shortened"] + keep = math.floor((0.15 - 1000 * 1e-4) / 1e-4) # 499 in floating point, as in MATLAB + np.testing.assert_array_equal(out["slap2_info"]["last_line"], [[1000, keep]] * 2) + out, info = trim_trial_table(table, 1.0, 1e-4) + assert info["n_trials_kept"] == 2 and not info["last_trial_shortened"] + with pytest.raises(ValueError): + trim_trial_table(table, 0.0, 1e-4) + + +def test_no_reference_stack_error(session: FakeSession, tmp_path: Path) -> None: + """A session without a reference stack raises FileNotFoundError.""" + session.triggered([100000], [100000]) + with pytest.raises(FileNotFoundError): + session.build(tmp_path / "out") + + +def test_unaligned_dmds_error(session: FakeSession, tmp_path: Path) -> None: + """Paths whose recordings do not line up raise an error.""" + session.triggered([100000], [150000]) + session.references() + with pytest.raises(ValueError, match="lining up"): + session.build(tmp_path / "out") + + +def test_unmatched_trailing_recordings_warn(session: FakeSession, tmp_path: Path) -> None: + """Data left after the last trial that lines up is left out, as in MATLAB, with a warning.""" + session.triggered([100000, 100000], [100000]) + session.references() + with pytest.warns(TrialTableWarning, match="100000 lines of DMD1"): + t = session.build(tmp_path / "out") + assert t["filename"].shape == (2, 1) + + +def test_no_trials_error(session: FakeSession, tmp_path: Path) -> None: + """A session in which no trial lines up warns and raises.""" + session.triggered([100000], []) + session.references() + with pytest.warns(TrialTableWarning, match="left out"): + with pytest.raises(ValueError, match="No trials"): + session.build(tmp_path / "out") + + +@pytest.mark.filterwarnings("ignore:Could not read acquisition times") +def test_mixed_continuous_and_triggered_error(session: FakeSession, tmp_path: Path) -> None: + """Continuous and triggered recordings in one folder raise an error.""" + session.triggered([100000], [100000]) + for n in ("acq2_DMD1-CYCLE-000000.dat", "acq2_DMD2-CYCLE-000000.dat"): + session.dat(n, 450000, START + datetime.timedelta(minutes=5)) + session.references() + with pytest.raises(ValueError, match="both continuous"): + session.build(tmp_path / "out") + + +def test_acquisition_order() -> None: + """Files sort by acquisition time and trial number; ambiguous names are refused.""" + names = [ + "a_20250314_111223_DMD1-TRIAL000010.dat", + "a_20250314_111223_DMD1-TRIAL000002.dat", + "b_20250314_101500_DMD1-TRIAL000001.dat", + ] + order, ok = acquisition_order(names) + assert ok and order.tolist() == [2, 1, 0] + order, ok = acquisition_order(["x_DMD1-TRIAL000002.dat", "x_DMD1-TRIAL000001.dat"]) + assert ok and order.tolist() == [1, 0] + _, ok = acquisition_order(["b_DMD1.dat", "a_DMD1.dat"]) + assert not ok + _, ok = acquisition_order(["x_DMD1.dat", "x_DMD1-CYCLE-000000.dat"]) + assert not ok # same position + + +def _write_mat_datetime(path: Path, ms: complex, tz: str = "") -> None: + """Write a v7.3 MAT file holding fpgaTimeReference as MATLAB writes it. + + The ``FileWrapper__`` blob lists strings, one class (datetime) and one + object whose properties are data (cell 0) and, when given, tz + (cell 1). + """ + strings = [b"data", b"datetime", b"fmt", b"tz"] + names = b"".join(s + b"\0" for s in strings) + names += b"\0" * (-len(names) % 8) + classes = struct.pack("<8I", 0, 0, 0, 0, 0, 2, 0, 0) + objects = struct.pack("<12I", 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1) + props = [(1, 1, 0)] + ([(4, 1, 1)] if tz else []) + words = [0, 0, len(props)] + [v for p in props for v in p] + words += [0] * (len(words) % 2) + sets = struct.pack(f"<{len(words)}I", *words) + o0 = 40 + len(names) + o1 = o0 + len(classes) + o2 = o1 + o3 = o2 + len(objects) + o4 = o3 + len(sets) + header = struct.pack(" None: + """The .meta decoder reads an unzoned MATLAB datetime.""" + # 2025-03-14 09:30:20.5 wall clock, unzoned + ms = ( + datetime.datetime(2025, 3, 14, 9, 30, 20, 500000) - datetime.datetime(1970, 1, 1) + ).total_seconds() * 1000 + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(ms, -8.6e-5)) + assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 8.6e-5, abs=1e-9) + assert read_mat_datetime_ms(p, "missing") is None + # zoned: data is UTC; the wall clock in Los Angeles is 7 h earlier in March + _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") + assert read_mat_datetime_ms(p, "fpgaTimeReference") == pytest.approx(ms - 7 * 3600e3) + + +def test_read_mat_datetime_offset_across_dst(tmp_path: Path) -> None: + """The offset is elapsed time. + + 01:30 PST plus two hours on the day DST starts is 04:30 PDT (MATLAB: + datetime + seconds). + """ + utc = datetime.datetime(2025, 3, 9, 9, 30) # 01:30 in Los Angeles (PST) + ms = (utc - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(ms, 0), tz="America/Los_Angeles") + wall = read_mat_datetime_ms(p, "fpgaTimeReference", offset_ms=2 * 3600e3) + expected = datetime.datetime(2025, 3, 9, 4, 30) - datetime.datetime(1970, 1, 1) + assert wall == pytest.approx(expected.total_seconds() * 1000, abs=1e-6) + + +@pytest.mark.parametrize("n", [0, 2]) +def test_read_mat_datetime_needs_one_value(tmp_path: Path, n: int) -> None: + """An empty or multi-element reference gives None, not an error or the first value. + + File times are used instead. + """ + p = tmp_path / "a.meta" + _write_mat_datetime(p, complex(1.7e12, 0)) + with h5py.File(p, "r+") as h: + del h["#refs#/c"] + h["#refs#"].create_dataset("c", data=np.zeros((1, n), [("real", " None: + """The first line's timestamp is read from the .dat file, after a magic-number check.""" + + class File: + """A stand-in for the SLAP2 data-file object.""" + + datFileName = str(tmp_path / "x.dat") + header = {"firstCycleOffsetBytes": 16} + + line = struct.pack(" TrialWarp: - """Each trial's map from the canvas to its registered frame. - - Returns - ------- - TrialWarp - The two trials' maps: shifts only for "rigid", otherwise with a patchwise displacement - field. - """ - shifts = np.array([[0.3, -0.4], [-0.6, 0.5]]) - if mode == "rigid": - return TrialWarp.from_shifts(shifts) - nodes = np.array([[10.0, 10.0], [10.0, 50.0], [30.0, 10.0], [30.0, 50.0]]) - rng = np.random.default_rng(1) - disp = shifts[:, None, :] + rng.uniform(-0.6, 0.6, (N_TRIALS, 4, 2)) - affine = np.zeros((N_TRIALS, 2, 3)) - affine[:, :, :2] = np.eye(2) - affine[:, :, 2] = shifts - return TrialWarp(affine, nodes, 15.0, disp) - - -def gaussian( - shape: tuple[int, int], - centre: Sequence[float], - sigma: float = SIGMA, - at: tuple[np.ndarray, np.ndarray] | None = None, -) -> np.ndarray: - """Build a Gaussian image summing to 1 on the canvas grid (zero beyond 3 sigma). - - With at = (rows, cols), the same function evaluated at those canvas - positions instead of the grid. - - Returns - ------- - np.ndarray - The Gaussian image, normalized by its sum on the grid. - """ - rr, cc = np.mgrid[: shape[0], : shape[1]] - - def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: - """Evaluate the truncated, unnormalized Gaussian. - - Returns - ------- - np.ndarray - The Gaussian at (r, c), zero beyond 3 sigma from the centre. - """ - d2 = (r - centre[0]) ** 2 + (c - centre[1]) ** 2 - return np.where(d2 > (3 * sigma) ** 2, 0.0, np.exp(-d2 / (2 * sigma**2))) - - z = f(rr, cc).sum() - return (f(rr, cc) if at is None else f(*at)) / z - - -def traces(n200: int, n_src: int) -> np.ndarray: - """Denoised traces (n200, sources): decaying events. - - Returns - ------- - np.ndarray - The (n200, n_src) traces: six random events per source, each decaying exponentially. - """ - rng = np.random.default_rng(2) - x = np.zeros((n200, n_src)) - k = np.exp(-np.arange(40) / 4.8) - for s in range(n_src): - spikes = np.zeros(n200) - spikes[rng.choice(np.arange(20, n200 - 50), 6, replace=False)] = rng.uniform(20, 80, 6) - x[:, s] = np.convolve(spikes, k)[:n200] - return x - - -def _put(g: h5py.Group, name: str, a: npt.ArrayLike) -> None: - """Write a as MATLAB would (h5py shows the axes reversed).""" - a = np.asarray(a) - g.create_dataset(name, data=a.T if a.ndim > 1 else a) - - -def _strings(a: npt.ArrayLike) -> np.ndarray: - """Convert to a string array for the trial table. - - Returns - ------- - np.ndarray - The values as an object array with h5py's string dtype. - """ - return np.asarray(a, dtype=object).astype(h5py.string_dtype()) - - -def write_session(root: Path, mode: str = "rigid", n80: int = 120) -> dict[str, Any]: - """Write the synthetic session under root. - - Returns - ------- - dict - Its folders (run, moco, base), the warp, the true trial-frame footprints - (true_fp) and the movies, the 200 Hz traces (x200), their frame lines and - the 80 Hz frame times (ds). - """ - root = Path(root) - moco, base, run = (root / x for x in ("moco", "base", "run")) - for d in (moco, base, run / "source_extraction"): - d.mkdir(parents=True, exist_ok=True) - warp = make_warp(mode) - n_src = CENTRES.shape[0] - ds = 1.0 + DT80 * np.arange(n80) - lines = np.ceil(1.0 + 53.4 * np.arange(int(ds[-1] / 53.4) + 1)) - n200 = lines.size - x200 = [traces(n200, n_src) * (1 + 0.2 * t) for t in range(N_TRIALS)] - true_fp, movies = [], [] - for t in range(N_TRIALS): - w, _ = frame_weights(lines, np.zeros(n200, bool), ds, DT80, 3 * DT80) - x80 = (w.T @ x200[t]).T # (sources, frames) - qr, qc = np.mgrid[:H, :W].astype(float) - at = warp.inverse(t, qr, qc) # canvas position of each trial pixel - fps = np.stack([gaussian((H, W), c, at=at) for c in CENTRES]) - mov = BASELINE + np.einsum("sab,sf->fab", fps, x80) - true_fp.append(fps) - movies.append(mov.astype(np.float32)) - stem = f"E1T{t + 1}DMD1" - with h5py.File(moco / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5", "w") as f: - f["mov"] = movies[-1].transpose(0, 2, 1) # (pages, cols, rows) - with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: - f["DSframes"] = ds[:, None] - f["alignHz"] = np.array([[80.0]]) - f["recNegErr"] = np.zeros((n80, 1)) - with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: - f["baseline"] = np.full((n80, W, H), BASELINE, np.float16) - _write_table(run / "trial_table.h5", run, moco) - _write_summaries(run / "source_extraction", warp, lines, x200, mode) - return { - "run": run, - "moco": moco, - "base": base, - "warp": warp, - "true_fp": true_fp, - "movies": movies, - "x200": x200, - "lines": lines, - "ds": ds, - } - - -def _write_table(path: Path, savedr: Path, moco: Path) -> None: - """Write a one-path, two-trial trial table (row-major).""" - names = [f"E1T{t + 1}DMD1" for t in range(N_TRIALS)] - with h5py.File(path, "w") as f: - f["row_major"] = np.array([[1]], np.uint8) - f["filename"] = _strings([[f"x-TRIAL{t + 1:06d}.dat" for t in range(N_TRIALS)]]) - g = f.create_group("motion_correction") - g["fn_reg_ds"] = _strings([[f"{n}_REGISTERED_DOWNSAMPLED-80Hz.h5" for n in names]]) - g["fn_adata"] = _strings([[f"{n}_ALIGNMENTDATA.h5" for n in names]]) - f["savedr"] = _strings([[str(savedr)]]) - f["datadr"] = _strings([[str(savedr / "raw")]]) - - -def _write_summaries( - out: Path, warp: TrialWarp, lines: np.ndarray, x200: list[np.ndarray], mode: str -) -> None: - """Both summaries of the synthetic run.""" - n_src, total = CENTRES.shape[0], lines.size * N_TRIALS - fp = np.stack([gaussian((H, W), c) for c in CENTRES]) # canvas - with h5py.File(out / "experiment_summary.h5", "w") as f: - p = f.create_group("params") - for k, v in ( - ("numChannels", 1), - ("activityChannel", 1), - ("alignHz", 80.0), - ("analyzeHz", 200.0), - ("motionThresh", 2.0), - ("discardInitial_s", 0.0), - ("nanThresh", 0.33), - ("peakth", 8.0), - ): - p[k] = np.array([[v]]) - p["validKernel"] = np.ones((5, 5)) - p["interTrialAlignment"] = mode - g = f.create_group("Path1") - act = fp.sum(0) - _put(g, "visualizations/act_im", act[None]) - _put(g, "visualizations/mean_im", (BASELINE + act)[None, None]) - rc = np.column_stack([np.zeros(n_src), CENTRES]) - _put( - g, - "visualizations/act_im_peaks", - np.column_stack([np.zeros(n_src), np.round(CENTRES)]), - ) - fi = "frame_info" - _put( - g, - f"{fi}/trial_num_frames", - np.full((N_TRIALS, 1), lines.size, np.int32), - ) - _put( - g, - f"{fi}/frame_line_idxs", - np.tile(lines, N_TRIALS)[:, None].astype(np.int32), - ) - _put(g, f"{fi}/discard_frames", np.zeros((total, 1), np.int8)) - _put(g, f"{fi}/trial_alignment_affine", warp.affine) - if mode == "patchwise": - disp = np.zeros((N_TRIALS, 2, H, W), np.float32) - rr, cc = np.mgrid[:H, :W] - for t in range(N_TRIALS): - r_t, c_t = warp.grid_coords(t, (H, W)) - disp[t, 0], disp[t, 1] = r_t - rr, c_t - cc - _put(g, f"{fi}/trial_alignment_displacement", disp) - _put(g, "sources/spatial/coords", rc) - _put(g, "sources/spatial/profiles", fp[:, None].astype(np.float32)) - x = np.concatenate(x200, 0) # (total, sources) - for name, val in ( - ("dF_denoised", x), - ("dF_ls", x + 1.0), - ("events", np.zeros_like(x)), - ("F0", np.full_like(x, 50.0)), - ): - _put(g, f"sources/temporal/{name}", val.T[:, None, :]) - _put(g, "sources/temporal/SNR", np.arange(1.0, n_src + 1)[:, None]) - _put(g, "sources/temporal/kinetic_score", np.full((n_src, 1), 0.8)) - _put( - g, - "sources/temporal/kinetic_n_events", - np.full((n_src, 1), 6, np.int32), - ) - _put(g, "sources/rejected/seed_coords", np.array([[0.0, 5.0, 5.0]])) - _put(g, "sources/rejected/kinetic_score", np.array([[0.1]])) - _put(g, "sources/rejected/kinetic_n_events", np.array([[3]], np.int32)) - with h5py.File(out / "per_trial_summary.h5", "w") as f: - g = f.create_group("Path1") - _put( - g, - "visualizations/per_trial_act_im", - np.stack([fp.sum(0)] * N_TRIALS)[:, None], - ) - _put( - g, - "visualizations/per_trial_mean_im", - np.stack([BASELINE + fp.sum(0)] * N_TRIALS)[:, None, None], - ) - _put( - g, - "sources/spatial/per_trial_profiles", - np.stack([fp[:, None]] * N_TRIALS).astype(np.float32), - ) - coords = np.zeros((N_TRIALS, n_src, 3)) - coords[:, :, 1:] = CENTRES - _put(g, "sources/spatial/per_trial_coords", coords) +"""A small synthetic SILo run for the viewer's tests. + +Writes what giant view reads, in the layout giant silo writes it +(the summaries in MATLAB's orientation, h5py's axes reversed): a trial +table, two trials of one path with registered 80 Hz movies (HDF5) and +alignment files, network baselines, and both summaries. The movie is a +constant baseline plus every source's footprint in the trial's frame (the +canvas Gaussian evaluated, exactly, at the map's inverse of each trial +pixel: SILo reads a trial's data through the same map) times its 200 Hz +trace averaged into the 80 Hz frames with the given weights. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +import h5py +import numpy as np +import numpy.typing as npt + +from giant_python.extraction.raster.alignment import TrialWarp +from giant_python.viewer.render import frame_weights + +H, W = 40, 60 +N_TRIALS = 2 +DT80 = 134 +SIGMA = 1.33 +CENTRES = np.array([[12.3, 15.6], [20.0, 30.4], [28.7, 44.2]]) +BASELINE = 10.0 + + +def make_warp(mode: str) -> TrialWarp: + """Each trial's map from the canvas to its registered frame. + + Returns + ------- + TrialWarp + The two trials' maps: shifts only for "rigid", otherwise with a patchwise displacement + field. + """ + shifts = np.array([[0.3, -0.4], [-0.6, 0.5]]) + if mode == "rigid": + return TrialWarp.from_shifts(shifts) + nodes = np.array([[10.0, 10.0], [10.0, 50.0], [30.0, 10.0], [30.0, 50.0]]) + rng = np.random.default_rng(1) + disp = shifts[:, None, :] + rng.uniform(-0.6, 0.6, (N_TRIALS, 4, 2)) + affine = np.zeros((N_TRIALS, 2, 3)) + affine[:, :, :2] = np.eye(2) + affine[:, :, 2] = shifts + return TrialWarp(affine, nodes, 15.0, disp) + + +def gaussian( + shape: tuple[int, int], + centre: Sequence[float], + sigma: float = SIGMA, + at: tuple[np.ndarray, np.ndarray] | None = None, +) -> np.ndarray: + """Build a Gaussian image summing to 1 on the canvas grid (zero beyond 3 sigma). + + With at = (rows, cols), the same function evaluated at those canvas + positions instead of the grid. + + Returns + ------- + np.ndarray + The Gaussian image, normalized by its sum on the grid. + """ + rr, cc = np.mgrid[: shape[0], : shape[1]] + + def f(r: np.ndarray, c: np.ndarray) -> np.ndarray: + """Evaluate the truncated, unnormalized Gaussian. + + Returns + ------- + np.ndarray + The Gaussian at (r, c), zero beyond 3 sigma from the centre. + """ + d2 = (r - centre[0]) ** 2 + (c - centre[1]) ** 2 + return np.where(d2 > (3 * sigma) ** 2, 0.0, np.exp(-d2 / (2 * sigma**2))) + + z = f(rr, cc).sum() + return (f(rr, cc) if at is None else f(*at)) / z + + +def traces(n200: int, n_src: int) -> np.ndarray: + """Denoised traces (n200, sources): decaying events. + + Returns + ------- + np.ndarray + The (n200, n_src) traces: six random events per source, each decaying exponentially. + """ + rng = np.random.default_rng(2) + x = np.zeros((n200, n_src)) + k = np.exp(-np.arange(40) / 4.8) + for s in range(n_src): + spikes = np.zeros(n200) + spikes[rng.choice(np.arange(20, n200 - 50), 6, replace=False)] = rng.uniform(20, 80, 6) + x[:, s] = np.convolve(spikes, k)[:n200] + return x + + +def _put(g: h5py.Group, name: str, a: npt.ArrayLike) -> None: + """Write a as MATLAB would (h5py shows the axes reversed).""" + a = np.asarray(a) + g.create_dataset(name, data=a.T if a.ndim > 1 else a) + + +def _strings(a: npt.ArrayLike) -> np.ndarray: + """Convert to a string array for the trial table. + + Returns + ------- + np.ndarray + The values as an object array with h5py's string dtype. + """ + return np.asarray(a, dtype=object).astype(h5py.string_dtype()) + + +def write_session(root: Path, mode: str = "rigid", n80: int = 120) -> dict[str, Any]: + """Write the synthetic session under root. + + Returns + ------- + dict + Its folders (run, moco, base), the warp, the true trial-frame footprints + (true_fp) and the movies, the 200 Hz traces (x200), their frame lines and + the 80 Hz frame times (ds). + """ + root = Path(root) + moco, base, run = (root / x for x in ("moco", "base", "run")) + for d in (moco, base, run / "source_extraction"): + d.mkdir(parents=True, exist_ok=True) + warp = make_warp(mode) + n_src = CENTRES.shape[0] + ds = 1.0 + DT80 * np.arange(n80) + lines = np.ceil(1.0 + 53.4 * np.arange(int(ds[-1] / 53.4) + 1)) + n200 = lines.size + x200 = [traces(n200, n_src) * (1 + 0.2 * t) for t in range(N_TRIALS)] + true_fp, movies = [], [] + for t in range(N_TRIALS): + w, _ = frame_weights(lines, np.zeros(n200, bool), ds, DT80, 3 * DT80) + x80 = (w.T @ x200[t]).T # (sources, frames) + qr, qc = np.mgrid[:H, :W].astype(float) + at = warp.inverse(t, qr, qc) # canvas position of each trial pixel + fps = np.stack([gaussian((H, W), c, at=at) for c in CENTRES]) + mov = BASELINE + np.einsum("sab,sf->fab", fps, x80) + true_fp.append(fps) + movies.append(mov.astype(np.float32)) + stem = f"E1T{t + 1}DMD1" + with h5py.File(moco / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz.h5", "w") as f: + f["mov"] = movies[-1].transpose(0, 2, 1) # (pages, cols, rows) + with h5py.File(moco / f"{stem}_ALIGNMENTDATA.h5", "w") as f: + f["DSframes"] = ds[:, None] + f["alignHz"] = np.array([[80.0]]) + f["recNegErr"] = np.zeros((n80, 1)) + with h5py.File(base / f"{stem}_BASELINE-80Hz.h5", "w") as f: + f["baseline"] = np.full((n80, W, H), BASELINE, np.float16) + _write_table(run / "trial_table.h5", run, moco) + _write_summaries(run / "source_extraction", warp, lines, x200, mode) + return { + "run": run, + "moco": moco, + "base": base, + "warp": warp, + "true_fp": true_fp, + "movies": movies, + "x200": x200, + "lines": lines, + "ds": ds, + } + + +def _write_table(path: Path, savedr: Path, moco: Path) -> None: + """Write a one-path, two-trial trial table (row-major).""" + names = [f"E1T{t + 1}DMD1" for t in range(N_TRIALS)] + with h5py.File(path, "w") as f: + f["row_major"] = np.array([[1]], np.uint8) + f["filename"] = _strings([[f"x-TRIAL{t + 1:06d}.dat" for t in range(N_TRIALS)]]) + g = f.create_group("motion_correction") + g["fn_reg_ds"] = _strings([[f"{n}_REGISTERED_DOWNSAMPLED-80Hz.h5" for n in names]]) + g["fn_adata"] = _strings([[f"{n}_ALIGNMENTDATA.h5" for n in names]]) + f["savedr"] = _strings([[str(savedr)]]) + f["datadr"] = _strings([[str(savedr / "raw")]]) + + +def _write_summaries( + out: Path, warp: TrialWarp, lines: np.ndarray, x200: list[np.ndarray], mode: str +) -> None: + """Both summaries of the synthetic run.""" + n_src, total = CENTRES.shape[0], lines.size * N_TRIALS + fp = np.stack([gaussian((H, W), c) for c in CENTRES]) # canvas + with h5py.File(out / "experiment_summary.h5", "w") as f: + p = f.create_group("params") + for k, v in ( + ("numChannels", 1), + ("activityChannel", 1), + ("alignHz", 80.0), + ("analyzeHz", 200.0), + ("motionThresh", 2.0), + ("discardInitial_s", 0.0), + ("nanThresh", 0.33), + ("peakth", 8.0), + ): + p[k] = np.array([[v]]) + p["validKernel"] = np.ones((5, 5)) + p["interTrialAlignment"] = mode + g = f.create_group("Path1") + act = fp.sum(0) + _put(g, "visualizations/act_im", act[None]) + _put(g, "visualizations/mean_im", (BASELINE + act)[None, None]) + rc = np.column_stack([np.zeros(n_src), CENTRES]) + _put( + g, + "visualizations/act_im_peaks", + np.column_stack([np.zeros(n_src), np.round(CENTRES)]), + ) + fi = "frame_info" + _put( + g, + f"{fi}/trial_num_frames", + np.full((N_TRIALS, 1), lines.size, np.int32), + ) + _put( + g, + f"{fi}/frame_line_idxs", + np.tile(lines, N_TRIALS)[:, None].astype(np.int32), + ) + _put(g, f"{fi}/discard_frames", np.zeros((total, 1), np.int8)) + _put(g, f"{fi}/trial_alignment_affine", warp.affine) + if mode == "patchwise": + disp = np.zeros((N_TRIALS, 2, H, W), np.float32) + rr, cc = np.mgrid[:H, :W] + for t in range(N_TRIALS): + r_t, c_t = warp.grid_coords(t, (H, W)) + disp[t, 0], disp[t, 1] = r_t - rr, c_t - cc + _put(g, f"{fi}/trial_alignment_displacement", disp) + _put(g, "sources/spatial/coords", rc) + _put(g, "sources/spatial/profiles", fp[:, None].astype(np.float32)) + x = np.concatenate(x200, 0) # (total, sources) + for name, val in ( + ("dF_denoised", x), + ("dF_ls", x + 1.0), + ("events", np.zeros_like(x)), + ("F0", np.full_like(x, 50.0)), + ): + _put(g, f"sources/temporal/{name}", val.T[:, None, :]) + _put(g, "sources/temporal/SNR", np.arange(1.0, n_src + 1)[:, None]) + _put(g, "sources/temporal/kinetic_score", np.full((n_src, 1), 0.8)) + _put( + g, + "sources/temporal/kinetic_n_events", + np.full((n_src, 1), 6, np.int32), + ) + _put(g, "sources/rejected/seed_coords", np.array([[0.0, 5.0, 5.0]])) + _put(g, "sources/rejected/kinetic_score", np.array([[0.1]])) + _put(g, "sources/rejected/kinetic_n_events", np.array([[3]], np.int32)) + with h5py.File(out / "per_trial_summary.h5", "w") as f: + g = f.create_group("Path1") + _put( + g, + "visualizations/per_trial_act_im", + np.stack([fp.sum(0)] * N_TRIALS)[:, None], + ) + _put( + g, + "visualizations/per_trial_mean_im", + np.stack([BASELINE + fp.sum(0)] * N_TRIALS)[:, None, None], + ) + _put( + g, + "sources/spatial/per_trial_profiles", + np.stack([fp[:, None]] * N_TRIALS).astype(np.float32), + ) + coords = np.zeros((N_TRIALS, n_src, 3)) + coords[:, :, 1:] = CENTRES + _put(g, "sources/spatial/per_trial_coords", coords) diff --git a/tests/viewer/test_viewer_render.py b/tests/viewer/test_viewer_render.py index 8065deea..2c9d0689 100644 --- a/tests/viewer/test_viewer_render.py +++ b/tests/viewer/test_viewer_render.py @@ -1,405 +1,405 @@ -"""Rendering of SILo's activity in a trial's movie (giant view).""" - -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.viewer.render import ( - KERNELS, - TrialMap, - exact_weights, - frame_weights, - interp_weights, - kernel_dt, - kernel_weights, - place_footprints, -) -from giant_python.viewer.run import SiloRun, footprint_width -from giant_python.viewer.trial import Session, load_trial, render_dt - -from .synthetic import ( - CENTRES, - N_TRIALS, - H, - W, - gaussian, - make_warp, - write_session, -) - - -def _exporter_weights( - lines200: np.ndarray, disc: np.ndarray, ds: np.ndarray, dt: float, half: float -) -> tuple[np.ndarray, np.ndarray]: - """Run the exporter's loop (exportF0TrainingData.m), as a dense matrix. - - Returns - ------- - weights : np.ndarray - (lines200.size, ds.size) weights of the kept 200 Hz lines in each frame, - each column normalized to sum to 1 (all zero when every line is discarded). - share : np.ndarray - Share of each frame's kernel weight that falls on discarded lines. - """ - wk = np.zeros((lines200.size, ds.size)) - share = np.zeros(ds.size) - for j in range(ds.size): - d = lines200 - ds[j] - sel = np.flatnonzero(np.abs(d) <= half) - w = np.exp(-np.abs(d[sel]) / dt) - share[j] = w[disc[sel]].sum() / max(w.sum(), np.finfo(float).eps) - keep = ~disc[sel] - if keep.any(): - wk[sel[keep], j] = w[keep] / w[keep].sum() - return wk, share - - -def test_frame_weights_match_the_exporter() -> None: - """Weights and discard shares equal the exporter's loop.""" - rng = np.random.default_rng(0) - lines200 = np.ceil(1 + 53.4 * np.arange(400)) - disc = rng.random(400) < 0.1 - ds = 1.0 + 134 * np.arange(150) + 7 - w, share = frame_weights(lines200, disc, ds, 134, 402) - ref, ref_share = _exporter_weights(lines200, disc, ds, 134, 402) - np.testing.assert_allclose(w.toarray(), ref, atol=1e-12) - np.testing.assert_allclose(share, ref_share, atol=1e-12) - full = np.asarray(w.sum(0)).ravel() - assert np.allclose(full[full > 0], 1.0) - - -def test_kernel_dt_and_matched_kernel() -> None: - """Dt from DSframes; the matched kernel removes the 200 Hz part.""" - assert kernel_dt(1 + 134 * np.arange(10), None, 2.5) == 134 - assert kernel_dt(np.array([5.0]), np.arange(0, 540, 54.0), 2.5) == 135 - lines = np.ceil(1 + 53.4 * np.arange(100)) - assert render_dt("exporter", 134, lines) == 134 - assert render_dt("matched", 134, lines) == pytest.approx(np.sqrt(134**2 - 54**2)) - with pytest.raises(ValueError): - render_dt("other", 134, lines) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_trial_map_inverse(mode: str) -> None: - """The map's inverse undoes it (and agrees with TrialWarp's).""" - warp = make_warp(mode) - rng = np.random.default_rng(3) - r, c = rng.uniform(3, H - 3, 200), rng.uniform(3, W - 3, 200) - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - rr, cc = np.mgrid[:H, :W] - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - fr, fc = m.forward(r, c) - er, ec = warp.coords(t, r, c) - tol = 1e-9 if mode == "rigid" else 2e-3 # bilinear field - np.testing.assert_allclose(fr, er, atol=tol) - np.testing.assert_allclose(fc, ec, atol=tol) - ir, ic = m.inverse(er, ec) - wr, wc = warp.inverse(t, er, ec) - np.testing.assert_allclose(ir, wr, atol=tol) - np.testing.assert_allclose(ic, wc, atol=tol) - - -def test_affine_map_inverse_is_exact() -> None: - """An affine map's inverse is exact.""" - a = np.array([[1.01, 0.02, 0.4], [-0.015, 0.99, -0.3]]) - m = TrialMap(a) - r, c = np.array([3.0, 10.5]), np.array([7.0, 2.25]) - fr, fc = m.forward(r, c) - ir, ic = m.inverse(fr, fc) - np.testing.assert_allclose(ir, r, atol=1e-12) - np.testing.assert_allclose(ic, c, atol=1e-12) - - -def _fp_tuple(img: np.ndarray, s: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Convert a canvas footprint image to (rows, cols, sources, values). - - Returns - ------- - tuple of np.ndarray - The row and column of each non-zero pixel, the source index s repeated - for each pixel, and the pixel values. - """ - r, c = np.nonzero(img) - return r, c, np.full(r.size, s), img[r, c] - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_place_footprints_moves_them_through_the_map(mode: str) -> None: - """A placed footprint lands at the mapped centroid. - - Its sum changes only by the map's local area factor (a few percent for - this bend). - """ - warp = make_warp(mode) - parts = [_fp_tuple(gaussian((H, W), c), s) for s, c in enumerate(CENTRES)] - fp = tuple(np.concatenate(x) for x in zip(*parts)) - rr, cc = np.mgrid[:H, :W] - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - h = place_footprints(fp, CENTRES.shape[0], m, (H, W)).toarray() - for s in range(CENTRES.shape[0]): - img = h[:, s].reshape(H, W) - tol = 0.01 if mode == "rigid" else 0.05 - assert img.sum() == pytest.approx(1.0, abs=tol) - cen = [(img * rr).sum() / img.sum(), (img * cc).sum() / img.sum()] - want = warp.coords(t, *CENTRES[s]) - np.testing.assert_allclose(cen, np.ravel(want), atol=0.02) - - -def test_place_footprints_blur_keeps_the_sum() -> None: - """A blurred footprint still sums to (about) 1.""" - m = TrialMap(np.array([[1.0, 0, 0.2], [0, 1.0, -0.1]])) - fp = _fp_tuple(gaussian((H, W), CENTRES[1]), 0) - h = place_footprints(fp, 1, m, (H, W), sigma=0.75).toarray() - assert h.sum() == pytest.approx(1.0, abs=0.01) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_rendered_activity_reproduces_the_movie(tmp_path: Path, mode: str) -> None: - """The rendered activity of a synthetic run has the movie's flux and centroids. - - On a synthetic run whose movie is footprints x 80 Hz traces plus a - baseline, the rendered activity has the movie's flux and centroids at - every source (rigid and patchwise maps); pixel by pixel it differs by - the bilinear interpolation of a 1.33 px footprint (up to ~12% at - a half-pixel shift). - """ - syn = write_session(tmp_path, mode) - run = SiloRun(syn["run"], "net") - assert run.path(1).alignment == mode - session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) - for t in range(N_TRIALS): - tr = load_trial([run], session, 1, t) - assert tr.layers == [ - "movie", - "activity:net", - "residual:net", - "baseline", - "residual-baseline:net", - ] - lay = tr.runs[0] - act = np.asarray((lay.footprints @ lay.x80["exporter"]).T) - signal = tr.movie - 10.0 - assert np.nanmax(np.abs(signal - act)) < 0.15 * np.nanmax(signal) - f = tr.busiest_frame() - for s in range(CENTRES.shape[0]): - want = np.ravel(syn["warp"].coords(t, *CENTRES[s])) - near = np.hypot(tr.rows - want[0], tr.cols - want[1]) < 4 - a, m = act[:, near].sum(1), signal[:, near].sum(1) - np.testing.assert_allclose(a, m, atol=0.02 * m.max()) - for img in (act[f, near], signal[f, near]): - cen = ( - np.array([ - (img * tr.rows[near]).sum(), - (img * tr.cols[near]).sum(), - ]) - / img.sum() - ) - np.testing.assert_allclose(cen, want, atol=0.03) - fr = tr.frame(f, 4) - assert fr.shape == (5, tr.N) - np.testing.assert_allclose(fr[2], fr[0] - fr[1], atol=1e-4) - tc, n = tr.trace(int(lay.kept_rc[0, 0]), int(lay.kept_rc[0, 1]), 1) - assert n == 9 and tc.shape == (5, tr.T) - np.testing.assert_allclose(tc[3], 10.0, atol=0.01) - # the matched kernel is narrower: same totals, sharper peaks - xm, xe = lay.x80["matched"], lay.x80["exporter"] - np.testing.assert_allclose(xm.sum(1), xe.sum(1), rtol=0.02) - assert (xm.max(1) > xe.max(1)).all() - fm = tr.frame(f, 1, "matched") - assert fm.shape == (5, tr.N) and not np.array_equal(fm[1], fr[1]) - - -def test_run_reader(tmp_path: Path) -> None: - """Sources, images, traces and per-trial footprints of a run.""" - syn = write_session(tmp_path, "rigid") - run = SiloRun(syn["run"], "r") - p = run.path(1) - assert p.shape == (H, W) and p.sources.n == 3 - np.testing.assert_allclose(p.sources.rc, CENTRES) - assert p.sources.rejected_rc.tolist() == [[5.0, 5.0]] - assert run.describe()["validKernel"] == 5 - tr = run.traces(1) - assert tr["dF_denoised"].shape == (2 * syn["lines"].size, 3) - fps = run.footprints(1) - assert len(fps) == N_TRIALS and fps[0][3].sum() == pytest.approx(3.0) - patch, _r0, _c0 = run.profile_patch(1, 0) - assert patch.shape == (15, 15) - w = footprint_width(gaussian((H, W), CENTRES[0]), *CENTRES[0]) - assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 - - -def test_movie_found_by_stem(tmp_path: Path) -> None: - """A table naming a TIFF finds the HDF5 movie, as SILo does.""" - import h5py - - syn = write_session(tmp_path, "rigid") - table = syn["run"] / "trial_table.h5" - with h5py.File(table, "r+") as f: - names = f["motion_correction/fn_reg_ds"][()].astype(str) - del f["motion_correction/fn_reg_ds"] - f["motion_correction/fn_reg_ds"] = ( - np.char.replace(names, ".h5", ".tif").astype(object).astype(h5py.string_dtype()) - ) - session = Session(table, syn["moco"], syn["base"]) - assert session.has_movie(0, 0) - assert session.movie_file(0, 0).suffix == ".h5" - - -def test_kernels_follow_each_runs_frame_lines(tmp_path: Path) -> None: - """Each run's matched kernel comes from its own 200 Hz frame lines.""" - syn = write_session(tmp_path, "rigid") - session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) - a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") - b.path(1).lines = ( - b.path(1).lines * 0 + np.arange(b.path(1).lines.size) * 30.0 + 1 - ) # another analysis rate: dt200 30 lines - tr = load_trial([a, b], session, 1, 0) - ka, kb = tr.runs[0].kernels["matched"][0], tr.runs[1].kernels["matched"][0] - assert ka == pytest.approx(np.sqrt(134**2 - 54**2)) - assert kb == pytest.approx(np.sqrt(134**2 - 30**2)) - assert set(tr.info["render_dt_lines"]) == {"a", "b"} - - -def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float) -> np.ndarray: - """Frames formed from a densely sampled signal as weighted means. - - One sample per line, line i + 1 holds x[i]; the weights are - ``exp(-|dline| / dt)`` within reach lines of each frame's line. - - Returns - ------- - np.ndarray - One weighted-mean value per entry of at. - """ - lines = np.arange(1, x.size + 1, dtype=float) - out = np.empty(at.size) - for j, a in enumerate(at): - sel = np.abs(lines - a) <= reach - w = np.exp(-np.abs(lines[sel] - a) / dt) - out[j] = (w * x[sel]).sum() / w.sum() - return out - - -def test_exact_kernel_undoes_the_double_smoothing() -> None: - """The exact kernel turns 200 Hz frames into the movie's 80 Hz frames to about 1%. - - On densely sampled data (kernels not truncated); the exporter's kernel - loses ~10% of a fast event's peak, the matched one ~5%. - """ - n = 60000 - x = np.zeros(n) - k = np.exp(-np.arange(1200) / 150.0) # ~14 ms decay at 10.7 kHz lines - for onset in range(4000, n - 5000, 7919): - x[onset : onset + k.size] += 100 * k - dt80, dt200, reach = 134, 54, 12 - lines200 = np.arange(1, n, dt200, dtype=float) - ds = np.arange(1, n, dt80, dtype=float) + 17 - f200 = _formed(x, lines200, dt200, reach * dt200) - f80 = _formed(x, ds, dt80, reach * dt80) - none = np.zeros(lines200.size, bool) - ok = (ds > 3000) & (ds < n - 3000) - peak, rms = {}, {} - for kern in KERNELS: - w, share, info = kernel_weights(kern, lines200, none, ds, dt80, reach * dt80) - assert np.allclose(share, 0) - via = w.T @ f200 - peak[kern] = via[ok].max() / f80[ok].max() - rms[kern] = np.sqrt(np.mean((via[ok] - f80[ok]) ** 2)) / np.sqrt(np.mean(f80[ok] ** 2)) - if kern == "exact": - assert info["r"] == pytest.approx((54 / 134) ** 2) - assert peak["exact"] == pytest.approx(1.0, abs=0.01) - assert rms["exact"] < 0.015 - assert peak["exporter"] < 0.95 - assert peak["exporter"] < peak["matched"] < peak["exact"] - assert rms["exact"] < rms["matched"] < rms["exporter"] - - -def test_interp_weights_skip_discarded_frames() -> None: - """Interpolation uses kept neighbours only, holds at the ends.""" - lines = np.array([10.0, 20, 30, 40, 50]) - keep = np.array([True, True, False, True, True]) - w = interp_weights(lines, keep, np.array([5.0, 25, 35, 45, 60])).toarray() - np.testing.assert_allclose(w.sum(0), 1.0) - assert w[0, 0] == 1 and w[4, 4] == 1 # nearest kept beyond the ends - np.testing.assert_allclose(w[[1, 3], 1], [0.75, 0.25]) # 20..40 - np.testing.assert_allclose(w[[1, 3], 2], [0.25, 0.75]) - assert not w[2].any() - assert interp_weights(lines, np.zeros(5, bool), lines).nnz == 0 - one = interp_weights(lines, keep & (lines == 40), lines).toarray() - assert (one[3] == 1).all() - - -def test_exact_weights_with_discarded_frames() -> None: - """Columns sum to 1; discarded frames get no weight. - - A frame with no kept 200 Hz frame within reach stays empty, as the - exporter's. - """ - rng = np.random.default_rng(4) - lines200 = np.ceil(1 + 53.4 * np.arange(400)) - disc = rng.random(400) < 0.1 - disc[200:240] = True # a long gap: frames in it have nothing in reach - ds = 1.0 + 134 * np.arange(150) + 7 - w, share, r = exact_weights(lines200, disc, ds, 134, 54, 402) - ref, ref_share = frame_weights(lines200, disc, ds, 134, 402) - np.testing.assert_allclose(share, ref_share) - tot = np.asarray(w.sum(0)).ravel() - empty = np.asarray(ref.sum(0)).ravel() == 0 - assert empty.any() and np.allclose(tot[empty], 0) - np.testing.assert_allclose(tot[~empty], 1.0) - assert not w.toarray()[disc].any() - assert r == pytest.approx((54 / 134) ** 2) - - -@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) -def test_cubic_placement_keeps_the_shape(mode: str) -> None: - """Moved by a fraction of a pixel, a footprint keeps its flux with either interpolation. - - The cubic spline also keeps its peak, where bilinear interpolation blurs - it. - """ - warp = make_warp(mode) - for t in range(N_TRIALS): - field = None - if mode == "patchwise": - rt, ct = warp.grid_coords(t, (H, W)) - rr, cc = np.mgrid[:H, :W] - field = np.stack([rt - rr, ct - cc]) - m = TrialMap(warp.affine[t], field) - qr, qc = np.mgrid[:H, :W].astype(float) - at = warp.inverse(t, qr, qc) - err = {} - for order in (1, 3): - for s, centre in enumerate(CENTRES): - fp = gaussian((H, W), centre) - r, c = np.nonzero(fp) - fps = (r, c, np.zeros(r.size, int), fp[r, c]) - h = place_footprints(fps, 1, m, (H, W), interp_order=order) - img = h.toarray()[:, 0].reshape(H, W) - want = gaussian((H, W), centre, at=at) - assert img.sum() == pytest.approx(want.sum(), rel=0.01) - err.setdefault(order, []).append(np.abs(img - want).max() / want.max()) - assert max(err[3]) < 0.02 - assert max(err[3]) < max(err[1]) - - -def test_matched_kernel_with_one_frame() -> None: - """With one 200 Hz frame the matched kernel keeps the movie's dt. - - As render_dt does, and it still renders the frame. - """ - w, _, info = kernel_weights( - "matched", np.array([100.0]), np.zeros(1, bool), np.array([90.0]), 134 - ) - assert info["dt"] == 134 and render_dt("matched", 134, [100.0]) == 134 - assert w.toarray()[0, 0] == pytest.approx(1.0) +"""Rendering of SILo's activity in a trial's movie (giant view).""" + +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.viewer.render import ( + KERNELS, + TrialMap, + exact_weights, + frame_weights, + interp_weights, + kernel_dt, + kernel_weights, + place_footprints, +) +from giant_python.viewer.run import SiloRun, footprint_width +from giant_python.viewer.trial import Session, load_trial, render_dt + +from .synthetic import ( + CENTRES, + N_TRIALS, + H, + W, + gaussian, + make_warp, + write_session, +) + + +def _exporter_weights( + lines200: np.ndarray, disc: np.ndarray, ds: np.ndarray, dt: float, half: float +) -> tuple[np.ndarray, np.ndarray]: + """Run the exporter's loop (exportF0TrainingData.m), as a dense matrix. + + Returns + ------- + weights : np.ndarray + (lines200.size, ds.size) weights of the kept 200 Hz lines in each frame, + each column normalized to sum to 1 (all zero when every line is discarded). + share : np.ndarray + Share of each frame's kernel weight that falls on discarded lines. + """ + wk = np.zeros((lines200.size, ds.size)) + share = np.zeros(ds.size) + for j in range(ds.size): + d = lines200 - ds[j] + sel = np.flatnonzero(np.abs(d) <= half) + w = np.exp(-np.abs(d[sel]) / dt) + share[j] = w[disc[sel]].sum() / max(w.sum(), np.finfo(float).eps) + keep = ~disc[sel] + if keep.any(): + wk[sel[keep], j] = w[keep] / w[keep].sum() + return wk, share + + +def test_frame_weights_match_the_exporter() -> None: + """Weights and discard shares equal the exporter's loop.""" + rng = np.random.default_rng(0) + lines200 = np.ceil(1 + 53.4 * np.arange(400)) + disc = rng.random(400) < 0.1 + ds = 1.0 + 134 * np.arange(150) + 7 + w, share = frame_weights(lines200, disc, ds, 134, 402) + ref, ref_share = _exporter_weights(lines200, disc, ds, 134, 402) + np.testing.assert_allclose(w.toarray(), ref, atol=1e-12) + np.testing.assert_allclose(share, ref_share, atol=1e-12) + full = np.asarray(w.sum(0)).ravel() + assert np.allclose(full[full > 0], 1.0) + + +def test_kernel_dt_and_matched_kernel() -> None: + """Dt from DSframes; the matched kernel removes the 200 Hz part.""" + assert kernel_dt(1 + 134 * np.arange(10), None, 2.5) == 134 + assert kernel_dt(np.array([5.0]), np.arange(0, 540, 54.0), 2.5) == 135 + lines = np.ceil(1 + 53.4 * np.arange(100)) + assert render_dt("exporter", 134, lines) == 134 + assert render_dt("matched", 134, lines) == pytest.approx(np.sqrt(134**2 - 54**2)) + with pytest.raises(ValueError): + render_dt("other", 134, lines) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_trial_map_inverse(mode: str) -> None: + """The map's inverse undoes it (and agrees with TrialWarp's).""" + warp = make_warp(mode) + rng = np.random.default_rng(3) + r, c = rng.uniform(3, H - 3, 200), rng.uniform(3, W - 3, 200) + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + rr, cc = np.mgrid[:H, :W] + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + fr, fc = m.forward(r, c) + er, ec = warp.coords(t, r, c) + tol = 1e-9 if mode == "rigid" else 2e-3 # bilinear field + np.testing.assert_allclose(fr, er, atol=tol) + np.testing.assert_allclose(fc, ec, atol=tol) + ir, ic = m.inverse(er, ec) + wr, wc = warp.inverse(t, er, ec) + np.testing.assert_allclose(ir, wr, atol=tol) + np.testing.assert_allclose(ic, wc, atol=tol) + + +def test_affine_map_inverse_is_exact() -> None: + """An affine map's inverse is exact.""" + a = np.array([[1.01, 0.02, 0.4], [-0.015, 0.99, -0.3]]) + m = TrialMap(a) + r, c = np.array([3.0, 10.5]), np.array([7.0, 2.25]) + fr, fc = m.forward(r, c) + ir, ic = m.inverse(fr, fc) + np.testing.assert_allclose(ir, r, atol=1e-12) + np.testing.assert_allclose(ic, c, atol=1e-12) + + +def _fp_tuple(img: np.ndarray, s: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Convert a canvas footprint image to (rows, cols, sources, values). + + Returns + ------- + tuple of np.ndarray + The row and column of each non-zero pixel, the source index s repeated + for each pixel, and the pixel values. + """ + r, c = np.nonzero(img) + return r, c, np.full(r.size, s), img[r, c] + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_place_footprints_moves_them_through_the_map(mode: str) -> None: + """A placed footprint lands at the mapped centroid. + + Its sum changes only by the map's local area factor (a few percent for + this bend). + """ + warp = make_warp(mode) + parts = [_fp_tuple(gaussian((H, W), c), s) for s, c in enumerate(CENTRES)] + fp = tuple(np.concatenate(x) for x in zip(*parts)) + rr, cc = np.mgrid[:H, :W] + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + h = place_footprints(fp, CENTRES.shape[0], m, (H, W)).toarray() + for s in range(CENTRES.shape[0]): + img = h[:, s].reshape(H, W) + tol = 0.01 if mode == "rigid" else 0.05 + assert img.sum() == pytest.approx(1.0, abs=tol) + cen = [(img * rr).sum() / img.sum(), (img * cc).sum() / img.sum()] + want = warp.coords(t, *CENTRES[s]) + np.testing.assert_allclose(cen, np.ravel(want), atol=0.02) + + +def test_place_footprints_blur_keeps_the_sum() -> None: + """A blurred footprint still sums to (about) 1.""" + m = TrialMap(np.array([[1.0, 0, 0.2], [0, 1.0, -0.1]])) + fp = _fp_tuple(gaussian((H, W), CENTRES[1]), 0) + h = place_footprints(fp, 1, m, (H, W), sigma=0.75).toarray() + assert h.sum() == pytest.approx(1.0, abs=0.01) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_rendered_activity_reproduces_the_movie(tmp_path: Path, mode: str) -> None: + """The rendered activity of a synthetic run has the movie's flux and centroids. + + On a synthetic run whose movie is footprints x 80 Hz traces plus a + baseline, the rendered activity has the movie's flux and centroids at + every source (rigid and patchwise maps); pixel by pixel it differs by + the bilinear interpolation of a 1.33 px footprint (up to ~12% at + a half-pixel shift). + """ + syn = write_session(tmp_path, mode) + run = SiloRun(syn["run"], "net") + assert run.path(1).alignment == mode + session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) + for t in range(N_TRIALS): + tr = load_trial([run], session, 1, t) + assert tr.layers == [ + "movie", + "activity:net", + "residual:net", + "baseline", + "residual-baseline:net", + ] + lay = tr.runs[0] + act = np.asarray((lay.footprints @ lay.x80["exporter"]).T) + signal = tr.movie - 10.0 + assert np.nanmax(np.abs(signal - act)) < 0.15 * np.nanmax(signal) + f = tr.busiest_frame() + for s in range(CENTRES.shape[0]): + want = np.ravel(syn["warp"].coords(t, *CENTRES[s])) + near = np.hypot(tr.rows - want[0], tr.cols - want[1]) < 4 + a, m = act[:, near].sum(1), signal[:, near].sum(1) + np.testing.assert_allclose(a, m, atol=0.02 * m.max()) + for img in (act[f, near], signal[f, near]): + cen = ( + np.array([ + (img * tr.rows[near]).sum(), + (img * tr.cols[near]).sum(), + ]) + / img.sum() + ) + np.testing.assert_allclose(cen, want, atol=0.03) + fr = tr.frame(f, 4) + assert fr.shape == (5, tr.N) + np.testing.assert_allclose(fr[2], fr[0] - fr[1], atol=1e-4) + tc, n = tr.trace(int(lay.kept_rc[0, 0]), int(lay.kept_rc[0, 1]), 1) + assert n == 9 and tc.shape == (5, tr.T) + np.testing.assert_allclose(tc[3], 10.0, atol=0.01) + # the matched kernel is narrower: same totals, sharper peaks + xm, xe = lay.x80["matched"], lay.x80["exporter"] + np.testing.assert_allclose(xm.sum(1), xe.sum(1), rtol=0.02) + assert (xm.max(1) > xe.max(1)).all() + fm = tr.frame(f, 1, "matched") + assert fm.shape == (5, tr.N) and not np.array_equal(fm[1], fr[1]) + + +def test_run_reader(tmp_path: Path) -> None: + """Sources, images, traces and per-trial footprints of a run.""" + syn = write_session(tmp_path, "rigid") + run = SiloRun(syn["run"], "r") + p = run.path(1) + assert p.shape == (H, W) and p.sources.n == 3 + np.testing.assert_allclose(p.sources.rc, CENTRES) + assert p.sources.rejected_rc.tolist() == [[5.0, 5.0]] + assert run.describe()["validKernel"] == 5 + tr = run.traces(1) + assert tr["dF_denoised"].shape == (2 * syn["lines"].size, 3) + fps = run.footprints(1) + assert len(fps) == N_TRIALS and fps[0][3].sum() == pytest.approx(3.0) + patch, _r0, _c0 = run.profile_patch(1, 0) + assert patch.shape == (15, 15) + w = footprint_width(gaussian((H, W), CENTRES[0]), *CENTRES[0]) + assert 1.2 < w < 1.4 # a truncated Gaussian of sigma 1.33 + + +def test_movie_found_by_stem(tmp_path: Path) -> None: + """A table naming a TIFF finds the HDF5 movie, as SILo does.""" + import h5py + + syn = write_session(tmp_path, "rigid") + table = syn["run"] / "trial_table.h5" + with h5py.File(table, "r+") as f: + names = f["motion_correction/fn_reg_ds"][()].astype(str) + del f["motion_correction/fn_reg_ds"] + f["motion_correction/fn_reg_ds"] = ( + np.char.replace(names, ".h5", ".tif").astype(object).astype(h5py.string_dtype()) + ) + session = Session(table, syn["moco"], syn["base"]) + assert session.has_movie(0, 0) + assert session.movie_file(0, 0).suffix == ".h5" + + +def test_kernels_follow_each_runs_frame_lines(tmp_path: Path) -> None: + """Each run's matched kernel comes from its own 200 Hz frame lines.""" + syn = write_session(tmp_path, "rigid") + session = Session(syn["run"] / "trial_table.h5", syn["moco"], syn["base"]) + a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") + b.path(1).lines = ( + b.path(1).lines * 0 + np.arange(b.path(1).lines.size) * 30.0 + 1 + ) # another analysis rate: dt200 30 lines + tr = load_trial([a, b], session, 1, 0) + ka, kb = tr.runs[0].kernels["matched"][0], tr.runs[1].kernels["matched"][0] + assert ka == pytest.approx(np.sqrt(134**2 - 54**2)) + assert kb == pytest.approx(np.sqrt(134**2 - 30**2)) + assert set(tr.info["render_dt_lines"]) == {"a", "b"} + + +def _formed(x: np.ndarray, at: np.ndarray, dt: float, reach: float) -> np.ndarray: + """Frames formed from a densely sampled signal as weighted means. + + One sample per line, line i + 1 holds x[i]; the weights are + ``exp(-|dline| / dt)`` within reach lines of each frame's line. + + Returns + ------- + np.ndarray + One weighted-mean value per entry of at. + """ + lines = np.arange(1, x.size + 1, dtype=float) + out = np.empty(at.size) + for j, a in enumerate(at): + sel = np.abs(lines - a) <= reach + w = np.exp(-np.abs(lines[sel] - a) / dt) + out[j] = (w * x[sel]).sum() / w.sum() + return out + + +def test_exact_kernel_undoes_the_double_smoothing() -> None: + """The exact kernel turns 200 Hz frames into the movie's 80 Hz frames to about 1%. + + On densely sampled data (kernels not truncated); the exporter's kernel + loses ~10% of a fast event's peak, the matched one ~5%. + """ + n = 60000 + x = np.zeros(n) + k = np.exp(-np.arange(1200) / 150.0) # ~14 ms decay at 10.7 kHz lines + for onset in range(4000, n - 5000, 7919): + x[onset : onset + k.size] += 100 * k + dt80, dt200, reach = 134, 54, 12 + lines200 = np.arange(1, n, dt200, dtype=float) + ds = np.arange(1, n, dt80, dtype=float) + 17 + f200 = _formed(x, lines200, dt200, reach * dt200) + f80 = _formed(x, ds, dt80, reach * dt80) + none = np.zeros(lines200.size, bool) + ok = (ds > 3000) & (ds < n - 3000) + peak, rms = {}, {} + for kern in KERNELS: + w, share, info = kernel_weights(kern, lines200, none, ds, dt80, reach * dt80) + assert np.allclose(share, 0) + via = w.T @ f200 + peak[kern] = via[ok].max() / f80[ok].max() + rms[kern] = np.sqrt(np.mean((via[ok] - f80[ok]) ** 2)) / np.sqrt(np.mean(f80[ok] ** 2)) + if kern == "exact": + assert info["r"] == pytest.approx((54 / 134) ** 2) + assert peak["exact"] == pytest.approx(1.0, abs=0.01) + assert rms["exact"] < 0.015 + assert peak["exporter"] < 0.95 + assert peak["exporter"] < peak["matched"] < peak["exact"] + assert rms["exact"] < rms["matched"] < rms["exporter"] + + +def test_interp_weights_skip_discarded_frames() -> None: + """Interpolation uses kept neighbours only, holds at the ends.""" + lines = np.array([10.0, 20, 30, 40, 50]) + keep = np.array([True, True, False, True, True]) + w = interp_weights(lines, keep, np.array([5.0, 25, 35, 45, 60])).toarray() + np.testing.assert_allclose(w.sum(0), 1.0) + assert w[0, 0] == 1 and w[4, 4] == 1 # nearest kept beyond the ends + np.testing.assert_allclose(w[[1, 3], 1], [0.75, 0.25]) # 20..40 + np.testing.assert_allclose(w[[1, 3], 2], [0.25, 0.75]) + assert not w[2].any() + assert interp_weights(lines, np.zeros(5, bool), lines).nnz == 0 + one = interp_weights(lines, keep & (lines == 40), lines).toarray() + assert (one[3] == 1).all() + + +def test_exact_weights_with_discarded_frames() -> None: + """Columns sum to 1; discarded frames get no weight. + + A frame with no kept 200 Hz frame within reach stays empty, as the + exporter's. + """ + rng = np.random.default_rng(4) + lines200 = np.ceil(1 + 53.4 * np.arange(400)) + disc = rng.random(400) < 0.1 + disc[200:240] = True # a long gap: frames in it have nothing in reach + ds = 1.0 + 134 * np.arange(150) + 7 + w, share, r = exact_weights(lines200, disc, ds, 134, 54, 402) + ref, ref_share = frame_weights(lines200, disc, ds, 134, 402) + np.testing.assert_allclose(share, ref_share) + tot = np.asarray(w.sum(0)).ravel() + empty = np.asarray(ref.sum(0)).ravel() == 0 + assert empty.any() and np.allclose(tot[empty], 0) + np.testing.assert_allclose(tot[~empty], 1.0) + assert not w.toarray()[disc].any() + assert r == pytest.approx((54 / 134) ** 2) + + +@pytest.mark.parametrize("mode", ["rigid", "patchwise"]) +def test_cubic_placement_keeps_the_shape(mode: str) -> None: + """Moved by a fraction of a pixel, a footprint keeps its flux with either interpolation. + + The cubic spline also keeps its peak, where bilinear interpolation blurs + it. + """ + warp = make_warp(mode) + for t in range(N_TRIALS): + field = None + if mode == "patchwise": + rt, ct = warp.grid_coords(t, (H, W)) + rr, cc = np.mgrid[:H, :W] + field = np.stack([rt - rr, ct - cc]) + m = TrialMap(warp.affine[t], field) + qr, qc = np.mgrid[:H, :W].astype(float) + at = warp.inverse(t, qr, qc) + err = {} + for order in (1, 3): + for s, centre in enumerate(CENTRES): + fp = gaussian((H, W), centre) + r, c = np.nonzero(fp) + fps = (r, c, np.zeros(r.size, int), fp[r, c]) + h = place_footprints(fps, 1, m, (H, W), interp_order=order) + img = h.toarray()[:, 0].reshape(H, W) + want = gaussian((H, W), centre, at=at) + assert img.sum() == pytest.approx(want.sum(), rel=0.01) + err.setdefault(order, []).append(np.abs(img - want).max() / want.max()) + assert max(err[3]) < 0.02 + assert max(err[3]) < max(err[1]) + + +def test_matched_kernel_with_one_frame() -> None: + """With one 200 Hz frame the matched kernel keeps the movie's dt. + + As render_dt does, and it still renders the frame. + """ + w, _, info = kernel_weights( + "matched", np.array([100.0]), np.zeros(1, bool), np.array([90.0]), 134 + ) + assert info["dt"] == 134 and render_dt("matched", 134, [100.0]) == 134 + assert w.toarray()[0, 0] == pytest.approx(1.0) diff --git a/tests/viewer/test_viewer_server.py b/tests/viewer/test_viewer_server.py index 0bf25fb9..ad9a0a6e 100644 --- a/tests/viewer/test_viewer_server.py +++ b/tests/viewer/test_viewer_server.py @@ -1,153 +1,153 @@ -"""API smoke test of the giant view server.""" - -import argparse -import json -import threading -import urllib.error -import urllib.request -from collections.abc import Iterator -from email.message import Message -from pathlib import Path - -import numpy as np -import pytest - -from giant_python.cli import build_parser -from giant_python.viewer.server import Store, make_server, make_store - -from .synthetic import N_TRIALS, H, W, write_session - - -@pytest.fixture -def server(tmp_path: Path) -> Iterator[tuple[str, Store]]: - """Start a running server on a synthetic session with two runs. - - Yields - ------ - url : str - The server's address. - store : Store - The store of runs the server serves. - """ - syn = write_session(tmp_path, "patchwise") - args = build_parser().parse_args([ - "view", - f"net={syn['run']}", - f"other={syn['run']}", - "--moco-dir", - str(syn["moco"]), - "--baseline-dir", - str(syn["base"]), - "--port", - "0", - "--no-browser", - ]) - assert isinstance(args, argparse.Namespace) and args.command == "view" - store = make_store(args) - srv = make_server(store, "127.0.0.1", 0) - th = threading.Thread(target=srv.serve_forever, daemon=True) - th.start() - yield f"http://127.0.0.1:{srv.server_address[1]}", store - srv.shutdown() - srv.server_close() - - -def _get(url: str) -> tuple[bytes, Message]: - """Body and headers of a GET. - - Returns - ------- - body : bytes - The response body. - headers : Message - The response headers. - """ - with urllib.request.urlopen(url, timeout=60) as r: - return r.read(), r.headers - - -def test_api(server: tuple[str, Store]) -> None: - """Every endpoint answers with the expected shapes.""" - base, store = server - body, _ = _get(base + "/") - assert b"SILo run viewer" in body - meta = json.loads(_get(base + "/api/meta")[0]) - assert [r["name"] for r in meta["runs"]] == ["net", "other"] - assert meta["paths"][0]["alignment"] == ["patchwise", "patchwise"] - assert len(meta["paths"][0]["trials"]) == N_TRIALS - src = json.loads(_get(base + "/api/sources?path=1")[0]) - assert src["shape"] == [H, W] and len(src["runs"]["net"]["kept"]) == 3 - img, hd = _get(base + "/api/image?path=1&run=net&kind=trial_act&trial=1") - assert json.loads(hd["X-Shape"]) == [H, W] - assert np.frombuffer(img, np.float32).size == H * W - s = json.loads(_get(base + "/api/source?path=1&run=net&id=1")[0]) - assert len(s["trial_rc"]) == N_TRIALS and s["events"] - tb, hd = _get(base + "/api/source_traces?path=1&run=net&id=1") - assert np.frombuffer(tb, np.float32).size == 4 * store.runs[0].path(1).lines.size - st = json.loads(_get(base + "/api/trial?path=1&trial=0")[0]) - n_layers = len(st["layers"]) - assert n_layers == 1 + 2 * 2 + 1 + 2 # movie, 2 runs x 2, base, 2 res - n = len(st["rows"]) - fr, hd = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4") - assert np.frombuffer(fr, np.float32).size == n_layers * n - fm, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=matched") - assert np.frombuffer(fm, np.float32).size == n_layers * n - fx, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=exact") - assert np.frombuffer(fx, np.float32).size == n_layers * n - tc, hd = _get(base + "/api/trace?path=1&trial=0&r=20&c=30&rad=1") - assert int(hd["X-Pixels"]) == 9 - assert np.frombuffer(tc, np.float32).size == n_layers * st["shape"][0] - assert json.loads(_get(base + "/api/progress?key=1/0")[0]) == {"msg": ""} - - -def test_api_errors(server: tuple[str, Store]) -> None: - """Unknown paths and bad keys are errors, not crashes.""" - base, _ = server - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/nothing") - assert e.value.code == 404 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/source?path=1&run=nobody&id=0") - assert e.value.code == 400 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/frame?path=1&trial=0") - assert e.value.code == 400 - with pytest.raises(urllib.error.HTTPError) as e: - _get(base + "/api/frame?path=1&trial=0&t=3&kernel=other") - assert e.value.code == 400 - - -def test_runs_must_share_the_activity_channel(tmp_path: Path) -> None: - """Runs read with different activity channels are not compared.""" - from giant_python.viewer.run import SiloRun - from giant_python.viewer.server import Store - from giant_python.viewer.trial import Session - - syn = write_session(tmp_path, "rigid") - a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") - b.params["activityChannel"] = 2 - session = Session(syn["run"] / "trial_table.h5", syn["moco"]) - with pytest.raises(ValueError, match="activityChannel"): - Store([a, b], session) - # a run without numChannels counts as 2 channels, as the loader reads it - b.params["activityChannel"] = 1 - a.params["numChannels"] = 2 - b.params.pop("numChannels") - Store([a, b], session) - a.params["numChannels"] = 1 - with pytest.raises(ValueError, match="numChannels"): - Store([a, b], session) - - -def test_large_valid_kernel_is_reported(tmp_path: Path) -> None: - """A 9 x 9 support (81 values) is still described.""" - import h5py - - from giant_python.viewer.run import SiloRun - - syn = write_session(tmp_path, "rigid") - es = syn["run"] / "source_extraction" / "experiment_summary.h5" - with h5py.File(es, "r+") as f: - del f["params/validKernel"] - f["params/validKernel"] = np.ones((9, 9)) - assert SiloRun(syn["run"]).describe()["validKernel"] == 9 +"""API smoke test of the giant view server.""" + +import argparse +import json +import threading +import urllib.error +import urllib.request +from collections.abc import Iterator +from email.message import Message +from pathlib import Path + +import numpy as np +import pytest + +from giant_python.cli import build_parser +from giant_python.viewer.server import Store, make_server, make_store + +from .synthetic import N_TRIALS, H, W, write_session + + +@pytest.fixture +def server(tmp_path: Path) -> Iterator[tuple[str, Store]]: + """Start a running server on a synthetic session with two runs. + + Yields + ------ + url : str + The server's address. + store : Store + The store of runs the server serves. + """ + syn = write_session(tmp_path, "patchwise") + args = build_parser().parse_args([ + "view", + f"net={syn['run']}", + f"other={syn['run']}", + "--moco-dir", + str(syn["moco"]), + "--baseline-dir", + str(syn["base"]), + "--port", + "0", + "--no-browser", + ]) + assert isinstance(args, argparse.Namespace) and args.command == "view" + store = make_store(args) + srv = make_server(store, "127.0.0.1", 0) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + yield f"http://127.0.0.1:{srv.server_address[1]}", store + srv.shutdown() + srv.server_close() + + +def _get(url: str) -> tuple[bytes, Message]: + """Body and headers of a GET. + + Returns + ------- + body : bytes + The response body. + headers : Message + The response headers. + """ + with urllib.request.urlopen(url, timeout=60) as r: + return r.read(), r.headers + + +def test_api(server: tuple[str, Store]) -> None: + """Every endpoint answers with the expected shapes.""" + base, store = server + body, _ = _get(base + "/") + assert b"SILo run viewer" in body + meta = json.loads(_get(base + "/api/meta")[0]) + assert [r["name"] for r in meta["runs"]] == ["net", "other"] + assert meta["paths"][0]["alignment"] == ["patchwise", "patchwise"] + assert len(meta["paths"][0]["trials"]) == N_TRIALS + src = json.loads(_get(base + "/api/sources?path=1")[0]) + assert src["shape"] == [H, W] and len(src["runs"]["net"]["kept"]) == 3 + img, hd = _get(base + "/api/image?path=1&run=net&kind=trial_act&trial=1") + assert json.loads(hd["X-Shape"]) == [H, W] + assert np.frombuffer(img, np.float32).size == H * W + s = json.loads(_get(base + "/api/source?path=1&run=net&id=1")[0]) + assert len(s["trial_rc"]) == N_TRIALS and s["events"] + tb, hd = _get(base + "/api/source_traces?path=1&run=net&id=1") + assert np.frombuffer(tb, np.float32).size == 4 * store.runs[0].path(1).lines.size + st = json.loads(_get(base + "/api/trial?path=1&trial=0")[0]) + n_layers = len(st["layers"]) + assert n_layers == 1 + 2 * 2 + 1 + 2 # movie, 2 runs x 2, base, 2 res + n = len(st["rows"]) + fr, hd = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4") + assert np.frombuffer(fr, np.float32).size == n_layers * n + fm, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=matched") + assert np.frombuffer(fm, np.float32).size == n_layers * n + fx, _ = _get(base + "/api/frame?path=1&trial=0&t=40&avg=4&kernel=exact") + assert np.frombuffer(fx, np.float32).size == n_layers * n + tc, hd = _get(base + "/api/trace?path=1&trial=0&r=20&c=30&rad=1") + assert int(hd["X-Pixels"]) == 9 + assert np.frombuffer(tc, np.float32).size == n_layers * st["shape"][0] + assert json.loads(_get(base + "/api/progress?key=1/0")[0]) == {"msg": ""} + + +def test_api_errors(server: tuple[str, Store]) -> None: + """Unknown paths and bad keys are errors, not crashes.""" + base, _ = server + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/nothing") + assert e.value.code == 404 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/source?path=1&run=nobody&id=0") + assert e.value.code == 400 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/frame?path=1&trial=0") + assert e.value.code == 400 + with pytest.raises(urllib.error.HTTPError) as e: + _get(base + "/api/frame?path=1&trial=0&t=3&kernel=other") + assert e.value.code == 400 + + +def test_runs_must_share_the_activity_channel(tmp_path: Path) -> None: + """Runs read with different activity channels are not compared.""" + from giant_python.viewer.run import SiloRun + from giant_python.viewer.server import Store + from giant_python.viewer.trial import Session + + syn = write_session(tmp_path, "rigid") + a, b = SiloRun(syn["run"], "a"), SiloRun(syn["run"], "b") + b.params["activityChannel"] = 2 + session = Session(syn["run"] / "trial_table.h5", syn["moco"]) + with pytest.raises(ValueError, match="activityChannel"): + Store([a, b], session) + # a run without numChannels counts as 2 channels, as the loader reads it + b.params["activityChannel"] = 1 + a.params["numChannels"] = 2 + b.params.pop("numChannels") + Store([a, b], session) + a.params["numChannels"] = 1 + with pytest.raises(ValueError, match="numChannels"): + Store([a, b], session) + + +def test_large_valid_kernel_is_reported(tmp_path: Path) -> None: + """A 9 x 9 support (81 values) is still described.""" + import h5py + + from giant_python.viewer.run import SiloRun + + syn = write_session(tmp_path, "rigid") + es = syn["run"] / "source_extraction" / "experiment_summary.h5" + with h5py.File(es, "r+") as f: + del f["params/validKernel"] + f["params/validKernel"] = np.ones((9, 9)) + assert SiloRun(syn["run"]).describe()["validKernel"] == 9 From 94ccc3b1f4762c0d1d7924de0a7843a8664d984a Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 15:03:32 -0800 Subject: [PATCH 12/14] Lower the interrogate fail-under threshold to 80 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 28bbc571..e06f6c13 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,4 +108,4 @@ docstring-code-format = true ignore-init-methods = true ignore-init-module = true exclude = ["docs", "build", ".conda", ".venv", "env"] -fail-under = 100 \ No newline at end of file +fail-under = 80 \ No newline at end of file From b24d698b52f6514ee71d480e75022cae4c6cd661 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 15:22:25 -0800 Subject: [PATCH 13/14] coverage fail under 80 instead of 100 (for now) --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e06f6c13..f8ff28d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,7 +74,7 @@ exclude_lines = [ "^import .*", "pragma: no cover" ] -fail_under = 100 +fail_under = 80 [tool.ruff] preview = true @@ -108,4 +108,4 @@ docstring-code-format = true ignore-init-methods = true ignore-init-module = true exclude = ["docs", "build", ".conda", ".venv", "env"] -fail-under = 80 \ No newline at end of file +fail-under = 100 \ No newline at end of file From 6def45fb61d9b16089bb1c39b971cd8a6e9c1246 Mon Sep 17 00:00:00 2001 From: Vanessa Arndorfer Date: Thu, 3 Dec 2026 15:53:47 -0800 Subject: [PATCH 14/14] Use static versioning so the release workflow and runtime version agree Set the version in pyproject.toml (the field 'uv version' updates in the tag_and_publish bump workflow), drop hatch-vcs, and read giant_python.__version__ from the installed package metadata so saved results record the same version as the distribution. --- pyproject.toml | 8 ++------ src/giant_python/__init__.py | 8 +++++++- uv.lock | 1 + 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f8ff28d0..b3ba65ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,9 +1,10 @@ [build-system] -requires = ["hatchling", "hatch-vcs"] +requires = ["hatchling"] build-backend = "hatchling.build" [project] name = "giant-python" +version = "0.1.14" description = "Python translation of the GIAnT-MATLAB analysis package." license = "MIT" requires-python = ">=3.10" @@ -14,7 +15,6 @@ 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 @@ -51,10 +51,6 @@ docs = [ [tool.uv.dependency-groups] docs = { requires-python = ">=3.12" } -[tool.hatch.version] -source = "vcs" -fallback-version = "0.0.0" - [tool.hatch.metadata] allow-direct-references = true diff --git a/src/giant_python/__init__.py b/src/giant_python/__init__.py index e68d9a27..d043aded 100644 --- a/src/giant_python/__init__.py +++ b/src/giant_python/__init__.py @@ -10,6 +10,8 @@ """ 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", diff --git a/uv.lock b/uv.lock index c904296e..0b4dc4c8 100644 --- a/uv.lock +++ b/uv.lock @@ -1523,6 +1523,7 @@ wheels = [ [[package]] name = "giant-python" +version = "0.1.14" source = { editable = "." } dependencies = [ { name = "bottleneck", version = "1.6.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },